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.
24 static const char rcsid[] =
25 "@(#) $Header: /tcpdump/master/libpcap/optimize.c,v 1.69 2001/11/12 21:57:06 fenner Exp $ (LBL)";
32 #include <sys/types.h>
45 #ifdef HAVE_OS_PROTO_H
53 #define A_ATOM BPF_MEMWORDS
54 #define X_ATOM (BPF_MEMWORDS+1)
59 * This define is used to represent *both* the accumulator and
60 * x register in use-def computations.
61 * Currently, the use-def code assumes only one definition per instruction.
63 #define AX_ATOM N_ATOMS
66 * A flag to indicate that further optimization is needed.
67 * Iterative passes are continued until a given pass yields no
73 * A block is marked if only if its mark equals the current mark.
74 * Rather than traverse the code array, marking each item, 'cur_mark' is
75 * incremented. This automatically makes each element unmarked.
78 #define isMarked(p) ((p)->mark == cur_mark)
79 #define unMarkAll() cur_mark += 1
80 #define Mark(p) ((p)->mark = cur_mark)
82 static void opt_init(struct block *);
83 static void opt_cleanup(void);
85 static void make_marks(struct block *);
86 static void mark_code(struct block *);
88 static void intern_blocks(struct block *);
90 static int eq_slist(struct slist *, struct slist *);
92 static void find_levels_r(struct block *);
94 static void find_levels(struct block *);
95 static void find_dom(struct block *);
96 static void propedom(struct edge *);
97 static void find_edom(struct block *);
98 static void find_closure(struct block *);
99 static int atomuse(struct stmt *);
100 static int atomdef(struct stmt *);
101 static void compute_local_ud(struct block *);
102 static void find_ud(struct block *);
103 static void init_val(void);
104 static int F(int, int, int);
105 static inline void vstore(struct stmt *, int *, int, int);
106 static void opt_blk(struct block *, int);
107 static int use_conflict(struct block *, struct block *);
108 static void opt_j(struct edge *);
109 static void or_pullup(struct block *);
110 static void and_pullup(struct block *);
111 static void opt_blks(struct block *, int);
112 static inline void link_inedge(struct edge *, struct block *);
113 static void find_inedges(struct block *);
114 static void opt_root(struct block **);
115 static void opt_loop(struct block *, int);
116 static void fold_op(struct stmt *, int, int);
117 static inline struct slist *this_op(struct slist *);
118 static void opt_not(struct block *);
119 static void opt_peep(struct block *);
120 static void opt_stmt(struct stmt *, int[], int);
121 static void deadstmt(struct stmt *, struct stmt *[]);
122 static void opt_deadstores(struct block *);
123 static void opt_blk(struct block *, int);
124 static int use_conflict(struct block *, struct block *);
125 static void opt_j(struct edge *);
126 static struct block *fold_edge(struct block *, struct edge *);
127 static inline int eq_blk(struct block *, struct block *);
128 static int slength(struct slist *);
129 static int count_blocks(struct block *);
130 static void number_blks_r(struct block *);
131 static int count_stmts(struct block *);
132 static int convert_code_r(struct block *);
134 static void opt_dump(struct block *);
138 struct block **blocks;
143 * A bit vector set representation of the dominators.
144 * We round up the set size to the next power of two.
146 static int nodewords;
147 static int edgewords;
148 struct block **levels;
150 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
152 * True if a is in uset {p}
154 #define SET_MEMBER(p, a) \
155 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
160 #define SET_INSERT(p, a) \
161 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
164 * Delete 'a' from uset p.
166 #define SET_DELETE(p, a) \
167 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
172 #define SET_INTERSECT(a, b, n)\
174 register bpf_u_int32 *_x = a, *_y = b;\
175 register int _n = n;\
176 while (--_n >= 0) *_x++ &= *_y++;\
182 #define SET_SUBTRACT(a, b, n)\
184 register bpf_u_int32 *_x = a, *_y = b;\
185 register int _n = n;\
186 while (--_n >= 0) *_x++ &=~ *_y++;\
192 #define SET_UNION(a, b, n)\
194 register bpf_u_int32 *_x = a, *_y = b;\
195 register int _n = n;\
196 while (--_n >= 0) *_x++ |= *_y++;\
199 static uset all_dom_sets;
200 static uset all_closure_sets;
201 static uset all_edge_sets;
204 #define MAX(a,b) ((a)>(b)?(a):(b))
220 find_levels_r(JT(b));
221 find_levels_r(JF(b));
222 level = MAX(JT(b)->level, JF(b)->level) + 1;
226 b->link = levels[level];
231 * Level graph. The levels go from 0 at the leaves to
232 * N_LEVELS at the root. The levels[] array points to the
233 * first node of the level list, whose elements are linked
234 * with the 'link' field of the struct block.
240 memset((char *)levels, 0, n_blocks * sizeof(*levels));
246 * Find dominator relationships.
247 * Assumes graph has been leveled.
258 * Initialize sets to contain all nodes.
261 i = n_blocks * nodewords;
264 /* Root starts off empty. */
265 for (i = nodewords; --i >= 0;)
268 /* root->level is the highest level no found. */
269 for (i = root->level; i >= 0; --i) {
270 for (b = levels[i]; b; b = b->link) {
271 SET_INSERT(b->dom, b->id);
274 SET_INTERSECT(JT(b)->dom, b->dom, nodewords);
275 SET_INTERSECT(JF(b)->dom, b->dom, nodewords);
284 SET_INSERT(ep->edom, ep->id);
286 SET_INTERSECT(ep->succ->et.edom, ep->edom, edgewords);
287 SET_INTERSECT(ep->succ->ef.edom, ep->edom, edgewords);
292 * Compute edge dominators.
293 * Assumes graph has been leveled and predecessors established.
304 for (i = n_edges * edgewords; --i >= 0; )
307 /* root->level is the highest level no found. */
308 memset(root->et.edom, 0, edgewords * sizeof(*(uset)0));
309 memset(root->ef.edom, 0, edgewords * sizeof(*(uset)0));
310 for (i = root->level; i >= 0; --i) {
311 for (b = levels[i]; b != 0; b = b->link) {
319 * Find the backwards transitive closure of the flow graph. These sets
320 * are backwards in the sense that we find the set of nodes that reach
321 * a given node, not the set of nodes that can be reached by a node.
323 * Assumes graph has been leveled.
333 * Initialize sets to contain no nodes.
335 memset((char *)all_closure_sets, 0,
336 n_blocks * nodewords * sizeof(*all_closure_sets));
338 /* root->level is the highest level no found. */
339 for (i = root->level; i >= 0; --i) {
340 for (b = levels[i]; b; b = b->link) {
341 SET_INSERT(b->closure, b->id);
344 SET_UNION(JT(b)->closure, b->closure, nodewords);
345 SET_UNION(JF(b)->closure, b->closure, nodewords);
351 * Return the register number that is used by s. If A and X are both
352 * used, return AX_ATOM. If no register is used, return -1.
354 * The implementation should probably change to an array access.
360 register int c = s->code;
365 switch (BPF_CLASS(c)) {
368 return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
369 (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
373 return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
374 (BPF_MODE(c) == BPF_MEM) ? s->k : -1;
384 if (BPF_SRC(c) == BPF_X)
389 return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
396 * Return the register number that is defined by 's'. We assume that
397 * a single stmt cannot define more than one register. If no register
398 * is defined, return -1.
400 * The implementation should probably change to an array access.
409 switch (BPF_CLASS(s->code)) {
423 return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
433 atomset def = 0, use = 0, kill = 0;
436 for (s = b->stmts; s; s = s->next) {
437 if (s->s.code == NOP)
439 atom = atomuse(&s->s);
441 if (atom == AX_ATOM) {
442 if (!ATOMELEM(def, X_ATOM))
443 use |= ATOMMASK(X_ATOM);
444 if (!ATOMELEM(def, A_ATOM))
445 use |= ATOMMASK(A_ATOM);
447 else if (atom < N_ATOMS) {
448 if (!ATOMELEM(def, atom))
449 use |= ATOMMASK(atom);
454 atom = atomdef(&s->s);
456 if (!ATOMELEM(use, atom))
457 kill |= ATOMMASK(atom);
458 def |= ATOMMASK(atom);
461 if (!ATOMELEM(def, A_ATOM) && BPF_CLASS(b->s.code) == BPF_JMP)
462 use |= ATOMMASK(A_ATOM);
470 * Assume graph is already leveled.
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. */
547 hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
550 for (p = hashtbl[hash]; p; p = p->next)
551 if (p->code == code && p->v0 == v0 && p->v1 == v1)
555 if (BPF_MODE(code) == BPF_IMM &&
556 (BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
557 vmap[val].const_val = v0;
558 vmap[val].is_const = 1;
565 p->next = hashtbl[hash];
572 vstore(s, valp, newval, alter)
578 if (alter && *valp == newval)
591 a = vmap[v0].const_val;
592 b = vmap[v1].const_val;
594 switch (BPF_OP(s->code)) {
609 bpf_error("division by zero");
637 s->code = BPF_LD|BPF_IMM;
641 static inline struct slist *
645 while (s != 0 && s->s.code == NOP)
654 struct block *tmp = JT(b);
665 struct slist *next, *last;
677 next = this_op(s->next);
683 * st M[k] --> st M[k]
686 if (s->s.code == BPF_ST &&
687 next->s.code == (BPF_LDX|BPF_MEM) &&
688 s->s.k == next->s.k) {
690 next->s.code = BPF_MISC|BPF_TAX;
696 if (s->s.code == (BPF_LD|BPF_IMM) &&
697 next->s.code == (BPF_MISC|BPF_TAX)) {
698 s->s.code = BPF_LDX|BPF_IMM;
699 next->s.code = BPF_MISC|BPF_TXA;
703 * This is an ugly special case, but it happens
704 * when you say tcp[k] or udp[k] where k is a constant.
706 if (s->s.code == (BPF_LD|BPF_IMM)) {
707 struct slist *add, *tax, *ild;
710 * Check that X isn't used on exit from this
711 * block (which the optimizer might cause).
712 * We know the code generator won't generate
713 * any local dependencies.
715 if (ATOMELEM(b->out_use, X_ATOM))
718 if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
721 add = this_op(next->next);
722 if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
725 tax = this_op(add->next);
726 if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
729 ild = this_op(tax->next);
730 if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
731 BPF_MODE(ild->s.code) != BPF_IND)
734 * XXX We need to check that X is not
735 * subsequently used. We know we can eliminate the
736 * accumulator modifications since it is defined
737 * by the last stmt of this sequence.
739 * We want to turn this sequence:
742 * (005) ldxms [14] {next} -- optional
745 * (008) ild [x+0] {ild}
747 * into this sequence:
765 * If we have a subtract to do a comparison, and the X register
766 * is a known constant, we can merge this value into the
769 if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X) &&
770 !ATOMELEM(b->out_use, A_ATOM)) {
771 val = b->val[X_ATOM];
772 if (vmap[val].is_const) {
775 b->s.k += vmap[val].const_val;
776 op = BPF_OP(b->s.code);
777 if (op == BPF_JGT || op == BPF_JGE) {
778 struct block *t = JT(b);
781 b->s.k += 0x80000000;
785 } else if (b->s.k == 0) {
791 b->s.code = BPF_CLASS(b->s.code) | BPF_OP(b->s.code) |
797 * Likewise, a constant subtract can be simplified.
799 else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K) &&
800 !ATOMELEM(b->out_use, A_ATOM)) {
805 op = BPF_OP(b->s.code);
806 if (op == BPF_JGT || op == BPF_JGE) {
807 struct block *t = JT(b);
810 b->s.k += 0x80000000;
818 if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
819 !ATOMELEM(b->out_use, A_ATOM) && b->s.k == 0) {
821 b->s.code = BPF_JMP|BPF_K|BPF_JSET;
827 * If the accumulator is a known constant, we can compute the
830 val = b->val[A_ATOM];
831 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
832 bpf_int32 v = vmap[val].const_val;
833 switch (BPF_OP(b->s.code)) {
840 v = (unsigned)v > b->s.k;
844 v = (unsigned)v >= b->s.k;
864 * Compute the symbolic value of expression of 's', and update
865 * anything it defines in the value table 'val'. If 'alter' is true,
866 * do various optimizations. This code would be cleaner if symbolic
867 * evaluation and code transformations weren't folded together.
870 opt_stmt(s, val, alter)
880 case BPF_LD|BPF_ABS|BPF_W:
881 case BPF_LD|BPF_ABS|BPF_H:
882 case BPF_LD|BPF_ABS|BPF_B:
883 v = F(s->code, s->k, 0L);
884 vstore(s, &val[A_ATOM], v, alter);
887 case BPF_LD|BPF_IND|BPF_W:
888 case BPF_LD|BPF_IND|BPF_H:
889 case BPF_LD|BPF_IND|BPF_B:
891 if (alter && vmap[v].is_const) {
892 s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
893 s->k += vmap[v].const_val;
894 v = F(s->code, s->k, 0L);
898 v = F(s->code, s->k, v);
899 vstore(s, &val[A_ATOM], v, alter);
903 v = F(s->code, 0L, 0L);
904 vstore(s, &val[A_ATOM], v, alter);
909 vstore(s, &val[A_ATOM], v, alter);
912 case BPF_LDX|BPF_IMM:
914 vstore(s, &val[X_ATOM], v, alter);
917 case BPF_LDX|BPF_MSH|BPF_B:
918 v = F(s->code, s->k, 0L);
919 vstore(s, &val[X_ATOM], v, alter);
922 case BPF_ALU|BPF_NEG:
923 if (alter && vmap[val[A_ATOM]].is_const) {
924 s->code = BPF_LD|BPF_IMM;
925 s->k = -vmap[val[A_ATOM]].const_val;
926 val[A_ATOM] = K(s->k);
929 val[A_ATOM] = F(s->code, val[A_ATOM], 0L);
932 case BPF_ALU|BPF_ADD|BPF_K:
933 case BPF_ALU|BPF_SUB|BPF_K:
934 case BPF_ALU|BPF_MUL|BPF_K:
935 case BPF_ALU|BPF_DIV|BPF_K:
936 case BPF_ALU|BPF_AND|BPF_K:
937 case BPF_ALU|BPF_OR|BPF_K:
938 case BPF_ALU|BPF_LSH|BPF_K:
939 case BPF_ALU|BPF_RSH|BPF_K:
940 op = BPF_OP(s->code);
943 /* don't optimize away "sub #0"
944 * as it may be needed later to
945 * fixup the generated math code */
947 op == BPF_LSH || op == BPF_RSH ||
952 if (op == BPF_MUL || op == BPF_AND) {
953 s->code = BPF_LD|BPF_IMM;
954 val[A_ATOM] = K(s->k);
958 if (vmap[val[A_ATOM]].is_const) {
959 fold_op(s, val[A_ATOM], K(s->k));
960 val[A_ATOM] = K(s->k);
964 val[A_ATOM] = F(s->code, val[A_ATOM], K(s->k));
967 case BPF_ALU|BPF_ADD|BPF_X:
968 case BPF_ALU|BPF_SUB|BPF_X:
969 case BPF_ALU|BPF_MUL|BPF_X:
970 case BPF_ALU|BPF_DIV|BPF_X:
971 case BPF_ALU|BPF_AND|BPF_X:
972 case BPF_ALU|BPF_OR|BPF_X:
973 case BPF_ALU|BPF_LSH|BPF_X:
974 case BPF_ALU|BPF_RSH|BPF_X:
975 op = BPF_OP(s->code);
976 if (alter && vmap[val[X_ATOM]].is_const) {
977 if (vmap[val[A_ATOM]].is_const) {
978 fold_op(s, val[A_ATOM], val[X_ATOM]);
979 val[A_ATOM] = K(s->k);
982 s->code = BPF_ALU|BPF_K|op;
983 s->k = vmap[val[X_ATOM]].const_val;
986 F(s->code, val[A_ATOM], K(s->k));
991 * Check if we're doing something to an accumulator
992 * that is 0, and simplify. This may not seem like
993 * much of a simplification but it could open up further
995 * XXX We could also check for mul by 1, and -1, etc.
997 if (alter && vmap[val[A_ATOM]].is_const
998 && vmap[val[A_ATOM]].const_val == 0) {
999 if (op == BPF_ADD || op == BPF_OR ||
1000 op == BPF_LSH || op == BPF_RSH || op == BPF_SUB) {
1001 s->code = BPF_MISC|BPF_TXA;
1002 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1005 else if (op == BPF_MUL || op == BPF_DIV ||
1007 s->code = BPF_LD|BPF_IMM;
1009 vstore(s, &val[A_ATOM], K(s->k), alter);
1012 else if (op == BPF_NEG) {
1017 val[A_ATOM] = F(s->code, val[A_ATOM], val[X_ATOM]);
1020 case BPF_MISC|BPF_TXA:
1021 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1024 case BPF_LD|BPF_MEM:
1026 if (alter && vmap[v].is_const) {
1027 s->code = BPF_LD|BPF_IMM;
1028 s->k = vmap[v].const_val;
1031 vstore(s, &val[A_ATOM], v, alter);
1034 case BPF_MISC|BPF_TAX:
1035 vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1038 case BPF_LDX|BPF_MEM:
1040 if (alter && vmap[v].is_const) {
1041 s->code = BPF_LDX|BPF_IMM;
1042 s->k = vmap[v].const_val;
1045 vstore(s, &val[X_ATOM], v, alter);
1049 vstore(s, &val[s->k], val[A_ATOM], alter);
1053 vstore(s, &val[s->k], val[X_ATOM], alter);
1060 register struct stmt *s;
1061 register struct stmt *last[];
1067 if (atom == AX_ATOM) {
1078 last[atom]->code = NOP;
1086 register struct block *b;
1088 register struct slist *s;
1090 struct stmt *last[N_ATOMS];
1092 memset((char *)last, 0, sizeof last);
1094 for (s = b->stmts; s != 0; s = s->next)
1095 deadstmt(&s->s, last);
1096 deadstmt(&b->s, last);
1098 for (atom = 0; atom < N_ATOMS; ++atom)
1099 if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1100 last[atom]->code = NOP;
1106 opt_blk(b, do_stmts)
1116 for (s = b->stmts; s && s->next; s = s->next)
1117 if (BPF_CLASS(s->s.code) == BPF_JMP) {
1124 * Initialize the atom values.
1125 * If we have no predecessors, everything is undefined.
1126 * Otherwise, we inherent our values from our predecessors.
1127 * If any register has an ambiguous value (i.e. control paths are
1128 * merging) give it the undefined value of 0.
1132 memset((char *)b->val, 0, sizeof(b->val));
1134 memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1135 while ((p = p->next) != NULL) {
1136 for (i = 0; i < N_ATOMS; ++i)
1137 if (b->val[i] != p->pred->val[i])
1141 aval = b->val[A_ATOM];
1142 for (s = b->stmts; s; s = s->next)
1143 opt_stmt(&s->s, b->val, do_stmts);
1146 * This is a special case: if we don't use anything from this
1147 * block, and we load the accumulator with value that is
1148 * already there, or if this block is a return,
1149 * eliminate all the statements.
1152 ((b->out_use == 0 && aval != 0 &&b->val[A_ATOM] == aval) ||
1153 BPF_CLASS(b->s.code) == BPF_RET)) {
1154 if (b->stmts != 0) {
1163 * Set up values for branch optimizer.
1165 if (BPF_SRC(b->s.code) == BPF_K)
1166 b->oval = K(b->s.k);
1168 b->oval = b->val[X_ATOM];
1169 b->et.code = b->s.code;
1170 b->ef.code = -b->s.code;
1174 * Return true if any register that is used on exit from 'succ', has
1175 * an exit value that is different from the corresponding exit value
1179 use_conflict(b, succ)
1180 struct block *b, *succ;
1183 atomset use = succ->out_use;
1188 for (atom = 0; atom < N_ATOMS; ++atom)
1189 if (ATOMELEM(use, atom))
1190 if (b->val[atom] != succ->val[atom])
1195 static struct block *
1196 fold_edge(child, ep)
1197 struct block *child;
1201 int aval0, aval1, oval0, oval1;
1202 int code = ep->code;
1210 if (child->s.code != code)
1213 aval0 = child->val[A_ATOM];
1214 oval0 = child->oval;
1215 aval1 = ep->pred->val[A_ATOM];
1216 oval1 = ep->pred->oval;
1223 * The operands are identical, so the
1224 * result is true if a true branch was
1225 * taken to get here, otherwise false.
1227 return sense ? JT(child) : JF(child);
1229 if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1231 * At this point, we only know the comparison if we
1232 * came down the true branch, and it was an equality
1233 * comparison with a constant. We rely on the fact that
1234 * distinct constants have distinct value numbers.
1246 register struct block *target;
1248 if (JT(ep->succ) == 0)
1251 if (JT(ep->succ) == JF(ep->succ)) {
1253 * Common branch targets can be eliminated, provided
1254 * there is no data dependency.
1256 if (!use_conflict(ep->pred, ep->succ->et.succ)) {
1258 ep->succ = JT(ep->succ);
1262 * For each edge dominator that matches the successor of this
1263 * edge, promote the edge successor to the its grandchild.
1265 * XXX We violate the set abstraction here in favor a reasonably
1269 for (i = 0; i < edgewords; ++i) {
1270 register bpf_u_int32 x = ep->edom[i];
1275 k += i * BITS_PER_WORD;
1277 target = fold_edge(ep->succ, edges[k]);
1279 * Check that there is no data dependency between
1280 * nodes that will be violated if we move the edge.
1282 if (target != 0 && !use_conflict(ep->pred, target)) {
1285 if (JT(target) != 0)
1287 * Start over unless we hit a leaf.
1303 struct block **diffp, **samep;
1311 * Make sure each predecessor loads the same value.
1314 val = ep->pred->val[A_ATOM];
1315 for (ep = ep->next; ep != 0; ep = ep->next)
1316 if (val != ep->pred->val[A_ATOM])
1319 if (JT(b->in_edges->pred) == b)
1320 diffp = &JT(b->in_edges->pred);
1322 diffp = &JF(b->in_edges->pred);
1329 if (JT(*diffp) != JT(b))
1332 if (!SET_MEMBER((*diffp)->dom, b->id))
1335 if ((*diffp)->val[A_ATOM] != val)
1338 diffp = &JF(*diffp);
1341 samep = &JF(*diffp);
1346 if (JT(*samep) != JT(b))
1349 if (!SET_MEMBER((*samep)->dom, b->id))
1352 if ((*samep)->val[A_ATOM] == val)
1355 /* XXX Need to check that there are no data dependencies
1356 between dp0 and dp1. Currently, the code generator
1357 will not produce such dependencies. */
1358 samep = &JF(*samep);
1361 /* XXX This doesn't cover everything. */
1362 for (i = 0; i < N_ATOMS; ++i)
1363 if ((*samep)->val[i] != pred->val[i])
1366 /* Pull up the node. */
1372 * At the top of the chain, each predecessor needs to point at the
1373 * pulled up node. Inside the chain, there is only one predecessor
1377 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1378 if (JT(ep->pred) == b)
1379 JT(ep->pred) = pull;
1381 JF(ep->pred) = pull;
1396 struct block **diffp, **samep;
1404 * Make sure each predecessor loads the same value.
1406 val = ep->pred->val[A_ATOM];
1407 for (ep = ep->next; ep != 0; ep = ep->next)
1408 if (val != ep->pred->val[A_ATOM])
1411 if (JT(b->in_edges->pred) == b)
1412 diffp = &JT(b->in_edges->pred);
1414 diffp = &JF(b->in_edges->pred);
1421 if (JF(*diffp) != JF(b))
1424 if (!SET_MEMBER((*diffp)->dom, b->id))
1427 if ((*diffp)->val[A_ATOM] != val)
1430 diffp = &JT(*diffp);
1433 samep = &JT(*diffp);
1438 if (JF(*samep) != JF(b))
1441 if (!SET_MEMBER((*samep)->dom, b->id))
1444 if ((*samep)->val[A_ATOM] == val)
1447 /* XXX Need to check that there are no data dependencies
1448 between diffp and samep. Currently, the code generator
1449 will not produce such dependencies. */
1450 samep = &JT(*samep);
1453 /* XXX This doesn't cover everything. */
1454 for (i = 0; i < N_ATOMS; ++i)
1455 if ((*samep)->val[i] != pred->val[i])
1458 /* Pull up the node. */
1464 * At the top of the chain, each predecessor needs to point at the
1465 * pulled up node. Inside the chain, there is only one predecessor
1469 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1470 if (JT(ep->pred) == b)
1471 JT(ep->pred) = pull;
1473 JF(ep->pred) = pull;
1483 opt_blks(root, do_stmts)
1491 maxlevel = root->level;
1494 for (i = maxlevel; i >= 0; --i)
1495 for (p = levels[i]; p; p = p->link)
1496 opt_blk(p, do_stmts);
1500 * No point trying to move branches; it can't possibly
1501 * make a difference at this point.
1505 for (i = 1; i <= maxlevel; ++i) {
1506 for (p = levels[i]; p; p = p->link) {
1513 for (i = 1; i <= maxlevel; ++i) {
1514 for (p = levels[i]; p; p = p->link) {
1522 link_inedge(parent, child)
1523 struct edge *parent;
1524 struct block *child;
1526 parent->next = child->in_edges;
1527 child->in_edges = parent;
1537 for (i = 0; i < n_blocks; ++i)
1538 blocks[i]->in_edges = 0;
1541 * Traverse the graph, adding each edge to the predecessor
1542 * list of its successors. Skip the leaves (i.e. level 0).
1544 for (i = root->level; i > 0; --i) {
1545 for (b = levels[i]; b != 0; b = b->link) {
1546 link_inedge(&b->et, JT(b));
1547 link_inedge(&b->ef, JF(b));
1556 struct slist *tmp, *s;
1560 while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
1569 * If the root node is a return, then there is no
1570 * point executing any statements (since the bpf machine
1571 * has no side effects).
1573 if (BPF_CLASS((*b)->s.code) == BPF_RET)
1578 opt_loop(root, do_stmts)
1585 printf("opt_loop(root, %d) begin\n", do_stmts);
1596 opt_blks(root, do_stmts);
1599 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts, done);
1607 * Optimize the filter code in its dag representation.
1611 struct block **rootp;
1620 intern_blocks(root);
1623 printf("after intern_blocks()\n");
1630 printf("after opt_root()\n");
1643 if (BPF_CLASS(p->s.code) != BPF_RET) {
1651 * Mark code array such that isMarked(i) is true
1652 * only for nodes that are alive.
1663 * True iff the two stmt lists load the same value from the packet into
1668 struct slist *x, *y;
1671 while (x && x->s.code == NOP)
1673 while (y && y->s.code == NOP)
1679 if (x->s.code != y->s.code || x->s.k != y->s.k)
1688 struct block *b0, *b1;
1690 if (b0->s.code == b1->s.code &&
1691 b0->s.k == b1->s.k &&
1692 b0->et.succ == b1->et.succ &&
1693 b0->ef.succ == b1->ef.succ)
1694 return eq_slist(b0->stmts, b1->stmts);
1707 for (i = 0; i < n_blocks; ++i)
1708 blocks[i]->link = 0;
1712 for (i = n_blocks - 1; --i >= 0; ) {
1713 if (!isMarked(blocks[i]))
1715 for (j = i + 1; j < n_blocks; ++j) {
1716 if (!isMarked(blocks[j]))
1718 if (eq_blk(blocks[i], blocks[j])) {
1719 blocks[i]->link = blocks[j]->link ?
1720 blocks[j]->link : blocks[j];
1725 for (i = 0; i < n_blocks; ++i) {
1731 JT(p) = JT(p)->link;
1735 JF(p) = JF(p)->link;
1745 free((void *)vnode_base);
1747 free((void *)edges);
1748 free((void *)space);
1749 free((void *)levels);
1750 free((void *)blocks);
1754 * Return the number of stmts in 's'.
1762 for (; s; s = s->next)
1763 if (s->s.code != NOP)
1769 * Return the number of nodes reachable by 'p'.
1770 * All nodes should be initially unmarked.
1776 if (p == 0 || isMarked(p))
1779 return count_blocks(JT(p)) + count_blocks(JF(p)) + 1;
1783 * Do a depth first search on the flow graph, numbering the
1784 * the basic blocks, and entering them into the 'blocks' array.`
1792 if (p == 0 || isMarked(p))
1800 number_blks_r(JT(p));
1801 number_blks_r(JF(p));
1805 * Return the number of stmts in the flowgraph reachable by 'p'.
1806 * The nodes should be unmarked before calling.
1808 * Note that "stmts" means "instructions", and that this includes
1810 * side-effect statements in 'p' (slength(p->stmts));
1812 * statements in the true branch from 'p' (count_stmts(JT(p)));
1814 * statements in the false branch from 'p' (count_stmts(JF(p)));
1816 * the conditional jump itself (1);
1818 * an extra long jump if the true branch requires it (p->longjt);
1820 * an extra long jump if the false branch requires it (p->longjf).
1828 if (p == 0 || isMarked(p))
1831 n = count_stmts(JT(p)) + count_stmts(JF(p));
1832 return slength(p->stmts) + n + 1 + p->longjt + p->longjf;
1836 * Allocate memory. All allocation is done before optimization
1837 * is begun. A linear bound on the size of all data structures is computed
1838 * from the total number of blocks and/or statements.
1845 int i, n, max_stmts;
1848 * First, count the blocks, so we can malloc an array to map
1849 * block number to block. Then, put the blocks into the array.
1852 n = count_blocks(root);
1853 blocks = (struct block **)malloc(n * sizeof(*blocks));
1856 number_blks_r(root);
1858 n_edges = 2 * n_blocks;
1859 edges = (struct edge **)malloc(n_edges * sizeof(*edges));
1862 * The number of levels is bounded by the number of nodes.
1864 levels = (struct block **)malloc(n_blocks * sizeof(*levels));
1866 edgewords = n_edges / (8 * sizeof(bpf_u_int32)) + 1;
1867 nodewords = n_blocks / (8 * sizeof(bpf_u_int32)) + 1;
1870 space = (bpf_u_int32 *)malloc(2 * n_blocks * nodewords * sizeof(*space)
1871 + n_edges * edgewords * sizeof(*space));
1874 for (i = 0; i < n; ++i) {
1878 all_closure_sets = p;
1879 for (i = 0; i < n; ++i) {
1880 blocks[i]->closure = p;
1884 for (i = 0; i < n; ++i) {
1885 register struct block *b = blocks[i];
1893 b->ef.id = n_blocks + i;
1894 edges[n_blocks + i] = &b->ef;
1899 for (i = 0; i < n; ++i)
1900 max_stmts += slength(blocks[i]->stmts) + 1;
1902 * We allocate at most 3 value numbers per statement,
1903 * so this is an upper bound on the number of valnodes
1906 maxval = 3 * max_stmts;
1907 vmap = (struct vmapinfo *)malloc(maxval * sizeof(*vmap));
1908 vnode_base = (struct valnode *)malloc(maxval * sizeof(*vnode_base));
1912 * Some pointers used to convert the basic block form of the code,
1913 * into the array form that BPF requires. 'fstart' will point to
1914 * the malloc'd array while 'ftail' is used during the recursive traversal.
1916 static struct bpf_insn *fstart;
1917 static struct bpf_insn *ftail;
1924 * Returns true if successful. Returns false if a branch has
1925 * an offset that is too large. If so, we have marked that
1926 * branch so that on a subsequent iteration, it will be treated
1933 struct bpf_insn *dst;
1937 int extrajmps; /* number of extra jumps inserted */
1938 struct slist **offset = NULL;
1940 if (p == 0 || isMarked(p))
1944 if (convert_code_r(JF(p)) == 0)
1946 if (convert_code_r(JT(p)) == 0)
1949 slen = slength(p->stmts);
1950 dst = ftail -= (slen + 1 + p->longjt + p->longjf);
1951 /* inflate length by any extra jumps */
1953 p->offset = dst - fstart;
1955 /* generate offset[] for convenience */
1957 offset = (struct slist **)calloc(sizeof(struct slist *), slen);
1959 bpf_error("not enough core");
1964 for (off = 0; off < slen && src; off++) {
1966 printf("off=%d src=%x\n", off, src);
1973 for (src = p->stmts; src; src = src->next) {
1974 if (src->s.code == NOP)
1976 dst->code = (u_short)src->s.code;
1979 /* fill block-local relative jump */
1980 if (BPF_CLASS(src->s.code) != BPF_JMP || src->s.code == (BPF_JMP|BPF_JA)) {
1982 if (src->s.jt || src->s.jf) {
1983 bpf_error("illegal jmp destination");
1989 if (off == slen - 2) /*???*/
1995 char *ljerr = "%s for block-local relative jump: off=%d";
1998 printf("code=%x off=%d %x %x\n", src->s.code,
1999 off, src->s.jt, src->s.jf);
2002 if (!src->s.jt || !src->s.jf) {
2003 bpf_error(ljerr, "no jmp destination", off);
2008 for (i = 0; i < slen; i++) {
2009 if (offset[i] == src->s.jt) {
2011 bpf_error(ljerr, "multiple matches", off);
2015 dst->jt = i - off - 1;
2018 if (offset[i] == src->s.jf) {
2020 bpf_error(ljerr, "multiple matches", off);
2023 dst->jf = i - off - 1;
2028 bpf_error(ljerr, "no destination found", off);
2040 bids[dst - fstart] = p->id + 1;
2042 dst->code = (u_short)p->s.code;
2046 off = JT(p)->offset - (p->offset + slen) - 1;
2048 /* offset too large for branch, must add a jump */
2049 if (p->longjt == 0) {
2050 /* mark this instruction and retry */
2054 /* branch if T to following jump */
2055 dst->jt = extrajmps;
2057 dst[extrajmps].code = BPF_JMP|BPF_JA;
2058 dst[extrajmps].k = off - extrajmps;
2062 off = JF(p)->offset - (p->offset + slen) - 1;
2064 /* offset too large for branch, must add a jump */
2065 if (p->longjf == 0) {
2066 /* mark this instruction and retry */
2070 /* branch if F to following jump */
2071 /* if two jumps are inserted, F goes to second one */
2072 dst->jf = extrajmps;
2074 dst[extrajmps].code = BPF_JMP|BPF_JA;
2075 dst[extrajmps].k = off - extrajmps;
2085 * Convert flowgraph intermediate representation to the
2086 * BPF array representation. Set *lenp to the number of instructions.
2089 icode_to_fcode(root, lenp)
2094 struct bpf_insn *fp;
2097 * Loop doing convert_code_r() until no branches remain
2098 * with too-large offsets.
2102 n = *lenp = count_stmts(root);
2104 fp = (struct bpf_insn *)malloc(sizeof(*fp) * n);
2105 memset((char *)fp, 0, sizeof(*fp) * n);
2110 if (convert_code_r(root))
2119 * Make a copy of a BPF program and put it in the "fcode" member of
2122 * If we fail to allocate memory for the copy, fill in the "errbuf"
2123 * member of the "pcap_t" with an error message, and return -1;
2124 * otherwise, return 0.
2127 install_bpf_program(pcap_t *p, struct bpf_program *fp)
2132 * Free up any already installed program.
2134 pcap_freecode(&p->fcode);
2136 prog_size = sizeof(*fp->bf_insns) * fp->bf_len;
2137 p->fcode.bf_len = fp->bf_len;
2138 p->fcode.bf_insns = (struct bpf_insn *)malloc(prog_size);
2139 if (p->fcode.bf_insns == NULL) {
2140 snprintf(p->errbuf, sizeof(p->errbuf),
2141 "malloc: %s", pcap_strerror(errno));
2144 memcpy(p->fcode.bf_insns, fp->bf_insns, prog_size);
2153 struct bpf_program f;
2155 memset(bids, 0, sizeof bids);
2156 f.bf_insns = icode_to_fcode(root, &f.bf_len);
2159 free((char *)f.bf_insns);