-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathLocalOpts.cpp
9251 lines (8047 loc) · 365 KB
/
LocalOpts.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/LocalOpts.hpp"
#include <algorithm>
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "codegen/CodeGenerator.hpp"
#include "env/FrontEnd.hpp"
#include "env/KnownObjectTable.hpp"
#include "codegen/RecognizedMethods.hpp"
#include "codegen/RegisterConstants.hpp"
#include "compile/Compilation.hpp"
#include "compile/Method.hpp"
#include "compile/ResolvedMethod.hpp"
#include "compile/SymbolReferenceTable.hpp"
#include "compile/VirtualGuard.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "control/Recompilation.hpp"
#include "cs2/sparsrbit.h"
#include "env/CompilerEnv.hpp"
#include "env/HeuristicRegion.hpp"
#include "env/PersistentInfo.hpp"
#include "env/StackMemoryRegion.hpp"
#include "env/TRMemory.hpp"
#include "env/jittypes.h"
#include "il/AliasSetInterface.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/NodePool.hpp"
#include "il/Node_inlines.hpp"
#include "il/ParameterSymbol.hpp"
#include "il/ResolvedMethodSymbol.hpp"
#include "il/StaticSymbol.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "ilgen/IlGenRequest.hpp"
#include "ilgen/IlGeneratorMethodDetails.hpp"
#include "infra/Array.hpp"
#include "infra/Assert.hpp"
#include "infra/Bit.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/ILWalk.hpp"
#include "infra/Link.hpp"
#include "infra/List.hpp"
#include "optimizer/Inliner.hpp"
#include "infra/Stack.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/OrderBlocks.hpp"
#include "optimizer/PreExistence.hpp"
#include "optimizer/Structure.hpp"
#include "optimizer/TransformUtil.hpp"
#include "optimizer/UseDefInfo.hpp"
#include "ras/Debug.hpp"
#include "ras/DebugCounter.hpp"
#include "ras/ILValidator.hpp"
#include "ras/ILValidationStrategies.hpp"
#include "runtime/Runtime.hpp"
#include "env/VMAccessCriticalSection.hpp"
#ifdef J9_PROJECT_SPECIFIC
#include "control/RecompilationInfo.hpp"
#include "runtime/J9ValueProfiler.hpp"
#include "runtime/J9Profiler.hpp"
#include "env/CHTable.hpp"
#include "env/ClassTableCriticalSection.hpp"
#include "env/PersistentCHTable.hpp"
#include "env/RuntimeAssumptionTable.hpp"
#include "env/VMJ9.h"
#include "runtime/RuntimeAssumptions.hpp"
#endif
// basic blocks peephole optimization.
// Return "true" if any basic block peephole optimization was done
TR_PeepHoleBasicBlocks::TR_PeepHoleBasicBlocks(TR::OptimizationManager *manager)
: TR_BlockManipulator(manager)
{}
int32_t TR_PeepHoleBasicBlocks::perform()
{
// The CFG must exist for this optimization
//
TR::CFG * cfg = comp()->getFlowGraph();
if (cfg == NULL || comp()->getOption(TR_DisableBasicBlockPeepHole))
return 0;
TR_OrderBlocks orderBlocks(manager());
cfg->setIgnoreUnreachableBlocks(true);
int32_t rc = orderBlocks.lookForPeepHoleOpportunities("O^O BLOCK PEEP HOLE: ");
cfg->setIgnoreUnreachableBlocks(false);
if(cfg->getHasUnreachableBlocks())
cfg->removeUnreachableBlocks();
return rc;
}
const char *
TR_PeepHoleBasicBlocks::optDetailString() const throw()
{
return "O^O BASIC BLOCK PEEPHOLE: ";
}
// Extend basic blocks.
// Return "true" if any basic block extension was done
TR_ExtendBasicBlocks::TR_ExtendBasicBlocks(TR::OptimizationManager *manager)
: TR_BlockManipulator(manager)
{}
int32_t TR_ExtendBasicBlocks::perform()
{
// The CFG must exist for this optimization
//
static const char *disableFreqCBO = feGetEnv("TR_disableFreqCBO");
int32_t orderBlocksResult=-5;
if (comp()->getFlowGraph() == NULL)
return 0;
// There are two basic block extension algorithms depending on whether or not
// block and edge frequencies are known,
//
if (true)
{
static const char *p = feGetEnv("TR_OlderBlockReordering");
if (p)
return orderBlocksWithFrequencyInfo();
}
if (!comp()->getOption(TR_DisableNewBlockOrdering))
{
TR_OrderBlocks orderBlocks(manager());
orderBlocks.extendBlocks();
orderBlocksResult = orderBlocks.perform();
// comp()->getFlowGraph()->setStructure(NULL); TR_OrderBlocks should reset structure if needed
return orderBlocksResult;
}
orderBlocksResult = orderBlocksWithoutFrequencyInfo();
if (!disableFreqCBO)
comp()->getFlowGraph()->setStructure(NULL);
return orderBlocksResult;
}
int32_t TR_ExtendBasicBlocks::orderBlocksWithoutFrequencyInfo()
{
// TR_Structure *rootStructure = NULL;
//
// Set up the block nesting depths
//
TR::CFG *cfg = comp()->getFlowGraph();
TR_Structure *rootStructure = cfg->getStructure();
if (rootStructure)
{
TR::CFGNode *node;
for (node = cfg->getFirstNode(); node; node = node->getNext())
{
TR::Block *block = toBlock(node);
int32_t nestingDepth = 0;
if (block->getStructureOf() != NULL)
block->getStructureOf()->setNestingDepths(&nestingDepth);
}
}
//markColdBlocks();
TR::TreeTop *endTreeTop = comp()->getMethodSymbol()->getLastTreeTop();
vcount_t visitCount = comp()->incVisitCount();
bool blocksWereExtended = false;
TR::Block * prevBlock = comp()->getStartTree()->getNode()->getBlock();
//prevBlock->setVisitCount(visitCount);
TR::Block * block = prevBlock->getNextBlock();
bool reattemptThisExtension = false;
for (; block; prevBlock = block, block = block->getNextBlock())
{
if (!reattemptThisExtension &&
(block->getVisitCount() == visitCount))
continue;
reattemptThisExtension = false;
prevBlock->setVisitCount(visitCount);
if (block->isExtensionOfPreviousBlock())
continue;
// Check that the previous block doesn't end with a switch.
//
TR::TreeTop * tt = prevBlock->getLastRealTreeTop();
TR::Node * prevNode = tt->getNode();
if(prevNode->getOpCodeValue() == TR::treetop)
prevNode = prevNode->getFirstChild();
if ( prevNode->getOpCode().isJumpWithMultipleTargets() || !prevBlock->hasSuccessor(block))
continue;
TR::CFGEdgeList & preds = block->getPredecessors();
bool cannotExtendWithCurrentFallThrough = false;
if (!(preds.size() == 1))
cannotExtendWithCurrentFallThrough = true;
TR::Block *bestExtension = NULL;
if (trace())
traceMsg(comp(), " Current block [%d] looking for best successor to extend it...\n", prevBlock->getNumber());
//int32_t blockHotness = block->getHotness(cfg);
int32_t blockFreq = block->getFrequency();
if (block->isCold() || (blockFreq >= 0))
{
bestExtension = getBestChoiceForExtension(prevBlock);
//
// If the only choice for extension is dead cold (frequency == 0)
// then do not extend even if it is possible. This is done to avoid
// cases where we will extend with a colder block than the original
// fall through (which was hotter).
//
if (cannotExtendWithCurrentFallThrough && bestExtension)
{
if (block != bestExtension)
{
//int32_t bestHotness = bestExtension->getHotness(cfg);
int32_t bestFreq = bestExtension->getFrequency();
if (!block->isCold() &&
(blockFreq >= 0) && (bestFreq >= 0))
//(blockHotness != unknownHotness) && (bestHotness != unknownHotness))
{
//if (((bestHotness == deadCold) && (blockHotness != deadCold)) || (blockHotness > (bestHotness + 1)))
if ((((bestFreq == (MAX_COLD_BLOCK_COUNT+1)) && (blockFreq != (MAX_COLD_BLOCK_COUNT+1))) || (blockFreq > bestFreq + 100)))
{
//bestExtension = NULL;
continue;
}
}
}
}
}
if (trace())
traceMsg(comp(), " Current block [%d] with freq %d, best extension is BB[%d]\n", prevBlock->getNumber(), block->getFrequency(), bestExtension?bestExtension->getNumber():-1);
if (cannotExtendWithCurrentFallThrough ||
(bestExtension &&
!bestExtension->isCold() &&
(bestExtension != block)))
{
//
// The prevBlock cannot be extended to include the current block.
// See if the prevBlock has a successor whose only predecessor is the prevBlock.
// If so, see if we can rearrange the blocks so that the prevBlock can be extended
// without adding any new gotos.
//
TR::Block * newBlock = 0;
if (!bestExtension)
{
TR::CFGEdgeList & prevSuccessors = prevBlock->getSuccessors();
for (auto e = prevSuccessors.begin(); e != prevSuccessors.end(); ++e)
if ((*e)->getTo()->getPredecessors().size() == 1)
{ newBlock = toBlock((*e)->getTo()); break; }
}
else
newBlock = bestExtension;
if (!newBlock)
continue; // there's no way to extend the prevBlock
if (!prevBlock->isCold() && newBlock->isCold()) continue;
// See if we can easily move the current block without adding a new goto.
//
TR::Block * lastBlockToMove = block, * next;
for (;; lastBlockToMove = next)
{
next = lastBlockToMove->getNextBlock();
if (!next || !lastBlockToMove->hasSuccessor(next))
break;
//if (!(next->getPredecessors().size() == 1))
// { lastBlockToMove = 0; break; }
}
if (lastBlockToMove)
{
TR::TreeTop *previousTree = newBlock->getEntry()->getPrevTreeTop();
if (newBlock->getPredecessors().size() == 1)
{
int32_t result = performChecksAndTreesMovement(newBlock, prevBlock, block, endTreeTop, visitCount, optimizer());
if (result < 0)
{
if (cannotExtendWithCurrentFallThrough)
continue;
}
else
{
if (result == 1)
endTreeTop = previousTree;
block = newBlock;
}
}
else
{
if (cannotExtendWithCurrentFallThrough)
continue;
}
}
else
{
if (cannotExtendWithCurrentFallThrough)
continue;
}
}
// This block can be merged with the preceding block
//
TR::TreeTop *firstNonFenceTree = block->getFirstRealTreeTop();
TR::TreeTop *lastNonFenceTree = block->getLastRealTreeTop();
if (prevNode->getOpCodeValue() == TR::Goto)
{
if (!performTransformation(comp(), "%sMerge blocks %d and %d\n", optDetailString(), prevBlock->getNumber(), block->getNumber()))
continue;
optimizer()->prepareForTreeRemoval(tt);
TR::TransformUtil::removeTree(comp(), tt);
}
else if ((firstNonFenceTree == lastNonFenceTree) &&
(lastNonFenceTree->getNode()->getOpCodeValue() == TR::Goto)
)
{
TR::Block * nextBlock = block->getNextBlock();
if (nextBlock && prevNode->getOpCode().isBranch() && !prevNode->isNopableInlineGuard())
{
TR::TreeTop *gotoDest = lastNonFenceTree->getNode()->getBranchDestination();
TR::Block * prevBranchDest = prevNode->getBranchDestination()->getNode()->getBlock();
if (prevNode->getBranchDestination() == nextBlock->getEntry() && !nextBlock->isCold())
{
if (!performTransformation(comp(), "%sReverse branch in block_%d\n", optDetailString(), prevBlock->getNumber()))
continue;
for (auto c = 0; c < prevNode->getNumChildren(); ++c)
{
TR_ASSERT(prevNode->getChild(c)->getOpCodeValue() != TR::GlRegDeps, "the conditional branch node has a GlRegDep child and we're changing control flow");
}
prevNode->reverseBranch(gotoDest);
TR::Block *gotoDestBlock = gotoDest->getNode()->getBlock();
if (!prevBlock->hasSuccessor(gotoDestBlock))
cfg->addEdge(prevBlock, gotoDestBlock);
cfg->removeEdge(block, gotoDestBlock);
cfg->removeEdge(prevBlock, block);
prevBlock->getExit()->join(nextBlock->getEntry());
block = prevBlock;
reattemptThisExtension = true;
continue;
}
else if (prevBranchDest->getVisitCount() < visitCount &&
prevBranchDest->getPredecessors().size() == 1)
{
// don't swing up cold blocks
if (prevBranchDest->isCold())
continue;
if (!performTransformation(comp(), "%sReverse branch in %d (possibly swinging up destintion and removign goto block_%d)\n", optDetailString(), prevBlock->getNumber(), block->getNumber()))
continue;
// snip T (and its fall-through-chain) and swing it upto F, reversing
// the branch in F, and potentially removing the goto block
//
TR::Block * F = prevBlock;
TR::Block * T = prevBranchDest;
TR::Block *pT = T->getPrevBlock();
TR::Block * G;
TR::Block *nG;
// if the F and pT are the same (we have a redundant compare) - do not do any transformation
if (F == pT) continue; // FIXME: maybe we should remove the redundant comparison
for (G = T, nG = G->getNextBlock();
nG && G->hasSuccessor(nG);
G = nG, nG = nG->getNextBlock())
;
if (nG)
pT->getExit()->join(nG->getEntry());
else
{
pT->getExit()->setNextTreeTop(0);
endTreeTop = pT->getExit();
}
F->getExit()->join(T->getEntry());
G->getExit()->join(block->getEntry());
TR_ASSERT(prevNode->getNumChildren() != 3, "the branch node has a GlRegDep child that we're about to invalidate");
prevNode->reverseBranch(gotoDest);
int32_t copiedFrequency = 0;
TR::CFGEdge *addedEdge = NULL;
if (!F->hasSuccessor(gotoDest->getNode()->getBlock()))
{
addedEdge = cfg->addEdge(F, gotoDest->getNode()->getBlock());
TR_SuccessorIterator ei(F);
for (TR::CFGEdge * edge = ei.getFirst(); edge != NULL; edge = ei.getNext())
{
if (edge->getTo() == block)
{
copiedFrequency = edge->getFrequency();
break;
}
}
addedEdge->setFrequency(copiedFrequency);
}
cfg->removeEdge(F, block); // ideally 'block' will become unreachable, and be removed
block = prevBlock;
reattemptThisExtension = true;
continue;
}
else if (gotoDest->getNode()->getBlock() == prevBlock->startOfExtendedBlock())
{
if (!performTransformation(comp(), "%sRemove backedge goto block_%d by reversing the branch in block_%d\n", optDetailString(), block->getNumber(), prevBlock->getNumber()))
continue;
// goto is a backedge, reverse branch, swap destinations between branch and goto
//
TR::TreeTop *prevDest = prevNode->getBranchDestination();
TR_ASSERT(prevNode->getNumChildren() != 3, "the branch node has a GlRegDep child that we're about to invalidate");
prevNode->reverseBranch(gotoDest);
cfg->addEdge (prevBlock, gotoDest->getNode()->getBlock());
cfg->addEdge (block, prevDest->getNode()->getBlock());
cfg->removeEdge(prevBlock, prevDest->getNode()->getBlock());
lastNonFenceTree->getNode()->setBranchDestination(prevDest);
cfg->removeEdge(block, gotoDest->getNode()->getBlock());
}
}
}
if (!performTransformation(comp(), "%sExtend blocks %d and %d\n", optDetailString(), prevBlock->getNumber(), block->getNumber()))
continue;
blocksWereExtended = true;
block->setIsExtensionOfPreviousBlock();
}
if (blocksWereExtended)
optimizer()->enableAllLocalOpts();
return 1; // actual cost
}
struct TR_SequenceEntry
{
TR_ALLOC(TR_Memory::Optimization)
TR_SequenceEntry *next;
TR::Block *block;
TR::Block *fallThrough;
};
struct TR_SequenceHead
{
TR_SequenceEntry *first;
TR_SequenceEntry *last;
};
int32_t TR_ExtendBasicBlocks::orderBlocksWithFrequencyInfo()
{
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
// Build sequences of blocks that are joined by edges with the highest
// frequencies.
//
TR::CFG *cfg = comp()->getFlowGraph();
TR::Block *block = NULL;
TR::TreeTop *treeTop = NULL;
TR::Node *node = NULL;
TR_SequenceEntry *entry = NULL;
int32_t i = 0;
int32_t numBlocks = cfg->getNextNodeNumber();
int32_t bestFrequency = 0, bestFrom = 0, bestTo = 0;
// Array of sequences - the Nth entry is the sequence that starts with
// block N.
//
TR_SequenceHead *sequences = (TR_SequenceHead*)trMemory()->allocateStackMemory(numBlocks*sizeof(TR_SequenceHead));
memset(sequences, 0, numBlocks*sizeof(TR_SequenceHead));
// Initialize each sequence with a single block
//
block = toBlock(cfg->getStart());
entry = new (trStackMemory()) TR_SequenceEntry;
entry->next = NULL;
entry->block = block;
i = block->getNumber();
sequences[i].first = entry;
sequences[i].last = entry;
block = toBlock(cfg->getEnd());
entry = new (trStackMemory()) TR_SequenceEntry;
entry->next = NULL;
entry->block = block;
i = block->getNumber();
sequences[i].first = entry;
sequences[i].last = entry;
// Remember if this block falls through to the next block
//
entry->fallThrough = NULL;
for (block = comp()->getStartTree()->getNode()->getBlock(); block;
block = block->getNextBlock())
{
entry = new (trStackMemory()) TR_SequenceEntry;
entry->next = NULL;
entry->block = block;
i = block->getNumber();
sequences[i].first = entry;
sequences[i].last = entry;
// Remember if this block falls through to the next block
//
entry->fallThrough = NULL;
treeTop = block->getLastRealTreeTop();
node = treeTop->getNode();
if (node->getOpCode().isCheck() || node->getOpCodeValue() == TR::treetop)
node = node->getFirstChild();
if (node->getOpCode().isBranch())
{
if (node->getOpCode().isIf())
entry->fallThrough = block->getNextBlock();
}
else if (!node->getOpCode().isReturn() &&
!node->getOpCode().isJumpWithMultipleTargets() &&
node->getOpCodeValue() != TR::athrow)
{
entry->fallThrough = block->getNextBlock();
}
}
// Give a preference to edges that will result in an extended basic block.
// The preference amount is the amount that the edge frequency will be
// increased by. It is calculated from a percentage point amount, i.e.
// units of 1/100 of a percent.
//
static const char *p;
static int32_t extendedBlockPointPreference = (p = feGetEnv("TR_ExtendedBlockPoints")) ? atoi(p) : 500;
int32_t extendedBlockPreference = extendedBlockPointPreference * (MAX_BLOCK_COUNT+MAX_COLD_BLOCK_COUNT) / 10000;
if (trace())
traceMsg(comp(), "Start block re-ordering\n");
// Merge sequences
//
int32_t numSequences;
int32_t oldNumSequences = numBlocks+1;
for (numSequences = numBlocks; numSequences > 1 && numSequences < oldNumSequences; )
{
oldNumSequences = numSequences;
// Find the sequence that has the output edge to another sequence with
// the highest frequency
//
bestFrequency = -1;
for (i = 0; i < numBlocks; ++i)
{
if (!sequences[i].first)
continue; // This block already consumed
TR_SequenceEntry *currentBlockEntry = sequences[i].last;
for (auto edge = currentBlockEntry->block->getSuccessors().begin(); edge != currentBlockEntry->block->getSuccessors().end(); ++edge)
{
int32_t edgeTo = (*edge)->getTo()->getNumber();
if (edgeTo != i && sequences[edgeTo].first)
{
int32_t edgeFrequency = (*edge)->getFrequency();
if ((*edge)->getTo()->getPredecessors().size() == 1)
{
block = toBlock((*edge)->getFrom());
if (block->getExit() &&
!(block->getLastRealTreeTop()->getNode()->getOpCode().isJumpWithMultipleTargets()))
{
edgeFrequency += extendedBlockPreference;
}
}
if ((edgeFrequency > bestFrequency) ||
((edgeFrequency == bestFrequency) &&
(currentBlockEntry->fallThrough == (*edge)->getTo())))
{
bestFrequency = edgeFrequency;
bestFrom = i;
bestTo = edgeTo;
}
}
}
}
// Join the sequences
//
if (bestFrequency >= 0)
{
sequences[bestFrom].last->next = sequences[bestTo].first;
sequences[bestFrom].last = sequences[bestTo].last;
sequences[bestTo].first = NULL;
numSequences--;
if (trace())
traceMsg(comp(), " add %d to %d\n", bestTo, bestFrom);
}
}
if (trace())
for (int32_t i = 0; i < numBlocks; ++i)
{
if (sequences[i].first != NULL)
{
traceMsg(comp(), "Seq %3d: ", i);
for (TR_SequenceEntry *entry = sequences[i].first; entry; entry = entry->next)
{
TR::Block *block = entry->block;
traceMsg(comp(), "%3d(%5d) ", block->getNumber(), block->getFrequency());
}
traceMsg(comp(), "\n");
}
}
bool blocksWereExtended = false;
// Now reorder the blocks so that the sequence containing the entry node is
// first, and order the rest in descending frequency of their first block.
//
TR::TreeTop *prevTree = NULL;
bestFrom = cfg->getStart()->getNumber();
while (bestFrom >= 0)
{
bool firstInSequence = true;
bool prevBlockHasSwitch = false;
for (entry = sequences[bestFrom].first; entry; entry = entry->next)
{
block = entry->block;
if (!block->getEntry())
continue;
if (trace())
traceMsg(comp(), " Insert block_%d %s\n", block->getNumber(), block->isCold() ? "cold" : "" );
// Join this block's trees to the previously processed block
//
if (prevTree)
prevTree->join(block->getEntry());
else
comp()->setStartTree(block->getEntry());
if (!firstInSequence && !prevBlockHasSwitch &&
(block->getPredecessors().size() == 1))
{
block->setIsExtensionOfPreviousBlock();
blocksWereExtended = true;
}
// See if the end of this block needs adjusting
//
treeTop = block->getLastRealTreeTop();
node = treeTop->getNode();
if (entry->next && entry->next->block->getEntry())
{
// This block will now fall through to the next block in the
// sequence
//
if (entry->fallThrough)
{
if (entry->next && entry->fallThrough == entry->next->block)
{
// The new fall-through block is the same as the original.
// There is nothing to do.
}
else
{
// This block originally fell through to a different block
//
TR_ASSERT(node->getOpCode().isIf(), "assertion failure");
node->reverseBranch(entry->fallThrough->getEntry());
}
}
else
{
// This block didn't fall through to anything. If it ended in a
// goto, the goto can be removed
//
if (node->getOpCodeValue() == TR::Goto)
{
optimizer()->prepareForTreeRemoval(treeTop);
TR::TransformUtil::removeTree(comp(), treeTop);
}
}
}
else
{
// This block will not fall through to any successor. If it
// originally did fall through, we must insert a goto to the
// original fallthrough target.
//
if (entry->fallThrough)
{
comp()->getFlowGraph()->setStructure(NULL);
TR::Block *extraBlock = TR::Block::createEmptyBlock(node, comp(), entry->fallThrough->getFrequency(), entry->fallThrough);
TR::TreeTop::create(comp(), extraBlock->getEntry(), TR::Node::create(node, TR::Goto, 0, entry->fallThrough->getEntry()));
block->getExit()->join(extraBlock->getEntry());
cfg->addNode(extraBlock);
cfg->addEdge(extraBlock, entry->fallThrough);
cfg->addEdge(block, extraBlock);
cfg->removeEdge(block, entry->fallThrough);
cfg->copyExceptionSuccessors(block, extraBlock);
block = extraBlock;
block->setIsExtensionOfPreviousBlock();
}
}
prevTree = block->getExit();
prevTree->setNextTreeTop(NULL);
firstInSequence = false;
prevBlockHasSwitch = node->getOpCode().isJumpWithMultipleTargets();
}
sequences[bestFrom].first = NULL;
// Find the next sequence to be processed
//
bestFrequency = -1;
bestFrom = -1;
for (i = numBlocks-1; i >= 0; i--)
{
entry = sequences[i].first;
if (entry && entry->block->getFrequency() > bestFrequency)
{
bestFrequency = entry->block->getFrequency();
bestFrom = i;
}
}
}
if (blocksWereExtended)
optimizer()->enableAllLocalOpts();
return 1; // actual cost
}
const char *
TR_ExtendBasicBlocks::optDetailString() const throw()
{
return "O^O BASIC BLOCK EXTENSION: ";
}
// void TR_BlockManipulator::markColdBlocks()
// {
// TR::Block *block = comp()->getStartTree()->getNode()->getBlock();
// for (; block;block = block->getNextBlock())
// {
// TR::TreeTop *lastNonFenceTree = block->getLastRealTreeTop();
// TR::Node *node = lastNonFenceTree->getNode();
// if (node->getOpCode().isReturn() ||
// (node->getOpCode().isTreeTop() &&
// (node->getNumChildren() > 0) &&
// (node->getFirstChild()->getOpCodeValue() == TR::athrow)))
// block->setIsCold();
// // mark the guarded virtual call blocks as being cold
// //
// if (node->isTheVirtualGuardForAGuardedInlinedCall())
// {
// TR::TreeTop *tt = node->getVirtualCallTreeForGuard();
// if (tt)
// {
// for (;
// tt->getNode()->getOpCodeValue() != TR::BBEnd;
// tt = tt->getNextRealTreeTop())
// ;
// tt->getNode()->getBlock()->setIsCold();
// }
// }
// }
// }
int32_t TR_BlockManipulator::estimatedHotness(TR::CFGEdge *edge, TR::Block *block)
{
return edge->getFrequency();
/*
int32_t hotness = unknownHotness;
if (block->isCold())
return -1;
if (edge)
hotness = edge->getHotness(comp()->getFlowGraph());
if (hotness == unknownHotness)
{
if (block->isCold())
hotness = -2;
else
{
hotness = block->getHotness(comp()->getFlowGraph());
if (hotness == unknownHotness)
hotness = block->getNestingDepth();
}
}
return hotness;
*/
}
TR::Block *TR_BlockManipulator::getBestChoiceForExtension(TR::Block *block1)
{
TR::Block *bestExtension = NULL;
int32_t numberOfRealTreesInBlock = -1;
TR::Block *fallThroughBlock = 0;
TR::TreeTop *nextTree = block1->getExit()->getNextRealTreeTop();
if (nextTree)
fallThroughBlock = nextTree->getNode()->getBlock();
if (block1->getLastRealTreeTop()->getNode()->getOpCode().isBranch() &&
block1->getLastRealTreeTop()->getNode()->isNopableInlineGuard())
return fallThroughBlock;
int32_t hotness = -3;
int32_t nestingDepth = -1;
for (auto nextEdge = block1->getSuccessors().begin(); nextEdge != block1->getSuccessors().end(); ++nextEdge)
{
TR::Block *nextBlock = toBlock((*nextEdge)->getTo());
if (!(nextBlock->getPredecessors().size() == 1))
continue; // Not a candidate for extension
int32_t nextHotness = estimatedHotness(*nextEdge, nextBlock);
if (trace())
traceMsg(comp(), " Estimating hotness for BB [%d], next BB [%d], estimated hotness %d\n", block1->getNumber(), nextBlock->getNumber(), nextHotness);
if (nextHotness > hotness)
{
bestExtension = nextBlock;
numberOfRealTreesInBlock = countNumberOfTreesInSameExtendedBlock(nextBlock);
hotness = nextHotness;
int32_t nextBlockNestingDepth = 1;
if (nextBlock->getStructureOf())
nextBlock->getStructureOf()->calculateFrequencyOfExecution(&nextBlockNestingDepth);
nestingDepth = nextBlockNestingDepth;
}
else if (hotness >= 0 && nextHotness == hotness)
{
int32_t nextBlockNestingDepth = 1;
if (nextBlock->getStructureOf())
nextBlock->getStructureOf()->calculateFrequencyOfExecution(&nextBlockNestingDepth);
int32_t nextBlockNumTrees = countNumberOfTreesInSameExtendedBlock(nextBlock);
if ((nextBlockNestingDepth > nestingDepth) ||
((nextBlockNestingDepth == nestingDepth) &&
(nextBlockNumTrees > numberOfRealTreesInBlock)))
{
bestExtension = nextBlock;
numberOfRealTreesInBlock = nextBlockNumTrees;
hotness = nextHotness;
nestingDepth = nextBlockNestingDepth;
}
else if ((nextBlockNestingDepth == nestingDepth) &&
(nextBlockNumTrees == numberOfRealTreesInBlock))
{
if (nextBlock == fallThroughBlock)
bestExtension = nextBlock;
}
}
else if (nextHotness == hotness)
{
// In case of a tie between cold blocks, favour nextBlock
// if it is the fall through block.
//
if (nextBlock == fallThroughBlock)
{
bestExtension = nextBlock;
numberOfRealTreesInBlock = countNumberOfTreesInSameExtendedBlock(nextBlock);
int32_t nextBlockNestingDepth = 1;
if (nextBlock->getStructureOf())
nextBlock->getStructureOf()->calculateFrequencyOfExecution(&nextBlockNestingDepth);
nestingDepth = nextBlockNestingDepth;
}
}
}
return bestExtension;
}
bool TR_BlockManipulator::isBestChoiceForFallThrough(TR::Block *block1, TR::Block *block2)
{
// We don't want supercold block to be fall-through block
if (block1->isSuperCold() ||
((block1->getSuccessors().size() == 1) &&
block1->getSuccessors().front()->getTo()->asBlock()->isSuperCold()))
return false;
bool bestSucc = false;
bool bestPred = false;
if (block1->getSuccessors().size() == 1)
bestSucc = true;
if (block2->getPredecessors().size() == 1)
bestPred = true;
if (bestSucc && bestPred)
return true;
// Loop back edges are usually desired to be backward branches
// into the loop entry block; the loop pre-header should fall into the
// entry. This is an exception to the usual rule where we allow the hottest
// block to fall into a successor. In this case the hottest block (block
// inside the loop that conditionally branches back to entry) branches back to
// the loop whereas the colder block falls into it
//
bool isLoopBackEdge = false;
if (comp()->getFlowGraph()->getStructure())
{
bool isLoopHdr = false;
TR_Structure *containingLoop = NULL;
TR_Structure *blockStructure2 = block2->getStructureOf();
while (blockStructure2)
{
if (blockStructure2->asRegion() && blockStructure2->asRegion()->isNaturalLoop())
{
if (blockStructure2->getNumber() == block2->getNumber())
isLoopHdr = true;
containingLoop = blockStructure2;
break;
}
blockStructure2 = blockStructure2->getParent();
}
if (isLoopHdr)
{
if (blockStructure2->asRegion()->getEntryBlock()->getStructureOf()->isEntryOfShortRunningLoop())
return false;
TR_Structure *blockStructure1 = block1->getStructureOf();
while (blockStructure1)
{
if (blockStructure1 == containingLoop)
{
isLoopBackEdge = true;
break;
}