forked from the-tcpdump-group/libpcap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimize.c
2686 lines (2405 loc) · 63.1 KB
/
optimize.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Optimization module for BPF code intermediate representation.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <pcap-types.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <setjmp.h>
#include <string.h>
#include <errno.h>
#include "pcap-int.h"
#include "gencode.h"
#include "optimize.h"
#ifdef HAVE_OS_PROTO_H
#include "os-proto.h"
#endif
#ifdef BDEBUG
/*
* The internal "debug printout" flag for the filter expression optimizer.
* The code to print that stuff is present only if BDEBUG is defined, so
* the flag, and the routine to set it, are defined only if BDEBUG is
* defined.
*/
static int pcap_optimizer_debug;
/*
* Routine to set that flag.
*
* This is intended for libpcap developers, not for general use.
* If you want to set these in a program, you'll have to declare this
* routine yourself, with the appropriate DLL import attribute on Windows;
* it's not declared in any header file, and won't be declared in any
* header file provided by libpcap.
*/
PCAP_API void pcap_set_optimizer_debug(int value);
PCAP_API_DEF void
pcap_set_optimizer_debug(int value)
{
pcap_optimizer_debug = value;
}
/*
* The internal "print dot graph" flag for the filter expression optimizer.
* The code to print that stuff is present only if BDEBUG is defined, so
* the flag, and the routine to set it, are defined only if BDEBUG is
* defined.
*/
static int pcap_print_dot_graph;
/*
* Routine to set that flag.
*
* This is intended for libpcap developers, not for general use.
* If you want to set these in a program, you'll have to declare this
* routine yourself, with the appropriate DLL import attribute on Windows;
* it's not declared in any header file, and won't be declared in any
* header file provided by libpcap.
*/
PCAP_API void pcap_set_print_dot_graph(int value);
PCAP_API_DEF void
pcap_set_print_dot_graph(int value)
{
pcap_print_dot_graph = value;
}
#endif
/*
* lowest_set_bit().
*
* Takes a 32-bit integer as an argument.
*
* If handed a non-zero value, returns the index of the lowest set bit,
* counting upwards fro zero.
*
* If handed zero, the results are platform- and compiler-dependent.
* Keep it out of the light, don't give it any water, don't feed it
* after midnight, and don't pass zero to it.
*
* This is the same as the count of trailing zeroes in the word.
*/
#if PCAP_IS_AT_LEAST_GNUC_VERSION(3,4)
/*
* GCC 3.4 and later; we have __builtin_ctz().
*/
#define lowest_set_bit(mask) __builtin_ctz(mask)
#elif defined(_MSC_VER)
/*
* Visual Studio; we support only 2005 and later, so use
* _BitScanForward().
*/
#include <intrin.h>
#ifndef __clang__
#pragma intrinsic(_BitScanForward)
#endif
static __forceinline int
lowest_set_bit(int mask)
{
unsigned long bit;
/*
* Don't sign-extend mask if long is longer than int.
* (It's currently not, in MSVC, even on 64-bit platforms, but....)
*/
if (_BitScanForward(&bit, (unsigned int)mask) == 0)
return -1; /* mask is zero */
return (int)bit;
}
#elif defined(MSDOS) && defined(__DJGPP__)
/*
* MS-DOS with DJGPP, which declares ffs() in <string.h>, which
* we've already included.
*/
#define lowest_set_bit(mask) (ffs((mask)) - 1)
#elif (defined(MSDOS) && defined(__WATCOMC__)) || defined(STRINGS_H_DECLARES_FFS)
/*
* MS-DOS with Watcom C, which has <strings.h> and declares ffs() there,
* or some other platform (UN*X conforming to a sufficient recent version
* of the Single UNIX Specification).
*/
#include <strings.h>
#define lowest_set_bit(mask) (ffs((mask)) - 1)
#else
/*
* None of the above.
* Use a perfect-hash-function-based function.
*/
static int
lowest_set_bit(int mask)
{
unsigned int v = (unsigned int)mask;
static const int MultiplyDeBruijnBitPosition[32] = {
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
/*
* We strip off all but the lowermost set bit (v & ~v),
* and perform a minimal perfect hash on it to look up the
* number of low-order zero bits in a table.
*
* See:
*
* http://7ooo.mooo.com/text/ComputingTrailingZerosHOWTO.pdf
*
* http://supertech.csail.mit.edu/papers/debruijn.pdf
*/
return (MultiplyDeBruijnBitPosition[((v & -v) * 0x077CB531U) >> 27]);
}
#endif
/*
* Represents a deleted instruction.
*/
#define NOP -1
/*
* Register numbers for use-def values.
* 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
* location. A_ATOM is the accumulator and X_ATOM is the index
* register.
*/
#define A_ATOM BPF_MEMWORDS
#define X_ATOM (BPF_MEMWORDS+1)
/*
* This define is used to represent *both* the accumulator and
* x register in use-def computations.
* Currently, the use-def code assumes only one definition per instruction.
*/
#define AX_ATOM N_ATOMS
/*
* These data structures are used in a Cocke and Shwarz style
* value numbering scheme. Since the flowgraph is acyclic,
* exit values can be propagated from a node's predecessors
* provided it is uniquely defined.
*/
struct valnode {
int code;
bpf_u_int32 v0, v1;
int val; /* the value number */
struct valnode *next;
};
/* Integer constants mapped with the load immediate opcode. */
#define K(i) F(opt_state, BPF_LD|BPF_IMM|BPF_W, i, 0U)
struct vmapinfo {
int is_const;
bpf_u_int32 const_val;
};
typedef struct {
/*
* Place to longjmp to on an error.
*/
jmp_buf top_ctx;
/*
* The buffer into which to put error message.
*/
char *errbuf;
/*
* A flag to indicate that further optimization is needed.
* Iterative passes are continued until a given pass yields no
* branch movement.
*/
int done;
int n_blocks;
struct block **blocks;
int n_edges;
struct edge **edges;
/*
* A bit vector set representation of the dominators.
* We round up the set size to the next power of two.
*/
int nodewords;
int edgewords;
struct block **levels;
bpf_u_int32 *space;
#define BITS_PER_WORD (8*sizeof(bpf_u_int32))
/*
* True if a is in uset {p}
*/
#define SET_MEMBER(p, a) \
((p)[(unsigned)(a) / BITS_PER_WORD] & ((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD)))
/*
* Add 'a' to uset p.
*/
#define SET_INSERT(p, a) \
(p)[(unsigned)(a) / BITS_PER_WORD] |= ((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD))
/*
* Delete 'a' from uset p.
*/
#define SET_DELETE(p, a) \
(p)[(unsigned)(a) / BITS_PER_WORD] &= ~((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD))
/*
* a := a intersect b
*/
#define SET_INTERSECT(a, b, n)\
{\
register bpf_u_int32 *_x = a, *_y = b;\
register int _n = n;\
while (--_n >= 0) *_x++ &= *_y++;\
}
/*
* a := a - b
*/
#define SET_SUBTRACT(a, b, n)\
{\
register bpf_u_int32 *_x = a, *_y = b;\
register int _n = n;\
while (--_n >= 0) *_x++ &=~ *_y++;\
}
/*
* a := a union b
*/
#define SET_UNION(a, b, n)\
{\
register bpf_u_int32 *_x = a, *_y = b;\
register int _n = n;\
while (--_n >= 0) *_x++ |= *_y++;\
}
uset all_dom_sets;
uset all_closure_sets;
uset all_edge_sets;
#define MODULUS 213
struct valnode *hashtbl[MODULUS];
bpf_u_int32 curval;
bpf_u_int32 maxval;
struct vmapinfo *vmap;
struct valnode *vnode_base;
struct valnode *next_vnode;
} opt_state_t;
typedef struct {
/*
* Place to longjmp to on an error.
*/
jmp_buf top_ctx;
/*
* The buffer into which to put error message.
*/
char *errbuf;
/*
* Some pointers used to convert the basic block form of the code,
* into the array form that BPF requires. 'fstart' will point to
* the malloc'd array while 'ftail' is used during the recursive
* traversal.
*/
struct bpf_insn *fstart;
struct bpf_insn *ftail;
} conv_state_t;
static void opt_init(opt_state_t *, struct icode *);
static void opt_cleanup(opt_state_t *);
static void PCAP_NORETURN opt_error(opt_state_t *, const char *, ...)
PCAP_PRINTFLIKE(2, 3);
static void intern_blocks(opt_state_t *, struct icode *);
static void find_inedges(opt_state_t *, struct block *);
#ifdef BDEBUG
static void opt_dump(opt_state_t *, struct icode *);
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
static void
find_levels_r(opt_state_t *opt_state, struct icode *ic, struct block *b)
{
int level;
if (isMarked(ic, b))
return;
Mark(ic, b);
b->link = 0;
if (JT(b)) {
find_levels_r(opt_state, ic, JT(b));
find_levels_r(opt_state, ic, JF(b));
level = MAX(JT(b)->level, JF(b)->level) + 1;
} else
level = 0;
b->level = level;
b->link = opt_state->levels[level];
opt_state->levels[level] = b;
}
/*
* Level graph. The levels go from 0 at the leaves to
* N_LEVELS at the root. The opt_state->levels[] array points to the
* first node of the level list, whose elements are linked
* with the 'link' field of the struct block.
*/
static void
find_levels(opt_state_t *opt_state, struct icode *ic)
{
memset((char *)opt_state->levels, 0, opt_state->n_blocks * sizeof(*opt_state->levels));
unMarkAll(ic);
find_levels_r(opt_state, ic, ic->root);
}
/*
* Find dominator relationships.
* Assumes graph has been leveled.
*/
static void
find_dom(opt_state_t *opt_state, struct block *root)
{
int i;
struct block *b;
bpf_u_int32 *x;
/*
* Initialize sets to contain all nodes.
*/
x = opt_state->all_dom_sets;
i = opt_state->n_blocks * opt_state->nodewords;
while (--i >= 0)
*x++ = 0xFFFFFFFFU;
/* Root starts off empty. */
for (i = opt_state->nodewords; --i >= 0;)
root->dom[i] = 0;
/* root->level is the highest level no found. */
for (i = root->level; i >= 0; --i) {
for (b = opt_state->levels[i]; b; b = b->link) {
SET_INSERT(b->dom, b->id);
if (JT(b) == 0)
continue;
SET_INTERSECT(JT(b)->dom, b->dom, opt_state->nodewords);
SET_INTERSECT(JF(b)->dom, b->dom, opt_state->nodewords);
}
}
}
static void
propedom(opt_state_t *opt_state, struct edge *ep)
{
SET_INSERT(ep->edom, ep->id);
if (ep->succ) {
SET_INTERSECT(ep->succ->et.edom, ep->edom, opt_state->edgewords);
SET_INTERSECT(ep->succ->ef.edom, ep->edom, opt_state->edgewords);
}
}
/*
* Compute edge dominators.
* Assumes graph has been leveled and predecessors established.
*/
static void
find_edom(opt_state_t *opt_state, struct block *root)
{
int i;
uset x;
struct block *b;
x = opt_state->all_edge_sets;
for (i = opt_state->n_edges * opt_state->edgewords; --i >= 0; )
x[i] = 0xFFFFFFFFU;
/* root->level is the highest level no found. */
memset(root->et.edom, 0, opt_state->edgewords * sizeof(*(uset)0));
memset(root->ef.edom, 0, opt_state->edgewords * sizeof(*(uset)0));
for (i = root->level; i >= 0; --i) {
for (b = opt_state->levels[i]; b != 0; b = b->link) {
propedom(opt_state, &b->et);
propedom(opt_state, &b->ef);
}
}
}
/*
* Find the backwards transitive closure of the flow graph. These sets
* are backwards in the sense that we find the set of nodes that reach
* a given node, not the set of nodes that can be reached by a node.
*
* Assumes graph has been leveled.
*/
static void
find_closure(opt_state_t *opt_state, struct block *root)
{
int i;
struct block *b;
/*
* Initialize sets to contain no nodes.
*/
memset((char *)opt_state->all_closure_sets, 0,
opt_state->n_blocks * opt_state->nodewords * sizeof(*opt_state->all_closure_sets));
/* root->level is the highest level no found. */
for (i = root->level; i >= 0; --i) {
for (b = opt_state->levels[i]; b; b = b->link) {
SET_INSERT(b->closure, b->id);
if (JT(b) == 0)
continue;
SET_UNION(JT(b)->closure, b->closure, opt_state->nodewords);
SET_UNION(JF(b)->closure, b->closure, opt_state->nodewords);
}
}
}
/*
* Return the register number that is used by s.
*
* Returns ATOM_A if A is used, ATOM_X if X is used, AX_ATOM if both A and X
* are used, the scratch memory location's number if a scratch memory
* location is used (e.g., 0 for M[0]), or -1 if none of those are used.
*
* The implementation should probably change to an array access.
*/
static int
atomuse(struct stmt *s)
{
register int c = s->code;
if (c == NOP)
return -1;
switch (BPF_CLASS(c)) {
case BPF_RET:
return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
(BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
case BPF_LD:
case BPF_LDX:
/*
* As there are fewer than 2^31 memory locations,
* s->k should be convertable to int without problems.
*/
return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
(BPF_MODE(c) == BPF_MEM) ? (int)s->k : -1;
case BPF_ST:
return A_ATOM;
case BPF_STX:
return X_ATOM;
case BPF_JMP:
case BPF_ALU:
if (BPF_SRC(c) == BPF_X)
return AX_ATOM;
return A_ATOM;
case BPF_MISC:
return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
}
abort();
/* NOTREACHED */
}
/*
* Return the register number that is defined by 's'. We assume that
* a single stmt cannot define more than one register. If no register
* is defined, return -1.
*
* The implementation should probably change to an array access.
*/
static int
atomdef(struct stmt *s)
{
if (s->code == NOP)
return -1;
switch (BPF_CLASS(s->code)) {
case BPF_LD:
case BPF_ALU:
return A_ATOM;
case BPF_LDX:
return X_ATOM;
case BPF_ST:
case BPF_STX:
return s->k;
case BPF_MISC:
return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
}
return -1;
}
/*
* Compute the sets of registers used, defined, and killed by 'b'.
*
* "Used" means that a statement in 'b' uses the register before any
* statement in 'b' defines it, i.e. it uses the value left in
* that register by a predecessor block of this block.
* "Defined" means that a statement in 'b' defines it.
* "Killed" means that a statement in 'b' defines it before any
* statement in 'b' uses it, i.e. it kills the value left in that
* register by a predecessor block of this block.
*/
static void
compute_local_ud(struct block *b)
{
struct slist *s;
atomset def = 0, use = 0, killed = 0;
int atom;
for (s = b->stmts; s; s = s->next) {
if (s->s.code == NOP)
continue;
atom = atomuse(&s->s);
if (atom >= 0) {
if (atom == AX_ATOM) {
if (!ATOMELEM(def, X_ATOM))
use |= ATOMMASK(X_ATOM);
if (!ATOMELEM(def, A_ATOM))
use |= ATOMMASK(A_ATOM);
}
else if (atom < N_ATOMS) {
if (!ATOMELEM(def, atom))
use |= ATOMMASK(atom);
}
else
abort();
}
atom = atomdef(&s->s);
if (atom >= 0) {
if (!ATOMELEM(use, atom))
killed |= ATOMMASK(atom);
def |= ATOMMASK(atom);
}
}
if (BPF_CLASS(b->s.code) == BPF_JMP) {
/*
* XXX - what about RET?
*/
atom = atomuse(&b->s);
if (atom >= 0) {
if (atom == AX_ATOM) {
if (!ATOMELEM(def, X_ATOM))
use |= ATOMMASK(X_ATOM);
if (!ATOMELEM(def, A_ATOM))
use |= ATOMMASK(A_ATOM);
}
else if (atom < N_ATOMS) {
if (!ATOMELEM(def, atom))
use |= ATOMMASK(atom);
}
else
abort();
}
}
b->def = def;
b->kill = killed;
b->in_use = use;
}
/*
* Assume graph is already leveled.
*/
static void
find_ud(opt_state_t *opt_state, struct block *root)
{
int i, maxlevel;
struct block *p;
/*
* root->level is the highest level no found;
* count down from there.
*/
maxlevel = root->level;
for (i = maxlevel; i >= 0; --i)
for (p = opt_state->levels[i]; p; p = p->link) {
compute_local_ud(p);
p->out_use = 0;
}
for (i = 1; i <= maxlevel; ++i) {
for (p = opt_state->levels[i]; p; p = p->link) {
p->out_use |= JT(p)->in_use | JF(p)->in_use;
p->in_use |= p->out_use &~ p->kill;
}
}
}
static void
init_val(opt_state_t *opt_state)
{
opt_state->curval = 0;
opt_state->next_vnode = opt_state->vnode_base;
memset((char *)opt_state->vmap, 0, opt_state->maxval * sizeof(*opt_state->vmap));
memset((char *)opt_state->hashtbl, 0, sizeof opt_state->hashtbl);
}
/*
* Because we really don't have an IR, this stuff is a little messy.
*
* This routine looks in the table of existing value number for a value
* with generated from an operation with the specified opcode and
* the specified values. If it finds it, it returns its value number,
* otherwise it makes a new entry in the table and returns the
* value number of that entry.
*/
static bpf_u_int32
F(opt_state_t *opt_state, int code, bpf_u_int32 v0, bpf_u_int32 v1)
{
u_int hash;
bpf_u_int32 val;
struct valnode *p;
hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
hash %= MODULUS;
for (p = opt_state->hashtbl[hash]; p; p = p->next)
if (p->code == code && p->v0 == v0 && p->v1 == v1)
return p->val;
/*
* Not found. Allocate a new value, and assign it a new
* value number.
*
* opt_state->curval starts out as 0, which means VAL_UNKNOWN; we
* increment it before using it as the new value number, which
* means we never assign VAL_UNKNOWN.
*
* XXX - unless we overflow, but we probably won't have 2^32-1
* values; we treat 32 bits as effectively infinite.
*/
val = ++opt_state->curval;
if (BPF_MODE(code) == BPF_IMM &&
(BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
opt_state->vmap[val].const_val = v0;
opt_state->vmap[val].is_const = 1;
}
p = opt_state->next_vnode++;
p->val = val;
p->code = code;
p->v0 = v0;
p->v1 = v1;
p->next = opt_state->hashtbl[hash];
opt_state->hashtbl[hash] = p;
return val;
}
static inline void
vstore(struct stmt *s, bpf_u_int32 *valp, bpf_u_int32 newval, int alter)
{
if (alter && newval != VAL_UNKNOWN && *valp == newval)
s->code = NOP;
else
*valp = newval;
}
/*
* Do constant-folding on binary operators.
* (Unary operators are handled elsewhere.)
*/
static void
fold_op(opt_state_t *opt_state, struct stmt *s, bpf_u_int32 v0, bpf_u_int32 v1)
{
bpf_u_int32 a, b;
a = opt_state->vmap[v0].const_val;
b = opt_state->vmap[v1].const_val;
switch (BPF_OP(s->code)) {
case BPF_ADD:
a += b;
break;
case BPF_SUB:
a -= b;
break;
case BPF_MUL:
a *= b;
break;
case BPF_DIV:
if (b == 0)
opt_error(opt_state, "division by zero");
a /= b;
break;
case BPF_MOD:
if (b == 0)
opt_error(opt_state, "modulus by zero");
a %= b;
break;
case BPF_AND:
a &= b;
break;
case BPF_OR:
a |= b;
break;
case BPF_XOR:
a ^= b;
break;
case BPF_LSH:
/*
* A left shift of more than the width of the type
* is undefined in C; we'll just treat it as shifting
* all the bits out.
*
* XXX - the BPF interpreter doesn't check for this,
* so its behavior is dependent on the behavior of
* the processor on which it's running. There are
* processors on which it shifts all the bits out
* and processors on which it does no shift.
*/
if (b < 32)
a <<= b;
else
a = 0;
break;
case BPF_RSH:
/*
* A right shift of more than the width of the type
* is undefined in C; we'll just treat it as shifting
* all the bits out.
*
* XXX - the BPF interpreter doesn't check for this,
* so its behavior is dependent on the behavior of
* the processor on which it's running. There are
* processors on which it shifts all the bits out
* and processors on which it does no shift.
*/
if (b < 32)
a >>= b;
else
a = 0;
break;
default:
abort();
}
s->k = a;
s->code = BPF_LD|BPF_IMM;
opt_state->done = 0;
}
static inline struct slist *
this_op(struct slist *s)
{
while (s != 0 && s->s.code == NOP)
s = s->next;
return s;
}
static void
opt_not(struct block *b)
{
struct block *tmp = JT(b);
JT(b) = JF(b);
JF(b) = tmp;
}
static void
opt_peep(opt_state_t *opt_state, struct block *b)
{
struct slist *s;
struct slist *next, *last;
bpf_u_int32 val;
s = b->stmts;
if (s == 0)
return;
last = s;
for (/*empty*/; /*empty*/; s = next) {
/*
* Skip over nops.
*/
s = this_op(s);
if (s == 0)
break; /* nothing left in the block */
/*
* Find the next real instruction after that one
* (skipping nops).
*/
next = this_op(s->next);
if (next == 0)
break; /* no next instruction */
last = next;
/*
* st M[k] --> st M[k]
* ldx M[k] tax
*/
if (s->s.code == BPF_ST &&
next->s.code == (BPF_LDX|BPF_MEM) &&
s->s.k == next->s.k) {
opt_state->done = 0;
next->s.code = BPF_MISC|BPF_TAX;
}
/*
* ld #k --> ldx #k
* tax txa
*/
if (s->s.code == (BPF_LD|BPF_IMM) &&
next->s.code == (BPF_MISC|BPF_TAX)) {
s->s.code = BPF_LDX|BPF_IMM;
next->s.code = BPF_MISC|BPF_TXA;
opt_state->done = 0;
}
/*
* This is an ugly special case, but it happens
* when you say tcp[k] or udp[k] where k is a constant.
*/
if (s->s.code == (BPF_LD|BPF_IMM)) {
struct slist *add, *tax, *ild;
/*
* Check that X isn't used on exit from this
* block (which the optimizer might cause).
* We know the code generator won't generate
* any local dependencies.
*/
if (ATOMELEM(b->out_use, X_ATOM))
continue;
/*
* Check that the instruction following the ldi
* is an addx, or it's an ldxms with an addx
* following it (with 0 or more nops between the
* ldxms and addx).
*/
if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
add = next;
else
add = this_op(next->next);
if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
continue;
/*
* Check that a tax follows that (with 0 or more
* nops between them).
*/
tax = this_op(add->next);
if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
continue;
/*
* Check that an ild follows that (with 0 or more
* nops between them).
*/
ild = this_op(tax->next);
if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
BPF_MODE(ild->s.code) != BPF_IND)
continue;
/*
* We want to turn this sequence:
*
* (004) ldi #0x2 {s}
* (005) ldxms [14] {next} -- optional
* (006) addx {add}
* (007) tax {tax}
* (008) ild [x+0] {ild}
*
* into this sequence:
*
* (004) nop
* (005) ldxms [14]
* (006) nop
* (007) nop
* (008) ild [x+2]
*
* XXX We need to check that X is not
* subsequently used, because we want to change
* what'll be in it after this sequence.
*
* We know we can eliminate the accumulator
* modifications earlier in the sequence since
* it is defined by the last stmt of this sequence
* (i.e., the last statement of the sequence loads
* a value into the accumulator, so we can eliminate
* earlier operations on the accumulator).
*/
ild->s.k += s->s.k;
s->s.code = NOP;
add->s.code = NOP;
tax->s.code = NOP;
opt_state->done = 0;
}
}
/*
* If the comparison at the end of a block is an equality
* comparison against a constant, and nobody uses the value
* we leave in the A register at the end of a block, and
* the operation preceding the comparison is an arithmetic
* operation, we can sometime optimize it away.
*/
if (b->s.code == (BPF_JMP|BPF_JEQ|BPF_K) &&
!ATOMELEM(b->out_use, A_ATOM)) {
/*
* We can optimize away certain subtractions of the
* X register.
*/
if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X)) {
val = b->val[X_ATOM];
if (opt_state->vmap[val].is_const) {