-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathOMRLocalCSE.cpp
1835 lines (1580 loc) · 69.7 KB
/
OMRLocalCSE.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/LocalCSE.hpp"
#include <stdlib.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "compile/Compilation.hpp"
#include "compile/Method.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 "env/jittypes.h"
#include "il/AliasSetInterface.hpp"
#include "il/AutomaticSymbol.hpp"
#include "il/Block.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/MethodSymbol.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.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/List.hpp"
#include "infra/SimpleRegex.hpp"
#include "optimizer/Optimization.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "ras/Debug.hpp"
#define MAX_DEPTH 3000
#define MAX_COPY_PROP 400
#define REPLACE_MARKER (MAX_SCOUNT-2)
#define NUM_BUCKETS 107
#define VOLATILE_ONLY 0
#define NON_VOLATILE_ONLY 1
#define VOLATILE_AND_NON_VOLATILE 2
OMR::LocalCSE::LocalCSE(TR::OptimizationManager *manager)
: TR::Optimization(manager),
_storeMap(NULL),
_arrayRefNodes(NULL)
{
static const char *e = feGetEnv("TR_loadaddrAsLoad");
_loadaddrAsLoad = e ? atoi(e) != 0 : 1;
}
TR::Optimization *OMR::LocalCSE::create(TR::OptimizationManager *manager)
{
return new (manager->allocator()) TR::LocalCSE(manager);
}
bool OMR::LocalCSE::shouldCopyPropagateNode(TR::Node *parent, TR::Node *node, int32_t childNum, TR::Node *storeNode)
{
int32_t childAdjust = storeNode->getOpCode().isWrtBar() ? 2 : 1;
int32_t maxChild = storeNode->getNumChildren() - childAdjust;
if (node->getNumChildren() < maxChild)
return false;
for (int32_t k = 0; k < maxChild; k++)
{
if (storeNode->getChild(k) != node->getChild(k))
return false;
}
if (_numCopyPropagations >= MAX_COPY_PROP)
{
if (trace())
traceMsg(comp(),"z^z : _numCopyPropagations %d >= max %d\n",_numCopyPropagations,MAX_COPY_PROP);
return false;
}
return true;
}
bool OMR::LocalCSE::shouldCommonNode(TR::Node *parent, TR::Node *node)
{
return !node->isDataAddrPointer() && isTreetopSafeToCommon();
}
TR::Node * getRHSOfStoreDefNode(TR::Node * storeNode)
{
int32_t childAdjust = (storeNode->getOpCode().isWrtBar()) ? 2 : 1;
int32_t maxChild = storeNode->getNumChildren() - childAdjust;
return storeNode->getChild(maxChild);
}
TR::Node *OMR::LocalCSE::getNode(TR::Node *node)
{
if (_volatileState != VOLATILE_ONLY)
return node;
if (_simulatedNodesAsArray[node->getGlobalIndex()])
{
TR::Node *toReturn = _simulatedNodesAsArray[node->getGlobalIndex()];
if (trace())
traceMsg(comp(), "Updating comparison node n%dn to n%dn due to volatile simulation\n", node->getGlobalIndex(), toReturn->getGlobalIndex());
return toReturn;
}
return node;
}
bool OMR::LocalCSE::doExtraPassForVolatiles()
{
if (TR::isJ9() && comp()->getMethodHotness() >= hot && !comp()->getOption(TR_DisableLocalCSEVolatileCommoning))
return true;
return false;
}
int32_t OMR::LocalCSE::perform()
{
if (trace())
traceMsg(comp(), "Starting LocalCommonSubexpressionElimination\n");
TR::Region &stackRegion = comp()->trMemory()->currentStackRegion();
_storeMap = new (stackRegion) StoreMap((StoreMapComparator()), StoreMapAllocator(stackRegion));
TR::TreeTop *tt, *exitTreeTop;
for (tt = comp()->getStartTree(); tt; tt = exitTreeTop->getNextTreeTop())
{
exitTreeTop = tt->getExtendedBlockExitTreeTop();
_volatileState = VOLATILE_AND_NON_VOLATILE;
if (doExtraPassForVolatiles())
{
if (trace())
traceMsg(comp(), "LocalCSE entering 2 pass mode for volatile elimination - pass 1 for volatiles ONLY\n");
_volatileState = VOLATILE_ONLY;
transformBlock(tt, exitTreeTop);
if (trace())
traceMsg(comp(), "LocalCSE volatile only pass 1 complete - pass 2 for non-volatiles ONLY\n");
_volatileState = NON_VOLATILE_ONLY;
transformBlock(tt, exitTreeTop);
}
else
transformBlock(tt, exitTreeTop);
}
if (trace())
traceMsg(comp(), "\nEnding LocalCommonSubexpressionElimination\n");
_storeMap = NULL;
return 1; // actual cost
}
int32_t OMR::LocalCSE::performOnBlock(TR::Block *block)
{
if (block->getEntry())
{
_volatileState = VOLATILE_AND_NON_VOLATILE;
if (doExtraPassForVolatiles())
{
if (trace())
traceMsg(comp(), "LocalCSE entering 2 pass mode for volatile elimination - pass 1 for volatiles ONLY\n");
_volatileState = VOLATILE_ONLY;
transformBlock(block->getEntry(), block->getEntry()->getExtendedBlockExitTreeTop());
if (trace())
traceMsg(comp(), "LocalCSE volatile only pass 1 complete - pass 2 for non-volatiles ONLY\n");
_volatileState = NON_VOLATILE_ONLY;
transformBlock(block->getEntry(), block->getEntry()->getExtendedBlockExitTreeTop());
}
else
transformBlock(block->getEntry(), block->getEntry()->getExtendedBlockExitTreeTop());
}
return 0;
}
void OMR::LocalCSE::prePerformOnBlocks()
{
TR::Region &stackRegion = comp()->trMemory()->currentStackRegion();
_storeMap = new (stackRegion) StoreMap((StoreMapComparator()), StoreMapAllocator(stackRegion));
int32_t symRefCount = 0;//comp()->getSymRefCount();
int32_t nodeCount = 0;//comp()->getNodeCount();
_seenCallSymbolReferences.init(symRefCount, stackRegion, growable);
_availableLoadExprs.init(symRefCount, stackRegion, growable);
_availablePinningArrayExprs.init(symRefCount, stackRegion, growable);
_availableCallExprs.init(symRefCount, stackRegion, growable);
_seenSymRefs.init(symRefCount, stackRegion, growable);
_possiblyRelevantNodes.init(symRefCount, stackRegion, growable);
_relevantNodes.init(symRefCount, stackRegion, growable);
_killedPinningArrayExprs.init(symRefCount, stackRegion, growable);
_killedNodes.init(nodeCount, stackRegion, growable);
_parentAddedToHT.init(nodeCount, stackRegion, growable);
comp()->incVisitCount();
_mayHaveRemovedChecks = false;
manager()->setAlteredCode(false);
_simulatedNodesAsArray = (TR::Node**)trMemory()->allocateStackMemory(comp()->getNodeCount()*sizeof(TR::Node*));
memset(_simulatedNodesAsArray, 0, comp()->getNodeCount()*sizeof(TR::Node*));
}
void OMR::LocalCSE::postPerformOnBlocks()
{
_storeMap = NULL;
if (_mayHaveRemovedChecks)
requestOpt(OMR::catchBlockRemoval);
}
bool
OMR::LocalCSE::isFirstReferenceToNode(TR::Node *parent, int32_t index, TR::Node *node, vcount_t visitCount)
{
return (visitCount > node->getVisitCount());
}
bool OMR::LocalCSE::shouldTransformBlock(TR::Block *block)
{
if (block->isCold())
return false;
return true;
}
void OMR::LocalCSE::transformBlock(TR::TreeTop * entryTree, TR::TreeTop * exitTree)
{
if (!shouldTransformBlock(entryTree->getNode()->getBlock()))
return;
// From here, down, stack memory allocations will die when the function returns
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
TR::TreeTop *currentTree = entryTree;
int32_t numStores = 0, numNullChecks = 0;
_numNodes = 0;
_numNullCheckNodes = 0;
_numCopyPropagations = 0;
_arrayRefNodes = new (stackMemoryRegion) TR_ScratchList<TR::Node>(trMemory());
// Count the number of stores and null checks in this method; this is
// required to allocate data structures of the correct size. Null checks
// need to be counted separately as they are slightly different from other
// nodes in that equivalence of NULLCHKs is dictated by the null check
// reference rather than the entire subtree under the NULLCHK. Stores need
// to be counted separately as local copy propagation is done simultaneously
// along with local CSE. Also the total number of nodes are counted for
// allocating data structures for local commoning.
//
_possiblyRelevantNodes.empty();
_relevantNodes.empty();
_availableLoadExprs.empty();
_availablePinningArrayExprs.empty();
_killedPinningArrayExprs.empty();
_availableCallExprs.empty();
_parentAddedToHT.empty();
_killedNodes.empty();
// Visit counts are incremented multiple times while transforming a block.
// For each block, make sure there is enough room in the visit count to do this.
comp()->incOrResetVisitCount();
for (currentTree = entryTree->getNextRealTreeTop();
currentTree != exitTree->getNextTreeTop();
currentTree = currentTree->getNextRealTreeTop())
{
TR::Node *node = currentTree->getNode();
if (node->getStoreNode())
numStores++;
if (node->getOpCodeValue() == TR::NULLCHK)
numNullChecks++;
getNumberOfNodes(node);
}
_storeMap->clear();
_nullCheckNodesAsArray = (TR::Node**)trMemory()->allocateStackMemory(numNullChecks*sizeof(TR::Node*));
memset(_nullCheckNodesAsArray, 0, numNullChecks*sizeof(TR::Node*));
_replacedNodesAsArray = (TR::Node**)trMemory()->allocateStackMemory(_numNodes*sizeof(TR::Node*));
_replacedNodesByAsArray = (TR::Node**)trMemory()->allocateStackMemory(_numNodes*sizeof(TR::Node*));
memset(_replacedNodesAsArray, 0, _numNodes*sizeof(TR::Node*));
memset(_replacedNodesByAsArray, 0, _numNodes*sizeof(TR::Node*));
_hashTable = new (stackMemoryRegion) HashTable(std::less<int32_t>(), stackMemoryRegion);
_hashTableWithSyms = new (stackMemoryRegion) HashTable(std::less<int32_t>(), stackMemoryRegion);
_hashTableWithCalls = new (stackMemoryRegion) HashTable(std::less<int32_t>(), stackMemoryRegion);
_hashTableWithConsts = new (stackMemoryRegion) HashTable(std::less<int32_t>(), stackMemoryRegion);
_nextReplacedNode = 0;
TR_BitVector seenAvailableLoadedSymbolReferences(stackMemoryRegion);
_seenCallSymbolReferences.empty();
_seenSymRefs.empty();
int32_t nextNodeIndex = 0;
comp()->incVisitCount();
_curBlock = entryTree->getNode()->getBlock();
for (currentTree = entryTree->getNextRealTreeTop();
currentTree != exitTree->getNextTreeTop();
currentTree = currentTree->getNextRealTreeTop())
{
// set up new current treetop being examined and do any
// processing necessary on the treetop
onNewTreeTop(currentTree);
_canBeAvailable = true;
_isAvailableNullCheck = true;
_inSubTreeOfNullCheckReference = false;
_isTreeTopNullCheck = false;
TR::Node *currentNode = currentTree->getNode();
if (currentNode->getOpCodeValue() == TR::NULLCHK)
_isTreeTopNullCheck = true;
else if (currentNode->getOpCodeValue() == TR::BBStart)
_curBlock = currentNode->getBlock();
//
// This is the call to do local commoning and local copy propagation on this tree
//
bool nodeCanBeAvailable = true;
examineNode(currentNode, seenAvailableLoadedSymbolReferences, NULL, -1, &nextNodeIndex, &nodeCanBeAvailable, 0);
}
comp()->invalidateAliasRegion();
}
#ifdef J9_PROJECT_SPECIFIC
void
OMR::LocalCSE::setIsInMemoryCopyPropFlag(TR::Node *rhsOfStoreDefNode)
{
if (_treeBeingExamined &&
!rhsOfStoreDefNode->getOpCode().isLoadConst() &&
cg()->IsInMemoryType(rhsOfStoreDefNode->getType()))
{
if (cg()->traceBCDCodeGen() && _treeBeingExamined->getNode()->chkOpsIsInMemoryCopyProp() && !_treeBeingExamined->getNode()->isInMemoryCopyProp())
traceMsg(comp(),"\tset IsInMemoryCopyProp on %s (%p), rhsOfStoreDefNode %s (%p)\n",
_treeBeingExamined->getNode()->getOpCode().getName(),_treeBeingExamined->getNode(),rhsOfStoreDefNode->getOpCode().getName(),rhsOfStoreDefNode);
_treeBeingExamined->getNode()->setIsInMemoryCopyProp(true);
}
}
#endif
bool
OMR::LocalCSE::allowNodeTypes(TR::Node *storeNode, TR::Node *node)
{
if (storeNode->getDataType() == node->getDataType())
{
return true;
}
else if (storeNode->getType().isIntegral() && node->getType().isAggregate() &&
storeNode->getSize() == node->getSize())
{
return true;
}
return false;
}
/**
* Method examineNode
* ------------------
*
* This method performs local copy propagation and local common
* subexpression elimination on a given node.
*/
void OMR::LocalCSE::examineNode(TR::Node *node, TR_BitVector &seenAvailableLoadedSymbolReferences, TR::Node *parent, int32_t childNum, int32_t *nextLoadIndex, bool *parentCanBeAvailable, int32_t depth)
{
if (depth > MAX_DEPTH)
{
comp()->failCompilation<TR::ExcessiveComplexity>("scratch space in local CSE");
}
// If register pressure is high at this point, then nothing should be commoned or copy propagated across this point
// To achieve that, we clear all the commoning and copy propagation related information here
if (!canAffordToIncreaseRegisterPressure(node))
{
killAllDataStructures(seenAvailableLoadedSymbolReferences);
}
TR::ILOpCodes opCodeValue = node->getOpCodeValue();
bool nodeCanBeAvailable = true;
vcount_t visitCount = comp()->getVisitCount();
if (trace())
traceMsg(comp(), "Examining node %p\n",node);
if (!isFirstReferenceToNode(parent, childNum, node, visitCount))
{
if (trace())
traceMsg(comp(), "\tNot first Reference to Node\n");
doCommoningAgainIfPreviouslyCommoned(node, parent, childNum);
return;
}
TR::Node *nullCheckReference = NULL;
if (_isTreeTopNullCheck)
{
if (_treeBeingExamined->getNode()->getNullCheckReference() == node)
{
_inSubTreeOfNullCheckReference = true;
nullCheckReference = node;
}
}
for (int32_t i = 0 ; i < node->getNumChildren(); i++)
examineNode(node->getChild(i), seenAvailableLoadedSymbolReferences, node, i, nextLoadIndex, &nodeCanBeAvailable, depth+1);
node->setVisitCount(visitCount);
bool doneCopyPropagation = false;
bool doneCommoning = false;
// Note : Local copy propagation has been disabled for floats and doubles
// because of strict/non strict problems when a very large float/double value
// is stored and then read.
//
TR::SymbolReference * symRef = node->getOpCode().hasSymbolReference() ? node->getSymbolReference() : 0;
if (symRef && node->getOpCode().isLoadVar())
{
StoreMap::iterator result = _storeMap->find(symRef->getReferenceNumber());
if (result != _storeMap->end() && result->second->getSymbolReference()->getReferenceNumber() == symRef->getReferenceNumber())
{
// Base case: where symrefs match
doCopyPropagationIfPossible(node, parent, childNum, result->second, symRef, visitCount, doneCopyPropagation);
}
else if (node->getOpCode().isLoadIndirect() &&
node->getFirstChild()->getVisitCount() >= visitCount)
{
// Case #2: symrefs don't match, but underlying objects match by checking sizes, types, offsets, etc.
for (auto itr = _storeMap->begin(), end = _storeMap->end(); itr != end; ++itr)
{
TR::Node *storeNode = itr->second;
if (storeNode->getOpCode().isStoreIndirect() &&
storeNode->getSymbolReference()->getSymbol()->getSize() == symRef->getSymbol()->getSize() &&
storeNode->getSymbolReference()->getSymbol()->getDataType() == symRef->getSymbol()->getDataType() &&
allowNodeTypes(storeNode, node) &&
storeNode->getSymbolReference()->getOffset() == symRef->getOffset()
#ifdef J9_PROJECT_SPECIFIC
&& (!storeNode->getType().isBCD() ||
storeNode->getDecimalPrecision() == node->getDecimalPrecision())
#endif
)
{
if (doCopyPropagationIfPossible(node, parent, childNum, storeNode, symRef, visitCount, doneCopyPropagation))
break;
}
}
}
}
// This node has not been commoned up before; so examine it now.
// The checks below isAvailableNullCheck and canBeAvailable are really
// fast checks that might rule out the possibility of the expression (node) being
// available. Essentially we check if ALL symbols in the expression are
// available (this does not guarantee that the expression is available)
// but if any symbol is unavailable, then it is impossible for the node
// to be available.
//
if (!doneCopyPropagation &&
(((node->getOpCodeValue() == TR::NULLCHK) && (isAvailableNullCheck(node, seenAvailableLoadedSymbolReferences))) ||
(canBeAvailable(parent, node, seenAvailableLoadedSymbolReferences, nodeCanBeAvailable))
|| (!_loadaddrAsLoad && node->getOpCodeValue() == TR::loadaddr)))
{
doCommoningIfAvailable(node, parent, childNum, doneCommoning);
}
// Code below deals with how the availability and copy propagation
// information is updated once this node is seen
//
TR_UseDefAliasSetInterface UseDefAliases = node->mayKill(true);
bool hasAliases = !UseDefAliases.isZero(comp());
bool alreadyKilledAtNonTransparentLoad = false;
if (hasAliases && !doneCommoning)
alreadyKilledAtNonTransparentLoad = killExpressionsIfNonTransparentLoad(node, seenAvailableLoadedSymbolReferences, UseDefAliases);
// Step 1 : add this node to the data structures so that it can be considered for commoning
//
if (!(doneCommoning || doneCopyPropagation))
{
makeNodeAvailableForCommoning(parent, node, seenAvailableLoadedSymbolReferences, parentCanBeAvailable);
}
if (trace())
{
TR_BitVector tmpAliases(comp()->trMemory()->currentStackRegion());
traceMsg(comp(), "For Node %p UseDefAliases = ",node);
UseDefAliases.getAliasesAndUnionWith(tmpAliases);
tmpAliases.print(comp());
traceMsg(comp(), "\n");
}
// Step 2 : if this node is a potential kill point then update the fast and slow
// commoning and copy propagation info
//
if (node->getOpCode().isStore() || hasAliases)
{
// This node is a potential kill point
//
if (trace())
traceMsg(comp(), "\tnode %p isStore = %d or hasAliases = %d\n",node,node->getOpCode().isStore(),hasAliases);
int32_t symRefNum = node->getSymbolReference()->getReferenceNumber();
bool previouslyAvailable = false;
if (hasAliases)
{
//
// Kill slow copy propagation info
//
if (UseDefAliases.containsAny(_seenSymRefs, comp()))
{
int32_t storeNodesSize = static_cast<int32_t>(_storeMap->size());
// If we have over 500 store nodes, get aliases and iterate over the smaller set,
// Less than 500 nodes should not be too significant as to which set to iterate over.
if(storeNodesSize >= 500)
{
// Getting aliases can be very expensive if there are alot of aliases
// For this reason we don't always want to do this, only if storeNodes is large
// and we can make up the cost of getting aliases by iterating the smaller set
TR_BitVector tmpAliases(comp()->trMemory()->currentStackRegion());
UseDefAliases.getAliasesAndUnionWith(tmpAliases);
// Iterate over the smaller set to save compile time, this can be very significant
if (storeNodesSize < tmpAliases.elementCount())
{
for (auto itr = _storeMap->begin(), end = _storeMap->end(); itr != end; )
{
// Kill stores that are available for copy propagation based
// on this definition
TR::Node *storeNode = itr->second;
int32_t storeSymRefNum = storeNode->getSymbolReference()->getReferenceNumber();
if ((symRef->getReferenceNumber() == storeSymRefNum) || tmpAliases.get(storeSymRefNum))
{
_storeMap->erase(itr++);
}
else
++itr;
}
}
else
{
TR_BitVectorIterator bvi(tmpAliases);
while (bvi.hasMoreElements())
{
int32_t sc = bvi.getNextElement();
StoreMap::iterator result = _storeMap->find(sc);
if (result != _storeMap->end())
_storeMap->erase(sc);
}
}
}
else
{
for (auto itr = _storeMap->begin(), end = _storeMap->end(); itr != end; )
{
TR::Node *storeNode = itr->second;
int32_t storeSymRefNum = storeNode->getSymbolReference()->getReferenceNumber();
if ((symRef->getReferenceNumber() == storeSymRefNum) || UseDefAliases.contains(storeSymRefNum, comp()))
{
_storeMap->erase(itr++);
}
else
++itr;
}
}
}
// Kill fast commoning info
//
TR_BitVector tmp(seenAvailableLoadedSymbolReferences);
tmp -= _seenCallSymbolReferences;
if (trace())
{
traceMsg(comp(), "For node %p tmp: ",node);
tmp.print(comp());
traceMsg(comp(), "\n_seenCallSymbolReferences: ");
_seenCallSymbolReferences.print(comp());
traceMsg(comp(), "\n seenAvailableLoadedSymbolReferences:");
seenAvailableLoadedSymbolReferences.print(comp());
traceMsg(comp(), "\n");
}
if (UseDefAliases.containsAny(tmp, comp()))
{
// we want to keep the last load of a particular sym ref alive but no earlier loads should survive
// note that volatile processing already handles killing symbols when necessary hence the else
if (alreadyKilledAtNonTransparentLoad)
seenAvailableLoadedSymbolReferences.set(symRef->getReferenceNumber());
else
{
previouslyAvailable = true;
tmp = seenAvailableLoadedSymbolReferences;
tmp &= _seenCallSymbolReferences;
UseDefAliases.getAliasesAndSubtractFrom(seenAvailableLoadedSymbolReferences);
seenAvailableLoadedSymbolReferences |= tmp;
}
if (alreadyKilledAtNonTransparentLoad) // we want to keep the last load of a particular sym ref alive but no earlier loads should surivive
seenAvailableLoadedSymbolReferences.set(symRef->getReferenceNumber());
}
}
else
{
// There are no use def aliases
//
int32_t symRefNumber = symRef->getReferenceNumber();
// Kill slow copy propagation info
//
if (_seenSymRefs.get(symRefNumber))
{
for (auto itr = _storeMap->begin(), end = _storeMap->end(); itr != end; ++itr)
{
// Kill stores that are available for copy propagation based
// on this definition
TR::Node *storeNode = itr->second;
int32_t storeSymRefNum = storeNode->getSymbolReference()->getReferenceNumber();
if (symRefNumber == storeSymRefNum)
{
_storeMap->erase(itr++);
}
}
}
// Kill fast availability info for commoning
//
if (seenAvailableLoadedSymbolReferences.get(symRef->getReferenceNumber()))
previouslyAvailable = true;
seenAvailableLoadedSymbolReferences.reset(symRef->getReferenceNumber());
}
// Internal pointers should be killed if the pinning array was killed
//
if (symRef && symRef->getSymbol()->isAuto() &&
_availablePinningArrayExprs.get(symRef->getReferenceNumber()))
{
killAllInternalPointersBasedOnThisPinningArray(symRef);
}
// Only go into killing available expressions (i.e. slow availability info for commoning) if the symbol
// is available now; otherwise there is nothing to kill.
//
if (previouslyAvailable)
{
if (hasAliases)
killAvailableExpressionsUsingAliases(UseDefAliases);
if (node->getOpCode().isLikeDef())
killAvailableExpressions(symRefNum);
}
// Step 3 : add this node as a copy propagation candidate if it is a store
//
if (node->getOpCode().isStore())
{
(*_storeMap)[symRefNum] = node;
}
if (symRef && !node->getOpCode().isCall())
_seenSymRefs.set(symRef->getReferenceNumber());
}
killAvailableExpressionsAtGCSafePoints(node, parent, seenAvailableLoadedSymbolReferences);
if (_isTreeTopNullCheck)
{
if (nullCheckReference != NULL)
_inSubTreeOfNullCheckReference = false;
}
if (node->getOpCode().isCall())
{
seenAvailableLoadedSymbolReferences.set(node->getSymbolReference()->getReferenceNumber());
// pure calls can be commoned so we must observe kills
if (!node->isPureCall())
_seenCallSymbolReferences.set(node->getSymbolReference()->getReferenceNumber());
}
static char *verboseProcessing = feGetEnv("TR_VerboseLocalCSEAvailableSymRefs");
if (verboseProcessing)
{
traceMsg(comp(), " after n%dn [%p] seenAvailableLoadedSymbolReferences:", node->getGlobalIndex(), node);
seenAvailableLoadedSymbolReferences.print(comp());
traceMsg(comp(), "\n");
}
}
void OMR::LocalCSE::doCommoningAgainIfPreviouslyCommoned(TR::Node *node, TR::Node *parent, int32_t childNum)
{
for (int32_t i = 0; i < _nextReplacedNode;i++)
{
// If we have already seen this node before and commoned it up,
// then it will be present in the _replacedNodesAsArray data structure
// and we can common it up now again. When a parent node is commoned
// all its children get put into _replacedNodesAsArray (as they have
// common counterparts (children of node that the parent is commoned with)
//
if (_replacedNodesAsArray[i] == node &&
shouldCommonNode(parent, node) &&
performTransformation(comp(), "%s Local Common Subexpression Elimination commoning node : %p again\n", optDetailString(), node))
{
TR::Node *replacingNode = _replacedNodesByAsArray[i];
parent->setChild(childNum, replacingNode);
if (replacingNode->getReferenceCount() == 0)
recursivelyIncReferenceCount(replacingNode);
else
replacingNode->incReferenceCount();
if (node->getReferenceCount() <= 1)
optimizer()->prepareForNodeRemoval(node);
node->recursivelyDecReferenceCount();
if (parent->getOpCode().isResolveOrNullCheck() || ((parent->getOpCodeValue() == TR::compressedRefs) && (childNum == 0)))
{
TR::Node::recreate(parent, TR::treetop);
for (int32_t index =1;index < parent->getNumChildren(); index++)
parent->getChild(index)->recursivelyDecReferenceCount() ;
parent->setNumChildren(1);
}
break;
}
}
}
/**
* We can allow auto or parms which are not global during the volatile only phase
* as we do not expect those field to be changing. This enables up to common volatiles that are based on an
* indirection chain of such non volatile autos or parms that are not global by definition.
* Following query returns true if the node can be commoned in volatile only pass
*/
bool OMR::LocalCSE::canCommonNodeInVolatilePass(TR::Node *node)
{
return node->getOpCode().hasSymbolReference() && (!node->getSymbol()->isTransparent() || node->getSymbol()->isAutoOrParm());
}
void OMR::LocalCSE::doCommoningIfAvailable(TR::Node *node, TR::Node *parent, int32_t childNum, bool &doneCommoning)
{
// If the expression can be available, search for it in the
// hash table and return the available expression; return NULL if
// no available expression was found to match this one.
//
TR::Node *availableExpression = getAvailableExpression(parent, node);
if (availableExpression && (availableExpression != node) &&
shouldCommonNode(parent, node) &&
performTransformation(comp(), "%s Local Common Subexpression Elimination commoning node : %p by available node : %p\n", optDetailString(), node, availableExpression))
{
if (!node->getOpCode().hasSymbolReference() ||
(_volatileState == VOLATILE_ONLY && canCommonNodeInVolatilePass(node)) ||
(_volatileState != VOLATILE_ONLY))
{
TR_ASSERT(_curBlock, "_curBlock should be non-null\n");
requestOpt(OMR::treeSimplification, true, _curBlock);
requestOpt(OMR::localReordering, true, _curBlock);
_mayHaveRemovedChecks = true;
if (parent != NULL)
{
// This node is not a treetop type node; so just make its
// (non NULL) parent point at the available child expression
//
doneCommoning = true;
manager()->setAlteredCode(true);
if (node->getLocalIndex() != REPLACE_MARKER)
collectAllReplacedNodes(node, availableExpression);
if ((!parent->getOpCode().isResolveOrNullCheck() &&
(parent->getOpCodeValue() != TR::DIVCHK)) &&
((parent->getOpCodeValue() != TR::compressedRefs) || (childNum != 0)))
commonNode(parent, childNum, node, availableExpression);
else
{
optimizer()->prepareForNodeRemoval(parent);
int32_t endIndex = _treeBeingExamined->getNode()->getNumChildren();
if (parent->getOpCodeValue() == TR::compressedRefs)
{
TR::Node::recreate(parent, TR::treetop);
for (int32_t index =1;index < parent->getNumChildren(); index++)
parent->getChild(index)->recursivelyDecReferenceCount() ;
parent->setNumChildren(1);
}
else
{
for (int32_t index =0;index < endIndex; index++)
_treeBeingExamined->getNode()->getChild(index)->recursivelyDecReferenceCount() ;
TR::TreeTop *prevTree = _treeBeingExamined->getPrevTreeTop();
TR::TreeTop *nextTree = _treeBeingExamined->getNextTreeTop();
prevTree->setNextTreeTop(nextTree);
nextTree->setPrevTreeTop(prevTree);
}
}
}
else
{
// This node is a treetop node; we might be able to remove the
// entire treetop if it is common (e.g. BNDCHK etc.)
//
TR::Node *node = _treeBeingExamined->getNode();
if (node->getOpCode().isResolveOrNullCheck())
{
TR_ASSERT(node->getNumChildren() == 1, "Local CSE, NULLCHK has more than one child");
// If the child of the nullchk is normally a treetop node, replace
// the nullchk with that node
//
if (node->getFirstChild()->getOpCode().isTreeTop())
{
if ((comp()->useAnchors() && node->getFirstChild()->getOpCode().isStoreIndirect()))
{
TR::Node::recreate(node, TR::treetop);
}
else
{
TR_ASSERT(node->getFirstChild()->getReferenceCount() == 1, "Local CSE, treetop child of NULLCHK has other uses");
// Make sure the child doesn't get removed too
//
node->getFirstChild()->incReferenceCount();
optimizer()->prepareForNodeRemoval(node);
node->getFirstChild()->setReferenceCount(0);
_treeBeingExamined->setNode(node->getFirstChild());
}
}
else
{
TR::Node::recreate(node, TR::treetop);
}
}
else
{
if (node->getLocalIndex() != REPLACE_MARKER)
collectAllReplacedNodes(node, availableExpression);
doneCommoning = true;
manager()->setAlteredCode(true);
optimizer()->prepareForNodeRemoval(node);
for (int32_t index =0;index < _treeBeingExamined->getNode()->getNumChildren(); index++)
_treeBeingExamined->getNode()->getChild(index)->recursivelyDecReferenceCount() ;
TR::TreeTop *prevTree = _treeBeingExamined->getPrevTreeTop();
TR::TreeTop *nextTree = _treeBeingExamined->getNextTreeTop();
prevTree->setNextTreeTop(nextTree);
nextTree->setPrevTreeTop(prevTree);
}
}
}
else
{
if (trace())
traceMsg(comp(), "Simulating commoning of node n%dn with n%dn - current mode %n\n", node->getGlobalIndex(), availableExpression->getGlobalIndex(), _volatileState);
_simulatedNodesAsArray[node->getGlobalIndex()] = availableExpression;
}
}
}
bool OMR::LocalCSE::doCopyPropagationIfPossible(TR::Node *node, TR::Node *parent, int32_t childNum, TR::Node *storeNode, TR::SymbolReference *symRef, vcount_t visitCount, bool &doneCopyPropagation)
{
if (!shouldCopyPropagateNode(parent, node, childNum, storeNode))
return false;
int32_t childAdjust = storeNode->getOpCode().isWrtBar() ? 2 : 1;
int32_t maxChild = storeNode->getNumChildren() - childAdjust;
TR::Node *rhsOfStoreDefNode = storeNode->getChild(maxChild);
bool isSafeToCommon = true;
if (!shouldCommonNode(node, rhsOfStoreDefNode))
isSafeToCommon = false;
if ((!comp()->getOption(TR_MimicInterpreterFrameShape) ||
!comp()->areSlotsSharedByRefAndNonRef() ||
!symRef->getSymbol()->isAuto() ||
!symRef->getSymbol()->castToAutoSymbol()->isSlotSharedByRefAndNonRef()) &&
shouldCommonNode(parent, node) &&
isSafeToCommon &&
canAffordToIncreaseRegisterPressure() &&
(!node->getOpCode().hasSymbolReference() ||
node->getSymbolReference() != comp()->getSymRefTab()->findVftSymbolRef()) &&
(symRef->storeCanBeRemoved() ||
(symRef->getSymbol()->isTransparent() &&
rhsOfStoreDefNode->getDataType() == TR::Float &&
(rhsOfStoreDefNode->getOpCode().isCall() ||
(rhsOfStoreDefNode->getOpCode().isLoadConst()) ||
rhsOfStoreDefNode->getOpCode().isLoadVar()))) &&
(!parent->getOpCode().isSpineCheck() || childNum != 0) &&
performTransformation(comp(), "%s Local Common Subexpression Elimination propagating local #%d in node : %p PARENT : %p from node %p\n", optDetailString(), symRef->getReferenceNumber(), node, parent, storeNode))
{
//TR::SymbolReference *originalSymbolReference = rhsOfStoreDefNode->getSymbolReference();
dumpOptDetails(comp(), "%s Rhs of store def node : %p\n", optDetailString(), rhsOfStoreDefNode);
TR_ASSERT(_curBlock, "_curBlock should be non-null\n");
requestOpt(OMR::treeSimplification, true, _curBlock);
requestOpt(OMR::localReordering, true, _curBlock);
#ifdef J9_PROJECT_SPECIFIC
// Set InMemoryCopyProp flag to help codegen evaluators distinguish between potential memory overlap
// created by the optimizer (vs present from the start) for in memory types (i.e. BCD and Aggregate)
setIsInMemoryCopyPropFlag(rhsOfStoreDefNode);
#endif
prepareToCopyPropagate(node, rhsOfStoreDefNode);
TR_ASSERT(parent, "No parent for eliminated expression");
manager()->setAlteredCode(true);
rhsOfStoreDefNode = replaceCopySymbolReferenceByOriginalIn(symRef/*, originalSymbolReference*/, storeNode, rhsOfStoreDefNode, node, parent, childNum);
node->setVisitCount(visitCount);
_replacedNodesAsArray[_nextReplacedNode] = node;
_replacedNodesByAsArray[_nextReplacedNode++] = rhsOfStoreDefNode;
if (parent->getOpCode().isResolveOrNullCheck() || ((parent->getOpCodeValue() == TR::compressedRefs) && (childNum == 0)))
{
TR::Node::recreate(parent, TR::treetop);
for (int32_t index =1;index < parent->getNumChildren(); index++)
parent->getChild(index)->recursivelyDecReferenceCount() ;
parent->setNumChildren(1);
}
doneCopyPropagation = true;
_numCopyPropagations++;
return true;
}
return false;
}
// Adjusts the availability information for the given node; called when
// the node is being examined by commoning
//
void OMR::LocalCSE::makeNodeAvailableForCommoning(TR::Node *parent, TR::Node *node, TR_BitVector &seenAvailableLoadedSymbolReferences, bool *canBeAvailable)
{
if (parent &&
(parent->getOpCodeValue() == TR::Prefetch) &&
(parent->getFirstChild() == node))
return;
if (comp()->cg()->supportsLengthMinusOneForMemoryOpts() && parent && parent->getOpCode().isMemToMemOp())
{
if (parent->getLastChild() == node)
return;
}
if (node->getOpCode().hasSymbolReference())
{
if (!seenAvailableLoadedSymbolReferences.get(node->getSymbolReference()->getReferenceNumber()))
{
*canBeAvailable = false;
if (_inSubTreeOfNullCheckReference)
_isAvailableNullCheck = false;
if (node->getOpCode().isLoadVar() ||
node->getOpCode().isCheck() ||
node->getOpCode().isCall() ||
node->getOpCodeValue() == TR::instanceof ||
((node->getOpCodeValue() == TR::loadaddr) &&
(node->getSymbol()->isNotCollected() ||
node->getSymbol()->isAutoOrParm())))
{
bool isCallDirect = false;
if (node->getOpCode().isCallDirect())
isCallDirect = true;