-
Notifications
You must be signed in to change notification settings - Fork 392
/
Structure.cpp
3719 lines (3189 loc) · 126 KB
/
Structure.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2000, 2020 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "optimizer/Structure.hpp"
#include <algorithm>
#include <set>
#include <vector>
#include <limits.h>
#include <string.h>
#include "compile/Compilation.hpp"
#include "cs2/sparsrbit.h"
#include "env/StackMemoryRegion.hpp"
#include "env/TRMemory.hpp"
#include "il/AliasSetInterface.hpp"
#include "il/Block.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/RegisterMappedSymbol.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/TreeTop.hpp"
#include "il/TreeTop_inlines.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/Cfg.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "infra/CfgNode.hpp"
#include "optimizer/RegisterCandidate.hpp"
#include "optimizer/DataFlowAnalysis.hpp"
#include "optimizer/LocalAnalysis.hpp"
#include "ras/Debug.hpp"
#define OPT_DETAILS "O^O STRUCTURE: "
// The "getKind" methods are made non-inline to identify this as the home for the
// vfts for this class hierarchy.
//
TR_Structure::Kind TR_Structure::getKind() {return Blank;}
TR_Structure::Kind TR_BlockStructure::getKind() {return Block;}
TR_Structure::Kind TR_RegionStructure::getKind() {return Region;}
TR_BlockStructure::TR_BlockStructure(TR::Compilation * comp, int32_t index, TR::Block *b) :
TR_Structure(comp, index), _block(b)
{
b->setStructureOf(this);
}
bool TR_BlockStructure::doDataFlowAnalysis(TR_DataFlowAnalysis *dfa, bool checkForChanges)
{
// LexicalTimer tlex("blockStructure_doDFA", comp()->phaseTimer());
return dfa->analyzeBlockStructure(this, checkForChanges);
}
bool TR_RegionStructure::doDataFlowAnalysis(TR_DataFlowAnalysis *dfa, bool checkForChanges)
{
// LexicalTimer tlex("regionStructure_doDFA", comp()->phaseTimer());
return dfa->analyzeRegionStructure(this, checkForChanges);
}
void TR_BlockStructure::clearAnalysisInfo()
{
setAnalysisInfo(NULL);
}
void TR_RegionStructure::clearAnalysisInfo()
{
setAnalysisInfo(NULL);
TR_RegionStructure::Cursor subs(*this);
for (TR_StructureSubGraphNode *p = subs.getFirst(); p != NULL; p = subs.getNext())
p->getStructure()->clearAnalysisInfo();
}
bool TR_Structure::contains(TR_Structure *other, TR_Structure *commonParent)
{
for (TR_Structure *s = other; s != NULL && s != commonParent; s = s->getParent())
if (s == this)
return true;
return false;
}
TR_RegionStructure *TR_Structure::getContainingLoop()
{
for (TR_RegionStructure *p = getParent(); p != NULL ; p = p->getParent())
if (p->isNaturalLoop())
return p;
return NULL;
}
// Note that if A contains B, the common parent is parent(A)
//
TR_RegionStructure *TR_Structure::findCommonParent(TR_Structure *other, TR::CFG *cfg)
{
for (TR_RegionStructure *parent = getParent()->asRegion();
parent;
parent = parent->getParent()->asRegion())
{
if (parent->contains(other))
return parent;
}
TR_ASSERT(this == cfg->getStructure() ||
other == cfg->getStructure(),
"A and B MUST have a common ancestor unless either of them is region 0");
return 0;
}
void TR_BlockStructure::replacePart(TR_Structure *from, TR_Structure *to)
{
TR_ASSERT(0,"bad structure found trying to replace a substructure");
}
void TR_RegionStructure::addSubNode(TR_StructureSubGraphNode *subNode)
{
_subNodes.push_back(subNode);
TR_Structure *node = subNode->getStructure();
node->setParent(this);
}
void TR_RegionStructure::cleanupAfterEdgeRemoval(TR::CFGNode *node)
{
TR_BlockStructure *blockSt = toStructureSubGraphNode(node)->getStructure()->asBlock();
if (node != getEntry() &&
node->getPredecessors().empty() &&
node->getExceptionPredecessors().empty())
{
// The node is now isolated and should be removed
//
if (node->getSuccessors().empty() &&
node->getExceptionSuccessors().empty())
{
// The node is completely isolated. It can be removed from the
// structure.
//
if (node->getNumber() != comp()->getFlowGraph()->getEnd()->getNumber())
removeSubNode(toStructureSubGraphNode(node));
}
else
{
// The node is isolated but it still has successor edges.
// It must be part of an unreachable cycle. Tell the CFG so that it
// can run its pass to remove unreachable cycles later.
//
comp()->getFlowGraph()->setHasUnreachableBlocks();
}
}
if (containsInternalCycles())
checkForInternalCycles();
else if ((numSubNodes() == 1) && !isNaturalLoop() &&
!getEntry()->hasSuccessor(getEntry()) &&
!getEntry()->hasExceptionSuccessor(getEntry()))
{
// This may be required if an acyclic region was created by
// getting rid of the back edge of a natural loop (say with only one block);
// in that case we want to collapse the entry into the parent
//
TR_RegionStructure::Cursor si(*this);
TR_ASSERT(si.getFirst() == getEntry(),"bad structure found trying to remove a block");
if (getParent() && (getEntry()->getStructure()->getParent() == this))
getParent()->replacePart(this, getEntry()->getStructure());
}
}
// Implementation of TR_RegionStructure::extractUnconditionalExits() below
class TR_RegionStructure::ExitExtraction
{
public:
ExitExtraction(TR::Compilation * const comp, TR::Region &memRegion)
: _comp(comp)
, _cfg(_comp->getFlowGraph())
, _trace(_comp->getOption(TR_TraceExitExtraction))
, _memRegion(memRegion)
, _structureRegion(_cfg->structureRegion())
, _workStack(_memRegion)
, _queued(std::less<TR_Structure*>(), _memRegion)
, _regionContents(RcCmp(), _memRegion)
, _allPreds(_memRegion)
, _succs(_memRegion)
, _excSuccs(_memRegion)
{ }
void extractUnconditionalExits(const TR::list<TR::Block*, TR::Region&> &blocks);
private:
typedef TR::typed_allocator<TR_Structure*, TR::Region&> StructureAlloc;
typedef std::vector<TR_Structure*, StructureAlloc> StructureVec;
typedef std::set<TR_Structure*, std::less<TR_Structure*>, StructureAlloc> StructureSet;
typedef TR::typed_allocator<TR::CFGEdge*, TR::Region&> EdgeVecAlloc;
typedef std::vector<TR::CFGEdge*, EdgeVecAlloc> EdgeVec;
typedef std::pair<TR_RegionStructure* const, TR_BitVector> RcEntry;
typedef TR::typed_allocator<RcEntry, TR::Region&> RcAlloc;
typedef std::less<TR_RegionStructure*> RcCmp;
typedef std::map<TR_RegionStructure*, TR_BitVector, RcCmp, RcAlloc> RegionContents;
void enqueue(TR_Structure*);
void collectWork(const TR::list<TR::Block*, TR::Region&> &blocks);
void collectWorkFromRegion(TR_RegionStructure *region, const StructureSet &relevant);
void extractStructure(TR_Structure*);
TR_BitVector ®ionContents(TR_RegionStructure *loop);
void removeContentsFromRegion(TR_Structure *removed, TR_RegionStructure *region);
void traceBitVector(TR_BitVector &bv);
void moveNodeIntoParent(TR_StructureSubGraphNode *node, TR_RegionStructure *region, TR_RegionStructure *parent);
void moveOutgoingEdgeToParent(TR_RegionStructure *region, TR_RegionStructure *parent, TR_StructureSubGraphNode *node, TR::CFGEdge *edge, bool isExceptionEdge);
TR::Compilation * const _comp;
TR::CFG * const _cfg;
const bool _trace;
TR::Region &_memRegion;
TR::Region &_structureRegion;
StructureVec _workStack;
StructureSet _queued;
RegionContents _regionContents;
// Reuse these vectors to avoid allocating three new vectors on each
// iteration of extractStructure().
EdgeVec _allPreds;
EdgeVec _succs;
EdgeVec _excSuccs;
};
/**
* Identify and extract subgraph nodes that no longer belong within loops.
*
* After deleting edges from the control flow graph, there may be blocks, or
* structure subgraph nodes more generally, from which execution is guaranteed
* to exit a containing loop. A fresh structural analysis would consider such
* nodes to be outside the loop, which is preferable for the sake of later loop
* optimizations.
*
* Given a list of blocks from which outgoing edges have been deleted, try to
* find these unconditionally exiting nodes, and extract them from as many
* containing loops as possible.
*
* Nodes are extracted one at a time, and a given node is moved to its
* outermost position before continuing on. When a node is moved out of a
* region, its (ex-)predecessors might now directly exit the same region, so
* they will also be considered.
*
* For example, suppose that an edge from \c block_7 to \c block_4 was removed,
* leaving the following structure:
*
\verbatim
0
|
v
2
|
v
+----(loop 3)------+
| v |
| +--->3--+ |
| | | | |
| | | | |
| | v v |
| +----4 5--->6 |
| | | |
| v | |
| 7<---+ |
| | |
+----------|-------+
|
v
8
|
v
1
\endverbatim
*
* First, 7 would be removed from the loop region:
*
\verbatim
0
|
v
2
|
v
+----(loop 3)------+
| v |
| +--->3--+ |
| | | | |
| | | | |
| | v v |
| +----4 5--->6 |
| | | |
+----------|----|--+
| |
v |
7<---+
|
v
8
|
v
1
\endverbatim
*
* Then 6 would follow 7:
*
\verbatim
0
|
v
2
|
v
+----(loop 3)------+
| v |
| +--->3--+ |
| | | | |
| | | | |
| | v v |
| +----4 5----+ |
| | | |
+----------|----|--+
| |
v v
7<---6
|
v
8
|
v
1
\endverbatim
*
* Finally, 5 would follow as well, leaving just 3 and 4 in the loop:
*
\verbatim
0
|
v
2
|
v
+-(loop 3)-+
| v |
| +--->3------>5--->6
| | | | | |
| | | | v |
| | v | 7<---+
| +----4 | |
| | v
+----------+ 8
|
v
1
\endverbatim
*
* This extraction is not automatic as part of structure maintenance because it
* would sometimes be triggered unexpectedly by intermediate states of the CFG.
* Instead it must be requested explicitly by calling this method.
*
* JIT options:
* - \c disableExitExtraction to disable
* - \c traceExitExtraction to trace
* - \c checkStructureDuringExitExtraction to \c checkStructure() in non-debug builds
* - \c extractExitsByInvalidatingStructure for invalidation instead of repair
*
* \param comp the compilation in progress
* \param blocks the blocks from which outgoing edges have been deleted
*
* Note that an unconditionally exiting node will only be discovered if it (or
* a block it contains) is listed in \p blocks. If \c block_7 were absent from
* \p blocks in the example above, the structure would be left unchanged.
*/
/* static */ void TR_RegionStructure::extractUnconditionalExits(
TR::Compilation * const comp,
const TR::list<TR::Block*, TR::Region&> &blocks)
{
if (blocks.empty())
return;
if (comp->getOption(TR_DisableExitExtraction))
return;
if (comp->getFlowGraph()->getStructure() == NULL)
return;
ExitExtraction xform(comp, comp->trMemory()->currentStackRegion());
xform.extractUnconditionalExits(blocks);
}
void TR_RegionStructure::ExitExtraction::extractUnconditionalExits(
const TR::list<TR::Block*, TR::Region&> &blocks)
{
collectWork(blocks);
if (_workStack.size() == 0)
return;
if (_trace)
_comp->dumpMethodTrees("Trees before unconditional exit extraction");
while (_workStack.size() > 0)
{
if (_trace)
{
traceMsg(_comp, "work stack:");
for (auto s = _workStack.begin(); s != _workStack.end(); ++s)
traceMsg(_comp, " %d:%p", (*s)->getNumber(), *s);
traceMsg(_comp, "\n");
}
TR_Structure * const s = _workStack.back();
_workStack.pop_back();
_queued.erase(s);
if (_trace)
traceMsg(_comp, "attempting to extract %d:%p\n", s->getNumber(), s);
extractStructure(s);
if (_cfg->getStructure() == NULL)
return;
}
}
void TR_RegionStructure::ExitExtraction::enqueue(TR_Structure * const s)
{
if (_trace)
traceMsg(_comp, "enqueueing %d:%p\n", s->getNumber(), s);
if (_queued.find(s) == _queued.end())
{
_workStack.push_back(s);
_queued.insert(s);
}
}
void TR_RegionStructure::ExitExtraction::collectWork(
const TR::list<TR::Block*, TR::Region&> &blocks)
{
StructureSet relevant(std::less<TR_Structure*>(), _memRegion);
for (auto b = blocks.begin(); b != blocks.end(); ++b)
{
TR_Structure *s = (*b)->getStructureOf();
while (s != NULL && relevant.find(s) == relevant.end())
{
TR_Structure * const parent = s->getParent();
if (_trace)
{
traceMsg(_comp,
"found relevant structure %d:%p, parent %d:%p\n",
s->getNumber(),
s,
parent == NULL ? -1 : parent->getNumber(),
parent);
}
relevant.insert(s);
s = parent;
}
}
auto * const root = _cfg->getStructure()->asRegion();
if (root != NULL) // in case the root might sometimes be a block structure
collectWorkFromRegion(root, relevant);
}
// Get the structures to process in post-order. Since the pending work is
// treated as a stack, that means that regions will be processed before their
// contents. That's a good order because moving a node out of a region never
// makes that region movable, but it might make it immovable.
void TR_RegionStructure::ExitExtraction::collectWorkFromRegion(
TR_RegionStructure *region,
const StructureSet &relevant)
{
TR_RegionStructure::Cursor it(*region);
for (auto node = it.getFirst(); node != NULL; node = it.getNext())
{
TR_Structure * const s = node->getStructure();
if (relevant.find(s) == relevant.end())
continue;
if (s->asRegion() != NULL)
collectWorkFromRegion(s->asRegion(), relevant);
else
enqueue(s);
}
enqueue(region);
}
void TR_RegionStructure::ExitExtraction::extractStructure(
TR_Structure * const initialStructure)
{
TR_RegionStructure *region = initialStructure->getParent();
if (region == NULL)
return; // ignore initialStructure because it has been detached
TR_RegionStructure *loop = initialStructure->getContainingLoop();
if (loop == NULL)
return;
TR_StructureSubGraphNode *node = region->subNodeFromStructure(initialStructure);
for (;;)
{
TR_ASSERT_FATAL(
node->getStructure()->getParent() == region,
"removeUnconditionalExit: node %p not (directly) in region %p\n",
node,
region);
if (!region->isNaturalLoop() && !region->isAcyclic())
return;
TR_RegionStructure * const parent = region->getParent();
if (parent == NULL)
return;
// Try to find a remaining successor of node in this region.
TR_SuccessorIterator sit(node);
for (auto e = sit.getFirst(); e != NULL; e = sit.getNext())
{
if (!region->isExitEdge(e))
return;
}
// None of this node's remaining successors are in this region, so it
// unconditionally exits, and we can move it into the parent region.
// However, we'd like to do so only if all of the remaining successors
// are outside the innermost containing loop. Otherwise we'll spend time
// dissolving acyclic regions, or worse, invalidate structure, for no
// useful purpose.
//
// This test is delayed until we know that all outgoing edges are exit
// edges in the hope that it will be unnecessary to build the set of node
// numbers contained in the loop.
//
// Note that if (region == loop), then we already know that all
// successors are outside loop, because they're outside region.
if (region != loop)
{
TR_BitVector &loopBlocks = regionContents(loop);
for (auto e = sit.getFirst(); e != NULL; e = sit.getNext())
{
if (loopBlocks.isSet(e->getTo()->getNumber()))
return;
}
}
// This node doesn't belong in the loop!
if (!performTransformation(_comp,
"%sMoving unconditional exit node %d "
"from region %d:%p into parent %d:%p\n",
OPT_DETAILS,
node->getNumber(),
region->getNumber(),
region,
parent->getNumber(),
parent))
return;
if (_comp->getOption(TR_ExtractExitsByInvalidatingStructure))
{
// There is a node that would be extracted; just kill structure instead
if (_trace)
traceMsg(_comp, "invalidating structure instead of fixing it\n");
// FIXME this should call invalidateStructure(), but doing so does not
// clear out blocks' getStructureOf(), and not everything that looks
// at getStructureOf() checks beforehand that structure is valid. So
// at the moment, invalidateStructure() can cause subsequent
// optimizations to dereference dangling pointers.
_cfg->setStructure(NULL);
return;
}
moveNodeIntoParent(node, region, parent);
removeContentsFromRegion(initialStructure, region);
if (_trace && _comp->getOutFile() != NULL)
{
traceMsg(_comp, "Structure after moving node into parent:\n<structure>\n");
_comp->getDebug()->print(_comp->getOutFile(), _cfg->getStructure(), 0);
traceMsg(_comp, "</structure>\n");
}
#ifdef DEBUG
const bool checkStructure = true;
#else
const bool checkStructure =
_comp->getOption(TR_CheckStructureDuringExitExtraction);
#endif
if (checkStructure)
{
auto * const mem = _comp->trMemory();
TR::StackMemoryRegion stackMemoryRegion(*mem);
TR_BitVector blocks(_cfg->getNextNodeNumber(), mem, stackAlloc);
_cfg->getStructure()->checkStructure(&blocks);
}
if (region == loop)
{
loop = loop->getContainingLoop();
if (loop == NULL)
return; // no more containing loops
}
region = parent;
}
}
TR_BitVector &TR_RegionStructure::ExitExtraction::regionContents(
TR_RegionStructure * const region)
{
auto existing = _regionContents.find(region);
if (existing != _regionContents.end())
return existing->second;
// Insert an empty bitvector into the map to avoid extra copying. It is
// populated in-place below.
auto new_entry = std::make_pair(region, TR_BitVector(_memRegion));
TR_BitVector &contents = _regionContents.insert(new_entry).first->second;
TR_RegionStructure::Cursor it(*region);
for (auto node = it.getFirst(); node != NULL; node = it.getNext())
{
TR_Structure * const s = node->getStructure();
if (s->asBlock() != NULL)
contents.set(s->getNumber());
else
contents |= regionContents(s->asRegion());
}
if (_trace)
{
traceMsg(_comp, "contents of region %d:%p:", region->getNumber(), region);
traceBitVector(contents);
}
return contents;
}
void TR_RegionStructure::ExitExtraction::removeContentsFromRegion(
TR_Structure * const removed,
TR_RegionStructure * const region)
{
auto entry = _regionContents.find(region);
if (entry == _regionContents.end())
return;
TR_BitVector &blocks = entry->second;
if (removed->asBlock() != NULL)
{
blocks.reset(removed->getNumber());
}
else
{
auto subregionEntry = _regionContents.find(removed->asRegion());
TR_ASSERT_FATAL(
subregionEntry != _regionContents.end(),
"region %d:%p has contents, "
"but (previously) contained subregion %d:%p does not\n",
region->getNumber(),
region,
removed->getNumber(),
removed);
blocks -= subregionEntry->second;
}
if (_trace)
{
traceMsg(_comp,
"adjusted contents of region %d:%p:",
region->getNumber(),
region);
traceBitVector(blocks);
}
}
void TR_RegionStructure::ExitExtraction::traceBitVector(TR_BitVector &bv)
{
TR_BitVectorIterator bvi(bv);
while (bvi.hasMoreElements())
traceMsg(_comp, " %d", bvi.getNextElement());
traceMsg(_comp, "\n");
}
void TR_RegionStructure::ExitExtraction::moveNodeIntoParent(
TR_StructureSubGraphNode * const node,
TR_RegionStructure * const region,
TR_RegionStructure * const parent)
{
if (node == region->getEntry())
{
// Replace this entire region in the parent, since entry can't be removed
TR_ASSERT_FATAL(
region->numSubNodes() == 1,
"removeUnconditionalExit: all successors of region %p entry are "
"outside region, but there are additional sub-nodes\n",
region);
parent->replacePart(region, node->getStructure());
return;
}
// Copy the original predecessors and successors
_allPreds.clear();
{
TR_PredecessorIterator pit(node);
for (auto e = pit.getFirst(); e != NULL; e = pit.getNext())
_allPreds.push_back(e);
}
_succs.clear();
{
TR::CFGEdgeList &l = node->getSuccessors();
_succs.insert(_succs.end(), l.begin(), l.end());
}
_excSuccs.clear();
{
TR::CFGEdgeList &l = node->getExceptionSuccessors();
_excSuccs.insert(_excSuccs.end(), l.begin(), l.end());
}
// Remove all incoming edges
for (auto e = _allPreds.begin(); e != _allPreds.end(); ++e)
{
region->removeEdgeWithoutCleanup(*e, false);
if (_trace)
{
traceMsg(_comp,
"removed edge (%d->%d):%p from region %d:%p\n",
(*e)->getFrom()->getNumber(),
(*e)->getTo()->getNumber(),
*e,
region->getNumber(),
region);
}
}
// Move node into parent
region->removeSubNodeWithoutCleanup(node);
parent->addSubNode(node);
if (_trace)
traceMsg(_comp, "moved node into parent\n");
// For each edge that was incoming, region has an exit edge
const bool nodeIsHandler =
node->getStructure()->getEntryBlock()->isCatchBlock();
for (auto e = _allPreds.begin(); e != _allPreds.end(); ++e)
{
auto * const src = toStructureSubGraphNode((*e)->getFrom());
region->addExitEdge(src, node->getNumber(), nodeIsHandler);
if (_trace)
{
traceMsg(_comp,
"added exit edge (%d->%d) to region %d:%p\n",
src->getNumber(),
node->getNumber(),
region->getNumber(),
region);
}
}
// Parent needs an edge from region to node
auto * const regionNode = parent->subNodeFromStructure(region);
if (nodeIsHandler)
TR::CFGEdge::createExceptionEdge(regionNode, node, _structureRegion);
else
TR::CFGEdge::createEdge(regionNode, node, _structureRegion);
if (_trace)
{
traceMsg(_comp,
"added %sedge (%d->%d) to region %d:%p\n",
nodeIsHandler ? "exception " : "",
regionNode->getNumber(),
node->getNumber(),
parent->getNumber(),
parent);
}
// Replace all outgoing (exit) edges with edges originating in parent
for (auto e = _succs.begin(); e != _succs.end(); ++e)
moveOutgoingEdgeToParent(region, parent, node, *e, false);
for (auto e = _excSuccs.begin(); e != _excSuccs.end(); ++e)
moveOutgoingEdgeToParent(region, parent, node, *e, true);
region->cleanupAfterNodeRemoval();
// Cleanup may have eliminated the current region.
if (region->getParent() == NULL)
{
if (_trace)
{
traceMsg(_comp,
"region %d:%p was eliminated by cleanupAfterNodeRemoval\n",
region->getNumber(),
region);
}
return;
}
TR_ASSERT_FATAL(
region->getParent() == parent,
"removeUnconditionalExit: region %p parent changed unexpectedly "
"from %p to %p\n",
region,
parent,
region->getParent());
// Each of the predecessors had edges removed within the subgraph.
// They've been replaced by exit edges, but these nodes may now
// themselves be unconditional exits from the region, so enqueue them.
for (auto e = _allPreds.begin(); e != _allPreds.end(); ++e)
{
auto * const src = toStructureSubGraphNode((*e)->getFrom());
region->cleanupAfterEdgeRemoval(src);
enqueue(src->getStructure());
}
}
void TR_RegionStructure::ExitExtraction::moveOutgoingEdgeToParent(
TR_RegionStructure * const region,
TR_RegionStructure * const parent,
TR_StructureSubGraphNode * const node,
TR::CFGEdge * const edge,
bool isExceptionEdge)
{
TR_ASSERT_FATAL(
region->isExitEdge(edge),
"moveOutgoingEdgeToParent: unconditional exit %p node has "
"non-exit edge %p outgoing\n",
node,
edge);
TR_ASSERT_FATAL(
toStructureSubGraphNode(edge->getFrom()) == node,
"moveOutgoingEdgeToParent: expected edge %p to originate from node %p\n",
edge,
node);
auto * const exitTgt = toStructureSubGraphNode(edge->getTo());
const int32_t tgtNum = exitTgt->getNumber();
region->removeEdgeWithoutCleanup(edge, /* isExitEdge = */ true);
if (_trace)
{
traceMsg(_comp,
"removed exit edge (%d->%d):%p from region %d:%p\n",
edge->getFrom()->getNumber(),
edge->getTo()->getNumber(),
edge,
region->getNumber(),
region);
}
// Determine whether region still exits to tgtNum
bool regionStillHasThisExit = false;
ListIterator<TR::CFGEdge> rExits(®ion->getExitEdges());
for (auto exit = rExits.getFirst(); exit != NULL; exit = rExits.getNext())
{
if (exit->getTo()->getNumber() == tgtNum)
{
regionStillHasThisExit = true;
break;
}
}
// In case region no longer exits to tgtNum, we have to remove the
// corresponding edge in parent (which may itself be an exit from parent)
if (!regionStillHasThisExit)
{
// Find the edge in parent outgoing from region that corresponds to this
// (now stale) exit from region.
auto * const regionNode = parent->subNodeFromStructure(region);
TR::CFGEdge *staleEdge = NULL;
TR_SuccessorIterator sit(regionNode);
for (auto e = sit.getFirst(); e != NULL; e = sit.getNext())
{
if (e->getTo()->getNumber() == tgtNum)
{
staleEdge = e;
break;
}
}
TR_ASSERT_FATAL(
staleEdge != NULL,
"moveOutgoingEdgeToParent: unable to find parent %p edge for "
"stale exit from region %p to %d\n",
parent,
region,
tgtNum);
// Remove the stale edge. NOTE: If this edge is an exit from parent, it
// may seem appropriate to check whether it too was the last such exit,
// and if so, continue removing edges in the parent of parent, and so
// forth toward the root. However, in that case parent will definitely
// have an exit edge from node to tgtNum, to be created below.
parent->removeEdgeWithoutCleanup(staleEdge, parent->isExitEdge(staleEdge));
if (_trace)
{
traceMsg(_comp,
"original region %d:%p no longer exits to %d - "
"removed corresponding exit from parent\n",
region->getNumber(),
region,
tgtNum);
}
}
auto * const redirect = parent->findSubNodeInRegion(tgtNum);
if (redirect == NULL)
{
// This is also an exit from parent.
parent->addExitEdge(node, tgtNum, isExceptionEdge);
if (_trace)
{
traceMsg(_comp,
"successor %d does not exist in parent - created new exit %sedge\n",
tgtNum,
isExceptionEdge ? "exception " : "");
}
}
else
{
if (isExceptionEdge)
TR::CFGEdge::createExceptionEdge(node, redirect, _structureRegion);
else
TR::CFGEdge::createEdge(node, redirect, _structureRegion);
if (_trace)
{
traceMsg(_comp,
"parent region contains %d - created internal %sedge\n",
tgtNum,
isExceptionEdge ? "exception " : "");
}
}
}
void TR_RegionStructure::cleanupAfterNodeRemoval()
{
// If the region now consists of a single node, replace this node in its
// parent by the subnode.
//
// If there is no parent, this node has already been removed from its parent
// region so don't bother replacing it.
//
if ((numSubNodes() == 1) && !isNaturalLoop() &&
!getEntry()->hasSuccessor(getEntry()) &&
!getEntry()->hasExceptionSuccessor(getEntry()))
{
TR_RegionStructure::Cursor si(*this);
TR_ASSERT(si.getFirst() == getEntry(),"bad structure found trying to remove a block");
if (getParent())
getParent()->replacePart(this, getEntry()->getStructure());
}
}
void TR_RegionStructure::removeSubNodeWithoutCleanup(TR_StructureSubGraphNode *node)
{
for (auto itr = _subNodes.begin(), end = _subNodes.end(); itr != end; ++itr)
{
if (*itr == node)
{
_subNodes.erase(itr);
break;
}
}