-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathIsolatedStoreElimination.cpp
1507 lines (1330 loc) · 58.1 KB
/
IsolatedStoreElimination.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 IBM Corp. and others 2000
*
* 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 https://www.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] https://openjdk.org/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR GPL-2.0-only WITH OpenJDK-assembly-exception-1.0
*******************************************************************************/
#include "optimizer/IsolatedStoreElimination.hpp"
#include <stdint.h>
#include <stdio.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "env/IO.hpp"
#include "env/StackMemoryRegion.hpp"
#include "env/TRMemory.hpp"
#include "il/Block.hpp"
#include "il/DataTypes.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/Array.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/Optimization.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/TransformUtil.hpp"
#include "optimizer/UnsafeSubexpressionRemover.hpp"
#include "optimizer/UseDefInfo.hpp"
#include "optimizer/VPConstraint.hpp"
#include "ras/Debug.hpp"
TR_IsolatedStoreElimination::TR_IsolatedStoreElimination(TR::OptimizationManager *manager)
: TR::Optimization(manager),
_mustUseUseDefInfo(false),
_deferUseDefInfoInvalidation(false),
_currentTree(NULL),
_usedSymbols(NULL),
_storeNodes(NULL),
_defParentOfUse(NULL),
_defStatus(NULL),
_groupsOfStoreNodes(NULL),
_trivialDefs(NULL)
{
}
int32_t TR_IsolatedStoreElimination::perform()
{
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
_storeNodes = new(trStackMemory()) TR_Array<TR::Node *>(trMemory(), 64, true, stackAlloc);
// If there is use/def information available, use it to find isolated stores.
// Otherwise we must munge through the trees.
//
TR_UseDefInfo *useDefInfo = optimizer()->getUseDefInfo();
int32_t cost = 0;
_mustUseUseDefInfo = false;
// The use of _mustUseUseDefInfo is temporary until all opts maintain proper
// changes to use/def info
//
if (useDefInfo)
{
if (trace())
traceMsg(comp(), "Starting Global Store Elimination (using use/def info)\n");
cost = performWithUseDefInfo();
}
else
{
if (trace())
traceMsg(comp(), "Starting Global Store Elimination (without using use/def info)\n");
cost = performWithoutUseDefInfo();
}
// Now remove the isolated stores.
//
bool eliminatedStore = false;
#ifdef J9_PROJECT_SPECIFIC
bool eliminatedBCDStore = false;
#endif
if (useDefInfo)
{
// Scan for unsafe nodes, which are loads that are uses of dead stores,
// or (recusrively) any node with at least one unsafe child.
// Even evaluating an unsafe node could cause incorrect behaviour; for
// example, if the unsafe node dereferences a load of a dead pointer
// whose store got deleted, then that dereference could crash at runtime.
//
OMR::UnsafeSubexpressionRemover usr(this);
for (uint32_t groupIndex = 0; groupIndex < _groupsOfStoreNodes->size(); groupIndex++)
{
TR_BitVector *groupOfStores = _groupsOfStoreNodes->element(groupIndex);
if (trace())
traceMsg(comp(), " Scanning store group %d for dead uses\n", groupIndex);
if (groupOfStores)
{
TR_BitVectorIterator storeIter(*groupOfStores);
while (storeIter.hasMoreElements())
{
int32_t defIndex = storeIter.getNextElement() + useDefInfo->getFirstDefIndex();
if (trace())
{
TR::Node *defNode = useDefInfo->getNode(defIndex);
traceMsg(comp(), " Scanning def %d %s n%dn for dead uses\n", defIndex, defNode->getOpCode().getName(), defNode->getGlobalIndex());
}
TR_UseDefInfo::BitVector useIndexes(comp()->allocator());
useDefInfo->getUsesFromDef(useIndexes, defIndex);
TR_UseDefInfo::BitVector::Cursor useCursor(useIndexes);
for (useCursor.SetToFirstOne(); useCursor.Valid(); useCursor.SetToNextOne())
{
int32_t useIndex = (int32_t)useCursor + useDefInfo->getFirstUseIndex();
TR::Node *useNode = useDefInfo->getNode(useIndex);
usr.recordDeadUse(useNode);
if (trace())
traceMsg(comp(), " Marked use %d %s n%dn dead\n", useIndex, useNode->getOpCode().getName(), useNode->getGlobalIndex());
}
}
}
}
// Now eliminate the dead stores
//
for (uint32_t groupIndex = 0; groupIndex < _groupsOfStoreNodes->size(); groupIndex++)
{
TR_BitVector *groupOfStores = _groupsOfStoreNodes->element(groupIndex);
if (groupOfStores && performTransformation(comp(), "%sGlobal Store Elimination eliminating group %d:\n", optDetailString(), groupIndex))
{
TR_BitVectorIterator bviUses(*groupOfStores);
while (bviUses.hasMoreElements())
{
int32_t index = bviUses.getNextElement() + useDefInfo->getFirstDefIndex();
TR::Node *node = useDefInfo->getNode(index);
TR::TreeTop *treeTop = useDefInfo->getTreeTop(index);
TR_ASSERT(node, "node should not be NULL at this point");
dumpOptDetails(comp(), "%sRemoving %s n%dn [" POINTER_PRINTF_FORMAT "] %s\n",
optDetailString(), node->getOpCode().getName(), node->getGlobalIndex(), node, node->getSymbolReference()->getSymbol()->isShadow() ? "(shadow)" : "");
#ifdef J9_PROJECT_SPECIFIC
if (node->getOpCode().isBCDStore())
eliminatedBCDStore = true;
#endif
_trivialDefs->reset(index); // It's not a trivial def if we're handling it as a group. If we try to do both, BOOM!
usr.eliminateStore(treeTop, node);
node->setFlags(0);
eliminatedStore = true;
}
}
}
TR_BitVectorIterator bvi(*_trivialDefs);
while (bvi.hasMoreElements())
{
int32_t index = bvi.getNextElement();
int32_t useDefIndex = index + useDefInfo->getFirstDefIndex();
TR::Node *node = useDefInfo->getNode(useDefIndex);
if (node)
{
if (trace())
{
traceMsg(comp(), "removing trivial node %p %s n%dn udi=%d\n", node, node->getOpCode().getName(), node->getGlobalIndex(), useDefIndex);
traceMsg(comp(), "correcting UseDefInfo:\n");
}
TR_UseDefInfo::BitVector defsOfRhs(comp()->allocator());
TR_UseDefInfo::BitVector nodeUses(comp()->allocator());
if (useDefInfo->getUseDef(defsOfRhs, node->getFirstChild()->getUseDefIndex()) && useDefInfo->getUsesFromDef(nodeUses, useDefIndex))
{
TR_UseDefInfo::BitVector::Cursor cursor1(defsOfRhs);
for (cursor1.SetToFirstOne(); cursor1.Valid(); cursor1.SetToNextOne())
{
int32_t nextDef = cursor1;
TR_UseDefInfo::BitVector::Cursor cursor2(nodeUses);
for (cursor2.SetToFirstOne(); cursor2.Valid(); cursor2.SetToNextOne())
{
int32_t nextUse = (int32_t) cursor2 + useDefInfo->getFirstUseIndex();
useDefInfo->resetUseDef(nextUse, index);
useDefInfo->setUseDef(nextUse, nextDef);
if (trace())
traceMsg(comp(), " useDefIndex %d defines %d\n", nextDef, nextUse);
}
}
}
useDefInfo->clearNode(node->getUseDefIndex());
if (node->getReferenceCount() < 1)
{
node->setFlags(0);
TR::Node::recreate(node, TR::treetop);
}
else
TR::Node::recreate(node, TR::PassThrough);
node->setFlags(0);
eliminatedStore = true;
dumpOptDetails(comp(), "%p \n",node);
}
}
//if (debug("deadStructure"))
//{
//
// Simplifying assumption made to avoid complications
// arising out of commoning across extended basic blocks that
// are partly in the loop and aprtly out of the loop.
// In such cases, the uses may appear to be all concentrated inside
// the loop but may not be the case because of commoning.
//
bool blocksHaveBeenExtended = false;
TR::Block *block = comp()->getStartTree()->getNode()->getBlock();
for (; block; block = block->getNextBlock())
{
if (block->isExtensionOfPreviousBlock())
{
blocksHaveBeenExtended = true;
break;
}
}
if (!blocksHaveBeenExtended && comp()->mayHaveLoops())
performDeadStructureRemoval(optimizer()->getUseDefInfo());
//}
}
else if (!_mustUseUseDefInfo)
{
for (int32_t i = _storeNodes->size()-1; i >= 0; --i)
{
TR::Node *node = _storeNodes->element(i);
if (node && performTransformation(comp(), "%s Global Store Elimination eliminating : %p\n", optDetailString(), node))
{
if (useDefInfo)
useDefInfo->clearNode(node->getUseDefIndex());
if (node->getReferenceCount() < 1)
{
node->setFlags(0);
TR::Node::recreate(node, TR::treetop);
}
else
TR::Node::recreate(node, TR::PassThrough);
node->setFlags(0);
eliminatedStore = true;
}
}
}
if (eliminatedStore)
{
#ifdef J9_PROJECT_SPECIFIC
if (eliminatedBCDStore)
requestOpt(OMR::treeSimplification); // some of the more complex BCD simplifications work best when refCounts == 1
#endif
requestDeadTreesCleanup();
requestOpt(OMR::catchBlockRemoval);
}
if (_deferUseDefInfoInvalidation)
{
_deferUseDefInfoInvalidation = false;
// useDefInfo was invalidated (deferred) so invalidate it now and release its memory
optimizer()->setUseDefInfo(NULL);
useDefInfo = NULL;
}
if (trace())
traceMsg(comp(), "\nEnding Global Store Elimination\n");
return cost; // Actual cost
}
bool TR_IsolatedStoreElimination::canRemoveStoreNode(TR::Node *node)
{
if (_currentTree) comp()->setCurrentBlock(_currentTree->getEnclosingBlock());
// We need to check for the special case when the RHS is a method meta data
// type as we have observed that this could in fact be some VM dependent
// operation that we do not want to remove.
//
if (!node->getSymbolReference()->getSymbol()->isTransparent())
return false;
if (node->dontEliminateStores())
return false;
TR_UseDefInfo *useDefInfo = optimizer()->getUseDefInfo();
return true;
}
void TR_IsolatedStoreElimination::removeRedundantSpills()
{
// Checking the following:
//
// iRegStore #123
// iload #123
// ...
//
// istore #123 <<< can be removed
// iRegLoad #123
//
TR_UseDefInfo *useDefInfo = optimizer()->getUseDefInfo();
for (TR::TreeTop *tt = comp()->getStartTree(); tt != 0; tt = tt->getNextTreeTop())
{
TR::Node *node = tt->getNode();
if (node->getOpCode().isStoreDirect() &&
node->getFirstChild()->getOpCode().isLoadReg() &&
node->getSymbolReference() == node->getFirstChild()->getRegLoadStoreSymbolReference())
{
uint16_t useIndex = node->getFirstChild()->getUseDefIndex();
if (!useIndex || !useDefInfo->isUseIndex(useIndex))
continue;
TR_UseDefInfo::BitVector defs(comp()->allocator());
if (useDefInfo->getUseDef(defs, useIndex))
{
bool redundantStore= true;
TR_UseDefInfo::BitVector::Cursor cursor(defs);
for (cursor.SetToFirstOne(); cursor.Valid(); cursor.SetToNextOne())
{
int32_t defIndex = cursor;
TR::Node *defNode;
if (defIndex >= useDefInfo->getFirstRealDefIndex() &&
(defNode = useDefInfo->getNode(defIndex)) &&
defNode->getOpCode().isStoreReg() &&
defNode->getFirstChild()->getOpCode().isLoadVarDirect() &&
defNode->getFirstChild()->getSymbolReference() == node->getSymbolReference())
{
// traceMsg(comp(), "Redundant store node=%p defNode=%p \n", node, defNode);
}
else
{
redundantStore = false;
}
}
if (redundantStore &&
performTransformation(comp(), "%s Removing redundant spill: (%p)\n", optDetailString(), node))
{
TR::Node::recreate(node, TR::treetop);
node->setFlags(0);
}
}
}
}
}
int32_t TR_IsolatedStoreElimination::performWithUseDefInfo()
{
removeRedundantSpills();
TR_UseDefInfo *info = optimizer()->getUseDefInfo();
int32_t i;
// Build up the set of all defs that are used by or'ing the usedef info for
// each use. The isolated stores are the ones that are left.
//
const int32_t bitVectorSize = info->getNumDefOnlyNodes();
_defParentOfUse = new(trStackMemory()) TR_Array<int32_t>(trMemory(), info->getNumUseNodes(), true, stackAlloc);
for (i = 0; i < info->getNumUseNodes();i++)
_defParentOfUse->add(-1);
//*******************************************************************************************
//FIXME: instead of having an array of int, use 4 bitvectors of states.
//One bitvetor will indicate if the node was visited or not.
//For those that were visited the corresponding bit in one of the bitvectors for ("ToBeRemoved" and "ShouldNotBeRemoved") should be set.
//The 4th bitvector is inTransit vector.
//So "NotToBeExamine should set the bits in "Visited" and also on "ShouldNotBeRemoved".
//After finding the group set the right bits in "ToBeRemoved" or "ShouldNotBeRemoved and update Visited vector. Also, emtpy InTransit vector
//*******************************************************************************************
_defStatus = new(trStackMemory()) TR_Array<defStatus>(trMemory(), info->getNumDefOnlyNodes(), true, stackAlloc);
_defStatus->setSize(info->getNumDefOnlyNodes());
_trivialDefs = new (trStackMemory()) TR_BitVector(info->getNumDefOnlyNodes(), trMemory(), stackAlloc);
_groupsOfStoreNodes = new(trStackMemory()) TR_Array<TR_BitVector *>(trMemory(), 4, true, stackAlloc);
info->buildDefUseInfo();
for (i = info->getNumDefOnlyNodes()-1; i >= 0; --i)
{
int32_t useDefIndex = i + info->getFirstDefIndex();
TR::Node *node = info->getNode(useDefIndex);
if (node && node->getOpCode().isStore())
{
TR::Symbol *sym = node->getSymbolReference()->getSymbol();
if (sym->isAuto() || sym->isParm() ||
sym->isAutoField() || sym->isParmField() ||
sym->isStatic() // the ones that reach exit will have it as a use
)
{
//into array of the size of uses walking the defs
collectDefParentInfo(useDefIndex,node,info);
TR::Node *firstChild = node->getFirstChild();
if (firstChild->getOpCode().isLoadVarDirect() &&
firstChild->getReferenceCount() == 1 &&
(firstChild->getSymbolReference() == node->getSymbolReference()))
{
_trivialDefs->set(i);
if (trace())
traceMsg(comp(), "Found trivial node %p %s n%dn udi=%d\n", node, node->getOpCode().getName(), node->getGlobalIndex(), i);
}
}
else
_defStatus->element(i) = doNotExamine;
}
else
_defStatus->element(i) = doNotExamine;
}
TR_BitVector currentGroupOfStores(bitVectorSize, trMemory(), stackAlloc);
for (i = info->getNumDefOnlyNodes()-1; i >= 0; --i)
{
if (_defStatus->element(i) == notVisited)
{
currentGroupOfStores.empty();
bool foundGroupOfStores = false;
foundGroupOfStores = groupIsolatedStores(i,¤tGroupOfStores, optimizer()->getUseDefInfo());
TR_BitVectorIterator bvi(currentGroupOfStores);
while (bvi.hasMoreElements())
{
int32_t index = bvi.getNextElement();
//update status
if (foundGroupOfStores)
_defStatus->element(index) = toBeRemoved;
else
_defStatus->element(index) = notToBeRemoved;
}
if (foundGroupOfStores)
{
TR_BitVector *newGroupOfStoresToRemove = new (trStackMemory()) TR_BitVector(bitVectorSize, trMemory(), stackAlloc);
newGroupOfStoresToRemove->setAll(bitVectorSize);
*newGroupOfStoresToRemove &= currentGroupOfStores;
_groupsOfStoreNodes->add(newGroupOfStoresToRemove);
}
}
}
return 0; // actual cost
}
void TR_IsolatedStoreElimination::collectDefParentInfo(int32_t defIndex,TR::Node *node, TR_UseDefInfo *info)
{
if (node->getReferenceCount() > 1)
return;
int32_t childNum;
for (childNum=0;childNum<node->getNumChildren();childNum++)
{
TR::Node *child = node->getChild(childNum);
if ((child->getReferenceCount() == 1) &&
child->getOpCode().isLoadVar())
{
int32_t index = child->getUseDefIndex();
if (index > 0) //parm or auto
{
int32_t useIndex = index - info->getFirstUseIndex();
_defParentOfUse->element(useIndex) = defIndex;
if (trace())
traceMsg(comp(), "DefParent - use %d has parent %d\n",useIndex,defIndex);
}
}
collectDefParentInfo(defIndex,child,info);
}
return;
}
// recusive check for node's children
static void examChildrenForValueNode(TR::TreeTop *tt, TR::Node *parent, TR::Node *valueNode, vcount_t visitCount)
{
if (parent->getVisitCount() == visitCount)
return;
parent->setVisitCount(visitCount);
for (int32_t childCount = 0; childCount < parent->getNumChildren(); childCount++)
{
TR::Node *child = parent->getChild(childCount);
if (child == valueNode)
child->decFutureUseCount();
examChildrenForValueNode(tt, child, valueNode, visitCount);
}
}
bool TR_IsolatedStoreElimination::groupIsolatedStores(int32_t defIndex,TR_BitVector *currentGroupOfStores, TR_UseDefInfo *info)
{
// TR_ASSERT(defIndex < info->getNumDefOnlyNodes(),"DSE: not a real def");
defStatus status = _defStatus->element(defIndex);
if ( status == inTransit || status == toBeRemoved)
{
if (trace())
traceMsg(comp(), "groupIsolated - DEF %d is inTransit or toBeRemoved - \n",defIndex);
return true;
}
else if ( status == notToBeRemoved)
{
if (trace())
traceMsg(comp(), "groupIsolated - DEF %d is notToBeRemoved - \n",defIndex);
return false;
}
else if (status == notVisited)
{
_defStatus->element(defIndex) = inTransit;
currentGroupOfStores->set(defIndex);
if (trace())
traceMsg(comp(), "groupIsolated - DEF %d is now investigated - \n", defIndex);
}
TR::Node *node = info->getNode(defIndex + info->getFirstDefIndex());
TR_ASSERT(node, "assertion failure");
TR::TreeTop *tt = info->getTreeTop(defIndex + info->getFirstDefIndex());
if (tt)
{
comp()->setCurrentBlock(tt->getEnclosingBlock());
#ifdef J9_PROJECT_SPECIFIC
// checking for killing of InMemoryLoadStore
if (node->getValueChild()->getOpCode().isBCDLoadVar() &&
node->getValueChild()->getOpCode().hasSymbolReference() &&
comp()->cg()->IsInMemoryType(node->getValueChild()->getType()) &&
node->getValueChild()->getReferenceCount() > 1)
{
TR::Node *valueChild = node->getValueChild();
valueChild->setFutureUseCount(valueChild->getReferenceCount() - 1);
vcount_t visitCount = comp()->incVisitCount();
for (TR::TreeTop *ttTemp = tt->getNextTreeTop(); ttTemp && (valueChild->getFutureUseCount() > 0); ttTemp = ttTemp->getNextTreeTop())
{
TR::Node *defNode = ttTemp->getNode()->getOpCodeValue() == TR::treetop ? ttTemp->getNode()->getFirstChild() : ttTemp->getNode();
bool defNodeHasSymRef = defNode->getOpCode().hasSymbolReference() && defNode->getSymbolReference();
if (defNodeHasSymRef && defNode->getSymbolReference()->canKill(valueChild->getSymbolReference()))
{
if (trace())
traceMsg(comp(), "%s groupIsolated - DEF %d cannot be removed due to InMemoryLoadStoreMarking \n", optDetailString(), defIndex);
return false;
}
examChildrenForValueNode(ttTemp, defNode, valueChild, visitCount);
}
}
#endif
}
if (!canRemoveStoreNode(node))
{
if (trace())
traceMsg(comp(), "groupIsolated - DEF %d cannot be removed \n",defIndex);
return false;
}
//Test that all uses of the def are under other store nodes (i.e. set in the defParent array).
//If even one of the uses is not under store node, then it imposible to remove this def, and thus return.
TR_UseDefInfo::BitVector usesOfThisDef(comp()->allocator());
if (!info->getUsesFromDef(usesOfThisDef, defIndex+info->getFirstDefIndex()))
{
if (trace())
traceMsg(comp(), "groupIsolated - DEF %d has no uses - can be removed \n", defIndex);
return true;
}
else
{
if (trace())
{
(*comp()) << usesOfThisDef << "\n";
}
}
TR_UseDefInfo::BitVector::Cursor cursor(usesOfThisDef);
for (cursor.SetToFirstOne(); cursor.Valid(); cursor.SetToNextOne())
{
int32_t useIndex = cursor;
//if store has no uses, can be removed.
if (_defParentOfUse->element(useIndex)== -1)
{
if (trace())
traceMsg(comp(), "groupIsolated - Use %d has no def parent - \n",useIndex);
return false;
}
}
//recurse: for each use of the def, get its parent store and recurse.
for (cursor.SetToFirstOne(); cursor.Valid(); cursor.SetToNextOne())
{
int32_t useIndex = cursor;
int32_t defParentIndex = _defParentOfUse->element(useIndex);
if (trace())
traceMsg(comp(), "groupIsolated - recursing for Def %d (parent of %d) - \n",defParentIndex,useIndex);
if (!groupIsolatedStores(defParentIndex,currentGroupOfStores,info))
return false;
}
return true;
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
int32_t TR_IsolatedStoreElimination::performWithoutUseDefInfo()
{
dumpOptDetails(comp(), "Perform without use def info\n");
// Assign an index to each local and parameter symbol.
//
TR::SymbolReferenceTable *symRefTab = comp()->getSymRefTab();
int32_t symRefCount = comp()->getSymRefCount();
int32_t i;
int32_t numSymbols = 1;
for (i = symRefTab->getIndexOfFirstSymRef(); i < symRefCount; i++)
{
TR::SymbolReference *symRef = symRefTab->getSymRef(i);
if (symRef)
{
TR::Symbol *sym = symRef->getSymbol();
if (sym)
{
if (sym->isParm() || sym->isAuto())
sym->setLocalIndex(numSymbols++);
else
sym->setLocalIndex(0);
}
}
}
_usedSymbols = new(trStackMemory()) TR_BitVector(numSymbols, trMemory(), stackAlloc);
// Go through the trees and
// 1) Mark each symbol referenced by a load as used
// 2) Remember all the stores to each symbol
//
vcount_t visitCount = comp()->incVisitCount();
bool seenMultiplyReferencedParent;
for (TR::TreeTop *treeTop = comp()->getStartTree(); treeTop; treeTop = treeTop->getNextTreeTop())
{
_currentTree = treeTop;
seenMultiplyReferencedParent = false;
examineNode(treeTop->getNode(), visitCount, seenMultiplyReferencedParent);
}
// Remove those stores that were not used when they were encountered in the
// tree walk but are now used.
//
for (i = _storeNodes->size()-1; i >= 0; --i)
{
TR::Node *node = _storeNodes->element(i);
if (node && _usedSymbols->get(node->getSymbolReference()->getSymbol()->getLocalIndex()))
_storeNodes->element(i) = NULL;
}
return 1; // actual cost
}
void TR_IsolatedStoreElimination::examineNode(TR::Node *node, vcount_t visitCount, bool seenMultiplyReferencedParent)
{
if (node->getVisitCount() == visitCount)
return;
node->setVisitCount(visitCount);
if (node->getReferenceCount() > 1)
seenMultiplyReferencedParent = true;
// Process the children
//
for (int32_t i = node->getNumChildren()-1; i >= 0; --i)
{
examineNode(node->getChild(i), visitCount, seenMultiplyReferencedParent);
}
// Now process this node. We are looking for stores or uses of a symbol to
// which we've assigned a non-zero local index (i.e. a local or a parm)
//
if (!node->getOpCode().hasSymbolReference())
return;
TR::SymbolReference *symRef = node->getSymbolReference();
if (symRef == NULL)
return;
TR::Symbol *sym = symRef->getSymbol();
if (!sym || !sym->getLocalIndex())
return;
// This is a reference to a symbol we're interested in.
//
if (node->getOpCode().isStore())
{
if (!_usedSymbols->get(sym->getLocalIndex()))
{
// Store to a local or parm that is (as yet) unused
//
if (canRemoveStoreNode(node))
_storeNodes->add(node);
}
}
else
{
if (seenMultiplyReferencedParent ||
(!(_currentTree->getNode()->getOpCode().isStore() &&
(_currentTree->getNode()->getSymbolReference()->getSymbol() == sym))))
{
// Use of a local or parm
//
_usedSymbols->set(sym->getLocalIndex());
}
//else
// printf("Ignoring load in same tree as store in %s\n", signature(comp()->getCurrentMethod()));
}
}
#define MAX_TOTAL_NODES 50000
#define MAX_CFG_SIZE 5000
void TR_IsolatedStoreElimination::performDeadStructureRemoval(TR_UseDefInfo *info)
{
TR::CFG * cfg = comp()->getFlowGraph();
if (info->getTotalNodes() > MAX_TOTAL_NODES || cfg->getNumberOfNodes() > MAX_CFG_SIZE)
return;
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
vcount_t visitCount = comp()->incVisitCount();
TR_Structure *rootStructure = comp()->getFlowGraph()->getStructure();
bool propagateRemovalToParent = false;
TR_BitVector *nodesInStructure = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
TR_BitVector *defsInStructure = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
findStructuresAndNodesUsedIn(info, rootStructure, visitCount, nodesInStructure, defsInStructure, &propagateRemovalToParent);
}
bool
TR_IsolatedStoreElimination::findStructuresAndNodesUsedIn(TR_UseDefInfo *info, TR_Structure *structure, vcount_t visitCount, TR_BitVector *nodesInStructure, TR_BitVector *defsInStructure, bool *propagateRemovalToParent)
{
bool canRemoveStructure = true;
int32_t onlyExitEdge = -1;
if (trace())
{
if (structure->asRegion())
traceMsg(comp(), "Inspecting region structure %d\n", structure->getNumber());
else
traceMsg(comp(), "Inspecting block structure %d\n",structure->getNumber());
}
if (structure->asRegion())
{
TR_RegionStructure *regionStructure = structure->asRegion();
if (regionStructure->isNaturalLoop() &&
regionStructure->numSubNodes() == 1 &&
(regionStructure->getParent() &&
regionStructure->getParent()->asRegion()->isCanonicalizedLoop()))
{
TR::Block *entryBlock = regionStructure->getEntryBlock();
TR_ScratchList<TR::Block> blocksInLoop(trMemory());
regionStructure->getBlocks(&blocksInLoop);
if ((blocksInLoop.getSize() == 1) &&
debug("deadStructure"))
analyzeSingleBlockLoop(regionStructure, entryBlock);
}
TR_StructureSubGraphNode *subNode;
TR_Structure *subStruct = NULL;
ListIterator<TR::CFGEdge> ei(®ionStructure->getExitEdges());
for (TR::CFGEdge *edge = ei.getCurrent(); edge != NULL; edge = ei.getNext())
{
TR_StructureSubGraphNode *edgeTo = toStructureSubGraphNode(edge->getTo());
if (onlyExitEdge == -1)
onlyExitEdge = edgeTo->getNumber();
else if (onlyExitEdge != edgeTo->getNumber())
{
onlyExitEdge = -1;
break;
}
}
if (onlyExitEdge == -1)
{
//try to propagate the removal if this structure to its parent.
//If the parent can be removed then it doesn't matter how many exit edges there are for this structure.
*propagateRemovalToParent = true;
if (regionStructure->getExitEdges().isDoubleton())
{
TR::CFGNode *firstNode = regionStructure->getExitEdges().getListHead()->getData()->getTo();
TR::CFGNode *secondNode = regionStructure->getExitEdges().getLastElement()->getData()->getTo();
TR::CFG *cfg = comp()->getFlowGraph();
TR::Block *firstExitBlock = NULL;
TR::Block *secondExitBlock = NULL;
for (TR::CFGNode *node = cfg->getFirstNode(); node; node = node->getNext())
{
if (node->getNumber() == firstNode->getNumber())
firstExitBlock = toBlock(node);
if (node->getNumber() == secondNode->getNumber())
secondExitBlock = toBlock(node);
if (firstExitBlock && secondExitBlock)
break;
}
//check if the 2 exists point one to another
//(i.e. if A,B are the exists and A is a goto block to B).
//then there is one target to the structure
if (firstExitBlock->isGotoBlock(comp()) &&
(firstExitBlock->getSuccessors().front()->getTo()->asBlock()->getNumber()==secondExitBlock->getNumber()))
onlyExitEdge = secondExitBlock->getNumber();
else if (secondExitBlock->isGotoBlock(comp()) &&
(secondExitBlock->getSuccessors().front()->getTo()->asBlock()->getNumber()==firstExitBlock->getNumber()))
onlyExitEdge = firstExitBlock->getNumber();
//found one target, no need to propagate
if (onlyExitEdge != -1)
*propagateRemovalToParent = false;
}
}
bool subStructureHasSideEffect = false;
TR_BitVector *nodesInSubStructure = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
TR_BitVector *defsInSubStructure = new (trStackMemory()) TR_BitVector(0, trMemory(), stackAlloc, growable);
TR_RegionStructure::Cursor si(*regionStructure);
for (subNode = si.getCurrent(); subNode != NULL; subNode = si.getNext())
{
bool toPropagateRemoval = false;
nodesInSubStructure->empty();
defsInSubStructure->empty();
subStruct = subNode->getStructure();
if (findStructuresAndNodesUsedIn(info, subStruct, visitCount, nodesInSubStructure, defsInSubStructure, &toPropagateRemoval))
{
if (!toPropagateRemoval)
{
if (trace())
traceMsg(comp(),"returned true - subStructureHasSideEffect\n");
subStructureHasSideEffect = true;
}
}
*nodesInStructure |= *nodesInSubStructure;
*defsInStructure |= *defsInSubStructure;
}
if (subStructureHasSideEffect)
{
*propagateRemovalToParent = false;
if (trace())
traceMsg(comp(),"end of region %d (hasSideEffect)\n",structure->getNumber());
return true;
}
} //if structure->asRegion()
else
{
TR::Block *nextBlock = structure->asBlock()->getBlock();
if (!(nextBlock->getSuccessors().size() == 1) ||
nextBlock->getPredecessors().empty())
{
if(trace())
traceMsg(comp(),"cannot remove structure, pred is empty or succ is not singleton\n");
canRemoveStructure = false;
}
else
onlyExitEdge = nextBlock->getSuccessors().front()->getTo()->getNumber();
bool hasSideEffects = false;
TR::TreeTop *currentTree = nextBlock->getEntry();
TR::TreeTop *exitTree = nextBlock->getExit();
//traceMsg(comp(), "Examining block_%d\n", nextBlock->getNumber());
while (currentTree != exitTree)
{
TR::Node *currentNode = currentTree->getNode();
if (markNodesAndLocateSideEffectIn(currentNode, visitCount, nodesInStructure, defsInStructure))
hasSideEffects = true;
currentTree = currentTree->getNextRealTreeTop();
}
if (!nextBlock->getExceptionSuccessors().empty() ||
!nextBlock->getExceptionPredecessors().empty())
hasSideEffects = true;
if (hasSideEffects)
{
if (trace())
traceMsg(comp(),"block_%d hasSideEffects\n",nextBlock->getNumber());
return true;
}
}
if (canRemoveStructure)
{
// check for any defs whose uses appear outside this region
// we cannot remove structure if we find any of these
TR_BitVectorIterator defs(*defsInStructure);
while (canRemoveStructure && defs.hasMoreElements())
{
int32_t defIndex = defs.getNextElement();
if (trace())
traceMsg(comp(), "Checking defIndex %d\n", defIndex);
TR_UseDefInfo::BitVector uses(comp()->allocator());
info->getUsesFromDef(uses, defIndex);
TR_UseDefInfo::BitVector::Cursor useCursor(uses);
for (useCursor.SetToFirstOne(); canRemoveStructure && useCursor.Valid(); useCursor.SetToNextOne())
{
int32_t useIndex = (int32_t)useCursor + info->getFirstUseIndex();
TR::Node *useNode = info->getNode(useIndex);
if (useNode && useNode->getReferenceCount() > 0 && !nodesInStructure->get(useNode->getUseDefIndex()))
{
if (trace())
{
if (structure->asRegion())
traceMsg(comp(), "Use Node %d invalidates region structure %d - will propagate removal to parent\n", useIndex, structure->getNumber());
else
traceMsg(comp(), "Use Node %d invalidates block structure %d\n", useIndex, structure->getNumber());
}
canRemoveStructure = false;
if (structure->asRegion())
*propagateRemovalToParent = true;
}
}
}
// if we can remove the strucutre then these defs are ok here and in all parent structures
// so we don't need to check them again
if (canRemoveStructure)
defsInStructure->empty();
}
TR_RegionStructure *regionStructure = structure->asRegion();
if (canRemoveStructure)
{
if (*propagateRemovalToParent)
return true;
TR_BlockStructure *loopInvariantBlock = NULL;
if (regionStructure &&
regionStructure->isNaturalLoop() &&
(regionStructure->getParent() /* &&
regionStructure->getParent()->asRegion()->isCanonicalizedLoop() */))
{
TR_RegionStructure *parentStructure = regionStructure->getParent()->asRegion();
TR_StructureSubGraphNode *subNode = NULL;
TR_RegionStructure::Cursor si(*parentStructure);
for (subNode = si.getCurrent(); subNode != NULL; subNode = si.getNext())