-
Notifications
You must be signed in to change notification settings - Fork 397
/
Copy pathGlobalRegisterAllocator.cpp
5067 lines (4396 loc) · 213 KB
/
GlobalRegisterAllocator.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, 2021 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/GlobalRegisterAllocator.hpp"
#include <stdint.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "codegen/Machine.hpp"
#include "codegen/RegisterConstants.hpp"
#include "compile/Compilation.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "cs2/bitvectr.h"
#include "cs2/hashtab.h"
#include "cs2/sparsrbit.h"
#include "env/CompilerEnv.hpp"
#include "env/IO.hpp"
#include "env/ObjectModel.hpp"
#include "env/StackMemoryRegion.hpp"
#include "env/TRMemory.hpp"
#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/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/ParameterSymbol.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/Link.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/Optimization.hpp"
#include "optimizer/Optimization_inlines.hpp"
#include "optimizer/OptimizationManager.hpp"
#include "optimizer/Optimizations.hpp"
#include "optimizer/Optimizer.hpp"
#include "optimizer/RegisterCandidate.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/TransformUtil.hpp"
#include "optimizer/DataFlowAnalysis.hpp"
#include "optimizer/UseDefInfo.hpp"
#include "ras/Debug.hpp"
#define GRA_COMPLEXITY_LIMIT 1000000000
static bool isHot(TR::Compilation *comp) { return comp->getMethodHotness() >= hot; }
#define HAVE_DIFFERENT_MSB_TO_LSB_OFFSETS(r1,r2) \
((((r1)->getHostByteOffset() + (r1)->getSize()) - ((r2)->getHostByteOffset() + (r2)->getSize())) != 0)
static bool dontAssignInColdBlocks(TR::Compilation *comp) { return comp->getMethodHotness() >= hot; }
#define keepAllStores false
//TODO:GRA: if we are going to have two versions of GRA one with Meta Data and one without then we can do someting here
// for different compilation level then we can have two version of this, one using CPIndex and one (i.e. with MetaData)
// using getReferenceNumber
#define GET_INDEX_FOR_CANDIDATE_FOR_SYMREF(S) (S)->getReferenceNumber()
#define CANDIDATE_FOR_SYMREF_SIZE (comp()->getSymRefCount()+1)
//static TR_BitVector *resetExits;
//static TR_BitVector *seenBlocks;
//static TR_BitVector *successorBits;
#define OPT_DETAILS "O^O GLOBAL REGISTER ASSIGNER: "
// For both switch/table instructions and igoto instructions, the
// same sort of processing has to be done for each successor block.
// These classes are meant to allow that work to be independent of
// the way that the successor blocks are actually identified.
class switchSuccessorIterator;
class SuccessorIterator
{
public:
virtual TR::Block *getFirstSuccessor() = 0;
virtual TR::Block *getNextSuccessor() = 0;
virtual switchSuccessorIterator *asSwitchSuccessor() { return NULL; }
};
class switchSuccessorIterator : public SuccessorIterator
{
public:
TR_ALLOC(TR_Memory::RegisterCandidates)
switchSuccessorIterator(TR::Node *node) : node_(node), i_(node_->getCaseIndexUpperBound()) { }
switchSuccessorIterator *asSwitchSuccessor() { return this; }
TR::Block *getFirstSuccessor() { i_ = node_->getCaseIndexUpperBound(); return getNextSuccessor(); }
TR::Block *getNextSuccessor()
{
for (i_ = (i_ > 0) ? i_ - 1 : 0;
i_ > 0 && !node_->getChild((int32_t)i_)->getOpCode().isCase();
--i_);
if (i_ == 0)
{
return NULL;
}
else
{
return node_->getChild((int32_t)i_)->getBranchDestination()->getNode()->getBlock();
}
}
TR::Node *getCaseNode()
{
TR_ASSERT(i_ > 0 && i_ < node_->getCaseIndexUpperBound(), "getCaseNode not called on valid successor");
return node_->getChild((int32_t)i_);
}
private:
TR::Node * node_;
intptr_t i_;
//TR::Compilation * comp_;
};
class multipleJumpSuccessorIterator : public SuccessorIterator
{
public:
TR_ALLOC(TR_Memory::RegisterCandidates)
multipleJumpSuccessorIterator(TR::Block * currBlock)
{
_list = &currBlock->getSuccessors();
_iterator = _list->begin();
}
TR::Block *getFirstSuccessor()
{
_iterator = _list->begin();
return getNextSuccessor_();
}
TR::Block *getNextSuccessor()
{
if (_iterator != _list->end())
++_iterator;
return getNextSuccessor_();
}
private:
TR::Block *getNextSuccessor_()
{
if (_iterator == _list->end())
return NULL;
else
return (*_iterator)->getTo()->asBlock();
}
TR::CFGEdgeList::iterator _iterator;
TR::CFGEdgeList* _list;
};
///////////////////////////////////////////////////////////////////
// TR_GlobalRegisterAllocator
///////////////////////////////////////////////////////////////////
TR_GlobalRegisterAllocator::TR_GlobalRegisterAllocator(TR::OptimizationManager *manager)
: TR::Optimization(manager),
_pairedSymbols(manager->trMemory()),
_newBlocks(manager->trMemory()),
_osrCatchSucc(NULL)
{}
void TR_GlobalRegisterAllocator::populateSymRefNodes(TR::Node *node, vcount_t visitCount)
{
if (node->getVisitCount() == visitCount)
return;
node->setVisitCount(visitCount);
if (node->getOpCode().hasSymbolReference())
_nodesForSymRefs[node->getSymbolReference()->getReferenceNumber()] = node;
for (int32_t i = 0; i < node->getNumChildren(); ++i)
{
TR::Node *child = node->getChild(i);
populateSymRefNodes(child, visitCount);
}
}
/**
* The cg considerTypeForGRA calls below are the functional tests (i.e. avoid BCD and some aggregates)
* The allocateFor checks are for tuning for scalability when running in limited GRA mode
*/
bool TR_GlobalRegisterAllocator::allocateForSymRef(TR::SymbolReference *symRef)
{
return true;
}
bool TR_GlobalRegisterAllocator::isSymRefAvailable(TR::SymbolReference *symRef)
{
if (!comp()->cg()->considerTypeForGRA(symRef))
return false;
return allocateForSymRef(symRef);
}
/**
* For the findLoops case consider the number of blocks too
*/
bool TR_GlobalRegisterAllocator::isSymRefAvailable(TR::SymbolReference *symRef, List<TR::Block> *blocksInLoop)
{
if (!comp()->cg()->considerTypeForGRA(symRef))
return false;
bool loopHasOneBlock = blocksInLoop && (blocksInLoop->getListHead()->getNextElement() == NULL);
return true;
}
bool TR_GlobalRegisterAllocator::allocateForType(TR::DataType dt)
{
return true;
}
bool TR_GlobalRegisterAllocator::isNodeAvailable(TR::Node *node)
{
if (!comp()->cg()->considerTypeForGRA(node))
return false;
return allocateForType(node->getDataType());
}
bool TR_GlobalRegisterAllocator::isTypeAvailable(TR::SymbolReference *symref)
{
if (!comp()->cg()->considerTypeForGRA(symref))
return false;
return allocateForType(symref->getSymbol()->getDataType());
}
void
TR_GlobalRegisterAllocator::visitNodeForDataType(TR::Node *node)
{
if(node->getVisitCount() >= comp()->getVisitCount())
return;
node->setVisitCount(comp()->getVisitCount());
//visit children
for(int32_t i = 0 ; i < node->getNumChildren() ; i++)
{
visitNodeForDataType(node->getChild(i));
}
if(!node->getOpCode().hasSymbolReference())
return;
if(node->getDataType() != node->getSymbol()->getDataType() && node->getSymbol()->getDataType() == TR::Aggregate)
{
comp()->cg()->addSymbolAndDataTypeToMap(node->getSymbol(),node->getDataType());
}
}
void
TR_GlobalRegisterAllocator::walkTreesAndCollectSymbolDataTypes()
{
comp()->incOrResetVisitCount();
for (TR::TreeTop * tt = comp()->getStartTree(); tt; tt = tt->getNextTreeTop())
{
visitNodeForDataType(tt->getNode());
}
}
int32_t
TR_GlobalRegisterAllocator::perform()
{
LexicalTimer t("TR_GlobalRegisterAllocator::perform", comp()->phaseTimer());
if (comp()->hasLargeNumberOfLoops())
{
return 0;
}
comp()->cg()->setGRACompleted(); // means "full GRA"
if (comp()->getOption(TR_MimicInterpreterFrameShape) && ((!comp()->getOption(TR_EnableOSR) && !comp()->getOption(TR_FSDGRA)) || comp()->getJittedMethodSymbol()->sharesStackSlots(comp())))
return 1;
if (comp()->isGPUCompilation())
return 1;
walkTreesAndCollectSymbolDataTypes();
comp()->getOptimizer()->setResetExitsGRA(0);
comp()->getOptimizer()->setSeenBlocksGRA(0);
comp()->getOptimizer()->setSuccessorBitsGRA(0);
bool globalFPAssignmentDone = false;
_appendBlock = 0;
TR::CFG * cfg = comp()->getFlowGraph();
TR::Block * *cfgBlocks = cfg->createArrayOfBlocks();
int32_t numberOfBlocks = cfg->getNextNodeNumber();
TR_RegisterCandidates * candidates = comp()->getGlobalRegisterCandidates();
candidates->_candidateForSymRefs = new (trStackMemory()) TR_RegisterCandidates::SymRefCandidateMap((TR_RegisterCandidates::SymRefCandidateMapComparator()), (TR_RegisterCandidates::SymRefCandidateMapAllocator(trMemory()->currentStackRegion())));
TR_RegisterCandidate *rc = candidates->getFirst();
for (; rc ; rc = rc->getNext())
(*candidates->_candidateForSymRefs)[GET_INDEX_FOR_CANDIDATE_FOR_SYMREF(rc->getSymbolReference())] = rc;
candidates->_startOfExtendedBBForBB.init(trMemory(),
(uint32_t)(comp()->getFlowGraph()->getNextNodeNumber() * sizeof(TR::Block *) * 1.5),
false, stackAlloc);
TR::Block * lastStartOfExtendedBB = comp()->getStartBlock();
for (TR::Block * b = lastStartOfExtendedBB; b; b = b->getNextBlock())
{
lastStartOfExtendedBB = b->isExtensionOfPreviousBlock() ? lastStartOfExtendedBB : b;
candidates->_startOfExtendedBBForBB[b->getNumber()] = lastStartOfExtendedBB;
}
comp()->getOptimizer()->setCachedExtendedBBInfoValid(true);
if (cg()->getSupportsGlRegDeps() && !debug("disableGRA") && cg()->prepareForGRA())
{
static char *useFreqs = feGetEnv("TR_GRA_UseProfilingFrequencies");
if (useFreqs)
comp()->setUsesBlockFrequencyInGRA();
TR_BitVector *liveVars = NULL;
if (!cg()->getLiveLocals())
{
int32_t numLocals = 0;
TR::AutomaticSymbol *a;
ListIterator<TR::AutomaticSymbol> locals(&comp()->getMethodSymbol()->getAutomaticList());
for (a = locals.getFirst(); a != NULL; a = locals.getNext())
++numLocals;
if (comp()->getOption(TR_EnableAggressiveLiveness))
{
TR::ParameterSymbol *p;
ListIterator<TR::ParameterSymbol> parms(&comp()->getMethodSymbol()->getParameterList());
for (p = parms.getFirst(); p != NULL; p = parms.getNext())
++numLocals;
}
const uint64_t MAX_BITVECTOR_MEMORY_USAGE = 1000000000;
uint64_t bitvectorMemoryUsage = numLocals * comp()->getFlowGraph()->getNextNodeNumber();
if (
numLocals > 0 && (!trace() || performTransformation(comp(), "%s Performing liveness for Global Register Allocator\n", OPT_DETAILS)))
{
// Perform liveness analysis
//
TR_Liveness liveLocals(comp(), optimizer(), comp()->getFlowGraph()->getStructure(),
false, NULL, false, comp()->getOption(TR_EnableAggressiveLiveness));
if (comp()->getVisitCount() > HIGH_VISIT_COUNT)
{
comp()->resetVisitCounts(1);
}
for (TR::CFGNode *cfgNode = comp()->getFlowGraph()->getFirstNode(); cfgNode; cfgNode = cfgNode->getNext())
{
TR::Block *block = toBlock(cfgNode);
int32_t blockNum = block->getNumber();
if (blockNum > 0 && liveLocals._blockAnalysisInfo[blockNum])
{
liveVars = new (trHeapMemory()) TR_BitVector(numLocals, trMemory());
*liveVars = *liveLocals._blockAnalysisInfo[blockNum];
block->setLiveLocals(liveVars);
}
}
// Make sure the code generator knows there are live locals for blocks, and
// create a bit vector of the correct size for it.
//
liveVars = new (trHeapMemory()) TR_BitVector(numLocals, trMemory());
cg()->setLiveLocals(liveVars);
}
}
if (trace())
comp()->dumpMethodTrees("Trees before tactical global register allocator", comp()->getMethodSymbol());
_candidatesNeedingSignExtension = NULL;
_candidatesSignExtendedInThisLoop = NULL;
_temp = NULL;
_origSymRefCount = comp()->getSymRefCount();
_temp2 = new (trStackMemory()) TR_BitVector(_origSymRefCount, trMemory(), stackAlloc);
if (comp()->target().is64Bit() &&
optimizer()->getUseDefInfo())
{
_temp = new (trStackMemory()) TR_BitVector(optimizer()->getUseDefInfo()->getNumDefNodes(), trMemory(), stackAlloc);
_candidatesNeedingSignExtension = new (trStackMemory()) TR_BitVector(_origSymRefCount, trMemory(), stackAlloc);
_candidatesSignExtendedInThisLoop = new (trStackMemory()) TR_BitVector(_origSymRefCount, trMemory(), stackAlloc);
}
candidates->getReferencedAutoSymRefs(comp()->trMemory()->currentStackRegion());
if (!comp()->mayHaveLoops() || cg()->considerAllAutosAsTacticalGlobalRegisterCandidates())
offerAllAutosAndRegisterParmAsCandidates(cfgBlocks, numberOfBlocks);
else
offerAllFPAutosAndParmsAsCandidates(cfgBlocks, numberOfBlocks);
_registerCandidates = new (trStackMemory()) SymRefCandidateMap((SymRefCandidateMapComparator()), SymRefCandidateMapAllocator(trMemory()->currentStackRegion()));
_candidates = comp()->getGlobalRegisterCandidates();
for (TR_RegisterCandidate * rc = _candidates->getFirst(); rc; rc = rc->getNext())
{
(*_registerCandidates)[rc->getSymbolReference()->getReferenceNumber()] = rc;
}
findIfThenRegisterCandidates();
findLoopAutoRegisterCandidates();
if (comp()->getOptions()->realTimeGC() &&
comp()->compilationShouldBeInterrupted(GRA_AFTER_FIND_LOOP_AUTO_CONTEXT))
{
comp()->failCompilation<TR::CompilationInterrupted>("interrupted during GRA");
}
bool canAffordAssignment = true;
if (!comp()->getOption(TR_ProcessHugeMethods))
{
int32_t numCands = 0;
for (TR_RegisterCandidate * rc = _candidates->getFirst(); rc; rc = rc->getNext())
numCands++;
int32_t hotnessFactor = 1;
if (comp()->getMethodHotness() >= scorching)
hotnessFactor = 4;
else if (comp()->getMethodHotness() >= hot)
hotnessFactor = 2;
// Use double here so we don't need to worry about overflow
//
double complexityEstimate = comp()->getFlowGraph()->getNumberOfNodes() * (double)numCands * numCands;
if (complexityEstimate / hotnessFactor > (double)GRA_COMPLEXITY_LIMIT)
canAffordAssignment = false;
}
_valueModifiedSymRefs = new (trStackMemory()) TR_BitVector(_origSymRefCount, trMemory(), stackAlloc);
TR_BitVector splitSymRefs(_origSymRefCount, trMemory(), stackAlloc);
TR_BitVector nonSplittingCopyStored(_origSymRefCount, trMemory(), stackAlloc);
//
// Assign registers to candidates
//
if (canAffordAssignment)
{
globalFPAssignmentDone = _candidates->assign(cfgBlocks, numberOfBlocks, _firstGlobalRegisterNumber, _lastGlobalRegisterNumber);
if (_lastGlobalRegisterNumber > -1)
{
_visitCount = comp()->incVisitCount();
_signExtAdjustmentReqd = new (trStackMemory()) TR_BitVector(_lastGlobalRegisterNumber+1, trMemory(), stackAlloc);
_signExtAdjustmentNotReqd = new (trStackMemory()) TR_BitVector(_lastGlobalRegisterNumber+1, trMemory(), stackAlloc);
_signExtDifference = new (trStackMemory()) TR_BitVector(_lastGlobalRegisterNumber+1, trMemory(), stackAlloc);
//
// Transform IL
//
for (TR::TreeTop * tt = comp()->getStartTree(); tt; tt = tt->getExtendedBlockExitTreeTop()->getNextTreeTop())
transformBlock(tt);
}
bool mayHaveDeadStore = false;
for (TR_RegisterCandidate * rc = _candidates->getFirst(); rc; rc = rc->getNext())
{
(*_registerCandidates)[rc->getSymbolReference()->getReferenceNumber()] = rc;
TR::SymbolReference *splitSymRef = rc->getSplitSymbolReference();
if (splitSymRef)
{
splitSymRefs.set(splitSymRef->getReferenceNumber());
}
ListIterator<TR::TreeTop> stores(&rc->getStores());
TR::TreeTop * store = stores.getFirst();
if (!rc->getValueModified())
for (; store; store = stores.getNext())
{
TR::TransformUtil::removeTree(comp(), store);
}
else
{
_valueModifiedSymRefs->set(rc->getSymbolReference()->getReferenceNumber());
if (store)
mayHaveDeadStore = true;
}
}
if (mayHaveDeadStore)
{
requestOpt(OMR::isolatedStoreGroup);
requestOpt(OMR::globalDeadStoreElimination);
}
// Post processing to remove redundant stores for live-range splitting.
//
if (!splitSymRefs.isEmpty())
{
bool trace = comp()->getOptions()->trace(OMR::tacticalGlobalRegisterAllocator);
// If a candidate is modified, and it has a restoreSymbolReference,
// then that one will be modified too (by the "restore" instruction
// after the loop). Hence, we propagage the modified info out of
// every level of the loop nest.
//
for (TR_RegisterCandidate * rc = _candidates->getFirst(); rc; rc = rc->getNext())
{
TR::SymbolReference *outerSymRef = rc->getRestoreSymbolReference();
while (outerSymRef)
{
TR_RegisterCandidate *outerRc = (*_registerCandidates)[outerSymRef->getReferenceNumber()];
if (!outerRc)
break;
if (_valueModifiedSymRefs->get(rc->getSymbolReference()->getReferenceNumber()))
_valueModifiedSymRefs->set(outerRc->getSymbolReference()->getReferenceNumber());
if (outerSymRef == rc->getSplitSymbolReference())
break;
outerSymRef = outerRc->getRestoreSymbolReference();
}
}
// Propagate the information about 'valueModified'.
// 'valueModified' flag is not set at the stores (copies) for live-range splitting.
// If source and destination locals of a copy receive registers, in other words, a register-register copy exists,
// and a value is modified in one of locals, another local must be indentified as 'valueModified'.
//
if (trace)
traceMsg(comp(), "\nPropagating value modified information\n");
List<TR::TreeTop> storesFromRegisters(trMemory());
TR::TreeTop *tt = NULL, *nextTreeTop = NULL;
for (tt = comp()->getStartTree(); tt; tt = tt->getNextTreeTop())
{
TR::Node *node = tt->getNode();
if (!node->getOpCode().isStore() &&
(node->getNumChildren() > 0))
node = node->getFirstChild();
if (isSplittingCopy(tt->getNode()))
{
TR::Node *store = tt->getNode(), *load = tt->getNode()->getFirstChild();
if (store->getOpCode().isStoreDirect() && load->getOpCode().isLoadReg()
&& !(*_registerCandidates)[store->getSymbolReference()->getReferenceNumber()]->extendedLiveRange())
{
storesFromRegisters.add(tt);
}
}
else if (node->getOpCode().isStoreDirect() && node->getSymbolReference()->getSymbol()->isAutoOrParm())
nonSplittingCopyStored.set(node->getSymbolReference()->getReferenceNumber());
}
// Restore original symbols. This can reduce the size of the stack area.
// In addition, dead store elimination can remove redundant stores (copies)
// where both of operands (source and destination) do not receive any register.
//
if (performTransformation(comp(), "%s Restoring original symbols from live range splitter\n", OPT_DETAILS))
{
vcount_t visitCount = comp()->incVisitCount();
for (tt = comp()->getStartTree(); tt; tt = tt->getNextTreeTop())
restoreOriginalSymbol(tt->getNode(), visitCount);
}
// Remove a store generated at the end of the live range when a value is not modified in the live range.
// If a value is not modified in a local which receives a register, the stores from the register is redundant.
//
if (trace)
traceMsg(comp(), "\nRemoving redundant stores\n");
ListIterator<TR::TreeTop> itr(&storesFromRegisters);
for (tt = itr.getFirst(); tt; tt = itr.getNext())
{
if (!_valueModifiedSymRefs->isSet(tt->getNode()->getFirstChild()->getRegLoadStoreSymbolReference()->getReferenceNumber()) &&
!nonSplittingCopyStored.isSet(tt->getNode()->getFirstChild()->getRegLoadStoreSymbolReference()->getReferenceNumber()))
{
if (trace) traceMsg(comp(), "Remove a redundant store %p\n", tt->getNode());
TR::TransformUtil::removeTree(comp(), tt);
}
}
}
}
}
cg()->setLiveLocals(NULL);
optimizer()->setUseDefInfo(NULL);
optimizer()->setValueNumberInfo(NULL);
TR::Block * block = comp()->getStartTree()->getNode()->getBlock();
for (; block; block = block->getNextBlock())
block->clearGlobalRegisters();
candidates->releaseCandidates();
return 1; // actual cost
}
bool
TR_GlobalRegisterAllocator::isSplittingCopy(TR::Node *node)
{
bool trace = comp()->getOptions()->trace(OMR::tacticalGlobalRegisterAllocator);
// Check whether or not this store is a copy for live-range splitting
if ((node->getOpCode().isStoreDirect() || node->getOpCode().isStoreReg()) &&
(node->getFirstChild()->getOpCode().isLoadVarDirect() || node->getFirstChild()->getOpCode().isLoadReg()))
{
if (trace) traceMsg(comp(), "Finding a copy at node %p\n", node);
TR::SymbolReference *storeSymRef = node->getSymbolReferenceOfAnyType();
TR::SymbolReference *loadSymRef = node->getFirstChild()->getSymbolReferenceOfAnyType();
if (storeSymRef && loadSymRef && storeSymRef != loadSymRef)
{
TR_RegisterCandidate *storeRc = (*_registerCandidates)[storeSymRef->getReferenceNumber()];
TR_RegisterCandidate *loadRc = (*_registerCandidates)[loadSymRef->getReferenceNumber()];
TR::SymbolReference *origStoreSymRef = storeRc ? storeRc->getSplitSymbolReference() : NULL;
TR::SymbolReference *origLoadSymRef = loadRc ? loadRc->getSplitSymbolReference() : NULL;
if ((origStoreSymRef && origLoadSymRef && origStoreSymRef == origLoadSymRef) ||
(origStoreSymRef && !origLoadSymRef && origStoreSymRef == loadSymRef) ||
(!origStoreSymRef && origLoadSymRef && storeSymRef == origLoadSymRef))
{
//if (trace) traceMsg(comp(), "Found a copy %p\n", node);
return true;
}
}
}
return false;
}
void
TR_GlobalRegisterAllocator::restoreOriginalSymbol(TR::Node *node, vcount_t visitCount)
{
if (node->getVisitCount() == visitCount)
return;
node->setVisitCount(visitCount);
for (int32_t i = 0; i < node->getNumChildren(); i++)
restoreOriginalSymbol(node->getChild(i), visitCount);
bool trace = comp()->getOptions()->trace(OMR::tacticalGlobalRegisterAllocator);
if (node->getOpCode().hasSymbolReference() || node->getOpCode().isLoadReg() || node->getOpCode().isStoreReg())
{
if (node->getSymbolReferenceOfAnyType())
{
int32_t symRefNum = node->getSymbolReferenceOfAnyType()->getReferenceNumber();
TR_RegisterCandidate *rc = (*_registerCandidates)[symRefNum];
TR::SymbolReference *origSymRef = rc ? rc->getRestoreSymbolReference() : NULL;
bool foundChangeSymRef = false;
bool setValueModified = false;
TR::SymbolReference *changeSymRef = rc ? rc->getSplitSymbolReference() : NULL;
while (origSymRef &&
(origSymRef != rc->getSplitSymbolReference()))
{
TR_RegisterCandidate *origRc = (*_registerCandidates)[origSymRef->getReferenceNumber()];
if (setValueModified)
_valueModifiedSymRefs->set(origRc->getSymbolReference()->getReferenceNumber());
if (!origRc ||
origRc->getValueModified() ||
origRc->extendedLiveRange())
{
if (!foundChangeSymRef)
{
if (origRc &&
!origRc->getValueModified() &&
origRc->getRestoreSymbolReference())
{
_valueModifiedSymRefs->set(origRc->getSymbolReference()->getReferenceNumber());
setValueModified = true;
}
foundChangeSymRef = true;
changeSymRef = origSymRef;
}
}
origSymRef = origRc->getRestoreSymbolReference();
}
TR_RegisterCandidate *oldRc = origSymRef ? (*_registerCandidates)[origSymRef->getReferenceNumber()] : 0;
if (oldRc && oldRc->extendedLiveRange())
{
_valueModifiedSymRefs->set(oldRc->getSymbolReference()->getReferenceNumber());
changeSymRef = NULL;
}
if (rc && !rc->extendedLiveRange() && changeSymRef)
{
if (trace) traceMsg(comp(), "Restore an original symbol #%d from #%d at %p\n", changeSymRef->getReferenceNumber(), symRefNum, node);
if(node->getOpCode().isLoadReg() || node->getOpCode().isStoreReg())
node->setRegLoadStoreSymbolReference(changeSymRef);
else
node->setSymbolReference(changeSymRef);
}
else
_valueModifiedSymRefs->set(symRefNum);
}
else if (trace)
traceMsg(comp(), "Node %p has no symbol\n", node);
}
}
/**
* Transforms extended block
* @param tt Is a bbStart
*/
void
TR_GlobalRegisterAllocator::transformBlock(TR::TreeTop * tt)
{
TR::Node * bbStart = tt->getNode();
TR::Block * block = bbStart->getBlock();
TR::Block * origBlock = block;
// Find out if there are any symbols that are in registers on entry and/or exit
//
TR_Array<TR_GlobalRegister> & registers = block->getGlobalRegisters(comp());
bool found = false;
int32_t i;
for (i = _firstGlobalRegisterNumber; i <= _lastGlobalRegisterNumber; ++i)
{
TR::Block * b = block;
while (b)
{
TR_Array<TR_GlobalRegister> & curRegisters = b->getGlobalRegisters(comp());
if (curRegisters[i].getRegisterCandidateOnEntry())
found = true;
if (curRegisters[i].getRegisterCandidateOnExit())
found = true;
b = b->getNextBlock();
if (b && !b->isExtensionOfPreviousBlock())
break;
}
}
if (!found)
{
bbStart->setVisitCount(_visitCount);
return;
}
_newBlocks.deleteAll();
_signExtAdjustmentReqd->empty();
_signExtAdjustmentNotReqd->empty();
_signExtDifference->empty();
//
// Walk the tree changing all load/stores of register candidates to RegLoads and RegStores.
// Also add RegLoads at branch points for registers live across the branch.
//
_storesInBlockInfo.setFirst(0);
TR::Node * node = tt->getNode();
TR_Array<TR_GlobalRegister> * curRegisters = NULL;
TR_NodeMappings extBlockNodeMapping;
do
{
if (node->getOpCodeValue() == TR::BBStart)
{
block = node->getBlock();
curRegisters = &block->getGlobalRegisters(comp());
// Mark all symbols that are in registers on entry and/or exit to this BB
//
for (i = _firstGlobalRegisterNumber; i <= _lastGlobalRegisterNumber; ++i)
{
if ((*curRegisters)[i].getRegisterCandidateOnEntry())
{
(*curRegisters)[i].getRegisterCandidateOnEntry()->getSymbolReference()->getSymbol()->setIsInGlobalRegister(true);
}
if ((*curRegisters)[i].getRegisterCandidateOnExit())
{
(*curRegisters)[i].getRegisterCandidateOnExit()->getSymbolReference()->getSymbol()->setIsInGlobalRegister(true);
}
}
}
else if (node->getOpCodeValue() == TR::BBEnd)
{
block = node->getBlock();
curRegisters = &block->getGlobalRegisters(comp());
// Reset all tagged symbols for this BB
//
for (i = _firstGlobalRegisterNumber; i <= _lastGlobalRegisterNumber; ++i)
{
if ((*curRegisters)[i].getRegisterCandidateOnEntry())
{
(*curRegisters)[i].getRegisterCandidateOnEntry()->getSymbolReference()->getSymbol()->setIsInGlobalRegister(false);
}
if ((*curRegisters)[i].getRegisterCandidateOnExit())
{
(*curRegisters)[i].getRegisterCandidateOnExit()->getSymbolReference()->getSymbol()->setIsInGlobalRegister(false);
}
}
}
transformNode(node, 0, 0, tt, block, *curRegisters, &extBlockNodeMapping);
}
while ((tt = tt->getNextTreeTop()) &&
(node = tt->getNode(), node->getOpCodeValue() != TR::BBStart || node->getBlock()->isExtensionOfPreviousBlock()));
*_signExtDifference = *_signExtAdjustmentNotReqd;
*_signExtDifference &= *_signExtAdjustmentReqd;
if (!_signExtDifference->isEmpty())
{
tt = origBlock->getEntry();
node = tt->getNode();
do
{
if (node->getOpCodeValue() == TR::treetop)
node = node->getFirstChild();
if (node->getOpCodeValue() == TR::iRegStore)
{
if (_signExtDifference->get(node->getGlobalRegisterNumber()))
node->setNeedsSignExtension(true);
}
}
while ((tt = tt->getNextTreeTop()) &&
(node = tt->getNode(), node->getOpCodeValue() != TR::BBStart || node->getBlock()->isExtensionOfPreviousBlock()));
}
if (block == _appendBlock)
_appendBlock = NULL;
}
TR::Node *
TR_GlobalRegisterAllocator::resolveTypeMismatch(TR::DataType oldType, TR::Node *newNode)
{
return resolveTypeMismatch(oldType, NULL, newNode);
}
TR::Node *
TR_GlobalRegisterAllocator::resolveTypeMismatch(TR::Node *oldNode, TR::Node *newNode)
{
return resolveTypeMismatch(TR::NoType, oldNode, newNode);
}
TR::Node *
TR_GlobalRegisterAllocator::resolveTypeMismatch(TR::DataType inputOldType, TR::Node *oldNode, TR::Node *newNode)
{
return newNode;
}
static void setAutoContainsRegisterValue(TR_RegisterCandidate *rc, TR_Array<TR_GlobalRegister> * extRegisters, int32_t i, TR::Compilation *comp)
{
bool needs2Regs = false;
if (rc->rcNeeds2Regs(comp))
needs2Regs = true;
(*extRegisters)[i].setAutoContainsRegisterValue(true);
if (needs2Regs)
{
int32_t highRegNum = rc->getHighGlobalRegisterNumber();
if (i == highRegNum)
{
int32_t lowRegNum = rc->getLowGlobalRegisterNumber();
(*extRegisters)[lowRegNum].setAutoContainsRegisterValue(true);
}
else
{
(*extRegisters)[highRegNum].setAutoContainsRegisterValue(true);
}
}
}
void
TR_GlobalRegisterAllocator::transformNode(
TR::Node * node, TR::Node * parent, int32_t childIndex, TR::TreeTop * tt, TR::Block * & block, TR_Array<TR_GlobalRegister> & registers, TR_NodeMappings *extBlockNodeMapping)
{
TR_ASSERT(comp()->getOptimizer()->cachedExtendedBBInfoValid(), "Incorrect value in _startOfExtendedBBForBB");
TR_Array<TR_GlobalRegister> * extRegisters = &(_candidates->_startOfExtendedBBForBB[block->getNumber()]->getGlobalRegisters(comp()));
if (node->getVisitCount() == _visitCount)
return;
node->setVisitCount(_visitCount);
TR::Node* origStoreToMetaData = NULL;
TR::Node* origLoadFromMetaData = NULL;
TR::TreeTop* origLoadFromMetaDataPrevTT = NULL;
TR::ILOpCode opcode = node->getOpCode();
if (opcode.getOpCodeValue() == TR::table) // (opcode.isSwitch() && debug("putGlRegDepOnSwitch"))
{
transformNode(node->getFirstChild(), node, 0, tt, block, registers, extBlockNodeMapping);
transformMultiWayBranch(tt, node, block, registers);
return;
}
int32_t i;
for (i = 0; i < node->getNumChildren(); ++i)
transformNode(node->getChild(i), node, i, tt, block, registers, extBlockNodeMapping);
bool transformDone = false;
if (node->getOpCode().isJumpWithMultipleTargets() && !node->getOpCode().isSwitch() && node->getOpCodeValue() != TR::tstart)
transformMultiWayBranch(tt, node, block, registers, transformDone);
else if (opcode.isBranch())
{
transformBlockExit(tt, node, block, registers, node->getBranchDestination()->getNode()->getBlock());
}
else if (opcode.getOpCodeValue() == TR::BBStart)
{
block = node->getBlock();
addCandidateReloadsToEntry(tt, *extRegisters, block);
if (!block->isExtensionOfPreviousBlock())
addRegLoadsToEntry(tt, registers, block);
_osrCatchSucc = NULL;
addStoresForCatchBlockLoads(tt, *extRegisters, block);
}
else if (opcode.getOpCodeValue() == TR::BBEnd)
{
TR::TreeTop * nextTT = tt->getNextTreeTop();
TR::TreeTop * prevTT = tt->getPrevRealTreeTop();
TR::Block * nextBlock = nextTT ? nextTT->getNode()->getBlock() : 0;
while (prevTT && prevTT->getNode()->getOpCode().isStoreReg())
prevTT = prevTT->getPrevTreeTop();
TR::Node *ttNode = prevTT->getNode();
if(ttNode->getOpCodeValue() == TR::treetop)
ttNode = ttNode->getFirstChild();
if (nextBlock && !nextBlock->isExtensionOfPreviousBlock() && block->hasSuccessor(nextBlock) && !ttNode->getOpCode().isJumpWithMultipleTargets() )
{
transformBlockExit(tt, node, block, registers, nextBlock);
}
}
else if (opcode.isLoadVar() && isNodeAvailable(node))
{
TR::Symbol * symbol = node->getSymbolReference()->getSymbol();
bool changeNode = true;
TR::Node * value = NULL;
TR_GlobalRegister *gr = NULL;
//traceMsg(comp(), "Node %p symbol %p tag %d\n", node, symbol, symbol->isInGlobalRegister());
changeNode = false;
value = extBlockNodeMapping->getTo(node);
if (value)
{
changeNode = true;
}
else if (symbol->isInGlobalRegister())
{
gr = getGlobalRegister(symbol, registers, block);
if (gr)
changeNode = true; // symbol is will be put into register right before exit
}
else
{
TR_GlobalRegister *ptrToGr = getGlobalRegisterWithoutChangingCurrentCandidate(symbol, registers, block);
if (ptrToGr)
{
TR_RegisterCandidate * rc = ptrToGr->getCurrentRegisterCandidate();
if (rc && (rc->getSymbolReference()->getSymbol() == symbol))
{
if (ptrToGr->getValue() &&
!ptrToGr->getAutoContainsRegisterValue())
ptrToGr->createStoreFromRegister(comp()->getVisitCount(), tt->getPrevTreeTop(), 1, comp(), true);
ptrToGr->setAutoContainsRegisterValue(true);
ptrToGr->setValue(0);