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