-
Notifications
You must be signed in to change notification settings - Fork 392
/
SinkStores.cpp
2818 lines (2514 loc) · 131 KB
/
SinkStores.cpp
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) 2000, 2020 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "optimizer/SinkStores.hpp"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "compile/ResolvedMethod.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "cs2/allocator.h"
#include "cs2/sparsrbit.h"
#include "env/IO.hpp"
#include "env/StackMemoryRegion.hpp"
#include "env/TRMemory.hpp"
#include "il/AliasSetInterface.hpp"
#include "il/AutomaticSymbol.hpp"
#include "il/Block.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/RegisterMappedSymbol.hpp"
#include "il/ResolvedMethodSymbol.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/HashTab.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/DataFlowAnalysis.hpp"
#include "optimizer/Optimization.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#define OPT_DETAILS "O^O SINK STORES: "
#define TR_USED_SYMBOLS_OPTION_1
// There are two ways to update a block with used symbols.
//
// 1. When a store is moved any savedLiveCommoned symbols that intersect with the moved stores used symbols are added to the used symbols
// for the source block of the store
// block 1:
// istore
// iload sym1 <savedLiveCommoned = (sym1,sym2) at this point, usedSymbols = (sym1) >
//
// sink the istore to block 4
// Update usedSymbolsInBlock[1] with (sym1,sym2) ^ (sym1) = sym1
//
// 2. Do not do the above but instead for any treetop/store that is not moved update the usedSymbolsInBlock for its block with any commoned symbols
// block 1:
// treetop
// =>iload sym1
//
// Update usedSymbolsInBlock[1] with sym1
//
// Option 1 is the current default as it was the original scheme and is more tested.
// Generally it is observed that with option 1 more stores are moved some distance but with option 2 less stores are moved a greater distance.
inline bool movedStorePinsCommonedSymbols()
{
#ifdef TR_USED_SYMBOLS_OPTION_1
return true;
#else
return false;
#endif
}
TR_LiveOnNotAllPaths::TR_LiveOnNotAllPaths(TR::Compilation * c, TR_Liveness * liveOnSomePaths, TR_LiveOnAllPaths * liveOnAllPaths)
: _comp(c)
{
TR_LiveVariableInformation *liveVarInfo = liveOnSomePaths->getLiveVariableInfo();
TR_ASSERT((liveVarInfo == liveOnAllPaths->getLiveVariableInfo()), "Possibly inconsistent live variable information");
bool trace = comp()->getOption(TR_TraceLiveness);
TR::CFG *cfg = comp()->getFlowGraph();
_numNodes = cfg->getNextNodeNumber();
int32_t arraySize = _numNodes * sizeof(TR_BitVector *);
_inSetInfo = (TR_BitVector **)trMemory()->allocateStackMemory(arraySize);
_outSetInfo = (TR_BitVector **)trMemory()->allocateStackMemory(arraySize);
memset(_inSetInfo, 0, arraySize);
memset(_outSetInfo, 0, arraySize);
_numLocals = liveVarInfo->numLocals();
// compute LiveOnNotAllPaths = LiveOnSomePaths(Liveness) - LiveOnAllPaths
for (TR::CFGNode *block = comp()->getFlowGraph()->getFirstNode(); block != NULL; block = block->getNext() )
{
int32_t b=block->getNumber();
_inSetInfo[b] = new (trStackMemory()) TR_BitVector(_numLocals, trMemory(), stackAlloc);
if (liveOnSomePaths->_blockAnalysisInfo[b])
{
*(_inSetInfo[b]) = *(liveOnSomePaths->_blockAnalysisInfo[b]);
if (liveOnAllPaths->_blockAnalysisInfo[b])
*(_inSetInfo[b]) -= *(liveOnAllPaths->_blockAnalysisInfo[b]);
}
TR_BitVector liveOnSomePathsOut(_numLocals, trMemory());
TR_BitVector liveOnAllPathsOut(_numLocals, trMemory());
TR_BitVector forcedLiveOnAllPathsSymbols(_numLocals, trMemory());
liveOnAllPathsOut.setAll(_numLocals);
// compute liveOnAllPaths at end of block
for (auto edge = block->getSuccessors().begin(); edge != block->getSuccessors().end(); ++edge)
{
TR::CFGNode *toBlock = (*edge)->getTo();
int32_t toBlockNumber = toBlock->getNumber();
if (liveOnAllPaths->_blockAnalysisInfo[toBlockNumber])
liveOnAllPathsOut &= *(liveOnAllPaths->_blockAnalysisInfo[toBlockNumber]);
else
liveOnAllPathsOut.empty();
if (liveOnSomePaths->_blockAnalysisInfo[toBlockNumber])
{
liveOnSomePathsOut |= *(liveOnSomePaths->_blockAnalysisInfo[toBlockNumber]);
int isBackEdge = (block->getForwardTraversalIndex() >= toBlock->getForwardTraversalIndex());
if (isBackEdge)
{
// Ensure we don't try to move things that are only live on the back edge
// By adding all symbols live on the back edge to the set of symbols that
// are live on ALL paths at this block's exit, we prevent any store to those
// symbols from moving lower than this block
if (trace)
traceMsg(comp(), " Adding backedge live vars from block_%d to LiveOnAllPaths for block_%d\n", toBlockNumber, b);
forcedLiveOnAllPathsSymbols |= *(liveOnSomePaths->_blockAnalysisInfo[toBlockNumber]);
}
}
}
liveOnAllPathsOut |= forcedLiveOnAllPathsSymbols;
// Adjustment 1
// these two are more important because it should stop stores from flowing through this block
(*liveOnAllPaths->_blockAnalysisInfo[b]) |= forcedLiveOnAllPathsSymbols;
(*_inSetInfo[b]) -= forcedLiveOnAllPathsSymbols;
// finally, compute LiveOnNotAllPaths at end of block
_outSetInfo[b] = new (trStackMemory()) TR_BitVector(_numLocals, trMemory(), stackAlloc);
*(_outSetInfo[b]) = liveOnSomePathsOut;
*(_outSetInfo[b]) -= liveOnAllPathsOut;
// Adjustment 2
// for non-exception edges: recompute LOAP_in
// for a local if LOAP_out (without exception edges) is true and LOSP_in
// is true, then LONAP_in should be false and thus LOAP_in should be forced to true
TR_BitVector LiveOnAllPathsNonExcIn(_numLocals, trMemory());
LiveOnAllPathsNonExcIn = liveOnAllPathsOut;
LiveOnAllPathsNonExcIn &= *(liveOnSomePaths->_blockAnalysisInfo[b]);
*(_inSetInfo[b]) -= LiveOnAllPathsNonExcIn;
*(liveOnAllPaths->_blockAnalysisInfo[b]) |= LiveOnAllPathsNonExcIn;
if (trace)
{
traceMsg(comp(), "Block %d:\n", b);
traceMsg(comp(), " Liveness IN: ");
liveOnSomePaths->_blockAnalysisInfo[b]->print(comp());
traceMsg(comp(), " OUT ");
liveOnSomePathsOut.print(comp());
traceMsg(comp(), "\n LiveOnAllPaths IN: ");
liveOnAllPaths->_blockAnalysisInfo[b]->print(comp());
traceMsg(comp(), " OUT ");
liveOnAllPathsOut.print(comp());
traceMsg(comp(), "\n LiveOnNotAllPaths IN: ");
_inSetInfo[b]->print(comp());
traceMsg(comp(), " OUT ");
_outSetInfo[b]->print(comp());
traceMsg(comp(), "\n");
}
}
}
ListElement<TR_BlockListEntry> *TR_OrderedBlockList::addInTraversalOrder(TR::Block * block, bool forward, TR::CFGEdge *edge)
{
ListElement<TR_BlockListEntry> *ptr = _pHead;
ListElement<TR_BlockListEntry> *prevPtr = NULL;
int32_t blockTraversalIndex = (forward) ? block->getForwardTraversalIndex() : block->getBackwardTraversalIndex();
TR_ASSERT(edge != NULL, "edge shouldn't be null in addInTraversalOrder");
while (ptr != NULL)
{
TR_BlockListEntry *ptrBlockEntry = ptr->getData();
TR::Block *ptrBlock = ptrBlockEntry->_block;
// if block is already in list: add pred to its list of preds, increment its count, and return it
if (ptrBlock == block)
{
ptrBlockEntry->_preds.add(edge);
ptrBlockEntry->_count++;
return ptr;
}
// otherwise, see if we should put it here
int32_t ptrTraversalIndex = (forward) ? ptrBlock->getForwardTraversalIndex() : ptrBlock->getBackwardTraversalIndex();
//traceMsg(comp(), "addInTraversalOrder: comparing block_%d (%d) to list block_%d (%d)\n", block->getNumber(), blockTraversalIndex, ptrBlock->getNumber(), ptrTraversalIndex);
if (blockTraversalIndex < ptrTraversalIndex)
// block is earlier in traversal, so insert it here
break;
prevPtr = ptr;
ptr = ptr->getNextElement();
}
return addAfter((new (getRegion()) TR_BlockListEntry(block, edge, getRegion())), prevPtr);
}
bool TR_OrderedBlockList::removeBlockFromList(TR::Block *block, TR::CFGEdge *edge)
{
ListElement<TR_BlockListEntry> *ptr = _pHead;
ListElement<TR_BlockListEntry> *prevPtr = NULL;
while (ptr != NULL)
{
TR_BlockListEntry *ptrBlockEntry = ptr->getData();
TR::Block *ptrBlock = ptrBlockEntry->_block;
// if block is already in list: remove pred from its list of preds, decrement its count, remove it from the list if resultant count is 0
if (ptrBlock == block &&
ptrBlockEntry->_preds.remove(edge))
{
ptrBlockEntry->_count--;
if (ptrBlockEntry->_count == 0)
{
removeNext(prevPtr);
return true;
}
}
prevPtr = ptr;
ptr = ptr->getNextElement();
}
return false;
}
TR_MovableStore::TR_MovableStore(TR_SinkStores *s, TR_UseOrKillInfo *useOrKillInfo,
int32_t symIdx,
TR_BitVector *commonedLoadsUnderTree,
TR_BitVector *commonedLoadsAfter,
int32_t depth,
TR_BitVector *needTempForCommonedLoads,
TR_BitVector *satisfiedCommonedLoads) :
_useOrKillInfo(useOrKillInfo),
_s(s),
_comp(s->comp()),
_symIdx(symIdx),
_commonedLoadsUnderTree(commonedLoadsUnderTree),
_commonedLoadsAfter(commonedLoadsAfter),
_depth(depth),
_needTempForCommonedLoads(needTempForCommonedLoads),
_movable(true),
_isLoadStatic(false)
{
_useOrKillInfo->_movableStore = this;
}
TR_SinkStores::TR_SinkStores(TR::OptimizationManager *manager)
: TR::Optimization(manager),
_allEdgePlacements(trMemory()),
_allBlockPlacements(trMemory())
{
_tempSymMap = new (trHeapMemory()) TR_HashTab(comp()->trMemory(), stackAlloc, 4);
// tuning parameters
_sinkAllStores = false;
_printSinkStoreStats = false;
_sinkThruException = false;
_firstSinkOptTransformationIndex = -1;
_lastSinkOptTransformationIndex = -1;
static const char *sinkAllStoresEnv = feGetEnv("TR_SinkAllStores");
static const char *printSinkStoreStatsEnv = feGetEnv("TR_PrintSinkStoreStats");
static const char *sinkThruExceptionEnv = feGetEnv("TR_SinkThruException");
static const char *firstSinkOptTransformationIndexEnv = feGetEnv("TR_FirstSinkOptTransformationIndex");
static const char *lastSinkOptTransformationIndexEnv = feGetEnv("TR_LastSinkOptTransformationIndex");
if (sinkAllStoresEnv)
_sinkAllStores = true;
if (printSinkStoreStatsEnv)
_printSinkStoreStats = true;
if (sinkThruExceptionEnv)
_sinkThruException = true;
if (firstSinkOptTransformationIndexEnv)
_firstSinkOptTransformationIndex = atoi(firstSinkOptTransformationIndexEnv);
if (lastSinkOptTransformationIndexEnv)
_lastSinkOptTransformationIndex = atoi(lastSinkOptTransformationIndexEnv);
if (manager->comp()->getOptions()->getStoreSinkingLastOpt() != -1)
{
_firstSinkOptTransformationIndex = 0;
_lastSinkOptTransformationIndex = manager->comp()->getOptions()->getStoreSinkingLastOpt();
}
}
TR_GeneralSinkStores::TR_GeneralSinkStores(TR::OptimizationManager *manager)
: TR_SinkStores(manager)
{
setUsesDataFlowAnalysis(true);
setExceptionFlagIsSticky(true);
setSinkStoresWithStaticLoads(true);
}
TR_EdgeInformation *TR_SinkStores::findEdgeInformation(TR::CFGEdge *edge, List<TR_EdgeInformation> & edgeList)
{
ListIterator<TR_EdgeInformation> edgeInfoIt(&edgeList);
TR_EdgeInformation *edgeInfo;
for (edgeInfo=edgeInfoIt.getFirst(); edgeInfo != NULL; edgeInfo = edgeInfoIt.getNext())
if (edgeInfo->_edge == edge)
break;
return edgeInfo;
}
void TR_SinkStores::recordPlacementForDefAlongEdge(TR_EdgeStorePlacement *edgePlacement)
{
TR_EdgeInformation *edgeInfo=edgePlacement->_edges.getListHead()->getData();
TR::CFGEdge *succEdge=edgeInfo->_edge;
int32_t toBlockNumber=succEdge->getTo()->getNumber();
TR_StoreInformation *storeInfo = edgePlacement->_stores.getListHead()->getData();
TR::TreeTop *tt=storeInfo->_store;
bool copyStore=storeInfo->_copy;
if (trace())
traceMsg(comp(), " RECORD placement along edge (%d->%d), for tt [" POINTER_PRINTF_FORMAT "] (copy=%d)\n", succEdge->getFrom()->getNumber(), succEdge->getTo()->getNumber(), tt, copyStore);
// for now, just put one edge in each placement...but collect all stores that go with that edge
// but, if we find an edge already in the list, just add this store to the list of stores for that edge
ListElement<TR_EdgeStorePlacement> *ptr = NULL;
if (_placementsForEdgesToBlock[toBlockNumber] != NULL)
{
ptr = _placementsForEdgesToBlock[toBlockNumber]->getListHead();
while (ptr != NULL)
{
TR_EdgeStorePlacement *placement = ptr->getData();
TR_EdgeInformation *placementEdgeInfo = findEdgeInformation(succEdge, placement->_edges);
if (placementEdgeInfo != NULL)
{
if (trace())
traceMsg(comp(), " adding tt to stores on this edge\n");
placement->_stores.add(storeInfo);
// NOTE that since stores are encountered in backwards order and "add" just puts new stores at the beginning of the list
// then when we ultimately place the stores on this edge, they will be stored in the correct order (i.e. a store X that
// originally appeared before another store Y in the code will be on _placement->_stores list in the order X, Y
// record what symbols are referenced along this edge
(*placementEdgeInfo->_symbolsUsedOrKilled) |= (*_usedSymbolsToMove);
(*placementEdgeInfo->_symbolsUsedOrKilled) |= (*_killedSymbolsToMove);
break;
}
ptr = ptr->getNextElement();
}
}
if (ptr == NULL)
{
// we didn't find this edge in the list already, so add it
if (trace())
traceMsg(comp(), " edge isn't in list already\n");
TR::Block *from=succEdge->getFrom()->asBlock();
if (from->isGotoBlock(comp()))
{
if (trace())
traceMsg(comp(), " from block_%d is a goto block\n", from->getNumber());
TR_BlockStorePlacement *newBlockPlacement = new (trStackMemory()) TR_BlockStorePlacement(storeInfo, from, trMemory());
recordPlacementForDefInBlock(newBlockPlacement);
}
else
{
edgeInfo->_symbolsUsedOrKilled = new (trStackMemory()) TR_BitVector(_liveVarInfo->numLocals(), trMemory());
(*edgeInfo->_symbolsUsedOrKilled) |= (*_usedSymbolsToMove);
(*edgeInfo->_symbolsUsedOrKilled) |= (*_killedSymbolsToMove);
_allEdgePlacements.add(edgePlacement);
optimizer()->setRequestOptimization(OMR::basicBlockOrdering, true);
if (_placementsForEdgesToBlock[toBlockNumber] == NULL)
_placementsForEdgesToBlock[toBlockNumber] = new (trStackMemory()) TR_EdgeStorePlacementList(trMemory());
_placementsForEdgesToBlock[toBlockNumber]->add(edgePlacement);
}
}
}
void TR_SinkStores::recordPlacementForDefInBlock(TR_BlockStorePlacement *blockPlacement)
{
TR::Block *block=blockPlacement->_block;
int32_t blockNumber=block->getNumber();
TR_StoreInformation *storeInfo = blockPlacement->_stores.getListHead()->getData();
TR::TreeTop *tt=storeInfo->_store;
bool copyStore=storeInfo->_copy;
if (trace())
traceMsg(comp(), " RECORD placement at beginning of block_%d for tt [" POINTER_PRINTF_FORMAT "] (copy=%d)\n", block->getNumber(), tt, (int32_t)copyStore);
ListElement<TR_BlockStorePlacement> *ptr=NULL;
if (_placementsForBlock[blockNumber] != NULL)
{
ptr = _placementsForBlock[blockNumber]->getListHead();
while (ptr != NULL)
{
TR_BlockStorePlacement *placement = ptr->getData();
if (placement->_block == block)
{
placement->_stores.add(storeInfo);
// NOTE that since stores are encountered in backwards order and "add" just puts new stores at the beginning of the list
// then when we ultimately place the stores on this edge, they will be stored in the correct order (i.e. a store X that
// originally appeared before another store Y in the code will be on _placement->_stores list in the order X, Y
break;
}
ptr = ptr->getNextElement();
}
}
else
{
_placementsForBlock[blockNumber] = new (trStackMemory()) TR_BlockStorePlacementList(trMemory());
}
if (ptr == NULL)
{
_allBlockPlacements.add(blockPlacement);
_placementsForBlock[blockNumber]->add(blockPlacement);
}
if (usesDataFlowAnalysis())
{
// update {LOSP,LOAP,LONAP}_IN liveness sets because we placed the store in block
// due to this placement, uses are now live on all paths, kills are no longer live
(*_liveOnSomePaths->_blockAnalysisInfo[blockNumber]) -= (*_killedSymbolsToMove);
(*_liveOnSomePaths->_blockAnalysisInfo[blockNumber]) |= (*_usedSymbolsToMove);
(*_liveOnAllPaths->_blockAnalysisInfo[blockNumber]) -= (*_killedSymbolsToMove);
(*_liveOnAllPaths->_blockAnalysisInfo[blockNumber]) |= (*_usedSymbolsToMove);
(*_liveOnNotAllPaths->_inSetInfo[blockNumber]) -= (*_killedSymbolsToMove);
}
// add kills to block's kill set, uses to block's gen set
// NOTE: we should already have visited these blocks, so we should only have to add these symbols to kills and uses
// so that later stores will not be pushed through this block
TR_ASSERT(_symbolsKilledInBlock[blockNumber] != NULL, "_symbolsKilledInBlock[%d] should have been initialized!", blockNumber);
//_symbolsKilledInBlock[blockNumber] = new (trStackMemory()) TR_BitVector(_liveVarInfo->numLocals(), trMemory());
if (trace())
{
traceMsg(comp(),"updating symbolsKilled in recordPlacementForDefInBlock\n");
traceMsg(comp(), "BEF _symbolsKilledInBlock[%d]: ",blockNumber);
_symbolsKilledInBlock[blockNumber]->print(comp());
traceMsg(comp(), "\n");
}
(*_symbolsKilledInBlock[blockNumber]) |= (*_killedSymbolsToMove);
if (trace())
{
traceMsg(comp(), "AFT _symbolsKilledInBlock[%d]: ",blockNumber);
_symbolsKilledInBlock[blockNumber]->print(comp());
traceMsg(comp(), "\n\n");
}
TR_ASSERT(_symbolsUsedInBlock[blockNumber] != NULL, "_symbolsUsedInBlock[%d] should have been initialized!", blockNumber);
//_symbolsUsedInBlock[blockNumber] = new (trStackMemory()) TR_BitVector(_liveVarInfo->numLocals(), trMemory());
if (trace())
{
traceMsg(comp(),"updating symbolsUsed in recordPlacementForDefInBlock\n");
traceMsg(comp(), "BEF _symbolsUsedInBlock[%d]: ",blockNumber);
_symbolsUsedInBlock[blockNumber]->print(comp());
traceMsg(comp(), "\n");
}
(*_symbolsUsedInBlock[blockNumber]) |= (*_usedSymbolsToMove);
if (trace())
{
traceMsg(comp(), "AFT _symbolsUsedInBlock[%d]: ",blockNumber);
_symbolsUsedInBlock[blockNumber]->print(comp());
traceMsg(comp(), "\n\n");
}
}
int32_t TR_GeneralSinkStores::perform()
{
if (comp()->getOption(TR_DisableStoreSinking))
{
return 0;
}
return performStoreSinking();
}
int32_t TR_SinkStores::performStoreSinking()
{
if (0 && trace())
{
comp()->dumpMethodTrees("Before Store Sinking");
}
_handlerIndex = comp()->getCurrentMethod()->numberOfExceptionHandlers();
_numPlacements = 0;
_numRemovedStores = 0;
_numTemps = 0;
_searchMarkCalls = 0;
_searchMarkWalks = 0;
_killMarkWalks = 0;
_numTransformations = 0;
TR::CFG *cfg = comp()->getFlowGraph();
TR_Structure *rootStructure = cfg->getStructure();
int32_t numBlocks = cfg->getNextNodeNumber();
{
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
// create forward and backward RPO traversal ordering to control block visitations and detect back edges
cfg->createTraversalOrder(true, stackAlloc);
if (0 && trace())
{
traceMsg(comp(), "Forward traversal:\n");
for (int16_t i=0;i < cfg->getForwardTraversalLength();i++)
traceMsg(comp(), "\t%d (%d)\n", cfg->getForwardTraversalElement(i)->getNumber(), cfg->getForwardTraversalElement(i)->getForwardTraversalIndex());
}
cfg->createTraversalOrder(false, stackAlloc);
if (0 && trace())
{
traceMsg(comp(), "Backward traversal:\n");
for (int16_t i=0;i < cfg->getBackwardTraversalLength();i++)
traceMsg(comp(), "\t%d (%d)\n", cfg->getBackwardTraversalElement(i)->getNumber(), cfg->getBackwardTraversalElement(i)->getBackwardTraversalIndex());
}
// Perform liveness analysis
//
_liveVarInfo = new (trStackMemory()) TR_LiveVariableInformation(comp(),
optimizer(),
rootStructure,
false, /* !splitLongs */
true, /* includeParms */
false);
if (_liveVarInfo->numLocals() == 0)
{
return 1;
}
_liveVarInfo->createGenAndKillSetCaches();
_liveVarInfo->trackLiveCommonedLoads();
if (usesDataFlowAnalysis())
{
_liveOnSomePaths = new (comp()->allocator()) TR_Liveness(comp(), optimizer(), rootStructure, false, _liveVarInfo, false, true);
_liveOnAllPaths = new (comp()->allocator()) TR_LiveOnAllPaths(comp(), optimizer(), rootStructure, _liveVarInfo, false, true);
_liveOnNotAllPaths = new (comp()->allocator()) TR_LiveOnNotAllPaths(comp(), _liveOnSomePaths, _liveOnAllPaths);
bool thereIsACandidate = false;
_candidateBlocks = new (trStackMemory()) TR_BitVector(numBlocks, trMemory());
for (int32_t b=0; b < numBlocks;b++)
{
if (_liveOnNotAllPaths->_outSetInfo[b] != NULL && !_liveOnNotAllPaths->_outSetInfo[b]->isEmpty())
{
_candidateBlocks->set(b);
thereIsACandidate = true;
}
}
}
//if (!thereIsACandidate)
//return 1;
int32_t numLocals = _liveVarInfo->numLocals();
// these arrays of bit vectors describe the symbols used and killed in each block in the method
int32_t arraySize = numBlocks * sizeof(void *);
_symbolsUsedInBlock = (TR_BitVector **) trMemory()->allocateStackMemory(arraySize);
memset(_symbolsUsedInBlock, 0, arraySize);
_symbolsKilledInBlock = (TR_BitVector **) trMemory()->allocateStackMemory(arraySize);
memset(_symbolsKilledInBlock, 0, arraySize);
// _symbolsExceptionUsedInBlock = (TR_BitVector **) trMemory()->allocateStackMemory(arraySize);
// memset(_symbolsExceptionUsedInBlock, 0, arraySize);
// _symbolsExceptionKilledInBlock = (TR_BitVector **) trMemory()->allocateStackMemory(arraySize);
// memset(_symbolsExceptionKilledInBlock, 0, arraySize);
// these arrays are used to maintain the stores placed in each block or in edges directed at each particular block
arraySize = numBlocks * sizeof(TR_BlockStorePlacementList *);
_placementsForBlock = (TR_BlockStorePlacementList **) trMemory()->allocateStackMemory(arraySize);
memset(_placementsForBlock, 0, arraySize);
arraySize = numBlocks * sizeof(TR_EdgeStorePlacementList *);
_placementsForEdgesToBlock = (TR_EdgeStorePlacementList **) trMemory()->allocateStackMemory(arraySize);
memset(_placementsForEdgesToBlock, 0, arraySize);
// grab what symbols are used/killed/exception killed from the live variable info
//
// The below call to initializeGenAndKillSetInfo is likely not needed at all as it looks like _symbolsUsedInBlock
// and _symbolsKilledInBlock are always initialized and set before they are used in lookForSinkableStores
// anyway (after the block loop is done). Having whole block info like this is probably not needed because we are
// always interested in just what is below the current node and not in the whole block
//
// if (usesDataFlowAnalysis())
// {
// _liveVarInfo->initializeGenAndKillSetInfo(_symbolsUsedInBlock,
// _symbolsKilledInBlock,
// _symbolsExceptionUsedInBlock,
// _symbolsExceptionKilledInBlock);
// }
// Set up the block nesting depths
//
if (rootStructure)
{
TR::CFGNode *node;
for (node = cfg->getFirstNode(); node; node = node->getNext())
{
TR::Block *block = toBlock(node);
int32_t nestingDepth = 0;
if (block->getStructureOf() != NULL)
block->getStructureOf()->setNestingDepths(&nestingDepth);
//if (block->getFrequency() < 0)
// block->setFrequency(0);
}
}
// set up the future use counts for all nodes
vcount_t futureUseVisitCount = comp()->incVisitCount();
for (TR::TreeTop *tt = comp()->getStartTree(); tt; tt = tt->getNextTreeTop())
tt->getNode()->initializeFutureUseCounts(futureUseVisitCount);
// now we have all the information we need, go look for stores to sink!
lookForSinkableStores();
// if we found any, transform the code now
doSinking();
if (0 && trace())
{
comp()->dumpMethodTrees("After Store Sinking");
}
} // scope of the stack memory region
optimizer()->enableAllLocalOpts();
if (trace())
{
traceMsg(comp()," Removed %d stores\n", _numRemovedStores);
traceMsg(comp()," Placed %d stores\n", _numPlacements);
traceMsg(comp()," Created %d temps\n", _numTemps);
traceMsg(comp()," Performed %d kill mark walks\n", _killMarkWalks);
traceMsg(comp()," Performed %d search mark walks\n", _searchMarkWalks);
traceMsg(comp()," Performed %d search mark calls\n", _searchMarkCalls);
/*
printf(" Removed %d stores\n", _numRemovedStores);
printf(" Placed %d stores\n", _numPlacements);
printf(" Created %d temps\n", _numTemps);
printf(" Performed %d kill mark walks\n", _killMarkWalks);
printf(" Performed %d search mark walks\n", _searchMarkWalks);
printf(" Performed %d search mark calls\n", _searchMarkCalls);
*/
}
if (_numTemps > 0)
optimizer()->setAliasSetsAreValid(false);
return 1;
}
void TR_SinkStores::lookForSinkableStores()
{
int32_t numLocals = _liveVarInfo->numLocals();
TR::CFG *cfg = comp()->getFlowGraph();
// visit blocks in backward RPO so that we move later stores before earlier stores
// so that the earlier ones don't get stuck behind another store that will be
// moved out of the block
// ALSO: visit entire EBBs at a time so that commoned references can be correctly captured
if (trace())
traceMsg(comp(), "Starting to look for stores to sink\n");
List<TR_UseOrKillInfo> useOrKillInfoList(trMemory());
ListElement<TR_UseOrKillInfo> *useOrKillInfoListPtr=NULL;
List<TR_MovableStore> potentiallyMovableStores(trMemory());
ListElement<TR_MovableStore> *storeListPtr=NULL;
// for keeping track of dataflow for each tree
TR_BitVector *savedLiveCommonedLoads = new (trStackMemory()) TR_BitVector(numLocals, trMemory());
TR_BitVector *satisfiedLiveCommonedLoads = new (trStackMemory()) TR_BitVector(numLocals, trMemory());
TR_BitVector *killedLiveCommonedLoads = new (trStackMemory()) TR_BitVector(numLocals, trMemory());
// treeVisitCount will be incremented for each tree in an EBB
// when starting a new EBB, treeVisitCount will be reset fo startVisitCount
// if treeVisitCount > highestVisitCount, comp()->incVisitCount() will be invoked to maintain consistency
vcount_t startVisitCount=comp()->incVisitCount();
vcount_t highestVisitCount = startVisitCount;
vcount_t treeVisitCount = startVisitCount - 1; // will be incremented inside loop
// this bit vector is used to collect commoned loads for every traversal
// it will be copied into a new bit vector for a store identified as potentially movable
TR_BitVector *treeCommonedLoads = new (trStackMemory()) TR_BitVector(numLocals, trMemory());
int32_t *satisfiedCommonedSymCount = (int32_t *)trMemory()->allocateStackMemory(numLocals*sizeof(int32_t));
memset(satisfiedCommonedSymCount, 0, numLocals*sizeof(int32_t));
for (int32_t i=0;i < cfg->getBackwardTraversalLength();i++)
{
TR::Block *block = cfg->getBackwardTraversalElement(i)->asBlock();
int32_t blockNumber = block->getNumber();
bool foundException = false;
if (trace())
traceMsg(comp(), " Looking for stores to sink in block_%d\n", blockNumber);
// walk trees in reverse order to (hopefully) create opportunities for earlier trees
if (block->getEntry() != NULL)
{
TR::TreeTop *tt = block->getLastRealTreeTop();
do
{
// FIXME: It is legal in trivialStoreSinking to reset the foundException flag at the start of each loop so
// return false for isExceptionFlagIsSticky() (more sinking opportunities are found)
// Is it also legal to reset the flag given the more general control flow found in generalStoreSinking?
if (!isExceptionFlagIsSticky())
foundException = false;
int32_t prevNumTemps = static_cast<int32_t>(_numTemps);
TR::Node *node = tt->getNode();
if (node->getOpCodeValue() == TR::treetop)
node = node->getFirstChild();
treeVisitCount++;
if (treeVisitCount > highestVisitCount)
{
TR_ASSERT(treeVisitCount == highestVisitCount+1, "treeVisitCount skipped a value");
highestVisitCount = comp()->incVisitCount();
}
if (node && node->getOpCodeValue() == TR::BBStart)
{
if (trace())
traceMsg(comp(), " Found BBStart, at beginning of block\n");
break;
}
if (trace())
traceMsg(comp(), " Examining node [" POINTER_PRINTF_FORMAT "] in block_%d\n", node,blockNumber);
if (node->exceptionsRaised() && block->hasExceptionSuccessors())
{
if (trace())
traceMsg(comp(), " Raises an exception in try region, cannot move any earlier trees\n");
foundException = true;
}
(*savedLiveCommonedLoads) = (*_liveVarInfo->liveCommonedLoads());
if (trace())
{
traceMsg(comp(), " savedLiveCommonedLoads: ");
savedLiveCommonedLoads->print(comp());
traceMsg(comp(), "\n");
}
// visit the tree below this node and find all the symbols it uses
TR_BitVector *usedSymbols = new (trStackMemory()) TR_BitVector(numLocals, trMemory());
TR_BitVector *killedSymbols = new (trStackMemory()) TR_BitVector(numLocals, trMemory());
// remove any commoned loads where the first reference to the load has been seen (it is 'satisfied')
// satisfiedLiveCommonedLoads was initialized, if required, on the previous node examined
// remember the currently live commoned loads so that we can figure out later if we can move this store
(*savedLiveCommonedLoads) = (*_liveVarInfo->liveCommonedLoads());
treeCommonedLoads->empty();
if (trace())
traceMsg(comp()," calling findLocalUses on node %p with treeVisitCount %d\n",tt->getNode(),treeVisitCount);
_liveVarInfo->findLocalUsesInBackwardsTreeWalk(tt->getNode(), blockNumber,
usedSymbols, killedSymbols,
treeCommonedLoads, treeVisitCount);
if (trace())
{
traceMsg(comp(), " killedSymbols: ");
killedSymbols->print(comp());
traceMsg(comp(), "\n");
traceMsg(comp(), " usedSymbols: ");
usedSymbols->print(comp());
traceMsg(comp(), " treeCommonedLoads: ");
treeCommonedLoads->print(comp());
traceMsg(comp(), "\n");
}
TR::RegisterMappedSymbol *local = NULL;
int32_t symIdx = 0;
if (node != NULL && node->getOpCode().isStoreDirect())
{
local = getSinkableSymbol(node);
}
// killedSymbols should have the same syms as _symbolsKilledInBlock[blockNumber] at this point
if (local != NULL)
{
symIdx = local->getLiveLocalIndex();
if (symIdx != INVALID_LIVENESS_INDEX)
{
TR_ASSERT(symIdx < numLocals, "Found store to local with larger index than my liveness information can deal with, idx = %d\n",symIdx);
if (trace())
traceMsg(comp(), " setting %d in killedSymbols\n",symIdx);
killedSymbols->set(symIdx);
}
else
{
local = NULL;
}
}
if (local &&
(savedLiveCommonedLoads->get(symIdx)))
{
// this store kills the currently live commoned loads
if (trace())
traceMsg(comp()," updating killedLiveCommonedLoads with savedLiveCommonedLoads, setting index %d\n",symIdx);
killedLiveCommonedLoads->set(symIdx);
}
if (trace())
{
traceMsg(comp(), " killedSymbols: ");
killedSymbols->print(comp());
traceMsg(comp(), "\n");
traceMsg(comp(), " usedSymbols: ");
usedSymbols->print(comp());
traceMsg(comp(), "\n");
traceMsg(comp(), " treeCommonedLoads: ");
treeCommonedLoads->print(comp());
traceMsg(comp(), "\n");
traceMsg(comp(), " savedLiveCommonedLoads: ");
savedLiveCommonedLoads->print(comp());
traceMsg(comp(), "\n");
traceMsg(comp(), " killedLiveCommonedLoads: ");
killedLiveCommonedLoads->print(comp());
traceMsg(comp(), "\n");
if (local)
traceMsg(comp(), " is store to local %d\n", symIdx);
}
// check to see if we can find a store to a local that is used later in the EBB via a commoned reference
TR_BitVectorIterator bvi(*killedLiveCommonedLoads);
while (bvi.hasMoreElements())
{
int32_t killedSymIdx = bvi.getNextElement();
if (trace())
traceMsg(comp(), " symbol stores to a live commoned reference, searching stores below that load this symbol via commoned reference ...\n");
_killMarkWalks++;
// find any stores that use this symbol (via a commoned reference) and mark them unmovable
ListElement<TR_MovableStore> *storeElement=potentiallyMovableStores.getListHead();
while (storeElement != NULL)
{
TR_MovableStore *store = storeElement->getData();
if (trace())
{
traceMsg(comp(), " examining store [" POINTER_PRINTF_FORMAT "]\n",store->_useOrKillInfo->_tt->getNode());
if (store->_movable &&
store->_commonedLoadsUnderTree &&
store->_commonedLoadsUnderTree->get(killedSymIdx))
{
traceMsg(comp(), " killedSymIdx = %d and temp is not needed\n", killedSymIdx);
}
}
if (store->_movable &&
store->_commonedLoadsUnderTree &&
store->_commonedLoadsUnderTree->get(killedSymIdx))
{
if (store->_depth >= MIN_TREE_DEPTH_TO_MOVE)
{
if (!store->_needTempForCommonedLoads)
store->_needTempForCommonedLoads = new (trStackMemory()) TR_BitVector(numLocals, trMemory());
store->_needTempForCommonedLoads->set(killedSymIdx);
store->_commonedLoadsUnderTree->reset(killedSymIdx);
}
else
store->_movable = false;
if (trace())
{
if (!store->_movable)
traceMsg(comp(), " marking store [" POINTER_PRINTF_FORMAT "] as unmovable because its tree depth is %d\n", store->_useOrKillInfo->_tt->getNode(), store->_depth);
else if (store->_needTempForCommonedLoads)
traceMsg(comp(), " marking store [" POINTER_PRINTF_FORMAT "] as movable with temp because it has commoned reference used sym %d\n", store->_useOrKillInfo->_tt->getNode(), killedSymIdx);
}
}
storeElement = storeElement->getNextElement();
}
}
// When the commoned symbols are tracked precisely it is enough to run the above code that intersects used
// with savedLiveCommonedLoads to find the first uses of symbols
// With this information an anchor or temp store can be created when/if it is actually needed in during
// sinkStorePlacement()
bool usedSymbolKilledBelow = usedSymbols->intersects(*killedLiveCommonedLoads);
if (usedSymbolKilledBelow)
{
TR_BitVector *firstRefsToKilledSymbols = new (trStackMemory()) TR_BitVector(*usedSymbols);
(*firstRefsToKilledSymbols) &= (*killedLiveCommonedLoads);
if (trace())
{
traceMsg(comp(), " (non-commoned) uses of killed symbols: ");
firstRefsToKilledSymbols->print(comp());
traceMsg(comp(), "\n");
}
ListElement<TR_MovableStore> *storeElement=potentiallyMovableStores.getListHead();
while (storeElement != NULL)
{
TR_MovableStore *store = storeElement->getData();
if (store->_movable &&
store->_needTempForCommonedLoads)
{
if (store->_needTempForCommonedLoads->intersects(*firstRefsToKilledSymbols))
{
// looking at bit vectors alone may not be enough to guarantee that a temp should actually be placed here see
// the comment in isCorrectCommonedLoad for more information
TR_BitVector *commonedLoadsUsedAboveStore = new (trStackMemory()) TR_BitVector(*(store->_needTempForCommonedLoads));
(*commonedLoadsUsedAboveStore) &= (*firstRefsToKilledSymbols);
if (trace())
{
traceMsg(comp()," found store [" POINTER_PRINTF_FORMAT "] below that may require a temp\n",store->_useOrKillInfo->_tt->getNode());
traceMsg(comp()," killed live commoned loads used above store:");
commonedLoadsUsedAboveStore->print(comp());
traceMsg(comp(),"\n");
}
genStoreToTempSyms(tt,
node,
commonedLoadsUsedAboveStore,
killedLiveCommonedLoads,
store->_useOrKillInfo->_tt->getNode(),
potentiallyMovableStores);
}
}
storeElement = storeElement->getNextElement();
}
}
bool canMoveStore=false;
TR_BitVector *moveStoreWithTemps = 0;
uint32_t indirectLoadCount = 0; // incremented by storeIsSinkingCandidate
int32_t treeDepth = 0;
bool isLoadStatic = false;
if (local != NULL &&
node->getOpCode().isStoreDirect())
{
TR::RegisterMappedSymbol *sym = node->getSymbolReference()->getSymbol()->getMethodMetaDataSymbol();
canMoveStore = true;
// TODO use aliasing to block sinking AR symbol stores
// It is not legal to sink AR symbols as exceptions points are implicit uses of these symbols
if (sym && sym->isMethodMetaData() && sym->castToMethodMetaDataSymbol()->getMethodMetaDataType() == TR_MethodMetaDataType_AR)
{
if (trace())
traceMsg(comp()," not sinking the AR symbol %s\n",sym->castToMethodMetaDataSymbol()->getName());
canMoveStore = false;
}
else if (foundException)
{
if (trace())
traceMsg(comp(), " can't move store with side effect\n");
canMoveStore = false;
}
else if (!storeIsSinkingCandidate(block, node, symIdx, false, indirectLoadCount, treeDepth, isLoadStatic, treeVisitCount,highestVisitCount)) // treeDepth is initialized when call return
{
if (trace())
traceMsg(comp(), " can't move store because it fails sinking candidate test\n");
canMoveStore = false;
}
else if (treeDepth > MAX_TREE_DEPTH_TO_MOVE)
{
if (trace())
traceMsg(comp(), " can't move store because the tree depth (%d) is too big (MAX_DEPTH = %d)\n", treeDepth, MAX_TREE_DEPTH_TO_MOVE);
canMoveStore = false;