]> The Tcpdump Group git mirrors - libpcap/blob - optimize.c
remove libpcap's own CVS keywords
[libpcap] / optimize.c
1 /*
2 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
16 * written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 *
21 * Optimization module for tcpdump intermediate representation.
22 */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #ifdef WIN32
29 #include <pcap-stdinc.h>
30 #else /* WIN32 */
31 #if HAVE_INTTYPES_H
32 #include <inttypes.h>
33 #elif HAVE_STDINT_H
34 #include <stdint.h>
35 #endif
36 #ifdef HAVE_SYS_BITYPES_H
37 #include <sys/bitypes.h>
38 #endif
39 #include <sys/types.h>
40 #endif /* WIN32 */
41
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <memory.h>
45 #include <string.h>
46
47 #include <errno.h>
48
49 #include "pcap-int.h"
50
51 #include "gencode.h"
52
53 #ifdef HAVE_OS_PROTO_H
54 #include "os-proto.h"
55 #endif
56
57 #ifdef BDEBUG
58 extern int dflag;
59 #endif
60
61 #if defined(MSDOS) && !defined(__DJGPP__)
62 extern int _w32_ffs (int mask);
63 #define ffs _w32_ffs
64 #endif
65
66 #if defined(WIN32) && defined (_MSC_VER)
67 int ffs(int mask);
68 #endif
69
70 /*
71 * Represents a deleted instruction.
72 */
73 #define NOP -1
74
75 /*
76 * Register numbers for use-def values.
77 * 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
78 * location. A_ATOM is the accumulator and X_ATOM is the index
79 * register.
80 */
81 #define A_ATOM BPF_MEMWORDS
82 #define X_ATOM (BPF_MEMWORDS+1)
83
84 /*
85 * This define is used to represent *both* the accumulator and
86 * x register in use-def computations.
87 * Currently, the use-def code assumes only one definition per instruction.
88 */
89 #define AX_ATOM N_ATOMS
90
91 /*
92 * A flag to indicate that further optimization is needed.
93 * Iterative passes are continued until a given pass yields no
94 * branch movement.
95 */
96 static int done;
97
98 /*
99 * A block is marked if only if its mark equals the current mark.
100 * Rather than traverse the code array, marking each item, 'cur_mark' is
101 * incremented. This automatically makes each element unmarked.
102 */
103 static int cur_mark;
104 #define isMarked(p) ((p)->mark == cur_mark)
105 #define unMarkAll() cur_mark += 1
106 #define Mark(p) ((p)->mark = cur_mark)
107
108 static void opt_init(struct block *);
109 static void opt_cleanup(void);
110
111 static void intern_blocks(struct block *);
112
113 static void find_inedges(struct block *);
114 #ifdef BDEBUG
115 static void opt_dump(struct block *);
116 #endif
117
118 static int n_blocks;
119 struct block **blocks;
120 static int n_edges;
121 struct edge **edges;
122
123 /*
124 * A bit vector set representation of the dominators.
125 * We round up the set size to the next power of two.
126 */
127 static int nodewords;
128 static int edgewords;
129 struct block **levels;
130 bpf_u_int32 *space;
131 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
132 /*
133 * True if a is in uset {p}
134 */
135 #define SET_MEMBER(p, a) \
136 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
137
138 /*
139 * Add 'a' to uset p.
140 */
141 #define SET_INSERT(p, a) \
142 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
143
144 /*
145 * Delete 'a' from uset p.
146 */
147 #define SET_DELETE(p, a) \
148 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
149
150 /*
151 * a := a intersect b
152 */
153 #define SET_INTERSECT(a, b, n)\
154 {\
155 register bpf_u_int32 *_x = a, *_y = b;\
156 register int _n = n;\
157 while (--_n >= 0) *_x++ &= *_y++;\
158 }
159
160 /*
161 * a := a - b
162 */
163 #define SET_SUBTRACT(a, b, n)\
164 {\
165 register bpf_u_int32 *_x = a, *_y = b;\
166 register int _n = n;\
167 while (--_n >= 0) *_x++ &=~ *_y++;\
168 }
169
170 /*
171 * a := a union b
172 */
173 #define SET_UNION(a, b, n)\
174 {\
175 register bpf_u_int32 *_x = a, *_y = b;\
176 register int _n = n;\
177 while (--_n >= 0) *_x++ |= *_y++;\
178 }
179
180 static uset all_dom_sets;
181 static uset all_closure_sets;
182 static uset all_edge_sets;
183
184 #ifndef MAX
185 #define MAX(a,b) ((a)>(b)?(a):(b))
186 #endif
187
188 static void
189 find_levels_r(struct block *b)
190 {
191 int level;
192
193 if (isMarked(b))
194 return;
195
196 Mark(b);
197 b->link = 0;
198
199 if (JT(b)) {
200 find_levels_r(JT(b));
201 find_levels_r(JF(b));
202 level = MAX(JT(b)->level, JF(b)->level) + 1;
203 } else
204 level = 0;
205 b->level = level;
206 b->link = levels[level];
207 levels[level] = b;
208 }
209
210 /*
211 * Level graph. The levels go from 0 at the leaves to
212 * N_LEVELS at the root. The levels[] array points to the
213 * first node of the level list, whose elements are linked
214 * with the 'link' field of the struct block.
215 */
216 static void
217 find_levels(struct block *root)
218 {
219 memset((char *)levels, 0, n_blocks * sizeof(*levels));
220 unMarkAll();
221 find_levels_r(root);
222 }
223
224 /*
225 * Find dominator relationships.
226 * Assumes graph has been leveled.
227 */
228 static void
229 find_dom(struct block *root)
230 {
231 int i;
232 struct block *b;
233 bpf_u_int32 *x;
234
235 /*
236 * Initialize sets to contain all nodes.
237 */
238 x = all_dom_sets;
239 i = n_blocks * nodewords;
240 while (--i >= 0)
241 *x++ = ~0;
242 /* Root starts off empty. */
243 for (i = nodewords; --i >= 0;)
244 root->dom[i] = 0;
245
246 /* root->level is the highest level no found. */
247 for (i = root->level; i >= 0; --i) {
248 for (b = levels[i]; b; b = b->link) {
249 SET_INSERT(b->dom, b->id);
250 if (JT(b) == 0)
251 continue;
252 SET_INTERSECT(JT(b)->dom, b->dom, nodewords);
253 SET_INTERSECT(JF(b)->dom, b->dom, nodewords);
254 }
255 }
256 }
257
258 static void
259 propedom(struct edge *ep)
260 {
261 SET_INSERT(ep->edom, ep->id);
262 if (ep->succ) {
263 SET_INTERSECT(ep->succ->et.edom, ep->edom, edgewords);
264 SET_INTERSECT(ep->succ->ef.edom, ep->edom, edgewords);
265 }
266 }
267
268 /*
269 * Compute edge dominators.
270 * Assumes graph has been leveled and predecessors established.
271 */
272 static void
273 find_edom(struct block *root)
274 {
275 int i;
276 uset x;
277 struct block *b;
278
279 x = all_edge_sets;
280 for (i = n_edges * edgewords; --i >= 0; )
281 x[i] = ~0;
282
283 /* root->level is the highest level no found. */
284 memset(root->et.edom, 0, edgewords * sizeof(*(uset)0));
285 memset(root->ef.edom, 0, edgewords * sizeof(*(uset)0));
286 for (i = root->level; i >= 0; --i) {
287 for (b = levels[i]; b != 0; b = b->link) {
288 propedom(&b->et);
289 propedom(&b->ef);
290 }
291 }
292 }
293
294 /*
295 * Find the backwards transitive closure of the flow graph. These sets
296 * are backwards in the sense that we find the set of nodes that reach
297 * a given node, not the set of nodes that can be reached by a node.
298 *
299 * Assumes graph has been leveled.
300 */
301 static void
302 find_closure(struct block *root)
303 {
304 int i;
305 struct block *b;
306
307 /*
308 * Initialize sets to contain no nodes.
309 */
310 memset((char *)all_closure_sets, 0,
311 n_blocks * nodewords * sizeof(*all_closure_sets));
312
313 /* root->level is the highest level no found. */
314 for (i = root->level; i >= 0; --i) {
315 for (b = levels[i]; b; b = b->link) {
316 SET_INSERT(b->closure, b->id);
317 if (JT(b) == 0)
318 continue;
319 SET_UNION(JT(b)->closure, b->closure, nodewords);
320 SET_UNION(JF(b)->closure, b->closure, nodewords);
321 }
322 }
323 }
324
325 /*
326 * Return the register number that is used by s. If A and X are both
327 * used, return AX_ATOM. If no register is used, return -1.
328 *
329 * The implementation should probably change to an array access.
330 */
331 static int
332 atomuse(struct stmt *s)
333 {
334 register int c = s->code;
335
336 if (c == NOP)
337 return -1;
338
339 switch (BPF_CLASS(c)) {
340
341 case BPF_RET:
342 return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
343 (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
344
345 case BPF_LD:
346 case BPF_LDX:
347 return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
348 (BPF_MODE(c) == BPF_MEM) ? s->k : -1;
349
350 case BPF_ST:
351 return A_ATOM;
352
353 case BPF_STX:
354 return X_ATOM;
355
356 case BPF_JMP:
357 case BPF_ALU:
358 if (BPF_SRC(c) == BPF_X)
359 return AX_ATOM;
360 return A_ATOM;
361
362 case BPF_MISC:
363 return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
364 }
365 abort();
366 /* NOTREACHED */
367 }
368
369 /*
370 * Return the register number that is defined by 's'. We assume that
371 * a single stmt cannot define more than one register. If no register
372 * is defined, return -1.
373 *
374 * The implementation should probably change to an array access.
375 */
376 static int
377 atomdef(struct stmt *s)
378 {
379 if (s->code == NOP)
380 return -1;
381
382 switch (BPF_CLASS(s->code)) {
383
384 case BPF_LD:
385 case BPF_ALU:
386 return A_ATOM;
387
388 case BPF_LDX:
389 return X_ATOM;
390
391 case BPF_ST:
392 case BPF_STX:
393 return s->k;
394
395 case BPF_MISC:
396 return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
397 }
398 return -1;
399 }
400
401 /*
402 * Compute the sets of registers used, defined, and killed by 'b'.
403 *
404 * "Used" means that a statement in 'b' uses the register before any
405 * statement in 'b' defines it, i.e. it uses the value left in
406 * that register by a predecessor block of this block.
407 * "Defined" means that a statement in 'b' defines it.
408 * "Killed" means that a statement in 'b' defines it before any
409 * statement in 'b' uses it, i.e. it kills the value left in that
410 * register by a predecessor block of this block.
411 */
412 static void
413 compute_local_ud(struct block *b)
414 {
415 struct slist *s;
416 atomset def = 0, use = 0, kill = 0;
417 int atom;
418
419 for (s = b->stmts; s; s = s->next) {
420 if (s->s.code == NOP)
421 continue;
422 atom = atomuse(&s->s);
423 if (atom >= 0) {
424 if (atom == AX_ATOM) {
425 if (!ATOMELEM(def, X_ATOM))
426 use |= ATOMMASK(X_ATOM);
427 if (!ATOMELEM(def, A_ATOM))
428 use |= ATOMMASK(A_ATOM);
429 }
430 else if (atom < N_ATOMS) {
431 if (!ATOMELEM(def, atom))
432 use |= ATOMMASK(atom);
433 }
434 else
435 abort();
436 }
437 atom = atomdef(&s->s);
438 if (atom >= 0) {
439 if (!ATOMELEM(use, atom))
440 kill |= ATOMMASK(atom);
441 def |= ATOMMASK(atom);
442 }
443 }
444 if (BPF_CLASS(b->s.code) == BPF_JMP) {
445 /*
446 * XXX - what about RET?
447 */
448 atom = atomuse(&b->s);
449 if (atom >= 0) {
450 if (atom == AX_ATOM) {
451 if (!ATOMELEM(def, X_ATOM))
452 use |= ATOMMASK(X_ATOM);
453 if (!ATOMELEM(def, A_ATOM))
454 use |= ATOMMASK(A_ATOM);
455 }
456 else if (atom < N_ATOMS) {
457 if (!ATOMELEM(def, atom))
458 use |= ATOMMASK(atom);
459 }
460 else
461 abort();
462 }
463 }
464
465 b->def = def;
466 b->kill = kill;
467 b->in_use = use;
468 }
469
470 /*
471 * Assume graph is already leveled.
472 */
473 static void
474 find_ud(struct block *root)
475 {
476 int i, maxlevel;
477 struct block *p;
478
479 /*
480 * root->level is the highest level no found;
481 * count down from there.
482 */
483 maxlevel = root->level;
484 for (i = maxlevel; i >= 0; --i)
485 for (p = levels[i]; p; p = p->link) {
486 compute_local_ud(p);
487 p->out_use = 0;
488 }
489
490 for (i = 1; i <= maxlevel; ++i) {
491 for (p = levels[i]; p; p = p->link) {
492 p->out_use |= JT(p)->in_use | JF(p)->in_use;
493 p->in_use |= p->out_use &~ p->kill;
494 }
495 }
496 }
497
498 /*
499 * These data structures are used in a Cocke and Shwarz style
500 * value numbering scheme. Since the flowgraph is acyclic,
501 * exit values can be propagated from a node's predecessors
502 * provided it is uniquely defined.
503 */
504 struct valnode {
505 int code;
506 int v0, v1;
507 int val;
508 struct valnode *next;
509 };
510
511 #define MODULUS 213
512 static struct valnode *hashtbl[MODULUS];
513 static int curval;
514 static int maxval;
515
516 /* Integer constants mapped with the load immediate opcode. */
517 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
518
519 struct vmapinfo {
520 int is_const;
521 bpf_int32 const_val;
522 };
523
524 struct vmapinfo *vmap;
525 struct valnode *vnode_base;
526 struct valnode *next_vnode;
527
528 static void
529 init_val(void)
530 {
531 curval = 0;
532 next_vnode = vnode_base;
533 memset((char *)vmap, 0, maxval * sizeof(*vmap));
534 memset((char *)hashtbl, 0, sizeof hashtbl);
535 }
536
537 /* Because we really don't have an IR, this stuff is a little messy. */
538 static int
539 F(int code, int v0, int v1)
540 {
541 u_int hash;
542 int val;
543 struct valnode *p;
544
545 hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
546 hash %= MODULUS;
547
548 for (p = hashtbl[hash]; p; p = p->next)
549 if (p->code == code && p->v0 == v0 && p->v1 == v1)
550 return p->val;
551
552 val = ++curval;
553 if (BPF_MODE(code) == BPF_IMM &&
554 (BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
555 vmap[val].const_val = v0;
556 vmap[val].is_const = 1;
557 }
558 p = next_vnode++;
559 p->val = val;
560 p->code = code;
561 p->v0 = v0;
562 p->v1 = v1;
563 p->next = hashtbl[hash];
564 hashtbl[hash] = p;
565
566 return val;
567 }
568
569 static inline void
570 vstore(struct stmt *s, int *valp, int newval, int alter)
571 {
572 if (alter && *valp == newval)
573 s->code = NOP;
574 else
575 *valp = newval;
576 }
577
578 /*
579 * Do constant-folding on binary operators.
580 * (Unary operators are handled elsewhere.)
581 */
582 static void
583 fold_op(struct stmt *s, int v0, int v1)
584 {
585 bpf_u_int32 a, b;
586
587 a = vmap[v0].const_val;
588 b = vmap[v1].const_val;
589
590 switch (BPF_OP(s->code)) {
591 case BPF_ADD:
592 a += b;
593 break;
594
595 case BPF_SUB:
596 a -= b;
597 break;
598
599 case BPF_MUL:
600 a *= b;
601 break;
602
603 case BPF_DIV:
604 if (b == 0)
605 bpf_error("division by zero");
606 a /= b;
607 break;
608
609 case BPF_AND:
610 a &= b;
611 break;
612
613 case BPF_OR:
614 a |= b;
615 break;
616
617 case BPF_LSH:
618 a <<= b;
619 break;
620
621 case BPF_RSH:
622 a >>= b;
623 break;
624
625 default:
626 abort();
627 }
628 s->k = a;
629 s->code = BPF_LD|BPF_IMM;
630 done = 0;
631 }
632
633 static inline struct slist *
634 this_op(struct slist *s)
635 {
636 while (s != 0 && s->s.code == NOP)
637 s = s->next;
638 return s;
639 }
640
641 static void
642 opt_not(struct block *b)
643 {
644 struct block *tmp = JT(b);
645
646 JT(b) = JF(b);
647 JF(b) = tmp;
648 }
649
650 static void
651 opt_peep(struct block *b)
652 {
653 struct slist *s;
654 struct slist *next, *last;
655 int val;
656
657 s = b->stmts;
658 if (s == 0)
659 return;
660
661 last = s;
662 for (/*empty*/; /*empty*/; s = next) {
663 /*
664 * Skip over nops.
665 */
666 s = this_op(s);
667 if (s == 0)
668 break; /* nothing left in the block */
669
670 /*
671 * Find the next real instruction after that one
672 * (skipping nops).
673 */
674 next = this_op(s->next);
675 if (next == 0)
676 break; /* no next instruction */
677 last = next;
678
679 /*
680 * st M[k] --> st M[k]
681 * ldx M[k] tax
682 */
683 if (s->s.code == BPF_ST &&
684 next->s.code == (BPF_LDX|BPF_MEM) &&
685 s->s.k == next->s.k) {
686 done = 0;
687 next->s.code = BPF_MISC|BPF_TAX;
688 }
689 /*
690 * ld #k --> ldx #k
691 * tax txa
692 */
693 if (s->s.code == (BPF_LD|BPF_IMM) &&
694 next->s.code == (BPF_MISC|BPF_TAX)) {
695 s->s.code = BPF_LDX|BPF_IMM;
696 next->s.code = BPF_MISC|BPF_TXA;
697 done = 0;
698 }
699 /*
700 * This is an ugly special case, but it happens
701 * when you say tcp[k] or udp[k] where k is a constant.
702 */
703 if (s->s.code == (BPF_LD|BPF_IMM)) {
704 struct slist *add, *tax, *ild;
705
706 /*
707 * Check that X isn't used on exit from this
708 * block (which the optimizer might cause).
709 * We know the code generator won't generate
710 * any local dependencies.
711 */
712 if (ATOMELEM(b->out_use, X_ATOM))
713 continue;
714
715 /*
716 * Check that the instruction following the ldi
717 * is an addx, or it's an ldxms with an addx
718 * following it (with 0 or more nops between the
719 * ldxms and addx).
720 */
721 if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
722 add = next;
723 else
724 add = this_op(next->next);
725 if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
726 continue;
727
728 /*
729 * Check that a tax follows that (with 0 or more
730 * nops between them).
731 */
732 tax = this_op(add->next);
733 if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
734 continue;
735
736 /*
737 * Check that an ild follows that (with 0 or more
738 * nops between them).
739 */
740 ild = this_op(tax->next);
741 if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
742 BPF_MODE(ild->s.code) != BPF_IND)
743 continue;
744 /*
745 * We want to turn this sequence:
746 *
747 * (004) ldi #0x2 {s}
748 * (005) ldxms [14] {next} -- optional
749 * (006) addx {add}
750 * (007) tax {tax}
751 * (008) ild [x+0] {ild}
752 *
753 * into this sequence:
754 *
755 * (004) nop
756 * (005) ldxms [14]
757 * (006) nop
758 * (007) nop
759 * (008) ild [x+2]
760 *
761 * XXX We need to check that X is not
762 * subsequently used, because we want to change
763 * what'll be in it after this sequence.
764 *
765 * We know we can eliminate the accumulator
766 * modifications earlier in the sequence since
767 * it is defined by the last stmt of this sequence
768 * (i.e., the last statement of the sequence loads
769 * a value into the accumulator, so we can eliminate
770 * earlier operations on the accumulator).
771 */
772 ild->s.k += s->s.k;
773 s->s.code = NOP;
774 add->s.code = NOP;
775 tax->s.code = NOP;
776 done = 0;
777 }
778 }
779 /*
780 * If the comparison at the end of a block is an equality
781 * comparison against a constant, and nobody uses the value
782 * we leave in the A register at the end of a block, and
783 * the operation preceding the comparison is an arithmetic
784 * operation, we can sometime optimize it away.
785 */
786 if (b->s.code == (BPF_JMP|BPF_JEQ|BPF_K) &&
787 !ATOMELEM(b->out_use, A_ATOM)) {
788 /*
789 * We can optimize away certain subtractions of the
790 * X register.
791 */
792 if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X)) {
793 val = b->val[X_ATOM];
794 if (vmap[val].is_const) {
795 /*
796 * If we have a subtract to do a comparison,
797 * and the X register is a known constant,
798 * we can merge this value into the
799 * comparison:
800 *
801 * sub x -> nop
802 * jeq #y jeq #(x+y)
803 */
804 b->s.k += vmap[val].const_val;
805 last->s.code = NOP;
806 done = 0;
807 } else if (b->s.k == 0) {
808 /*
809 * If the X register isn't a constant,
810 * and the comparison in the test is
811 * against 0, we can compare with the
812 * X register, instead:
813 *
814 * sub x -> nop
815 * jeq #0 jeq x
816 */
817 last->s.code = NOP;
818 b->s.code = BPF_JMP|BPF_JEQ|BPF_X;
819 done = 0;
820 }
821 }
822 /*
823 * Likewise, a constant subtract can be simplified:
824 *
825 * sub #x -> nop
826 * jeq #y -> jeq #(x+y)
827 */
828 else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K)) {
829 last->s.code = NOP;
830 b->s.k += last->s.k;
831 done = 0;
832 }
833 /*
834 * And, similarly, a constant AND can be simplified
835 * if we're testing against 0, i.e.:
836 *
837 * and #k nop
838 * jeq #0 -> jset #k
839 */
840 else if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
841 b->s.k == 0) {
842 b->s.k = last->s.k;
843 b->s.code = BPF_JMP|BPF_K|BPF_JSET;
844 last->s.code = NOP;
845 done = 0;
846 opt_not(b);
847 }
848 }
849 /*
850 * jset #0 -> never
851 * jset #ffffffff -> always
852 */
853 if (b->s.code == (BPF_JMP|BPF_K|BPF_JSET)) {
854 if (b->s.k == 0)
855 JT(b) = JF(b);
856 if (b->s.k == 0xffffffff)
857 JF(b) = JT(b);
858 }
859 /*
860 * If we're comparing against the index register, and the index
861 * register is a known constant, we can just compare against that
862 * constant.
863 */
864 val = b->val[X_ATOM];
865 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_X) {
866 bpf_int32 v = vmap[val].const_val;
867 b->s.code &= ~BPF_X;
868 b->s.k = v;
869 }
870 /*
871 * If the accumulator is a known constant, we can compute the
872 * comparison result.
873 */
874 val = b->val[A_ATOM];
875 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
876 bpf_int32 v = vmap[val].const_val;
877 switch (BPF_OP(b->s.code)) {
878
879 case BPF_JEQ:
880 v = v == b->s.k;
881 break;
882
883 case BPF_JGT:
884 v = (unsigned)v > b->s.k;
885 break;
886
887 case BPF_JGE:
888 v = (unsigned)v >= b->s.k;
889 break;
890
891 case BPF_JSET:
892 v &= b->s.k;
893 break;
894
895 default:
896 abort();
897 }
898 if (JF(b) != JT(b))
899 done = 0;
900 if (v)
901 JF(b) = JT(b);
902 else
903 JT(b) = JF(b);
904 }
905 }
906
907 /*
908 * Compute the symbolic value of expression of 's', and update
909 * anything it defines in the value table 'val'. If 'alter' is true,
910 * do various optimizations. This code would be cleaner if symbolic
911 * evaluation and code transformations weren't folded together.
912 */
913 static void
914 opt_stmt(struct stmt *s, int val[], int alter)
915 {
916 int op;
917 int v;
918
919 switch (s->code) {
920
921 case BPF_LD|BPF_ABS|BPF_W:
922 case BPF_LD|BPF_ABS|BPF_H:
923 case BPF_LD|BPF_ABS|BPF_B:
924 v = F(s->code, s->k, 0L);
925 vstore(s, &val[A_ATOM], v, alter);
926 break;
927
928 case BPF_LD|BPF_IND|BPF_W:
929 case BPF_LD|BPF_IND|BPF_H:
930 case BPF_LD|BPF_IND|BPF_B:
931 v = val[X_ATOM];
932 if (alter && vmap[v].is_const) {
933 s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
934 s->k += vmap[v].const_val;
935 v = F(s->code, s->k, 0L);
936 done = 0;
937 }
938 else
939 v = F(s->code, s->k, v);
940 vstore(s, &val[A_ATOM], v, alter);
941 break;
942
943 case BPF_LD|BPF_LEN:
944 v = F(s->code, 0L, 0L);
945 vstore(s, &val[A_ATOM], v, alter);
946 break;
947
948 case BPF_LD|BPF_IMM:
949 v = K(s->k);
950 vstore(s, &val[A_ATOM], v, alter);
951 break;
952
953 case BPF_LDX|BPF_IMM:
954 v = K(s->k);
955 vstore(s, &val[X_ATOM], v, alter);
956 break;
957
958 case BPF_LDX|BPF_MSH|BPF_B:
959 v = F(s->code, s->k, 0L);
960 vstore(s, &val[X_ATOM], v, alter);
961 break;
962
963 case BPF_ALU|BPF_NEG:
964 if (alter && vmap[val[A_ATOM]].is_const) {
965 s->code = BPF_LD|BPF_IMM;
966 s->k = -vmap[val[A_ATOM]].const_val;
967 val[A_ATOM] = K(s->k);
968 }
969 else
970 val[A_ATOM] = F(s->code, val[A_ATOM], 0L);
971 break;
972
973 case BPF_ALU|BPF_ADD|BPF_K:
974 case BPF_ALU|BPF_SUB|BPF_K:
975 case BPF_ALU|BPF_MUL|BPF_K:
976 case BPF_ALU|BPF_DIV|BPF_K:
977 case BPF_ALU|BPF_AND|BPF_K:
978 case BPF_ALU|BPF_OR|BPF_K:
979 case BPF_ALU|BPF_LSH|BPF_K:
980 case BPF_ALU|BPF_RSH|BPF_K:
981 op = BPF_OP(s->code);
982 if (alter) {
983 if (s->k == 0) {
984 /* don't optimize away "sub #0"
985 * as it may be needed later to
986 * fixup the generated math code */
987 if (op == BPF_ADD ||
988 op == BPF_LSH || op == BPF_RSH ||
989 op == BPF_OR) {
990 s->code = NOP;
991 break;
992 }
993 if (op == BPF_MUL || op == BPF_AND) {
994 s->code = BPF_LD|BPF_IMM;
995 val[A_ATOM] = K(s->k);
996 break;
997 }
998 }
999 if (vmap[val[A_ATOM]].is_const) {
1000 fold_op(s, val[A_ATOM], K(s->k));
1001 val[A_ATOM] = K(s->k);
1002 break;
1003 }
1004 }
1005 val[A_ATOM] = F(s->code, val[A_ATOM], K(s->k));
1006 break;
1007
1008 case BPF_ALU|BPF_ADD|BPF_X:
1009 case BPF_ALU|BPF_SUB|BPF_X:
1010 case BPF_ALU|BPF_MUL|BPF_X:
1011 case BPF_ALU|BPF_DIV|BPF_X:
1012 case BPF_ALU|BPF_AND|BPF_X:
1013 case BPF_ALU|BPF_OR|BPF_X:
1014 case BPF_ALU|BPF_LSH|BPF_X:
1015 case BPF_ALU|BPF_RSH|BPF_X:
1016 op = BPF_OP(s->code);
1017 if (alter && vmap[val[X_ATOM]].is_const) {
1018 if (vmap[val[A_ATOM]].is_const) {
1019 fold_op(s, val[A_ATOM], val[X_ATOM]);
1020 val[A_ATOM] = K(s->k);
1021 }
1022 else {
1023 s->code = BPF_ALU|BPF_K|op;
1024 s->k = vmap[val[X_ATOM]].const_val;
1025 done = 0;
1026 val[A_ATOM] =
1027 F(s->code, val[A_ATOM], K(s->k));
1028 }
1029 break;
1030 }
1031 /*
1032 * Check if we're doing something to an accumulator
1033 * that is 0, and simplify. This may not seem like
1034 * much of a simplification but it could open up further
1035 * optimizations.
1036 * XXX We could also check for mul by 1, etc.
1037 */
1038 if (alter && vmap[val[A_ATOM]].is_const
1039 && vmap[val[A_ATOM]].const_val == 0) {
1040 if (op == BPF_ADD || op == BPF_OR) {
1041 s->code = BPF_MISC|BPF_TXA;
1042 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1043 break;
1044 }
1045 else if (op == BPF_MUL || op == BPF_DIV ||
1046 op == BPF_AND || op == BPF_LSH || op == BPF_RSH) {
1047 s->code = BPF_LD|BPF_IMM;
1048 s->k = 0;
1049 vstore(s, &val[A_ATOM], K(s->k), alter);
1050 break;
1051 }
1052 else if (op == BPF_NEG) {
1053 s->code = NOP;
1054 break;
1055 }
1056 }
1057 val[A_ATOM] = F(s->code, val[A_ATOM], val[X_ATOM]);
1058 break;
1059
1060 case BPF_MISC|BPF_TXA:
1061 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1062 break;
1063
1064 case BPF_LD|BPF_MEM:
1065 v = val[s->k];
1066 if (alter && vmap[v].is_const) {
1067 s->code = BPF_LD|BPF_IMM;
1068 s->k = vmap[v].const_val;
1069 done = 0;
1070 }
1071 vstore(s, &val[A_ATOM], v, alter);
1072 break;
1073
1074 case BPF_MISC|BPF_TAX:
1075 vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1076 break;
1077
1078 case BPF_LDX|BPF_MEM:
1079 v = val[s->k];
1080 if (alter && vmap[v].is_const) {
1081 s->code = BPF_LDX|BPF_IMM;
1082 s->k = vmap[v].const_val;
1083 done = 0;
1084 }
1085 vstore(s, &val[X_ATOM], v, alter);
1086 break;
1087
1088 case BPF_ST:
1089 vstore(s, &val[s->k], val[A_ATOM], alter);
1090 break;
1091
1092 case BPF_STX:
1093 vstore(s, &val[s->k], val[X_ATOM], alter);
1094 break;
1095 }
1096 }
1097
1098 static void
1099 deadstmt(register struct stmt *s, register struct stmt *last[])
1100 {
1101 register int atom;
1102
1103 atom = atomuse(s);
1104 if (atom >= 0) {
1105 if (atom == AX_ATOM) {
1106 last[X_ATOM] = 0;
1107 last[A_ATOM] = 0;
1108 }
1109 else
1110 last[atom] = 0;
1111 }
1112 atom = atomdef(s);
1113 if (atom >= 0) {
1114 if (last[atom]) {
1115 done = 0;
1116 last[atom]->code = NOP;
1117 }
1118 last[atom] = s;
1119 }
1120 }
1121
1122 static void
1123 opt_deadstores(register struct block *b)
1124 {
1125 register struct slist *s;
1126 register int atom;
1127 struct stmt *last[N_ATOMS];
1128
1129 memset((char *)last, 0, sizeof last);
1130
1131 for (s = b->stmts; s != 0; s = s->next)
1132 deadstmt(&s->s, last);
1133 deadstmt(&b->s, last);
1134
1135 for (atom = 0; atom < N_ATOMS; ++atom)
1136 if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1137 last[atom]->code = NOP;
1138 done = 0;
1139 }
1140 }
1141
1142 static void
1143 opt_blk(struct block *b, int do_stmts)
1144 {
1145 struct slist *s;
1146 struct edge *p;
1147 int i;
1148 bpf_int32 aval, xval;
1149
1150 #if 0
1151 for (s = b->stmts; s && s->next; s = s->next)
1152 if (BPF_CLASS(s->s.code) == BPF_JMP) {
1153 do_stmts = 0;
1154 break;
1155 }
1156 #endif
1157
1158 /*
1159 * Initialize the atom values.
1160 */
1161 p = b->in_edges;
1162 if (p == 0) {
1163 /*
1164 * We have no predecessors, so everything is undefined
1165 * upon entry to this block.
1166 */
1167 memset((char *)b->val, 0, sizeof(b->val));
1168 } else {
1169 /*
1170 * Inherit values from our predecessors.
1171 *
1172 * First, get the values from the predecessor along the
1173 * first edge leading to this node.
1174 */
1175 memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1176 /*
1177 * Now look at all the other nodes leading to this node.
1178 * If, for the predecessor along that edge, a register
1179 * has a different value from the one we have (i.e.,
1180 * control paths are merging, and the merging paths
1181 * assign different values to that register), give the
1182 * register the undefined value of 0.
1183 */
1184 while ((p = p->next) != NULL) {
1185 for (i = 0; i < N_ATOMS; ++i)
1186 if (b->val[i] != p->pred->val[i])
1187 b->val[i] = 0;
1188 }
1189 }
1190 aval = b->val[A_ATOM];
1191 xval = b->val[X_ATOM];
1192 for (s = b->stmts; s; s = s->next)
1193 opt_stmt(&s->s, b->val, do_stmts);
1194
1195 /*
1196 * This is a special case: if we don't use anything from this
1197 * block, and we load the accumulator or index register with a
1198 * value that is already there, or if this block is a return,
1199 * eliminate all the statements.
1200 *
1201 * XXX - what if it does a store?
1202 *
1203 * XXX - why does it matter whether we use anything from this
1204 * block? If the accumulator or index register doesn't change
1205 * its value, isn't that OK even if we use that value?
1206 *
1207 * XXX - if we load the accumulator with a different value,
1208 * and the block ends with a conditional branch, we obviously
1209 * can't eliminate it, as the branch depends on that value.
1210 * For the index register, the conditional branch only depends
1211 * on the index register value if the test is against the index
1212 * register value rather than a constant; if nothing uses the
1213 * value we put into the index register, and we're not testing
1214 * against the index register's value, and there aren't any
1215 * other problems that would keep us from eliminating this
1216 * block, can we eliminate it?
1217 */
1218 if (do_stmts &&
1219 ((b->out_use == 0 && aval != 0 && b->val[A_ATOM] == aval &&
1220 xval != 0 && b->val[X_ATOM] == xval) ||
1221 BPF_CLASS(b->s.code) == BPF_RET)) {
1222 if (b->stmts != 0) {
1223 b->stmts = 0;
1224 done = 0;
1225 }
1226 } else {
1227 opt_peep(b);
1228 opt_deadstores(b);
1229 }
1230 /*
1231 * Set up values for branch optimizer.
1232 */
1233 if (BPF_SRC(b->s.code) == BPF_K)
1234 b->oval = K(b->s.k);
1235 else
1236 b->oval = b->val[X_ATOM];
1237 b->et.code = b->s.code;
1238 b->ef.code = -b->s.code;
1239 }
1240
1241 /*
1242 * Return true if any register that is used on exit from 'succ', has
1243 * an exit value that is different from the corresponding exit value
1244 * from 'b'.
1245 */
1246 static int
1247 use_conflict(struct block *b, struct block *succ)
1248 {
1249 int atom;
1250 atomset use = succ->out_use;
1251
1252 if (use == 0)
1253 return 0;
1254
1255 for (atom = 0; atom < N_ATOMS; ++atom)
1256 if (ATOMELEM(use, atom))
1257 if (b->val[atom] != succ->val[atom])
1258 return 1;
1259 return 0;
1260 }
1261
1262 static struct block *
1263 fold_edge(struct block *child, struct edge *ep)
1264 {
1265 int sense;
1266 int aval0, aval1, oval0, oval1;
1267 int code = ep->code;
1268
1269 if (code < 0) {
1270 code = -code;
1271 sense = 0;
1272 } else
1273 sense = 1;
1274
1275 if (child->s.code != code)
1276 return 0;
1277
1278 aval0 = child->val[A_ATOM];
1279 oval0 = child->oval;
1280 aval1 = ep->pred->val[A_ATOM];
1281 oval1 = ep->pred->oval;
1282
1283 if (aval0 != aval1)
1284 return 0;
1285
1286 if (oval0 == oval1)
1287 /*
1288 * The operands of the branch instructions are
1289 * identical, so the result is true if a true
1290 * branch was taken to get here, otherwise false.
1291 */
1292 return sense ? JT(child) : JF(child);
1293
1294 if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1295 /*
1296 * At this point, we only know the comparison if we
1297 * came down the true branch, and it was an equality
1298 * comparison with a constant.
1299 *
1300 * I.e., if we came down the true branch, and the branch
1301 * was an equality comparison with a constant, we know the
1302 * accumulator contains that constant. If we came down
1303 * the false branch, or the comparison wasn't with a
1304 * constant, we don't know what was in the accumulator.
1305 *
1306 * We rely on the fact that distinct constants have distinct
1307 * value numbers.
1308 */
1309 return JF(child);
1310
1311 return 0;
1312 }
1313
1314 static void
1315 opt_j(struct edge *ep)
1316 {
1317 register int i, k;
1318 register struct block *target;
1319
1320 if (JT(ep->succ) == 0)
1321 return;
1322
1323 if (JT(ep->succ) == JF(ep->succ)) {
1324 /*
1325 * Common branch targets can be eliminated, provided
1326 * there is no data dependency.
1327 */
1328 if (!use_conflict(ep->pred, ep->succ->et.succ)) {
1329 done = 0;
1330 ep->succ = JT(ep->succ);
1331 }
1332 }
1333 /*
1334 * For each edge dominator that matches the successor of this
1335 * edge, promote the edge successor to the its grandchild.
1336 *
1337 * XXX We violate the set abstraction here in favor a reasonably
1338 * efficient loop.
1339 */
1340 top:
1341 for (i = 0; i < edgewords; ++i) {
1342 register bpf_u_int32 x = ep->edom[i];
1343
1344 while (x != 0) {
1345 k = ffs(x) - 1;
1346 x &=~ (1 << k);
1347 k += i * BITS_PER_WORD;
1348
1349 target = fold_edge(ep->succ, edges[k]);
1350 /*
1351 * Check that there is no data dependency between
1352 * nodes that will be violated if we move the edge.
1353 */
1354 if (target != 0 && !use_conflict(ep->pred, target)) {
1355 done = 0;
1356 ep->succ = target;
1357 if (JT(target) != 0)
1358 /*
1359 * Start over unless we hit a leaf.
1360 */
1361 goto top;
1362 return;
1363 }
1364 }
1365 }
1366 }
1367
1368
1369 static void
1370 or_pullup(struct block *b)
1371 {
1372 int val, at_top;
1373 struct block *pull;
1374 struct block **diffp, **samep;
1375 struct edge *ep;
1376
1377 ep = b->in_edges;
1378 if (ep == 0)
1379 return;
1380
1381 /*
1382 * Make sure each predecessor loads the same value.
1383 * XXX why?
1384 */
1385 val = ep->pred->val[A_ATOM];
1386 for (ep = ep->next; ep != 0; ep = ep->next)
1387 if (val != ep->pred->val[A_ATOM])
1388 return;
1389
1390 if (JT(b->in_edges->pred) == b)
1391 diffp = &JT(b->in_edges->pred);
1392 else
1393 diffp = &JF(b->in_edges->pred);
1394
1395 at_top = 1;
1396 while (1) {
1397 if (*diffp == 0)
1398 return;
1399
1400 if (JT(*diffp) != JT(b))
1401 return;
1402
1403 if (!SET_MEMBER((*diffp)->dom, b->id))
1404 return;
1405
1406 if ((*diffp)->val[A_ATOM] != val)
1407 break;
1408
1409 diffp = &JF(*diffp);
1410 at_top = 0;
1411 }
1412 samep = &JF(*diffp);
1413 while (1) {
1414 if (*samep == 0)
1415 return;
1416
1417 if (JT(*samep) != JT(b))
1418 return;
1419
1420 if (!SET_MEMBER((*samep)->dom, b->id))
1421 return;
1422
1423 if ((*samep)->val[A_ATOM] == val)
1424 break;
1425
1426 /* XXX Need to check that there are no data dependencies
1427 between dp0 and dp1. Currently, the code generator
1428 will not produce such dependencies. */
1429 samep = &JF(*samep);
1430 }
1431 #ifdef notdef
1432 /* XXX This doesn't cover everything. */
1433 for (i = 0; i < N_ATOMS; ++i)
1434 if ((*samep)->val[i] != pred->val[i])
1435 return;
1436 #endif
1437 /* Pull up the node. */
1438 pull = *samep;
1439 *samep = JF(pull);
1440 JF(pull) = *diffp;
1441
1442 /*
1443 * At the top of the chain, each predecessor needs to point at the
1444 * pulled up node. Inside the chain, there is only one predecessor
1445 * to worry about.
1446 */
1447 if (at_top) {
1448 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1449 if (JT(ep->pred) == b)
1450 JT(ep->pred) = pull;
1451 else
1452 JF(ep->pred) = pull;
1453 }
1454 }
1455 else
1456 *diffp = pull;
1457
1458 done = 0;
1459 }
1460
1461 static void
1462 and_pullup(struct block *b)
1463 {
1464 int val, at_top;
1465 struct block *pull;
1466 struct block **diffp, **samep;
1467 struct edge *ep;
1468
1469 ep = b->in_edges;
1470 if (ep == 0)
1471 return;
1472
1473 /*
1474 * Make sure each predecessor loads the same value.
1475 */
1476 val = ep->pred->val[A_ATOM];
1477 for (ep = ep->next; ep != 0; ep = ep->next)
1478 if (val != ep->pred->val[A_ATOM])
1479 return;
1480
1481 if (JT(b->in_edges->pred) == b)
1482 diffp = &JT(b->in_edges->pred);
1483 else
1484 diffp = &JF(b->in_edges->pred);
1485
1486 at_top = 1;
1487 while (1) {
1488 if (*diffp == 0)
1489 return;
1490
1491 if (JF(*diffp) != JF(b))
1492 return;
1493
1494 if (!SET_MEMBER((*diffp)->dom, b->id))
1495 return;
1496
1497 if ((*diffp)->val[A_ATOM] != val)
1498 break;
1499
1500 diffp = &JT(*diffp);
1501 at_top = 0;
1502 }
1503 samep = &JT(*diffp);
1504 while (1) {
1505 if (*samep == 0)
1506 return;
1507
1508 if (JF(*samep) != JF(b))
1509 return;
1510
1511 if (!SET_MEMBER((*samep)->dom, b->id))
1512 return;
1513
1514 if ((*samep)->val[A_ATOM] == val)
1515 break;
1516
1517 /* XXX Need to check that there are no data dependencies
1518 between diffp and samep. Currently, the code generator
1519 will not produce such dependencies. */
1520 samep = &JT(*samep);
1521 }
1522 #ifdef notdef
1523 /* XXX This doesn't cover everything. */
1524 for (i = 0; i < N_ATOMS; ++i)
1525 if ((*samep)->val[i] != pred->val[i])
1526 return;
1527 #endif
1528 /* Pull up the node. */
1529 pull = *samep;
1530 *samep = JT(pull);
1531 JT(pull) = *diffp;
1532
1533 /*
1534 * At the top of the chain, each predecessor needs to point at the
1535 * pulled up node. Inside the chain, there is only one predecessor
1536 * to worry about.
1537 */
1538 if (at_top) {
1539 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1540 if (JT(ep->pred) == b)
1541 JT(ep->pred) = pull;
1542 else
1543 JF(ep->pred) = pull;
1544 }
1545 }
1546 else
1547 *diffp = pull;
1548
1549 done = 0;
1550 }
1551
1552 static void
1553 opt_blks(struct block *root, int do_stmts)
1554 {
1555 int i, maxlevel;
1556 struct block *p;
1557
1558 init_val();
1559 maxlevel = root->level;
1560
1561 find_inedges(root);
1562 for (i = maxlevel; i >= 0; --i)
1563 for (p = levels[i]; p; p = p->link)
1564 opt_blk(p, do_stmts);
1565
1566 if (do_stmts)
1567 /*
1568 * No point trying to move branches; it can't possibly
1569 * make a difference at this point.
1570 */
1571 return;
1572
1573 for (i = 1; i <= maxlevel; ++i) {
1574 for (p = levels[i]; p; p = p->link) {
1575 opt_j(&p->et);
1576 opt_j(&p->ef);
1577 }
1578 }
1579
1580 find_inedges(root);
1581 for (i = 1; i <= maxlevel; ++i) {
1582 for (p = levels[i]; p; p = p->link) {
1583 or_pullup(p);
1584 and_pullup(p);
1585 }
1586 }
1587 }
1588
1589 static inline void
1590 link_inedge(struct edge *parent, struct block *child)
1591 {
1592 parent->next = child->in_edges;
1593 child->in_edges = parent;
1594 }
1595
1596 static void
1597 find_inedges(struct block *root)
1598 {
1599 int i;
1600 struct block *b;
1601
1602 for (i = 0; i < n_blocks; ++i)
1603 blocks[i]->in_edges = 0;
1604
1605 /*
1606 * Traverse the graph, adding each edge to the predecessor
1607 * list of its successors. Skip the leaves (i.e. level 0).
1608 */
1609 for (i = root->level; i > 0; --i) {
1610 for (b = levels[i]; b != 0; b = b->link) {
1611 link_inedge(&b->et, JT(b));
1612 link_inedge(&b->ef, JF(b));
1613 }
1614 }
1615 }
1616
1617 static void
1618 opt_root(struct block **b)
1619 {
1620 struct slist *tmp, *s;
1621
1622 s = (*b)->stmts;
1623 (*b)->stmts = 0;
1624 while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
1625 *b = JT(*b);
1626
1627 tmp = (*b)->stmts;
1628 if (tmp != 0)
1629 sappend(s, tmp);
1630 (*b)->stmts = s;
1631
1632 /*
1633 * If the root node is a return, then there is no
1634 * point executing any statements (since the bpf machine
1635 * has no side effects).
1636 */
1637 if (BPF_CLASS((*b)->s.code) == BPF_RET)
1638 (*b)->stmts = 0;
1639 }
1640
1641 static void
1642 opt_loop(struct block *root, int do_stmts)
1643 {
1644
1645 #ifdef BDEBUG
1646 if (dflag > 1) {
1647 printf("opt_loop(root, %d) begin\n", do_stmts);
1648 opt_dump(root);
1649 }
1650 #endif
1651 do {
1652 done = 1;
1653 find_levels(root);
1654 find_dom(root);
1655 find_closure(root);
1656 find_ud(root);
1657 find_edom(root);
1658 opt_blks(root, do_stmts);
1659 #ifdef BDEBUG
1660 if (dflag > 1) {
1661 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts, done);
1662 opt_dump(root);
1663 }
1664 #endif
1665 } while (!done);
1666 }
1667
1668 /*
1669 * Optimize the filter code in its dag representation.
1670 */
1671 void
1672 bpf_optimize(struct block **rootp)
1673 {
1674 struct block *root;
1675
1676 root = *rootp;
1677
1678 opt_init(root);
1679 opt_loop(root, 0);
1680 opt_loop(root, 1);
1681 intern_blocks(root);
1682 #ifdef BDEBUG
1683 if (dflag > 1) {
1684 printf("after intern_blocks()\n");
1685 opt_dump(root);
1686 }
1687 #endif
1688 opt_root(rootp);
1689 #ifdef BDEBUG
1690 if (dflag > 1) {
1691 printf("after opt_root()\n");
1692 opt_dump(root);
1693 }
1694 #endif
1695 opt_cleanup();
1696 }
1697
1698 static void
1699 make_marks(struct block *p)
1700 {
1701 if (!isMarked(p)) {
1702 Mark(p);
1703 if (BPF_CLASS(p->s.code) != BPF_RET) {
1704 make_marks(JT(p));
1705 make_marks(JF(p));
1706 }
1707 }
1708 }
1709
1710 /*
1711 * Mark code array such that isMarked(i) is true
1712 * only for nodes that are alive.
1713 */
1714 static void
1715 mark_code(struct block *p)
1716 {
1717 cur_mark += 1;
1718 make_marks(p);
1719 }
1720
1721 /*
1722 * True iff the two stmt lists load the same value from the packet into
1723 * the accumulator.
1724 */
1725 static int
1726 eq_slist(struct slist *x, struct slist *y)
1727 {
1728 while (1) {
1729 while (x && x->s.code == NOP)
1730 x = x->next;
1731 while (y && y->s.code == NOP)
1732 y = y->next;
1733 if (x == 0)
1734 return y == 0;
1735 if (y == 0)
1736 return x == 0;
1737 if (x->s.code != y->s.code || x->s.k != y->s.k)
1738 return 0;
1739 x = x->next;
1740 y = y->next;
1741 }
1742 }
1743
1744 static inline int
1745 eq_blk(struct block *b0, struct block *b1)
1746 {
1747 if (b0->s.code == b1->s.code &&
1748 b0->s.k == b1->s.k &&
1749 b0->et.succ == b1->et.succ &&
1750 b0->ef.succ == b1->ef.succ)
1751 return eq_slist(b0->stmts, b1->stmts);
1752 return 0;
1753 }
1754
1755 static void
1756 intern_blocks(struct block *root)
1757 {
1758 struct block *p;
1759 int i, j;
1760 int done1; /* don't shadow global */
1761 top:
1762 done1 = 1;
1763 for (i = 0; i < n_blocks; ++i)
1764 blocks[i]->link = 0;
1765
1766 mark_code(root);
1767
1768 for (i = n_blocks - 1; --i >= 0; ) {
1769 if (!isMarked(blocks[i]))
1770 continue;
1771 for (j = i + 1; j < n_blocks; ++j) {
1772 if (!isMarked(blocks[j]))
1773 continue;
1774 if (eq_blk(blocks[i], blocks[j])) {
1775 blocks[i]->link = blocks[j]->link ?
1776 blocks[j]->link : blocks[j];
1777 break;
1778 }
1779 }
1780 }
1781 for (i = 0; i < n_blocks; ++i) {
1782 p = blocks[i];
1783 if (JT(p) == 0)
1784 continue;
1785 if (JT(p)->link) {
1786 done1 = 0;
1787 JT(p) = JT(p)->link;
1788 }
1789 if (JF(p)->link) {
1790 done1 = 0;
1791 JF(p) = JF(p)->link;
1792 }
1793 }
1794 if (!done1)
1795 goto top;
1796 }
1797
1798 static void
1799 opt_cleanup(void)
1800 {
1801 free((void *)vnode_base);
1802 free((void *)vmap);
1803 free((void *)edges);
1804 free((void *)space);
1805 free((void *)levels);
1806 free((void *)blocks);
1807 }
1808
1809 /*
1810 * Return the number of stmts in 's'.
1811 */
1812 static u_int
1813 slength(struct slist *s)
1814 {
1815 u_int n = 0;
1816
1817 for (; s; s = s->next)
1818 if (s->s.code != NOP)
1819 ++n;
1820 return n;
1821 }
1822
1823 /*
1824 * Return the number of nodes reachable by 'p'.
1825 * All nodes should be initially unmarked.
1826 */
1827 static int
1828 count_blocks(struct block *p)
1829 {
1830 if (p == 0 || isMarked(p))
1831 return 0;
1832 Mark(p);
1833 return count_blocks(JT(p)) + count_blocks(JF(p)) + 1;
1834 }
1835
1836 /*
1837 * Do a depth first search on the flow graph, numbering the
1838 * the basic blocks, and entering them into the 'blocks' array.`
1839 */
1840 static void
1841 number_blks_r(struct block *p)
1842 {
1843 int n;
1844
1845 if (p == 0 || isMarked(p))
1846 return;
1847
1848 Mark(p);
1849 n = n_blocks++;
1850 p->id = n;
1851 blocks[n] = p;
1852
1853 number_blks_r(JT(p));
1854 number_blks_r(JF(p));
1855 }
1856
1857 /*
1858 * Return the number of stmts in the flowgraph reachable by 'p'.
1859 * The nodes should be unmarked before calling.
1860 *
1861 * Note that "stmts" means "instructions", and that this includes
1862 *
1863 * side-effect statements in 'p' (slength(p->stmts));
1864 *
1865 * statements in the true branch from 'p' (count_stmts(JT(p)));
1866 *
1867 * statements in the false branch from 'p' (count_stmts(JF(p)));
1868 *
1869 * the conditional jump itself (1);
1870 *
1871 * an extra long jump if the true branch requires it (p->longjt);
1872 *
1873 * an extra long jump if the false branch requires it (p->longjf).
1874 */
1875 static u_int
1876 count_stmts(struct block *p)
1877 {
1878 u_int n;
1879
1880 if (p == 0 || isMarked(p))
1881 return 0;
1882 Mark(p);
1883 n = count_stmts(JT(p)) + count_stmts(JF(p));
1884 return slength(p->stmts) + n + 1 + p->longjt + p->longjf;
1885 }
1886
1887 /*
1888 * Allocate memory. All allocation is done before optimization
1889 * is begun. A linear bound on the size of all data structures is computed
1890 * from the total number of blocks and/or statements.
1891 */
1892 static void
1893 opt_init(struct block *root)
1894 {
1895 bpf_u_int32 *p;
1896 int i, n, max_stmts;
1897
1898 /*
1899 * First, count the blocks, so we can malloc an array to map
1900 * block number to block. Then, put the blocks into the array.
1901 */
1902 unMarkAll();
1903 n = count_blocks(root);
1904 blocks = (struct block **)calloc(n, sizeof(*blocks));
1905 if (blocks == NULL)
1906 bpf_error("malloc");
1907 unMarkAll();
1908 n_blocks = 0;
1909 number_blks_r(root);
1910
1911 n_edges = 2 * n_blocks;
1912 edges = (struct edge **)calloc(n_edges, sizeof(*edges));
1913 if (edges == NULL)
1914 bpf_error("malloc");
1915
1916 /*
1917 * The number of levels is bounded by the number of nodes.
1918 */
1919 levels = (struct block **)calloc(n_blocks, sizeof(*levels));
1920 if (levels == NULL)
1921 bpf_error("malloc");
1922
1923 edgewords = n_edges / (8 * sizeof(bpf_u_int32)) + 1;
1924 nodewords = n_blocks / (8 * sizeof(bpf_u_int32)) + 1;
1925
1926 /* XXX */
1927 space = (bpf_u_int32 *)malloc(2 * n_blocks * nodewords * sizeof(*space)
1928 + n_edges * edgewords * sizeof(*space));
1929 if (space == NULL)
1930 bpf_error("malloc");
1931 p = space;
1932 all_dom_sets = p;
1933 for (i = 0; i < n; ++i) {
1934 blocks[i]->dom = p;
1935 p += nodewords;
1936 }
1937 all_closure_sets = p;
1938 for (i = 0; i < n; ++i) {
1939 blocks[i]->closure = p;
1940 p += nodewords;
1941 }
1942 all_edge_sets = p;
1943 for (i = 0; i < n; ++i) {
1944 register struct block *b = blocks[i];
1945
1946 b->et.edom = p;
1947 p += edgewords;
1948 b->ef.edom = p;
1949 p += edgewords;
1950 b->et.id = i;
1951 edges[i] = &b->et;
1952 b->ef.id = n_blocks + i;
1953 edges[n_blocks + i] = &b->ef;
1954 b->et.pred = b;
1955 b->ef.pred = b;
1956 }
1957 max_stmts = 0;
1958 for (i = 0; i < n; ++i)
1959 max_stmts += slength(blocks[i]->stmts) + 1;
1960 /*
1961 * We allocate at most 3 value numbers per statement,
1962 * so this is an upper bound on the number of valnodes
1963 * we'll need.
1964 */
1965 maxval = 3 * max_stmts;
1966 vmap = (struct vmapinfo *)calloc(maxval, sizeof(*vmap));
1967 vnode_base = (struct valnode *)calloc(maxval, sizeof(*vnode_base));
1968 if (vmap == NULL || vnode_base == NULL)
1969 bpf_error("malloc");
1970 }
1971
1972 /*
1973 * Some pointers used to convert the basic block form of the code,
1974 * into the array form that BPF requires. 'fstart' will point to
1975 * the malloc'd array while 'ftail' is used during the recursive traversal.
1976 */
1977 static struct bpf_insn *fstart;
1978 static struct bpf_insn *ftail;
1979
1980 #ifdef BDEBUG
1981 int bids[1000];
1982 #endif
1983
1984 /*
1985 * Returns true if successful. Returns false if a branch has
1986 * an offset that is too large. If so, we have marked that
1987 * branch so that on a subsequent iteration, it will be treated
1988 * properly.
1989 */
1990 static int
1991 convert_code_r(struct block *p)
1992 {
1993 struct bpf_insn *dst;
1994 struct slist *src;
1995 int slen;
1996 u_int off;
1997 int extrajmps; /* number of extra jumps inserted */
1998 struct slist **offset = NULL;
1999
2000 if (p == 0 || isMarked(p))
2001 return (1);
2002 Mark(p);
2003
2004 if (convert_code_r(JF(p)) == 0)
2005 return (0);
2006 if (convert_code_r(JT(p)) == 0)
2007 return (0);
2008
2009 slen = slength(p->stmts);
2010 dst = ftail -= (slen + 1 + p->longjt + p->longjf);
2011 /* inflate length by any extra jumps */
2012
2013 p->offset = dst - fstart;
2014
2015 /* generate offset[] for convenience */
2016 if (slen) {
2017 offset = (struct slist **)calloc(slen, sizeof(struct slist *));
2018 if (!offset) {
2019 bpf_error("not enough core");
2020 /*NOTREACHED*/
2021 }
2022 }
2023 src = p->stmts;
2024 for (off = 0; off < slen && src; off++) {
2025 #if 0
2026 printf("off=%d src=%x\n", off, src);
2027 #endif
2028 offset[off] = src;
2029 src = src->next;
2030 }
2031
2032 off = 0;
2033 for (src = p->stmts; src; src = src->next) {
2034 if (src->s.code == NOP)
2035 continue;
2036 dst->code = (u_short)src->s.code;
2037 dst->k = src->s.k;
2038
2039 /* fill block-local relative jump */
2040 if (BPF_CLASS(src->s.code) != BPF_JMP || src->s.code == (BPF_JMP|BPF_JA)) {
2041 #if 0
2042 if (src->s.jt || src->s.jf) {
2043 bpf_error("illegal jmp destination");
2044 /*NOTREACHED*/
2045 }
2046 #endif
2047 goto filled;
2048 }
2049 if (off == slen - 2) /*???*/
2050 goto filled;
2051
2052 {
2053 int i;
2054 int jt, jf;
2055 const char *ljerr = "%s for block-local relative jump: off=%d";
2056
2057 #if 0
2058 printf("code=%x off=%d %x %x\n", src->s.code,
2059 off, src->s.jt, src->s.jf);
2060 #endif
2061
2062 if (!src->s.jt || !src->s.jf) {
2063 bpf_error(ljerr, "no jmp destination", off);
2064 /*NOTREACHED*/
2065 }
2066
2067 jt = jf = 0;
2068 for (i = 0; i < slen; i++) {
2069 if (offset[i] == src->s.jt) {
2070 if (jt) {
2071 bpf_error(ljerr, "multiple matches", off);
2072 /*NOTREACHED*/
2073 }
2074
2075 dst->jt = i - off - 1;
2076 jt++;
2077 }
2078 if (offset[i] == src->s.jf) {
2079 if (jf) {
2080 bpf_error(ljerr, "multiple matches", off);
2081 /*NOTREACHED*/
2082 }
2083 dst->jf = i - off - 1;
2084 jf++;
2085 }
2086 }
2087 if (!jt || !jf) {
2088 bpf_error(ljerr, "no destination found", off);
2089 /*NOTREACHED*/
2090 }
2091 }
2092 filled:
2093 ++dst;
2094 ++off;
2095 }
2096 if (offset)
2097 free(offset);
2098
2099 #ifdef BDEBUG
2100 bids[dst - fstart] = p->id + 1;
2101 #endif
2102 dst->code = (u_short)p->s.code;
2103 dst->k = p->s.k;
2104 if (JT(p)) {
2105 extrajmps = 0;
2106 off = JT(p)->offset - (p->offset + slen) - 1;
2107 if (off >= 256) {
2108 /* offset too large for branch, must add a jump */
2109 if (p->longjt == 0) {
2110 /* mark this instruction and retry */
2111 p->longjt++;
2112 return(0);
2113 }
2114 /* branch if T to following jump */
2115 dst->jt = extrajmps;
2116 extrajmps++;
2117 dst[extrajmps].code = BPF_JMP|BPF_JA;
2118 dst[extrajmps].k = off - extrajmps;
2119 }
2120 else
2121 dst->jt = off;
2122 off = JF(p)->offset - (p->offset + slen) - 1;
2123 if (off >= 256) {
2124 /* offset too large for branch, must add a jump */
2125 if (p->longjf == 0) {
2126 /* mark this instruction and retry */
2127 p->longjf++;
2128 return(0);
2129 }
2130 /* branch if F to following jump */
2131 /* if two jumps are inserted, F goes to second one */
2132 dst->jf = extrajmps;
2133 extrajmps++;
2134 dst[extrajmps].code = BPF_JMP|BPF_JA;
2135 dst[extrajmps].k = off - extrajmps;
2136 }
2137 else
2138 dst->jf = off;
2139 }
2140 return (1);
2141 }
2142
2143
2144 /*
2145 * Convert flowgraph intermediate representation to the
2146 * BPF array representation. Set *lenp to the number of instructions.
2147 *
2148 * This routine does *NOT* leak the memory pointed to by fp. It *must
2149 * not* do free(fp) before returning fp; doing so would make no sense,
2150 * as the BPF array pointed to by the return value of icode_to_fcode()
2151 * must be valid - it's being returned for use in a bpf_program structure.
2152 *
2153 * If it appears that icode_to_fcode() is leaking, the problem is that
2154 * the program using pcap_compile() is failing to free the memory in
2155 * the BPF program when it's done - the leak is in the program, not in
2156 * the routine that happens to be allocating the memory. (By analogy, if
2157 * a program calls fopen() without ever calling fclose() on the FILE *,
2158 * it will leak the FILE structure; the leak is not in fopen(), it's in
2159 * the program.) Change the program to use pcap_freecode() when it's
2160 * done with the filter program. See the pcap man page.
2161 */
2162 struct bpf_insn *
2163 icode_to_fcode(struct block *root, u_int *lenp)
2164 {
2165 u_int n;
2166 struct bpf_insn *fp;
2167
2168 /*
2169 * Loop doing convert_code_r() until no branches remain
2170 * with too-large offsets.
2171 */
2172 while (1) {
2173 unMarkAll();
2174 n = *lenp = count_stmts(root);
2175
2176 fp = (struct bpf_insn *)malloc(sizeof(*fp) * n);
2177 if (fp == NULL)
2178 bpf_error("malloc");
2179 memset((char *)fp, 0, sizeof(*fp) * n);
2180 fstart = fp;
2181 ftail = fp + n;
2182
2183 unMarkAll();
2184 if (convert_code_r(root))
2185 break;
2186 free(fp);
2187 }
2188
2189 return fp;
2190 }
2191
2192 /*
2193 * Make a copy of a BPF program and put it in the "fcode" member of
2194 * a "pcap_t".
2195 *
2196 * If we fail to allocate memory for the copy, fill in the "errbuf"
2197 * member of the "pcap_t" with an error message, and return -1;
2198 * otherwise, return 0.
2199 */
2200 int
2201 install_bpf_program(pcap_t *p, struct bpf_program *fp)
2202 {
2203 size_t prog_size;
2204
2205 /*
2206 * Validate the program.
2207 */
2208 if (!bpf_validate(fp->bf_insns, fp->bf_len)) {
2209 snprintf(p->errbuf, sizeof(p->errbuf),
2210 "BPF program is not valid");
2211 return (-1);
2212 }
2213
2214 /*
2215 * Free up any already installed program.
2216 */
2217 pcap_freecode(&p->fcode);
2218
2219 prog_size = sizeof(*fp->bf_insns) * fp->bf_len;
2220 p->fcode.bf_len = fp->bf_len;
2221 p->fcode.bf_insns = (struct bpf_insn *)malloc(prog_size);
2222 if (p->fcode.bf_insns == NULL) {
2223 snprintf(p->errbuf, sizeof(p->errbuf),
2224 "malloc: %s", pcap_strerror(errno));
2225 return (-1);
2226 }
2227 memcpy(p->fcode.bf_insns, fp->bf_insns, prog_size);
2228 return (0);
2229 }
2230
2231 #ifdef BDEBUG
2232 static void
2233 opt_dump(struct block *root)
2234 {
2235 struct bpf_program f;
2236
2237 memset(bids, 0, sizeof bids);
2238 f.bf_insns = icode_to_fcode(root, &f.bf_len);
2239 bpf_dump(&f, 1);
2240 putchar('\n');
2241 free((char *)f.bf_insns);
2242 }
2243 #endif