/
ir_opt.c
6139 lines (5483 loc) · 203 KB
/
ir_opt.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
/* -*- mode: C; c-basic-offset: 3; -*- */
/*---------------------------------------------------------------*/
/*--- begin ir_opt.c ---*/
/*---------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2004-2013 OpenWorks LLP
info@open-works.net
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
The GNU General Public License is contained in the file COPYING.
Neither the names of the U.S. Department of Energy nor the
University of California nor the names of its contributors may be
used to endorse or promote products derived from this software
without prior written permission.
*/
#include "libvex_basictypes.h"
#include "libvex_ir.h"
#include "libvex.h"
#include "main_util.h"
#include "main_globals.h"
#include "ir_opt.h"
/* Set to 1 for lots of debugging output. */
#define DEBUG_IROPT 0
/* Set to 1 to gather some statistics. Currently only for sameIRExprs. */
#define STATS_IROPT 0
/* What iropt does, 29 Dec 04.
It takes an IRSB and produces a new one with the same meaning,
defined thus:
After execution of the new BB, all guest state and guest memory is
the same as after execution of the original. This is true
regardless of how the block was exited (at the end vs side exit).
In addition, parts of the guest state will be identical to that
created by execution of the original at the following observation
points:
* In a dirty helper call, any parts of the guest state that the
helper states that it reads or modifies will be up to date.
Also, guest memory will be up to date. Parts of the guest state
not marked as being read or modified by the helper cannot be
assumed to be up-to-date at the point where the helper is called.
* If iropt_register_updates == VexRegUpdSpAtMemAccess :
The guest state is only up to date only as explained above
(i.e. at SB exits and as specified by dirty helper call).
Also, the stack pointer register is up to date at memory
exception points (as this is needed for the stack extension
logic in m_signals.c).
* If iropt_register_updates == VexRegUpdUnwindregsAtMemAccess :
Immediately prior to any load or store, those parts of the guest
state marked as requiring precise exceptions will be up to date.
Also, guest memory will be up to date. Parts of the guest state
not marked as requiring precise exceptions cannot be assumed to
be up-to-date at the point of the load/store.
* If iropt_register_updates == VexRegUpdAllregsAtMemAccess:
Same as minimal, but all the guest state is up to date at memory
exception points.
* If iropt_register_updates == VexRegUpdAllregsAtEachInsn :
Guest state is up to date at each instruction.
The relative order of loads and stores (including loads/stores of
guest memory done by dirty helpers annotated as such) is not
changed. However, the relative order of loads with no intervening
stores/modifies may be changed.
Transformation order
~~~~~~~~~~~~~~~~~~~~
There are three levels of optimisation, controlled by
vex_control.iropt_level. Define first:
"Cheap transformations" are the following sequence:
* Redundant-Get removal
* Redundant-Put removal
* Constant propagation/folding
* Dead code removal
* Specialisation of clean helper functions
* Dead code removal
"Expensive transformations" are the following sequence:
* CSE
* Folding of add/sub chains
* Redundant-GetI removal
* Redundant-PutI removal
* Dead code removal
Then the transformations are as follows, as defined by
vex_control.iropt_level:
Level 0:
* Flatten into atomic form.
Level 1: the following sequence:
* Flatten into atomic form.
* Cheap transformations.
Level 2: the following sequence
* Flatten into atomic form.
* Cheap transformations.
* If block contains any floating or vector types, CSE.
* If block contains GetI or PutI, Expensive transformations.
* Try unrolling loops. Three possible outcomes:
- No effect: do nothing more.
- Unrolled a loop, and block does not contain GetI or PutI:
Do: * CSE
* Dead code removal
- Unrolled a loop, and block contains GetI or PutI:
Do: * Expensive transformations
* Cheap transformations
*/
/* Implementation notes, 29 Dec 04.
TODO (important): I think rPutI removal ignores precise exceptions
and is therefore in a sense, wrong. In the sense that PutIs are
assumed not to write parts of the guest state that we need to have
up-to-date at loads/stores. So far on x86 guest that has not
mattered since indeed only the x87 FP registers and tags are
accessed using GetI/PutI, and there is no need so far for them to
be up to date at mem exception points. The rPutI pass should be
fixed.
TODO: improve pessimistic handling of precise exceptions
in the tree builder.
TODO: check interaction of rGetI and dirty helpers.
F64i constants are treated differently from other constants.
They are not regarded as atoms, and instead lifted off and
bound to temps. This allows them to participate in CSE, which
is important for getting good performance for x86 guest code.
CSE up F64 literals (already doing F64is)
CSE: consider carefully the requirement for precise exns
prior to making CSE any more aggressive. */
/*---------------------------------------------------------------*/
/*--- Finite mappery, of a sort ---*/
/*---------------------------------------------------------------*/
/* General map from HWord-sized thing HWord-sized thing. Could be by
hashing, but it's not clear whether or not this would really be any
faster. */
typedef
struct {
Bool* inuse;
HWord* key;
HWord* val;
Int size;
Int used;
}
HashHW;
static HashHW* newHHW ( void )
{
HashHW* h = LibVEX_Alloc(sizeof(HashHW));
h->size = 8;
h->used = 0;
h->inuse = LibVEX_Alloc(h->size * sizeof(Bool));
h->key = LibVEX_Alloc(h->size * sizeof(HWord));
h->val = LibVEX_Alloc(h->size * sizeof(HWord));
return h;
}
/* Look up key in the map. */
static Bool lookupHHW ( HashHW* h, /*OUT*/HWord* val, HWord key )
{
Int i;
/* vex_printf("lookupHHW(%llx)\n", key ); */
for (i = 0; i < h->used; i++) {
if (h->inuse[i] && h->key[i] == key) {
if (val)
*val = h->val[i];
return True;
}
}
return False;
}
/* Add key->val to the map. Replaces any existing binding for key. */
static void addToHHW ( HashHW* h, HWord key, HWord val )
{
Int i, j;
/* vex_printf("addToHHW(%llx, %llx)\n", key, val); */
/* Find and replace existing binding, if any. */
for (i = 0; i < h->used; i++) {
if (h->inuse[i] && h->key[i] == key) {
h->val[i] = val;
return;
}
}
/* Ensure a space is available. */
if (h->used == h->size) {
/* Copy into arrays twice the size. */
Bool* inuse2 = LibVEX_Alloc(2 * h->size * sizeof(Bool));
HWord* key2 = LibVEX_Alloc(2 * h->size * sizeof(HWord));
HWord* val2 = LibVEX_Alloc(2 * h->size * sizeof(HWord));
for (i = j = 0; i < h->size; i++) {
if (!h->inuse[i]) continue;
inuse2[j] = True;
key2[j] = h->key[i];
val2[j] = h->val[i];
j++;
}
h->used = j;
h->size *= 2;
h->inuse = inuse2;
h->key = key2;
h->val = val2;
}
/* Finally, add it. */
vassert(h->used < h->size);
h->inuse[h->used] = True;
h->key[h->used] = key;
h->val[h->used] = val;
h->used++;
}
/*---------------------------------------------------------------*/
/*--- Flattening out a BB into atomic SSA form ---*/
/*---------------------------------------------------------------*/
/* Non-critical helper, heuristic for reducing the number of tmp-tmp
copies made by flattening. If in doubt return False. */
static Bool isFlat ( IRExpr* e )
{
if (e->tag == Iex_Get)
return True;
if (e->tag == Iex_Binop)
return toBool( isIRAtom(e->Iex.Binop.arg1)
&& isIRAtom(e->Iex.Binop.arg2) );
if (e->tag == Iex_Load)
return isIRAtom(e->Iex.Load.addr);
return False;
}
/* Flatten out 'ex' so it is atomic, returning a new expression with
the same value, after having appended extra IRTemp assignments to
the end of 'bb'. */
static IRExpr* flatten_Expr ( IRSB* bb, IRExpr* ex )
{
Int i;
IRExpr** newargs;
IRType ty = typeOfIRExpr(bb->tyenv, ex);
IRTemp t1;
switch (ex->tag) {
case Iex_GetI:
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_GetI(ex->Iex.GetI.descr,
flatten_Expr(bb, ex->Iex.GetI.ix),
ex->Iex.GetI.bias)));
return IRExpr_RdTmp(t1);
case Iex_Get:
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb,
IRStmt_WrTmp(t1, ex));
return IRExpr_RdTmp(t1);
case Iex_Qop: {
IRQop* qop = ex->Iex.Qop.details;
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_Qop(qop->op,
flatten_Expr(bb, qop->arg1),
flatten_Expr(bb, qop->arg2),
flatten_Expr(bb, qop->arg3),
flatten_Expr(bb, qop->arg4))));
return IRExpr_RdTmp(t1);
}
case Iex_Triop: {
IRTriop* triop = ex->Iex.Triop.details;
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_Triop(triop->op,
flatten_Expr(bb, triop->arg1),
flatten_Expr(bb, triop->arg2),
flatten_Expr(bb, triop->arg3))));
return IRExpr_RdTmp(t1);
}
case Iex_Binop:
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_Binop(ex->Iex.Binop.op,
flatten_Expr(bb, ex->Iex.Binop.arg1),
flatten_Expr(bb, ex->Iex.Binop.arg2))));
return IRExpr_RdTmp(t1);
case Iex_Unop:
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_Unop(ex->Iex.Unop.op,
flatten_Expr(bb, ex->Iex.Unop.arg))));
return IRExpr_RdTmp(t1);
case Iex_Load:
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_Load(ex->Iex.Load.end,
ex->Iex.Load.ty,
flatten_Expr(bb, ex->Iex.Load.addr))));
return IRExpr_RdTmp(t1);
case Iex_CCall:
newargs = shallowCopyIRExprVec(ex->Iex.CCall.args);
for (i = 0; newargs[i]; i++)
newargs[i] = flatten_Expr(bb, newargs[i]);
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_CCall(ex->Iex.CCall.cee,
ex->Iex.CCall.retty,
newargs)));
return IRExpr_RdTmp(t1);
case Iex_ITE:
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_ITE(flatten_Expr(bb, ex->Iex.ITE.cond),
flatten_Expr(bb, ex->Iex.ITE.iftrue),
flatten_Expr(bb, ex->Iex.ITE.iffalse))));
return IRExpr_RdTmp(t1);
case Iex_Const:
/* Lift F64i constants out onto temps so they can be CSEd
later. */
if (ex->Iex.Const.con->tag == Ico_F64i) {
t1 = newIRTemp(bb->tyenv, ty);
addStmtToIRSB(bb, IRStmt_WrTmp(t1,
IRExpr_Const(ex->Iex.Const.con)));
return IRExpr_RdTmp(t1);
} else {
/* Leave all other constants alone. */
return ex;
}
case Iex_RdTmp:
return ex;
default:
vex_printf("\n");
ppIRExpr(ex);
vex_printf("\n");
vpanic("flatten_Expr");
}
}
/* Append a completely flattened form of 'st' to the end of 'bb'. */
static void flatten_Stmt ( IRSB* bb, IRStmt* st )
{
Int i;
IRExpr *e1, *e2, *e3, *e4, *e5;
IRDirty *d, *d2;
IRCAS *cas, *cas2;
IRPutI *puti, *puti2;
IRLoadG *lg;
IRStoreG *sg;
switch (st->tag) {
case Ist_Put:
if (isIRAtom(st->Ist.Put.data)) {
/* optimisation to reduce the amount of heap wasted
by the flattener */
addStmtToIRSB(bb, st);
} else {
/* general case, always correct */
e1 = flatten_Expr(bb, st->Ist.Put.data);
addStmtToIRSB(bb, IRStmt_Put(st->Ist.Put.offset, e1));
}
break;
case Ist_PutI:
puti = st->Ist.PutI.details;
e1 = flatten_Expr(bb, puti->ix);
e2 = flatten_Expr(bb, puti->data);
puti2 = mkIRPutI(puti->descr, e1, puti->bias, e2);
addStmtToIRSB(bb, IRStmt_PutI(puti2));
break;
case Ist_WrTmp:
if (isFlat(st->Ist.WrTmp.data)) {
/* optimisation, to reduce the number of tmp-tmp
copies generated */
addStmtToIRSB(bb, st);
} else {
/* general case, always correct */
e1 = flatten_Expr(bb, st->Ist.WrTmp.data);
addStmtToIRSB(bb, IRStmt_WrTmp(st->Ist.WrTmp.tmp, e1));
}
break;
case Ist_Store:
e1 = flatten_Expr(bb, st->Ist.Store.addr);
e2 = flatten_Expr(bb, st->Ist.Store.data);
addStmtToIRSB(bb, IRStmt_Store(st->Ist.Store.end, e1,e2));
break;
case Ist_StoreG:
sg = st->Ist.StoreG.details;
e1 = flatten_Expr(bb, sg->addr);
e2 = flatten_Expr(bb, sg->data);
e3 = flatten_Expr(bb, sg->guard);
addStmtToIRSB(bb, IRStmt_StoreG(sg->end, e1, e2, e3));
break;
case Ist_LoadG:
lg = st->Ist.LoadG.details;
e1 = flatten_Expr(bb, lg->addr);
e2 = flatten_Expr(bb, lg->alt);
e3 = flatten_Expr(bb, lg->guard);
addStmtToIRSB(bb, IRStmt_LoadG(lg->end, lg->cvt, lg->dst,
e1, e2, e3));
break;
case Ist_CAS:
cas = st->Ist.CAS.details;
e1 = flatten_Expr(bb, cas->addr);
e2 = cas->expdHi ? flatten_Expr(bb, cas->expdHi) : NULL;
e3 = flatten_Expr(bb, cas->expdLo);
e4 = cas->dataHi ? flatten_Expr(bb, cas->dataHi) : NULL;
e5 = flatten_Expr(bb, cas->dataLo);
cas2 = mkIRCAS( cas->oldHi, cas->oldLo, cas->end,
e1, e2, e3, e4, e5 );
addStmtToIRSB(bb, IRStmt_CAS(cas2));
break;
case Ist_LLSC:
e1 = flatten_Expr(bb, st->Ist.LLSC.addr);
e2 = st->Ist.LLSC.storedata
? flatten_Expr(bb, st->Ist.LLSC.storedata)
: NULL;
addStmtToIRSB(bb, IRStmt_LLSC(st->Ist.LLSC.end,
st->Ist.LLSC.result, e1, e2));
break;
case Ist_Dirty:
d = st->Ist.Dirty.details;
d2 = emptyIRDirty();
*d2 = *d;
d2->args = shallowCopyIRExprVec(d2->args);
if (d2->mFx != Ifx_None) {
d2->mAddr = flatten_Expr(bb, d2->mAddr);
} else {
vassert(d2->mAddr == NULL);
}
d2->guard = flatten_Expr(bb, d2->guard);
for (i = 0; d2->args[i]; i++) {
IRExpr* arg = d2->args[i];
if (LIKELY(!is_IRExpr_VECRET_or_BBPTR(arg)))
d2->args[i] = flatten_Expr(bb, arg);
}
addStmtToIRSB(bb, IRStmt_Dirty(d2));
break;
case Ist_NoOp:
case Ist_MBE:
case Ist_IMark:
addStmtToIRSB(bb, st);
break;
case Ist_AbiHint:
e1 = flatten_Expr(bb, st->Ist.AbiHint.base);
e2 = flatten_Expr(bb, st->Ist.AbiHint.nia);
addStmtToIRSB(bb, IRStmt_AbiHint(e1, st->Ist.AbiHint.len, e2));
break;
case Ist_Exit:
e1 = flatten_Expr(bb, st->Ist.Exit.guard);
addStmtToIRSB(bb, IRStmt_Exit(e1, st->Ist.Exit.jk,
st->Ist.Exit.dst,
st->Ist.Exit.offsIP));
break;
default:
vex_printf("\n");
ppIRStmt(st);
vex_printf("\n");
vpanic("flatten_Stmt");
}
}
static IRSB* flatten_BB ( IRSB* in )
{
Int i;
IRSB* out;
out = emptyIRSB();
out->tyenv = deepCopyIRTypeEnv( in->tyenv );
for (i = 0; i < in->stmts_used; i++)
if (in->stmts[i])
flatten_Stmt( out, in->stmts[i] );
out->next = flatten_Expr( out, in->next );
out->jumpkind = in->jumpkind;
out->offsIP = in->offsIP;
return out;
}
/*---------------------------------------------------------------*/
/*--- In-place removal of redundant GETs ---*/
/*---------------------------------------------------------------*/
/* Scan forwards, building up an environment binding (min offset, max
offset) pairs to values, which will either be temps or constants.
On seeing 't = Get(minoff,maxoff)', look up (minoff,maxoff) in the
env and if it matches, replace the Get with the stored value. If
there is no match, add a (minoff,maxoff) :-> t binding.
On seeing 'Put (minoff,maxoff) = t or c', first remove in the env
any binding which fully or partially overlaps with (minoff,maxoff).
Then add a new (minoff,maxoff) :-> t or c binding. */
/* Extract the min/max offsets from a guest state array descriptor. */
inline
static void getArrayBounds ( IRRegArray* descr,
UInt* minoff, UInt* maxoff )
{
*minoff = descr->base;
*maxoff = *minoff + descr->nElems*sizeofIRType(descr->elemTy) - 1;
vassert((*minoff & ~0xFFFF) == 0);
vassert((*maxoff & ~0xFFFF) == 0);
vassert(*minoff <= *maxoff);
}
/* Create keys, of the form ((minoffset << 16) | maxoffset). */
static UInt mk_key_GetPut ( Int offset, IRType ty )
{
/* offset should fit in 16 bits. */
UInt minoff = offset;
UInt maxoff = minoff + sizeofIRType(ty) - 1;
vassert((minoff & ~0xFFFF) == 0);
vassert((maxoff & ~0xFFFF) == 0);
return (minoff << 16) | maxoff;
}
static UInt mk_key_GetIPutI ( IRRegArray* descr )
{
UInt minoff, maxoff;
getArrayBounds( descr, &minoff, &maxoff );
vassert((minoff & ~0xFFFF) == 0);
vassert((maxoff & ~0xFFFF) == 0);
return (minoff << 16) | maxoff;
}
/* Supposing h has keys of the form generated by mk_key_GetPut and
mk_key_GetIPutI, invalidate any key which overlaps (k_lo
.. k_hi).
*/
static void invalidateOverlaps ( HashHW* h, UInt k_lo, UInt k_hi )
{
Int j;
UInt e_lo, e_hi;
vassert(k_lo <= k_hi);
/* invalidate any env entries which in any way overlap (k_lo
.. k_hi) */
/* vex_printf("invalidate %d .. %d\n", k_lo, k_hi ); */
for (j = 0; j < h->used; j++) {
if (!h->inuse[j])
continue;
e_lo = (((UInt)h->key[j]) >> 16) & 0xFFFF;
e_hi = ((UInt)h->key[j]) & 0xFFFF;
vassert(e_lo <= e_hi);
if (e_hi < k_lo || k_hi < e_lo)
continue; /* no overlap possible */
else
/* overlap; invalidate */
h->inuse[j] = False;
}
}
static void redundant_get_removal_BB ( IRSB* bb )
{
HashHW* env = newHHW();
UInt key = 0; /* keep gcc -O happy */
Int i, j;
HWord val;
for (i = 0; i < bb->stmts_used; i++) {
IRStmt* st = bb->stmts[i];
if (st->tag == Ist_NoOp)
continue;
/* Deal with Gets */
if (st->tag == Ist_WrTmp
&& st->Ist.WrTmp.data->tag == Iex_Get) {
/* st is 't = Get(...)'. Look up in the environment and see
if the Get can be replaced. */
IRExpr* get = st->Ist.WrTmp.data;
key = (HWord)mk_key_GetPut( get->Iex.Get.offset,
get->Iex.Get.ty );
if (lookupHHW(env, &val, (HWord)key)) {
/* found it */
/* Note, we could do better here. If the types are
different we don't do the substitution, since doing so
could lead to invalidly-typed IR. An improvement would
be to stick in a reinterpret-style cast, although that
would make maintaining flatness more difficult. */
IRExpr* valE = (IRExpr*)val;
Bool typesOK = toBool( typeOfIRExpr(bb->tyenv,valE)
== st->Ist.WrTmp.data->Iex.Get.ty );
if (typesOK && DEBUG_IROPT) {
vex_printf("rGET: "); ppIRExpr(get);
vex_printf(" -> "); ppIRExpr(valE);
vex_printf("\n");
}
if (typesOK)
bb->stmts[i] = IRStmt_WrTmp(st->Ist.WrTmp.tmp, valE);
} else {
/* Not found, but at least we know that t and the Get(...)
are now associated. So add a binding to reflect that
fact. */
addToHHW( env, (HWord)key,
(HWord)(void*)(IRExpr_RdTmp(st->Ist.WrTmp.tmp)) );
}
}
/* Deal with Puts: invalidate any env entries overlapped by this
Put */
if (st->tag == Ist_Put || st->tag == Ist_PutI) {
UInt k_lo, k_hi;
if (st->tag == Ist_Put) {
key = mk_key_GetPut( st->Ist.Put.offset,
typeOfIRExpr(bb->tyenv,st->Ist.Put.data) );
} else {
vassert(st->tag == Ist_PutI);
key = mk_key_GetIPutI( st->Ist.PutI.details->descr );
}
k_lo = (key >> 16) & 0xFFFF;
k_hi = key & 0xFFFF;
invalidateOverlaps(env, k_lo, k_hi);
}
else
if (st->tag == Ist_Dirty) {
/* Deal with dirty helpers which write or modify guest state.
Invalidate the entire env. We could do a lot better
here. */
IRDirty* d = st->Ist.Dirty.details;
Bool writes = False;
for (j = 0; j < d->nFxState; j++) {
if (d->fxState[j].fx == Ifx_Modify
|| d->fxState[j].fx == Ifx_Write)
writes = True;
}
if (writes) {
/* dump the entire env (not clever, but correct ...) */
for (j = 0; j < env->used; j++)
env->inuse[j] = False;
if (0) vex_printf("rGET: trash env due to dirty helper\n");
}
}
/* add this one to the env, if appropriate */
if (st->tag == Ist_Put) {
vassert(isIRAtom(st->Ist.Put.data));
addToHHW( env, (HWord)key, (HWord)(st->Ist.Put.data));
}
} /* for (i = 0; i < bb->stmts_used; i++) */
}
/*---------------------------------------------------------------*/
/*--- In-place removal of redundant PUTs ---*/
/*---------------------------------------------------------------*/
/* Find any Get uses in st and invalidate any partially or fully
overlapping ranges listed in env. Due to the flattening phase, the
only stmt kind we expect to find a Get on is IRStmt_WrTmp. */
static void handle_gets_Stmt (
HashHW* env,
IRStmt* st,
Bool (*preciseMemExnsFn)(Int,Int)
)
{
Int j;
UInt key = 0; /* keep gcc -O happy */
Bool isGet;
Bool memRW = False;
IRExpr* e;
switch (st->tag) {
/* This is the only interesting case. Deal with Gets in the RHS
expression. */
case Ist_WrTmp:
e = st->Ist.WrTmp.data;
switch (e->tag) {
case Iex_Get:
isGet = True;
key = mk_key_GetPut ( e->Iex.Get.offset, e->Iex.Get.ty );
break;
case Iex_GetI:
isGet = True;
key = mk_key_GetIPutI ( e->Iex.GetI.descr );
break;
case Iex_Load:
isGet = False;
memRW = True;
break;
default:
isGet = False;
}
if (isGet) {
UInt k_lo, k_hi;
k_lo = (key >> 16) & 0xFFFF;
k_hi = key & 0xFFFF;
invalidateOverlaps(env, k_lo, k_hi);
}
break;
/* Be very conservative for dirty helper calls; dump the entire
environment. The helper might read guest state, in which
case it needs to be flushed first. Also, the helper might
access guest memory, in which case all parts of the guest
state requiring precise exceptions needs to be flushed. The
crude solution is just to flush everything; we could easily
enough do a lot better if needed. */
/* Probably also overly-conservative, but also dump everything
if we hit a memory bus event (fence, lock, unlock). Ditto
AbiHints, CASs, LLs and SCs. */
case Ist_AbiHint:
vassert(isIRAtom(st->Ist.AbiHint.base));
vassert(isIRAtom(st->Ist.AbiHint.nia));
/* fall through */
case Ist_MBE:
case Ist_Dirty:
case Ist_CAS:
case Ist_LLSC:
for (j = 0; j < env->used; j++)
env->inuse[j] = False;
break;
/* all other cases are boring. */
case Ist_Store:
vassert(isIRAtom(st->Ist.Store.addr));
vassert(isIRAtom(st->Ist.Store.data));
memRW = True;
break;
case Ist_StoreG: {
IRStoreG* sg = st->Ist.StoreG.details;
vassert(isIRAtom(sg->addr));
vassert(isIRAtom(sg->data));
vassert(isIRAtom(sg->guard));
memRW = True;
break;
}
case Ist_LoadG: {
IRLoadG* lg = st->Ist.LoadG.details;
vassert(isIRAtom(lg->addr));
vassert(isIRAtom(lg->alt));
vassert(isIRAtom(lg->guard));
memRW = True;
break;
}
case Ist_Exit:
vassert(isIRAtom(st->Ist.Exit.guard));
break;
case Ist_Put:
vassert(isIRAtom(st->Ist.Put.data));
break;
case Ist_PutI:
vassert(isIRAtom(st->Ist.PutI.details->ix));
vassert(isIRAtom(st->Ist.PutI.details->data));
break;
case Ist_NoOp:
case Ist_IMark:
break;
default:
vex_printf("\n");
ppIRStmt(st);
vex_printf("\n");
vpanic("handle_gets_Stmt");
}
if (memRW) {
/* This statement accesses memory. So we might need to dump all parts
of the environment corresponding to guest state that may not
be reordered with respect to memory references. That means
at least the stack pointer. */
switch (vex_control.iropt_register_updates) {
case VexRegUpdAllregsAtMemAccess:
/* Precise exceptions required at mem access.
Flush all guest state. */
for (j = 0; j < env->used; j++)
env->inuse[j] = False;
break;
case VexRegUpdSpAtMemAccess:
/* We need to dump the stack pointer
(needed for stack extension in m_signals.c).
preciseMemExnsFn will use vex_control.iropt_register_updates
to verify only the sp is to be checked. */
/* fallthrough */
case VexRegUpdUnwindregsAtMemAccess:
for (j = 0; j < env->used; j++) {
if (!env->inuse[j])
continue;
/* Just flush the minimal amount required, as computed by
preciseMemExnsFn. */
HWord k_lo = (env->key[j] >> 16) & 0xFFFF;
HWord k_hi = env->key[j] & 0xFFFF;
if (preciseMemExnsFn( k_lo, k_hi ))
env->inuse[j] = False;
}
break;
case VexRegUpdAllregsAtEachInsn:
// VexRegUpdAllregsAtEachInsn cannot happen here.
// fall through
default:
vassert(0);
}
} /* if (memRW) */
}
/* Scan backwards, building up a set of (min offset, max
offset) pairs, indicating those parts of the guest state
for which the next event is a write.
On seeing a conditional exit, empty the set.
On seeing 'Put (minoff,maxoff) = t or c', if (minoff,maxoff) is
completely within the set, remove the Put. Otherwise, add
(minoff,maxoff) to the set.
On seeing 'Get (minoff,maxoff)', remove any part of the set
overlapping (minoff,maxoff). The same has to happen for any events
which implicitly read parts of the guest state: dirty helper calls
and loads/stores.
*/
static void redundant_put_removal_BB (
IRSB* bb,
Bool (*preciseMemExnsFn)(Int,Int)
)
{
Int i, j;
Bool isPut;
IRStmt* st;
UInt key = 0; /* keep gcc -O happy */
vassert(vex_control.iropt_register_updates < VexRegUpdAllregsAtEachInsn);
HashHW* env = newHHW();
/* Initialise the running env with the fact that the final exit
writes the IP (or, whatever it claims to write. We don't
care.) */
key = mk_key_GetPut(bb->offsIP, typeOfIRExpr(bb->tyenv, bb->next));
addToHHW(env, (HWord)key, 0);
/* And now scan backwards through the statements. */
for (i = bb->stmts_used-1; i >= 0; i--) {
st = bb->stmts[i];
if (st->tag == Ist_NoOp)
continue;
/* Deal with conditional exits. */
if (st->tag == Ist_Exit) {
//Bool re_add;
/* Need to throw out from the env, any part of it which
doesn't overlap with the guest state written by this exit.
Since the exit only writes one section, it's simplest to
do this: (1) check whether env contains a write that
completely overlaps the write done by this exit; (2) empty
out env; and (3) if (1) was true, add the write done by
this exit.
To make (1) a bit simpler, merely search for a write that
exactly matches the one done by this exit. That's safe
because it will fail as often or more often than a full
overlap check, and failure to find an overlapping write in
env is the safe case (we just nuke env if that
happens). */
//vassert(isIRAtom(st->Ist.Exit.guard));
/* (1) */
//key = mk_key_GetPut(st->Ist.Exit.offsIP,
// typeOfIRConst(st->Ist.Exit.dst));
//re_add = lookupHHW(env, NULL, key);
/* (2) */
for (j = 0; j < env->used; j++)
env->inuse[j] = False;
/* (3) */
//if (0 && re_add)
// addToHHW(env, (HWord)key, 0);
continue;
}
/* Deal with Puts */
switch (st->tag) {
case Ist_Put:
isPut = True;
key = mk_key_GetPut( st->Ist.Put.offset,
typeOfIRExpr(bb->tyenv,st->Ist.Put.data) );
vassert(isIRAtom(st->Ist.Put.data));
break;
case Ist_PutI:
isPut = True;
key = mk_key_GetIPutI( st->Ist.PutI.details->descr );
vassert(isIRAtom(st->Ist.PutI.details->ix));
vassert(isIRAtom(st->Ist.PutI.details->data));
break;
default:
isPut = False;
}
if (isPut && st->tag != Ist_PutI) {
/* See if any single entry in env overlaps this Put. This is
simplistic in that the transformation is valid if, say, two
or more entries in the env overlap this Put, but the use of
lookupHHW will only find a single entry which exactly
overlaps this Put. This is suboptimal but safe. */
if (lookupHHW(env, NULL, (HWord)key)) {
/* This Put is redundant because a later one will overwrite
it. So NULL (nop) it out. */
if (DEBUG_IROPT) {
vex_printf("rPUT: "); ppIRStmt(st);
vex_printf("\n");
}
bb->stmts[i] = IRStmt_NoOp();
} else {
/* We can't demonstrate that this Put is redundant, so add it
to the running collection. */
addToHHW(env, (HWord)key, 0);
}
continue;
}
/* Deal with Gets. These remove bits of the environment since
appearance of a Get means that the next event for that slice
of the guest state is no longer a write, but a read. Also
deals with implicit reads of guest state needed to maintain
precise exceptions. */
handle_gets_Stmt( env, st, preciseMemExnsFn );
}
}
/*---------------------------------------------------------------*/
/*--- Constant propagation and folding ---*/
/*---------------------------------------------------------------*/
#if STATS_IROPT
/* How often sameIRExprs was invoked */
static UInt invocation_count;
/* How often sameIRExprs recursed through IRTemp assignments */
static UInt recursion_count;
/* How often sameIRExprs found identical IRExprs */
static UInt success_count;