2 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
3 * The Regents of the University of California. All rights reserved.
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
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.
21 * Optimization module for tcpdump intermediate representation.
29 #include <pcap-stdinc.h>
36 #ifdef HAVE_SYS_BITYPES_H
37 #include <sys/bitypes.h>
39 #include <sys/types.h>
53 #ifdef HAVE_OS_PROTO_H
61 #if defined(MSDOS) && !defined(__DJGPP__)
62 extern int _w32_ffs (int mask);
66 #if defined(WIN32) && defined (_MSC_VER)
71 * Represents a deleted instruction.
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
81 #define A_ATOM BPF_MEMWORDS
82 #define X_ATOM (BPF_MEMWORDS+1)
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.
89 #define AX_ATOM N_ATOMS
92 * A flag to indicate that further optimization is needed.
93 * Iterative passes are continued until a given pass yields no
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.
104 #define isMarked(p) ((p)->mark == cur_mark)
105 #define unMarkAll() cur_mark += 1
106 #define Mark(p) ((p)->mark = cur_mark)
108 static void opt_init(struct block *);
109 static void opt_cleanup(void);
111 static void intern_blocks(struct block *);
113 static void find_inedges(struct block *);
115 static void opt_dump(struct block *);
119 struct block **blocks;
124 * A bit vector set representation of the dominators.
125 * We round up the set size to the next power of two.
127 static int nodewords;
128 static int edgewords;
129 struct block **levels;
131 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
133 * True if a is in uset {p}
135 #define SET_MEMBER(p, a) \
136 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
141 #define SET_INSERT(p, a) \
142 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
145 * Delete 'a' from uset p.
147 #define SET_DELETE(p, a) \
148 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
153 #define SET_INTERSECT(a, b, n)\
155 register bpf_u_int32 *_x = a, *_y = b;\
156 register int _n = n;\
157 while (--_n >= 0) *_x++ &= *_y++;\
163 #define SET_SUBTRACT(a, b, n)\
165 register bpf_u_int32 *_x = a, *_y = b;\
166 register int _n = n;\
167 while (--_n >= 0) *_x++ &=~ *_y++;\
173 #define SET_UNION(a, b, n)\
175 register bpf_u_int32 *_x = a, *_y = b;\
176 register int _n = n;\
177 while (--_n >= 0) *_x++ |= *_y++;\
180 static uset all_dom_sets;
181 static uset all_closure_sets;
182 static uset all_edge_sets;
185 #define MAX(a,b) ((a)>(b)?(a):(b))
189 find_levels_r(struct block *b)
200 find_levels_r(JT(b));
201 find_levels_r(JF(b));
202 level = MAX(JT(b)->level, JF(b)->level) + 1;
206 b->link = levels[level];
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.
217 find_levels(struct block *root)
219 memset((char *)levels, 0, n_blocks * sizeof(*levels));
225 * Find dominator relationships.
226 * Assumes graph has been leveled.
229 find_dom(struct block *root)
236 * Initialize sets to contain all nodes.
239 i = n_blocks * nodewords;
242 /* Root starts off empty. */
243 for (i = nodewords; --i >= 0;)
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);
252 SET_INTERSECT(JT(b)->dom, b->dom, nodewords);
253 SET_INTERSECT(JF(b)->dom, b->dom, nodewords);
259 propedom(struct edge *ep)
261 SET_INSERT(ep->edom, ep->id);
263 SET_INTERSECT(ep->succ->et.edom, ep->edom, edgewords);
264 SET_INTERSECT(ep->succ->ef.edom, ep->edom, edgewords);
269 * Compute edge dominators.
270 * Assumes graph has been leveled and predecessors established.
273 find_edom(struct block *root)
280 for (i = n_edges * edgewords; --i >= 0; )
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) {
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.
299 * Assumes graph has been leveled.
302 find_closure(struct block *root)
308 * Initialize sets to contain no nodes.
310 memset((char *)all_closure_sets, 0,
311 n_blocks * nodewords * sizeof(*all_closure_sets));
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);
319 SET_UNION(JT(b)->closure, b->closure, nodewords);
320 SET_UNION(JF(b)->closure, b->closure, nodewords);
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.
329 * The implementation should probably change to an array access.
332 atomuse(struct stmt *s)
334 register int c = s->code;
339 switch (BPF_CLASS(c)) {
342 return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
343 (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
347 return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
348 (BPF_MODE(c) == BPF_MEM) ? s->k : -1;
358 if (BPF_SRC(c) == BPF_X)
363 return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
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.
374 * The implementation should probably change to an array access.
377 atomdef(struct stmt *s)
382 switch (BPF_CLASS(s->code)) {
396 return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
402 * Compute the sets of registers used, defined, and killed by 'b'.
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.
413 compute_local_ud(struct block *b)
416 atomset def = 0, use = 0, kill = 0;
419 for (s = b->stmts; s; s = s->next) {
420 if (s->s.code == NOP)
422 atom = atomuse(&s->s);
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);
430 else if (atom < N_ATOMS) {
431 if (!ATOMELEM(def, atom))
432 use |= ATOMMASK(atom);
437 atom = atomdef(&s->s);
439 if (!ATOMELEM(use, atom))
440 kill |= ATOMMASK(atom);
441 def |= ATOMMASK(atom);
444 if (BPF_CLASS(b->s.code) == BPF_JMP) {
446 * XXX - what about RET?
448 atom = atomuse(&b->s);
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);
456 else if (atom < N_ATOMS) {
457 if (!ATOMELEM(def, atom))
458 use |= ATOMMASK(atom);
471 * Assume graph is already leveled.
474 find_ud(struct block *root)
480 * root->level is the highest level no found;
481 * count down from there.
483 maxlevel = root->level;
484 for (i = maxlevel; i >= 0; --i)
485 for (p = levels[i]; p; p = p->link) {
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;
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.
508 struct valnode *next;
512 static struct valnode *hashtbl[MODULUS];
516 /* Integer constants mapped with the load immediate opcode. */
517 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
524 struct vmapinfo *vmap;
525 struct valnode *vnode_base;
526 struct valnode *next_vnode;
532 next_vnode = vnode_base;
533 memset((char *)vmap, 0, maxval * sizeof(*vmap));
534 memset((char *)hashtbl, 0, sizeof hashtbl);
537 /* Because we really don't have an IR, this stuff is a little messy. */
539 F(int code, int v0, int v1)
545 hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
548 for (p = hashtbl[hash]; p; p = p->next)
549 if (p->code == code && p->v0 == v0 && p->v1 == v1)
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;
563 p->next = hashtbl[hash];
570 vstore(struct stmt *s, int *valp, int newval, int alter)
572 if (alter && *valp == newval)
579 * Do constant-folding on binary operators.
580 * (Unary operators are handled elsewhere.)
583 fold_op(struct stmt *s, int v0, int v1)
587 a = vmap[v0].const_val;
588 b = vmap[v1].const_val;
590 switch (BPF_OP(s->code)) {
605 bpf_error("division by zero");
611 bpf_error("modulus by zero");
639 s->code = BPF_LD|BPF_IMM;
643 static inline struct slist *
644 this_op(struct slist *s)
646 while (s != 0 && s->s.code == NOP)
652 opt_not(struct block *b)
654 struct block *tmp = JT(b);
661 opt_peep(struct block *b)
664 struct slist *next, *last;
672 for (/*empty*/; /*empty*/; s = next) {
678 break; /* nothing left in the block */
681 * Find the next real instruction after that one
684 next = this_op(s->next);
686 break; /* no next instruction */
690 * st M[k] --> st M[k]
693 if (s->s.code == BPF_ST &&
694 next->s.code == (BPF_LDX|BPF_MEM) &&
695 s->s.k == next->s.k) {
697 next->s.code = BPF_MISC|BPF_TAX;
703 if (s->s.code == (BPF_LD|BPF_IMM) &&
704 next->s.code == (BPF_MISC|BPF_TAX)) {
705 s->s.code = BPF_LDX|BPF_IMM;
706 next->s.code = BPF_MISC|BPF_TXA;
710 * This is an ugly special case, but it happens
711 * when you say tcp[k] or udp[k] where k is a constant.
713 if (s->s.code == (BPF_LD|BPF_IMM)) {
714 struct slist *add, *tax, *ild;
717 * Check that X isn't used on exit from this
718 * block (which the optimizer might cause).
719 * We know the code generator won't generate
720 * any local dependencies.
722 if (ATOMELEM(b->out_use, X_ATOM))
726 * Check that the instruction following the ldi
727 * is an addx, or it's an ldxms with an addx
728 * following it (with 0 or more nops between the
731 if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
734 add = this_op(next->next);
735 if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
739 * Check that a tax follows that (with 0 or more
740 * nops between them).
742 tax = this_op(add->next);
743 if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
747 * Check that an ild follows that (with 0 or more
748 * nops between them).
750 ild = this_op(tax->next);
751 if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
752 BPF_MODE(ild->s.code) != BPF_IND)
755 * We want to turn this sequence:
758 * (005) ldxms [14] {next} -- optional
761 * (008) ild [x+0] {ild}
763 * into this sequence:
771 * XXX We need to check that X is not
772 * subsequently used, because we want to change
773 * what'll be in it after this sequence.
775 * We know we can eliminate the accumulator
776 * modifications earlier in the sequence since
777 * it is defined by the last stmt of this sequence
778 * (i.e., the last statement of the sequence loads
779 * a value into the accumulator, so we can eliminate
780 * earlier operations on the accumulator).
790 * If the comparison at the end of a block is an equality
791 * comparison against a constant, and nobody uses the value
792 * we leave in the A register at the end of a block, and
793 * the operation preceding the comparison is an arithmetic
794 * operation, we can sometime optimize it away.
796 if (b->s.code == (BPF_JMP|BPF_JEQ|BPF_K) &&
797 !ATOMELEM(b->out_use, A_ATOM)) {
799 * We can optimize away certain subtractions of the
802 if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X)) {
803 val = b->val[X_ATOM];
804 if (vmap[val].is_const) {
806 * If we have a subtract to do a comparison,
807 * and the X register is a known constant,
808 * we can merge this value into the
814 b->s.k += vmap[val].const_val;
817 } else if (b->s.k == 0) {
819 * If the X register isn't a constant,
820 * and the comparison in the test is
821 * against 0, we can compare with the
822 * X register, instead:
828 b->s.code = BPF_JMP|BPF_JEQ|BPF_X;
833 * Likewise, a constant subtract can be simplified:
836 * jeq #y -> jeq #(x+y)
838 else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K)) {
844 * And, similarly, a constant AND can be simplified
845 * if we're testing against 0, i.e.:
850 else if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
853 b->s.code = BPF_JMP|BPF_K|BPF_JSET;
861 * jset #ffffffff -> always
863 if (b->s.code == (BPF_JMP|BPF_K|BPF_JSET)) {
866 if (b->s.k == 0xffffffff)
870 * If we're comparing against the index register, and the index
871 * register is a known constant, we can just compare against that
874 val = b->val[X_ATOM];
875 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_X) {
876 bpf_int32 v = vmap[val].const_val;
881 * If the accumulator is a known constant, we can compute the
884 val = b->val[A_ATOM];
885 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
886 bpf_int32 v = vmap[val].const_val;
887 switch (BPF_OP(b->s.code)) {
894 v = (unsigned)v > b->s.k;
898 v = (unsigned)v >= b->s.k;
918 * Compute the symbolic value of expression of 's', and update
919 * anything it defines in the value table 'val'. If 'alter' is true,
920 * do various optimizations. This code would be cleaner if symbolic
921 * evaluation and code transformations weren't folded together.
924 opt_stmt(struct stmt *s, int val[], int alter)
931 case BPF_LD|BPF_ABS|BPF_W:
932 case BPF_LD|BPF_ABS|BPF_H:
933 case BPF_LD|BPF_ABS|BPF_B:
934 v = F(s->code, s->k, 0L);
935 vstore(s, &val[A_ATOM], v, alter);
938 case BPF_LD|BPF_IND|BPF_W:
939 case BPF_LD|BPF_IND|BPF_H:
940 case BPF_LD|BPF_IND|BPF_B:
942 if (alter && vmap[v].is_const) {
943 s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
944 s->k += vmap[v].const_val;
945 v = F(s->code, s->k, 0L);
949 v = F(s->code, s->k, v);
950 vstore(s, &val[A_ATOM], v, alter);
954 v = F(s->code, 0L, 0L);
955 vstore(s, &val[A_ATOM], v, alter);
960 vstore(s, &val[A_ATOM], v, alter);
963 case BPF_LDX|BPF_IMM:
965 vstore(s, &val[X_ATOM], v, alter);
968 case BPF_LDX|BPF_MSH|BPF_B:
969 v = F(s->code, s->k, 0L);
970 vstore(s, &val[X_ATOM], v, alter);
973 case BPF_ALU|BPF_NEG:
974 if (alter && vmap[val[A_ATOM]].is_const) {
975 s->code = BPF_LD|BPF_IMM;
976 s->k = -vmap[val[A_ATOM]].const_val;
977 val[A_ATOM] = K(s->k);
980 val[A_ATOM] = F(s->code, val[A_ATOM], 0L);
983 case BPF_ALU|BPF_ADD|BPF_K:
984 case BPF_ALU|BPF_SUB|BPF_K:
985 case BPF_ALU|BPF_MUL|BPF_K:
986 case BPF_ALU|BPF_DIV|BPF_K:
987 case BPF_ALU|BPF_MOD|BPF_K:
988 case BPF_ALU|BPF_AND|BPF_K:
989 case BPF_ALU|BPF_OR|BPF_K:
990 case BPF_ALU|BPF_XOR|BPF_K:
991 case BPF_ALU|BPF_LSH|BPF_K:
992 case BPF_ALU|BPF_RSH|BPF_K:
993 op = BPF_OP(s->code);
996 /* don't optimize away "sub #0"
997 * as it may be needed later to
998 * fixup the generated math code */
1000 op == BPF_LSH || op == BPF_RSH ||
1001 op == BPF_OR || op == BPF_XOR) {
1005 if (op == BPF_MUL || op == BPF_AND) {
1006 s->code = BPF_LD|BPF_IMM;
1007 val[A_ATOM] = K(s->k);
1011 if (vmap[val[A_ATOM]].is_const) {
1012 fold_op(s, val[A_ATOM], K(s->k));
1013 val[A_ATOM] = K(s->k);
1017 val[A_ATOM] = F(s->code, val[A_ATOM], K(s->k));
1020 case BPF_ALU|BPF_ADD|BPF_X:
1021 case BPF_ALU|BPF_SUB|BPF_X:
1022 case BPF_ALU|BPF_MUL|BPF_X:
1023 case BPF_ALU|BPF_DIV|BPF_X:
1024 case BPF_ALU|BPF_MOD|BPF_X:
1025 case BPF_ALU|BPF_AND|BPF_X:
1026 case BPF_ALU|BPF_OR|BPF_X:
1027 case BPF_ALU|BPF_XOR|BPF_X:
1028 case BPF_ALU|BPF_LSH|BPF_X:
1029 case BPF_ALU|BPF_RSH|BPF_X:
1030 op = BPF_OP(s->code);
1031 if (alter && vmap[val[X_ATOM]].is_const) {
1032 if (vmap[val[A_ATOM]].is_const) {
1033 fold_op(s, val[A_ATOM], val[X_ATOM]);
1034 val[A_ATOM] = K(s->k);
1037 s->code = BPF_ALU|BPF_K|op;
1038 s->k = vmap[val[X_ATOM]].const_val;
1041 F(s->code, val[A_ATOM], K(s->k));
1046 * Check if we're doing something to an accumulator
1047 * that is 0, and simplify. This may not seem like
1048 * much of a simplification but it could open up further
1050 * XXX We could also check for mul by 1, etc.
1052 if (alter && vmap[val[A_ATOM]].is_const
1053 && vmap[val[A_ATOM]].const_val == 0) {
1054 if (op == BPF_ADD || op == BPF_OR || op == BPF_XOR) {
1055 s->code = BPF_MISC|BPF_TXA;
1056 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1059 else if (op == BPF_MUL || op == BPF_DIV || op == BPF_MOD ||
1060 op == BPF_AND || op == BPF_LSH || op == BPF_RSH) {
1061 s->code = BPF_LD|BPF_IMM;
1063 vstore(s, &val[A_ATOM], K(s->k), alter);
1066 else if (op == BPF_NEG) {
1071 val[A_ATOM] = F(s->code, val[A_ATOM], val[X_ATOM]);
1074 case BPF_MISC|BPF_TXA:
1075 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1078 case BPF_LD|BPF_MEM:
1080 if (alter && vmap[v].is_const) {
1081 s->code = BPF_LD|BPF_IMM;
1082 s->k = vmap[v].const_val;
1085 vstore(s, &val[A_ATOM], v, alter);
1088 case BPF_MISC|BPF_TAX:
1089 vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1092 case BPF_LDX|BPF_MEM:
1094 if (alter && vmap[v].is_const) {
1095 s->code = BPF_LDX|BPF_IMM;
1096 s->k = vmap[v].const_val;
1099 vstore(s, &val[X_ATOM], v, alter);
1103 vstore(s, &val[s->k], val[A_ATOM], alter);
1107 vstore(s, &val[s->k], val[X_ATOM], alter);
1113 deadstmt(register struct stmt *s, register struct stmt *last[])
1119 if (atom == AX_ATOM) {
1130 last[atom]->code = NOP;
1137 opt_deadstores(register struct block *b)
1139 register struct slist *s;
1141 struct stmt *last[N_ATOMS];
1143 memset((char *)last, 0, sizeof last);
1145 for (s = b->stmts; s != 0; s = s->next)
1146 deadstmt(&s->s, last);
1147 deadstmt(&b->s, last);
1149 for (atom = 0; atom < N_ATOMS; ++atom)
1150 if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1151 last[atom]->code = NOP;
1157 opt_blk(struct block *b, int do_stmts)
1162 bpf_int32 aval, xval;
1165 for (s = b->stmts; s && s->next; s = s->next)
1166 if (BPF_CLASS(s->s.code) == BPF_JMP) {
1173 * Initialize the atom values.
1178 * We have no predecessors, so everything is undefined
1179 * upon entry to this block.
1181 memset((char *)b->val, 0, sizeof(b->val));
1184 * Inherit values from our predecessors.
1186 * First, get the values from the predecessor along the
1187 * first edge leading to this node.
1189 memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1191 * Now look at all the other nodes leading to this node.
1192 * If, for the predecessor along that edge, a register
1193 * has a different value from the one we have (i.e.,
1194 * control paths are merging, and the merging paths
1195 * assign different values to that register), give the
1196 * register the undefined value of 0.
1198 while ((p = p->next) != NULL) {
1199 for (i = 0; i < N_ATOMS; ++i)
1200 if (b->val[i] != p->pred->val[i])
1204 aval = b->val[A_ATOM];
1205 xval = b->val[X_ATOM];
1206 for (s = b->stmts; s; s = s->next)
1207 opt_stmt(&s->s, b->val, do_stmts);
1210 * This is a special case: if we don't use anything from this
1211 * block, and we load the accumulator or index register with a
1212 * value that is already there, or if this block is a return,
1213 * eliminate all the statements.
1215 * XXX - what if it does a store?
1217 * XXX - why does it matter whether we use anything from this
1218 * block? If the accumulator or index register doesn't change
1219 * its value, isn't that OK even if we use that value?
1221 * XXX - if we load the accumulator with a different value,
1222 * and the block ends with a conditional branch, we obviously
1223 * can't eliminate it, as the branch depends on that value.
1224 * For the index register, the conditional branch only depends
1225 * on the index register value if the test is against the index
1226 * register value rather than a constant; if nothing uses the
1227 * value we put into the index register, and we're not testing
1228 * against the index register's value, and there aren't any
1229 * other problems that would keep us from eliminating this
1230 * block, can we eliminate it?
1233 ((b->out_use == 0 && aval != 0 && b->val[A_ATOM] == aval &&
1234 xval != 0 && b->val[X_ATOM] == xval) ||
1235 BPF_CLASS(b->s.code) == BPF_RET)) {
1236 if (b->stmts != 0) {
1245 * Set up values for branch optimizer.
1247 if (BPF_SRC(b->s.code) == BPF_K)
1248 b->oval = K(b->s.k);
1250 b->oval = b->val[X_ATOM];
1251 b->et.code = b->s.code;
1252 b->ef.code = -b->s.code;
1256 * Return true if any register that is used on exit from 'succ', has
1257 * an exit value that is different from the corresponding exit value
1261 use_conflict(struct block *b, struct block *succ)
1264 atomset use = succ->out_use;
1269 for (atom = 0; atom < N_ATOMS; ++atom)
1270 if (ATOMELEM(use, atom))
1271 if (b->val[atom] != succ->val[atom])
1276 static struct block *
1277 fold_edge(struct block *child, struct edge *ep)
1280 int aval0, aval1, oval0, oval1;
1281 int code = ep->code;
1289 if (child->s.code != code)
1292 aval0 = child->val[A_ATOM];
1293 oval0 = child->oval;
1294 aval1 = ep->pred->val[A_ATOM];
1295 oval1 = ep->pred->oval;
1302 * The operands of the branch instructions are
1303 * identical, so the result is true if a true
1304 * branch was taken to get here, otherwise false.
1306 return sense ? JT(child) : JF(child);
1308 if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1310 * At this point, we only know the comparison if we
1311 * came down the true branch, and it was an equality
1312 * comparison with a constant.
1314 * I.e., if we came down the true branch, and the branch
1315 * was an equality comparison with a constant, we know the
1316 * accumulator contains that constant. If we came down
1317 * the false branch, or the comparison wasn't with a
1318 * constant, we don't know what was in the accumulator.
1320 * We rely on the fact that distinct constants have distinct
1329 opt_j(struct edge *ep)
1332 register struct block *target;
1334 if (JT(ep->succ) == 0)
1337 if (JT(ep->succ) == JF(ep->succ)) {
1339 * Common branch targets can be eliminated, provided
1340 * there is no data dependency.
1342 if (!use_conflict(ep->pred, ep->succ->et.succ)) {
1344 ep->succ = JT(ep->succ);
1348 * For each edge dominator that matches the successor of this
1349 * edge, promote the edge successor to the its grandchild.
1351 * XXX We violate the set abstraction here in favor a reasonably
1355 for (i = 0; i < edgewords; ++i) {
1356 register bpf_u_int32 x = ep->edom[i];
1361 k += i * BITS_PER_WORD;
1363 target = fold_edge(ep->succ, edges[k]);
1365 * Check that there is no data dependency between
1366 * nodes that will be violated if we move the edge.
1368 if (target != 0 && !use_conflict(ep->pred, target)) {
1371 if (JT(target) != 0)
1373 * Start over unless we hit a leaf.
1384 or_pullup(struct block *b)
1388 struct block **diffp, **samep;
1396 * Make sure each predecessor loads the same value.
1399 val = ep->pred->val[A_ATOM];
1400 for (ep = ep->next; ep != 0; ep = ep->next)
1401 if (val != ep->pred->val[A_ATOM])
1404 if (JT(b->in_edges->pred) == b)
1405 diffp = &JT(b->in_edges->pred);
1407 diffp = &JF(b->in_edges->pred);
1414 if (JT(*diffp) != JT(b))
1417 if (!SET_MEMBER((*diffp)->dom, b->id))
1420 if ((*diffp)->val[A_ATOM] != val)
1423 diffp = &JF(*diffp);
1426 samep = &JF(*diffp);
1431 if (JT(*samep) != JT(b))
1434 if (!SET_MEMBER((*samep)->dom, b->id))
1437 if ((*samep)->val[A_ATOM] == val)
1440 /* XXX Need to check that there are no data dependencies
1441 between dp0 and dp1. Currently, the code generator
1442 will not produce such dependencies. */
1443 samep = &JF(*samep);
1446 /* XXX This doesn't cover everything. */
1447 for (i = 0; i < N_ATOMS; ++i)
1448 if ((*samep)->val[i] != pred->val[i])
1451 /* Pull up the node. */
1457 * At the top of the chain, each predecessor needs to point at the
1458 * pulled up node. Inside the chain, there is only one predecessor
1462 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1463 if (JT(ep->pred) == b)
1464 JT(ep->pred) = pull;
1466 JF(ep->pred) = pull;
1476 and_pullup(struct block *b)
1480 struct block **diffp, **samep;
1488 * Make sure each predecessor loads the same value.
1490 val = ep->pred->val[A_ATOM];
1491 for (ep = ep->next; ep != 0; ep = ep->next)
1492 if (val != ep->pred->val[A_ATOM])
1495 if (JT(b->in_edges->pred) == b)
1496 diffp = &JT(b->in_edges->pred);
1498 diffp = &JF(b->in_edges->pred);
1505 if (JF(*diffp) != JF(b))
1508 if (!SET_MEMBER((*diffp)->dom, b->id))
1511 if ((*diffp)->val[A_ATOM] != val)
1514 diffp = &JT(*diffp);
1517 samep = &JT(*diffp);
1522 if (JF(*samep) != JF(b))
1525 if (!SET_MEMBER((*samep)->dom, b->id))
1528 if ((*samep)->val[A_ATOM] == val)
1531 /* XXX Need to check that there are no data dependencies
1532 between diffp and samep. Currently, the code generator
1533 will not produce such dependencies. */
1534 samep = &JT(*samep);
1537 /* XXX This doesn't cover everything. */
1538 for (i = 0; i < N_ATOMS; ++i)
1539 if ((*samep)->val[i] != pred->val[i])
1542 /* Pull up the node. */
1548 * At the top of the chain, each predecessor needs to point at the
1549 * pulled up node. Inside the chain, there is only one predecessor
1553 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1554 if (JT(ep->pred) == b)
1555 JT(ep->pred) = pull;
1557 JF(ep->pred) = pull;
1567 opt_blks(struct block *root, int do_stmts)
1573 maxlevel = root->level;
1576 for (i = maxlevel; i >= 0; --i)
1577 for (p = levels[i]; p; p = p->link)
1578 opt_blk(p, do_stmts);
1582 * No point trying to move branches; it can't possibly
1583 * make a difference at this point.
1587 for (i = 1; i <= maxlevel; ++i) {
1588 for (p = levels[i]; p; p = p->link) {
1595 for (i = 1; i <= maxlevel; ++i) {
1596 for (p = levels[i]; p; p = p->link) {
1604 link_inedge(struct edge *parent, struct block *child)
1606 parent->next = child->in_edges;
1607 child->in_edges = parent;
1611 find_inedges(struct block *root)
1616 for (i = 0; i < n_blocks; ++i)
1617 blocks[i]->in_edges = 0;
1620 * Traverse the graph, adding each edge to the predecessor
1621 * list of its successors. Skip the leaves (i.e. level 0).
1623 for (i = root->level; i > 0; --i) {
1624 for (b = levels[i]; b != 0; b = b->link) {
1625 link_inedge(&b->et, JT(b));
1626 link_inedge(&b->ef, JF(b));
1632 opt_root(struct block **b)
1634 struct slist *tmp, *s;
1638 while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
1647 * If the root node is a return, then there is no
1648 * point executing any statements (since the bpf machine
1649 * has no side effects).
1651 if (BPF_CLASS((*b)->s.code) == BPF_RET)
1656 opt_loop(struct block *root, int do_stmts)
1661 printf("opt_loop(root, %d) begin\n", do_stmts);
1672 opt_blks(root, do_stmts);
1675 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts, done);
1683 * Optimize the filter code in its dag representation.
1686 bpf_optimize(struct block **rootp)
1695 intern_blocks(root);
1698 printf("after intern_blocks()\n");
1705 printf("after opt_root()\n");
1713 make_marks(struct block *p)
1717 if (BPF_CLASS(p->s.code) != BPF_RET) {
1725 * Mark code array such that isMarked(i) is true
1726 * only for nodes that are alive.
1729 mark_code(struct block *p)
1736 * True iff the two stmt lists load the same value from the packet into
1740 eq_slist(struct slist *x, struct slist *y)
1743 while (x && x->s.code == NOP)
1745 while (y && y->s.code == NOP)
1751 if (x->s.code != y->s.code || x->s.k != y->s.k)
1759 eq_blk(struct block *b0, struct block *b1)
1761 if (b0->s.code == b1->s.code &&
1762 b0->s.k == b1->s.k &&
1763 b0->et.succ == b1->et.succ &&
1764 b0->ef.succ == b1->ef.succ)
1765 return eq_slist(b0->stmts, b1->stmts);
1770 intern_blocks(struct block *root)
1774 int done1; /* don't shadow global */
1777 for (i = 0; i < n_blocks; ++i)
1778 blocks[i]->link = 0;
1782 for (i = n_blocks - 1; --i >= 0; ) {
1783 if (!isMarked(blocks[i]))
1785 for (j = i + 1; j < n_blocks; ++j) {
1786 if (!isMarked(blocks[j]))
1788 if (eq_blk(blocks[i], blocks[j])) {
1789 blocks[i]->link = blocks[j]->link ?
1790 blocks[j]->link : blocks[j];
1795 for (i = 0; i < n_blocks; ++i) {
1801 JT(p) = JT(p)->link;
1805 JF(p) = JF(p)->link;
1815 free((void *)vnode_base);
1817 free((void *)edges);
1818 free((void *)space);
1819 free((void *)levels);
1820 free((void *)blocks);
1824 * Return the number of stmts in 's'.
1827 slength(struct slist *s)
1831 for (; s; s = s->next)
1832 if (s->s.code != NOP)
1838 * Return the number of nodes reachable by 'p'.
1839 * All nodes should be initially unmarked.
1842 count_blocks(struct block *p)
1844 if (p == 0 || isMarked(p))
1847 return count_blocks(JT(p)) + count_blocks(JF(p)) + 1;
1851 * Do a depth first search on the flow graph, numbering the
1852 * the basic blocks, and entering them into the 'blocks' array.`
1855 number_blks_r(struct block *p)
1859 if (p == 0 || isMarked(p))
1867 number_blks_r(JT(p));
1868 number_blks_r(JF(p));
1872 * Return the number of stmts in the flowgraph reachable by 'p'.
1873 * The nodes should be unmarked before calling.
1875 * Note that "stmts" means "instructions", and that this includes
1877 * side-effect statements in 'p' (slength(p->stmts));
1879 * statements in the true branch from 'p' (count_stmts(JT(p)));
1881 * statements in the false branch from 'p' (count_stmts(JF(p)));
1883 * the conditional jump itself (1);
1885 * an extra long jump if the true branch requires it (p->longjt);
1887 * an extra long jump if the false branch requires it (p->longjf).
1890 count_stmts(struct block *p)
1894 if (p == 0 || isMarked(p))
1897 n = count_stmts(JT(p)) + count_stmts(JF(p));
1898 return slength(p->stmts) + n + 1 + p->longjt + p->longjf;
1902 * Allocate memory. All allocation is done before optimization
1903 * is begun. A linear bound on the size of all data structures is computed
1904 * from the total number of blocks and/or statements.
1907 opt_init(struct block *root)
1910 int i, n, max_stmts;
1913 * First, count the blocks, so we can malloc an array to map
1914 * block number to block. Then, put the blocks into the array.
1917 n = count_blocks(root);
1918 blocks = (struct block **)calloc(n, sizeof(*blocks));
1920 bpf_error("malloc");
1923 number_blks_r(root);
1925 n_edges = 2 * n_blocks;
1926 edges = (struct edge **)calloc(n_edges, sizeof(*edges));
1928 bpf_error("malloc");
1931 * The number of levels is bounded by the number of nodes.
1933 levels = (struct block **)calloc(n_blocks, sizeof(*levels));
1935 bpf_error("malloc");
1937 edgewords = n_edges / (8 * sizeof(bpf_u_int32)) + 1;
1938 nodewords = n_blocks / (8 * sizeof(bpf_u_int32)) + 1;
1941 space = (bpf_u_int32 *)malloc(2 * n_blocks * nodewords * sizeof(*space)
1942 + n_edges * edgewords * sizeof(*space));
1944 bpf_error("malloc");
1947 for (i = 0; i < n; ++i) {
1951 all_closure_sets = p;
1952 for (i = 0; i < n; ++i) {
1953 blocks[i]->closure = p;
1957 for (i = 0; i < n; ++i) {
1958 register struct block *b = blocks[i];
1966 b->ef.id = n_blocks + i;
1967 edges[n_blocks + i] = &b->ef;
1972 for (i = 0; i < n; ++i)
1973 max_stmts += slength(blocks[i]->stmts) + 1;
1975 * We allocate at most 3 value numbers per statement,
1976 * so this is an upper bound on the number of valnodes
1979 maxval = 3 * max_stmts;
1980 vmap = (struct vmapinfo *)calloc(maxval, sizeof(*vmap));
1981 vnode_base = (struct valnode *)calloc(maxval, sizeof(*vnode_base));
1982 if (vmap == NULL || vnode_base == NULL)
1983 bpf_error("malloc");
1987 * Some pointers used to convert the basic block form of the code,
1988 * into the array form that BPF requires. 'fstart' will point to
1989 * the malloc'd array while 'ftail' is used during the recursive traversal.
1991 static struct bpf_insn *fstart;
1992 static struct bpf_insn *ftail;
1999 * Returns true if successful. Returns false if a branch has
2000 * an offset that is too large. If so, we have marked that
2001 * branch so that on a subsequent iteration, it will be treated
2005 convert_code_r(struct block *p)
2007 struct bpf_insn *dst;
2011 int extrajmps; /* number of extra jumps inserted */
2012 struct slist **offset = NULL;
2014 if (p == 0 || isMarked(p))
2018 if (convert_code_r(JF(p)) == 0)
2020 if (convert_code_r(JT(p)) == 0)
2023 slen = slength(p->stmts);
2024 dst = ftail -= (slen + 1 + p->longjt + p->longjf);
2025 /* inflate length by any extra jumps */
2027 p->offset = dst - fstart;
2029 /* generate offset[] for convenience */
2031 offset = (struct slist **)calloc(slen, sizeof(struct slist *));
2033 bpf_error("not enough core");
2038 for (off = 0; off < slen && src; off++) {
2040 printf("off=%d src=%x\n", off, src);
2047 for (src = p->stmts; src; src = src->next) {
2048 if (src->s.code == NOP)
2050 dst->code = (u_short)src->s.code;
2053 /* fill block-local relative jump */
2054 if (BPF_CLASS(src->s.code) != BPF_JMP || src->s.code == (BPF_JMP|BPF_JA)) {
2056 if (src->s.jt || src->s.jf) {
2057 bpf_error("illegal jmp destination");
2063 if (off == slen - 2) /*???*/
2069 const char *ljerr = "%s for block-local relative jump: off=%d";
2072 printf("code=%x off=%d %x %x\n", src->s.code,
2073 off, src->s.jt, src->s.jf);
2076 if (!src->s.jt || !src->s.jf) {
2077 bpf_error(ljerr, "no jmp destination", off);
2082 for (i = 0; i < slen; i++) {
2083 if (offset[i] == src->s.jt) {
2085 bpf_error(ljerr, "multiple matches", off);
2089 dst->jt = i - off - 1;
2092 if (offset[i] == src->s.jf) {
2094 bpf_error(ljerr, "multiple matches", off);
2097 dst->jf = i - off - 1;
2102 bpf_error(ljerr, "no destination found", off);
2114 bids[dst - fstart] = p->id + 1;
2116 dst->code = (u_short)p->s.code;
2120 off = JT(p)->offset - (p->offset + slen) - 1;
2122 /* offset too large for branch, must add a jump */
2123 if (p->longjt == 0) {
2124 /* mark this instruction and retry */
2128 /* branch if T to following jump */
2129 dst->jt = extrajmps;
2131 dst[extrajmps].code = BPF_JMP|BPF_JA;
2132 dst[extrajmps].k = off - extrajmps;
2136 off = JF(p)->offset - (p->offset + slen) - 1;
2138 /* offset too large for branch, must add a jump */
2139 if (p->longjf == 0) {
2140 /* mark this instruction and retry */
2144 /* branch if F to following jump */
2145 /* if two jumps are inserted, F goes to second one */
2146 dst->jf = extrajmps;
2148 dst[extrajmps].code = BPF_JMP|BPF_JA;
2149 dst[extrajmps].k = off - extrajmps;
2159 * Convert flowgraph intermediate representation to the
2160 * BPF array representation. Set *lenp to the number of instructions.
2162 * This routine does *NOT* leak the memory pointed to by fp. It *must
2163 * not* do free(fp) before returning fp; doing so would make no sense,
2164 * as the BPF array pointed to by the return value of icode_to_fcode()
2165 * must be valid - it's being returned for use in a bpf_program structure.
2167 * If it appears that icode_to_fcode() is leaking, the problem is that
2168 * the program using pcap_compile() is failing to free the memory in
2169 * the BPF program when it's done - the leak is in the program, not in
2170 * the routine that happens to be allocating the memory. (By analogy, if
2171 * a program calls fopen() without ever calling fclose() on the FILE *,
2172 * it will leak the FILE structure; the leak is not in fopen(), it's in
2173 * the program.) Change the program to use pcap_freecode() when it's
2174 * done with the filter program. See the pcap man page.
2177 icode_to_fcode(struct block *root, u_int *lenp)
2180 struct bpf_insn *fp;
2183 * Loop doing convert_code_r() until no branches remain
2184 * with too-large offsets.
2188 n = *lenp = count_stmts(root);
2190 fp = (struct bpf_insn *)malloc(sizeof(*fp) * n);
2192 bpf_error("malloc");
2193 memset((char *)fp, 0, sizeof(*fp) * n);
2198 if (convert_code_r(root))
2207 * Make a copy of a BPF program and put it in the "fcode" member of
2210 * If we fail to allocate memory for the copy, fill in the "errbuf"
2211 * member of the "pcap_t" with an error message, and return -1;
2212 * otherwise, return 0.
2215 install_bpf_program(pcap_t *p, struct bpf_program *fp)
2220 * Validate the program.
2222 if (!bpf_validate(fp->bf_insns, fp->bf_len)) {
2223 snprintf(p->errbuf, sizeof(p->errbuf),
2224 "BPF program is not valid");
2229 * Free up any already installed program.
2231 pcap_freecode(&p->fcode);
2233 prog_size = sizeof(*fp->bf_insns) * fp->bf_len;
2234 p->fcode.bf_len = fp->bf_len;
2235 p->fcode.bf_insns = (struct bpf_insn *)malloc(prog_size);
2236 if (p->fcode.bf_insns == NULL) {
2237 snprintf(p->errbuf, sizeof(p->errbuf),
2238 "malloc: %s", pcap_strerror(errno));
2241 memcpy(p->fcode.bf_insns, fp->bf_insns, prog_size);
2247 opt_dump(struct block *root)
2249 struct bpf_program f;
2251 memset(bids, 0, sizeof bids);
2252 f.bf_insns = icode_to_fcode(root, &f.bf_len);
2255 free((char *)f.bf_insns);