blob: 7fe87f9319b6a164b1612cc0de2d3726c04132c9 [file] [log] [blame]
Matt Arsenaultd46fce12013-06-19 20:18:24 +00001//===-- StructurizeCFG.cpp ------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00009
Matt Arsenaultd46fce12013-06-19 20:18:24 +000010#include "llvm/Transforms/Scalar.h"
Christian Konig90b45122013-03-26 10:24:20 +000011#include "llvm/ADT/MapVector.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000012#include "llvm/ADT/SCCIterator.h"
Tom Stellard1f0dded2014-12-03 04:28:32 +000013#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000014#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000015#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000016#include "llvm/Analysis/RegionPass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Module.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000019#include "llvm/Transforms/Utils/SSAUpdater.h"
Tom Stellardf8794352012-12-19 22:10:31 +000020
21using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000022using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000023
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "structurizecfg"
25
Tom Stellardf8794352012-12-19 22:10:31 +000026namespace {
27
28// Definition of the complex types used in this pass.
29
30typedef std::pair<BasicBlock *, Value *> BBValuePair;
Tom Stellardf8794352012-12-19 22:10:31 +000031
32typedef SmallVector<RegionNode*, 8> RNVector;
33typedef SmallVector<BasicBlock*, 8> BBVector;
Tom Stellard048f14f2013-02-08 22:24:37 +000034typedef SmallVector<BranchInst*, 8> BranchVector;
Tom Stellardf8794352012-12-19 22:10:31 +000035typedef SmallVector<BBValuePair, 2> BBValueVector;
36
Tom Stellard048f14f2013-02-08 22:24:37 +000037typedef SmallPtrSet<BasicBlock *, 8> BBSet;
38
Christian Konig90b45122013-03-26 10:24:20 +000039typedef MapVector<PHINode *, BBValueVector> PhiMap;
40typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap;
41
Christian Konigd08e3d72013-02-16 11:27:29 +000042typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
Tom Stellardf8794352012-12-19 22:10:31 +000043typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
44typedef DenseMap<BasicBlock *, Value *> BBPredicates;
45typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
Christian Konigfc6a9852013-02-16 11:27:45 +000046typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
Tom Stellardf8794352012-12-19 22:10:31 +000047
48// The name for newly created blocks.
49
Craig Topperd3a34f82013-07-16 01:17:10 +000050static const char *const FlowBlockName = "Flow";
Tom Stellardf8794352012-12-19 22:10:31 +000051
Christian Konigd08e3d72013-02-16 11:27:29 +000052/// @brief Find the nearest common dominator for multiple BasicBlocks
53///
Matt Arsenaultd46fce12013-06-19 20:18:24 +000054/// Helper class for StructurizeCFG
Christian Konigd08e3d72013-02-16 11:27:29 +000055/// TODO: Maybe move into common code
56class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000057 DominatorTree *DT;
58
59 DTN2UnsignedMap IndexMap;
60
61 BasicBlock *Result;
62 unsigned ResultIndex;
63 bool ExplicitMentioned;
64
65public:
66 /// \brief Start a new query
67 NearestCommonDominator(DominatorTree *DomTree) {
68 DT = DomTree;
Craig Topperf40110f2014-04-25 05:29:35 +000069 Result = nullptr;
Christian Konigd08e3d72013-02-16 11:27:29 +000070 }
71
72 /// \brief Add BB to the resulting dominator
73 void addBlock(BasicBlock *BB, bool Remember = true) {
Christian Konigd08e3d72013-02-16 11:27:29 +000074 DomTreeNode *Node = DT->getNode(BB);
75
Craig Topperf40110f2014-04-25 05:29:35 +000076 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000077 unsigned Numbering = 0;
78 for (;Node;Node = Node->getIDom())
79 IndexMap[Node] = ++Numbering;
80 Result = BB;
81 ResultIndex = 1;
82 ExplicitMentioned = Remember;
83 return;
84 }
85
86 for (;Node;Node = Node->getIDom())
87 if (IndexMap.count(Node))
88 break;
89 else
90 IndexMap[Node] = 0;
91
92 assert(Node && "Dominator tree invalid!");
93
94 unsigned Numbering = IndexMap[Node];
95 if (Numbering > ResultIndex) {
96 Result = Node->getBlock();
97 ResultIndex = Numbering;
98 ExplicitMentioned = Remember && (Result == BB);
99 } else if (Numbering == ResultIndex) {
100 ExplicitMentioned |= Remember;
101 }
102 }
103
104 /// \brief Is "Result" one of the BBs added with "Remember" = True?
105 bool wasResultExplicitMentioned() {
106 return ExplicitMentioned;
107 }
108
109 /// \brief Get the query result
110 BasicBlock *getResult() {
111 return Result;
112 }
113};
114
Tom Stellardf8794352012-12-19 22:10:31 +0000115/// @brief Transforms the control flow graph on one single entry/exit region
116/// at a time.
117///
118/// After the transform all "If"/"Then"/"Else" style control flow looks like
119/// this:
120///
121/// \verbatim
122/// 1
123/// ||
124/// | |
125/// 2 |
126/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000127/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000128/// 3
129/// || Where:
130/// | | 1 = "If" block, calculates the condition
131/// 4 | 2 = "Then" subregion, runs if the condition is true
132/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
133/// |/ 4 = "Else" optional subregion, runs if the condition is false
134/// 5 5 = "End" block, also rejoins the control flow
135/// \endverbatim
136///
137/// Control flow is expressed as a branch where the true exit goes into the
138/// "Then"/"Else" region, while the false exit skips the region
139/// The condition for the optional "Else" region is expressed as a PHI node.
140/// The incomming values of the PHI node are true for the "If" edge and false
141/// for the "Then" edge.
142///
143/// Additionally to that even complicated loops look like this:
144///
145/// \verbatim
146/// 1
147/// ||
148/// | |
149/// 2 ^ Where:
150/// | / 1 = "Entry" block
151/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
152/// 3 3 = "Flow" block, with back edge to entry block
153/// |
154/// \endverbatim
155///
156/// The back edge of the "Flow" block is always on the false side of the branch
157/// while the true side continues the general flow. So the loop condition
158/// consist of a network of PHI nodes where the true incoming values expresses
159/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000160class StructurizeCFG : public RegionPass {
Tom Stellardf8794352012-12-19 22:10:31 +0000161 Type *Boolean;
162 ConstantInt *BoolTrue;
163 ConstantInt *BoolFalse;
164 UndefValue *BoolUndef;
165
166 Function *Func;
167 Region *ParentRegion;
168
169 DominatorTree *DT;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000170 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000171
172 RNVector Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000173 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000174
Tom Stellardf8794352012-12-19 22:10:31 +0000175 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000176 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000177
178 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000179 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000180
Christian Konigfc6a9852013-02-16 11:27:45 +0000181 BB2BBMap Loops;
182 PredMap LoopPreds;
183 BranchVector LoopConds;
184
185 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000186
187 void orderNodes();
188
Christian Konigfc6a9852013-02-16 11:27:45 +0000189 void analyzeLoops(RegionNode *N);
190
Christian Konigd8860992013-02-16 11:27:50 +0000191 Value *invert(Value *Condition);
192
Tom Stellard048f14f2013-02-08 22:24:37 +0000193 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000194
Christian Konigfc6a9852013-02-16 11:27:45 +0000195 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000196
197 void collectInfos();
198
Christian Konigfc6a9852013-02-16 11:27:45 +0000199 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000200
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000201 void delPhiValues(BasicBlock *From, BasicBlock *To);
202
203 void addPhiValues(BasicBlock *From, BasicBlock *To);
204
205 void setPhiValues();
206
Tom Stellardf8794352012-12-19 22:10:31 +0000207 void killTerminator(BasicBlock *BB);
208
Tom Stellard7370ede2013-02-08 22:24:38 +0000209 void changeExit(RegionNode *Node, BasicBlock *NewExit,
210 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000211
Tom Stellard7370ede2013-02-08 22:24:38 +0000212 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000213
Christian Konigfc6a9852013-02-16 11:27:45 +0000214 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000215
Tom Stellard7370ede2013-02-08 22:24:38 +0000216 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
217
Christian Konigfc6a9852013-02-16 11:27:45 +0000218 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000219
220 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
221
Christian Konigfc6a9852013-02-16 11:27:45 +0000222 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000223
Christian Konigfc6a9852013-02-16 11:27:45 +0000224 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
225
226 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000227
228 void createFlow();
229
Tom Stellardf8794352012-12-19 22:10:31 +0000230 void rebuildSSA();
231
232public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000233 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000234
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000235 StructurizeCFG() :
236 RegionPass(ID) {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000237 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
Tom Stellardf8794352012-12-19 22:10:31 +0000238 }
239
Christian Konig01fd1f62013-03-01 09:46:11 +0000240 using Pass::doInitialization;
Craig Topper3e4c6972014-03-05 09:10:37 +0000241 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000242
Craig Topper3e4c6972014-03-05 09:10:37 +0000243 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000244
Craig Topper3e4c6972014-03-05 09:10:37 +0000245 const char *getPassName() const override {
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000246 return "Structurize control flow";
Tom Stellardf8794352012-12-19 22:10:31 +0000247 }
248
Craig Topper3e4c6972014-03-05 09:10:37 +0000249 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000250 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000251 AU.addRequired<DominatorTreeWrapperPass>();
Tom Stellard1f0dded2014-12-03 04:28:32 +0000252 AU.addRequired<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000253 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000254 RegionPass::getAnalysisUsage(AU);
255 }
Tom Stellardf8794352012-12-19 22:10:31 +0000256};
257
258} // end anonymous namespace
259
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000260char StructurizeCFG::ID = 0;
261
262INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
263 false, false)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000264INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000265INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000266INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000267INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
268 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000269
270/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000271bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000272 LLVMContext &Context = R->getEntry()->getContext();
273
274 Boolean = Type::getInt1Ty(Context);
275 BoolTrue = ConstantInt::getTrue(Context);
276 BoolFalse = ConstantInt::getFalse(Context);
277 BoolUndef = UndefValue::get(Boolean);
278
279 return false;
280}
281
282/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000283void StructurizeCFG::orderNodes() {
Duncan P. N. Exon Smith8e661ef2014-02-04 19:19:07 +0000284 scc_iterator<Region *> I = scc_begin(ParentRegion);
285 for (Order.clear(); !I.isAtEnd(); ++I) {
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000286 const std::vector<RegionNode *> &Nodes = *I;
Tom Stellardf8794352012-12-19 22:10:31 +0000287 Order.append(Nodes.begin(), Nodes.end());
288 }
289}
290
Christian Konigfc6a9852013-02-16 11:27:45 +0000291/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000292void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000293 if (N->isSubRegion()) {
294 // Test for exit as back edge
295 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
296 if (Visited.count(Exit))
297 Loops[Exit] = N->getEntry();
298
299 } else {
300 // Test for sucessors as back edge
301 BasicBlock *BB = N->getNodeAs<BasicBlock>();
302 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
303
304 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
305 BasicBlock *Succ = Term->getSuccessor(i);
306
Tom Stellard1f0dded2014-12-03 04:28:32 +0000307 if (Visited.count(Succ) && LI->isLoopHeader(Succ) ) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000308 Loops[Succ] = BB;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000309 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000310 }
311 }
312}
313
Christian Konigd8860992013-02-16 11:27:50 +0000314/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000315Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000316 // First: Check if it's a constant
317 if (Condition == BoolTrue)
318 return BoolFalse;
319
320 if (Condition == BoolFalse)
321 return BoolTrue;
322
323 if (Condition == BoolUndef)
324 return BoolUndef;
325
326 // Second: If the condition is already inverted, return the original value
327 if (match(Condition, m_Not(m_Value(Condition))))
328 return Condition;
329
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000330 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
331 // Third: Check all the users for an invert
332 BasicBlock *Parent = Inst->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000333 for (User *U : Condition->users())
334 if (Instruction *I = dyn_cast<Instruction>(U))
335 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
336 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000337
338 // Last option: Create a new instruction
339 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000340 }
341
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000342 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
343 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
344 return BinaryOperator::CreateNot(Condition,
345 Arg->getName() + ".inv",
346 EntryBlock.getTerminator());
347 }
348
349 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000350}
351
Tom Stellard048f14f2013-02-08 22:24:37 +0000352/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000353Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
354 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000355 Value *Cond = Invert ? BoolFalse : BoolTrue;
356 if (Term->isConditional()) {
357 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000358
Aaron Ballman19978552013-06-04 01:03:03 +0000359 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000360 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000361 }
362 return Cond;
363}
364
Tom Stellard048f14f2013-02-08 22:24:37 +0000365/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000366void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000367 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000368 BasicBlock *BB = N->getEntry();
369 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000370 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000371
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000372 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
373 PI != PE; ++PI) {
374
Christian Konigfc6a9852013-02-16 11:27:45 +0000375 // Ignore it if it's a branch from outside into our region entry
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000376 if (!ParentRegion->contains(*PI))
Tom Stellard048f14f2013-02-08 22:24:37 +0000377 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000378
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000379 Region *R = RI->getRegionFor(*PI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000380 if (R == ParentRegion) {
Tom Stellardf8794352012-12-19 22:10:31 +0000381
Tom Stellard048f14f2013-02-08 22:24:37 +0000382 // It's a top level block in our region
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000383 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000384 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
385 BasicBlock *Succ = Term->getSuccessor(i);
386 if (Succ != BB)
387 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000388
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000389 if (Visited.count(*PI)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000390 // Normal forward edge
391 if (Term->isConditional()) {
392 // Try to treat it like an ELSE block
393 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000394 if (Visited.count(Other) && !Loops.count(Other) &&
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000395 !Pred.count(Other) && !Pred.count(*PI)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000396
Tom Stellard048f14f2013-02-08 22:24:37 +0000397 Pred[Other] = BoolFalse;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000398 Pred[*PI] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000399 continue;
400 }
401 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000402 Pred[*PI] = buildCondition(Term, i, false);
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000403
Tom Stellard048f14f2013-02-08 22:24:37 +0000404 } else {
405 // Back edge
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000406 LPred[*PI] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000407 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000408 }
409
410 } else {
411
412 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000413 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000414 R = R->getParent();
415
416 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000417 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000418 continue;
419
420 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000421 if (Visited.count(Entry))
422 Pred[Entry] = BoolTrue;
423 else
424 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000425 }
426 }
427}
428
429/// \brief Collect various loop and predicate infos
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000430void StructurizeCFG::collectInfos() {
Tom Stellardf8794352012-12-19 22:10:31 +0000431 // Reset predicate
432 Predicates.clear();
433
434 // and loop infos
Christian Konigfc6a9852013-02-16 11:27:45 +0000435 Loops.clear();
436 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000437
Tom Stellard048f14f2013-02-08 22:24:37 +0000438 // Reset the visited nodes
439 Visited.clear();
440
441 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
442 OI != OE; ++OI) {
Tom Stellardf8794352012-12-19 22:10:31 +0000443
444 // Analyze all the conditions leading to a node
Christian Konigfc6a9852013-02-16 11:27:45 +0000445 gatherPredicates(*OI);
Tom Stellardf8794352012-12-19 22:10:31 +0000446
Tom Stellard048f14f2013-02-08 22:24:37 +0000447 // Remember that we've seen this node
Tom Stellard7370ede2013-02-08 22:24:38 +0000448 Visited.insert((*OI)->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000449
Christian Konigfc6a9852013-02-16 11:27:45 +0000450 // Find the last back edges
451 analyzeLoops(*OI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000452 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000453}
454
455/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000456void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000457 BranchVector &Conds = Loops ? LoopConds : Conditions;
458 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000459 SSAUpdater PhiInserter;
460
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000461 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000462 assert(Term->isConditional());
463
Christian Konigfc6a9852013-02-16 11:27:45 +0000464 BasicBlock *Parent = Term->getParent();
465 BasicBlock *SuccTrue = Term->getSuccessor(0);
466 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000467
Christian Konigb5d88662013-02-16 11:27:40 +0000468 PhiInserter.Initialize(Boolean, "");
469 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000470 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000471
Christian Konigfc6a9852013-02-16 11:27:45 +0000472 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000473
474 NearestCommonDominator Dominator(DT);
475 Dominator.addBlock(Parent, false);
476
Craig Topperf40110f2014-04-25 05:29:35 +0000477 Value *ParentValue = nullptr;
Tom Stellard048f14f2013-02-08 22:24:37 +0000478 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
479 PI != PE; ++PI) {
480
Christian Konigb5d88662013-02-16 11:27:40 +0000481 if (PI->first == Parent) {
482 ParentValue = PI->second;
483 break;
484 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000485 PhiInserter.AddAvailableValue(PI->first, PI->second);
Christian Konigb5d88662013-02-16 11:27:40 +0000486 Dominator.addBlock(PI->first);
Tom Stellard048f14f2013-02-08 22:24:37 +0000487 }
488
Christian Konigb5d88662013-02-16 11:27:40 +0000489 if (ParentValue) {
490 Term->setCondition(ParentValue);
491 } else {
492 if (!Dominator.wasResultExplicitMentioned())
493 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
494
Tom Stellard048f14f2013-02-08 22:24:37 +0000495 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000496 }
Tom Stellardf8794352012-12-19 22:10:31 +0000497 }
498}
499
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000500/// \brief Remove all PHI values coming from "From" into "To" and remember
501/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000502void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000503 PhiMap &Map = DeletedPhis[To];
504 for (BasicBlock::iterator I = To->begin(), E = To->end();
505 I != E && isa<PHINode>(*I);) {
506
507 PHINode &Phi = cast<PHINode>(*I++);
508 while (Phi.getBasicBlockIndex(From) != -1) {
509 Value *Deleted = Phi.removeIncomingValue(From, false);
510 Map[&Phi].push_back(std::make_pair(From, Deleted));
511 }
512 }
513}
514
515/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000516void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000517 for (BasicBlock::iterator I = To->begin(), E = To->end();
518 I != E && isa<PHINode>(*I);) {
519
520 PHINode &Phi = cast<PHINode>(*I++);
521 Value *Undef = UndefValue::get(Phi.getType());
522 Phi.addIncoming(Undef, From);
523 }
524 AddedPhis[To].push_back(From);
525}
526
527/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000528void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000529 SSAUpdater Updater;
530 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
531 AI != AE; ++AI) {
532
533 BasicBlock *To = AI->first;
534 BBVector &From = AI->second;
535
536 if (!DeletedPhis.count(To))
537 continue;
538
539 PhiMap &Map = DeletedPhis[To];
540 for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
541 PI != PE; ++PI) {
542
543 PHINode *Phi = PI->first;
544 Value *Undef = UndefValue::get(Phi->getType());
545 Updater.Initialize(Phi->getType(), "");
546 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
547 Updater.AddAvailableValue(To, Undef);
548
Christian Konig0bccf9d2013-02-16 11:27:35 +0000549 NearestCommonDominator Dominator(DT);
550 Dominator.addBlock(To, false);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000551 for (BBValueVector::iterator VI = PI->second.begin(),
552 VE = PI->second.end(); VI != VE; ++VI) {
553
554 Updater.AddAvailableValue(VI->first, VI->second);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000555 Dominator.addBlock(VI->first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000556 }
557
Christian Konig0bccf9d2013-02-16 11:27:35 +0000558 if (!Dominator.wasResultExplicitMentioned())
559 Updater.AddAvailableValue(Dominator.getResult(), Undef);
560
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000561 for (BBVector::iterator FI = From.begin(), FE = From.end();
562 FI != FE; ++FI) {
563
564 int Idx = Phi->getBasicBlockIndex(*FI);
565 assert(Idx != -1);
566 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
567 }
568 }
569
570 DeletedPhis.erase(To);
571 }
572 assert(DeletedPhis.empty());
573}
574
Tom Stellard7370ede2013-02-08 22:24:38 +0000575/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000576void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000577 TerminatorInst *Term = BB->getTerminator();
578 if (!Term)
579 return;
580
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000581 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
582 SI != SE; ++SI) {
583
584 delPhiValues(BB, *SI);
585 }
Tom Stellardf8794352012-12-19 22:10:31 +0000586
587 Term->eraseFromParent();
588}
589
Tom Stellard7370ede2013-02-08 22:24:38 +0000590/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000591void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
592 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000593 if (Node->isSubRegion()) {
594 Region *SubRegion = Node->getNodeAs<Region>();
595 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000596 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000597
Tom Stellard7370ede2013-02-08 22:24:38 +0000598 // Find all the edges from the sub region to the exit
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000599 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
600 I != E;) {
601
602 BasicBlock *BB = *I++;
Tom Stellard7370ede2013-02-08 22:24:38 +0000603 if (!SubRegion->contains(BB))
604 continue;
605
606 // Modify the edges to point to the new exit
607 delPhiValues(BB, OldExit);
608 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
609 addPhiValues(BB, NewExit);
610
611 // Find the new dominator (if requested)
612 if (IncludeDominator) {
613 if (!Dominator)
614 Dominator = BB;
615 else
616 Dominator = DT->findNearestCommonDominator(Dominator, BB);
617 }
Tom Stellardf8794352012-12-19 22:10:31 +0000618 }
619
Tom Stellard7370ede2013-02-08 22:24:38 +0000620 // Change the dominator (if requested)
621 if (Dominator)
622 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000623
Tom Stellard7370ede2013-02-08 22:24:38 +0000624 // Update the region info
625 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000626
Tom Stellardf8794352012-12-19 22:10:31 +0000627 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000628 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
629 killTerminator(BB);
630 BranchInst::Create(NewExit, BB);
631 addPhiValues(BB, NewExit);
632 if (IncludeDominator)
633 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000634 }
Tom Stellardf8794352012-12-19 22:10:31 +0000635}
636
Tom Stellardf8794352012-12-19 22:10:31 +0000637/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000638BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000639 LLVMContext &Context = Func->getContext();
640 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
641 Order.back()->getEntry();
642 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
643 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000644 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000645 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000646 return Flow;
647}
648
Tom Stellard7370ede2013-02-08 22:24:38 +0000649/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000650BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000651 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000652
Christian Konigfc6a9852013-02-16 11:27:45 +0000653 if (!PrevNode->isSubRegion()) {
654 killTerminator(Entry);
655 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
656 return Entry;
Tom Stellard7370ede2013-02-08 22:24:38 +0000657
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000658 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000659
Christian Konigfc6a9852013-02-16 11:27:45 +0000660 // create a new flow node
661 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000662
Christian Konigfc6a9852013-02-16 11:27:45 +0000663 // and wire it up
664 changeExit(PrevNode, Flow, true);
665 PrevNode = ParentRegion->getBBNode(Flow);
666 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000667}
668
669/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000670BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
671 bool ExitUseAllowed) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000672 if (Order.empty() && ExitUseAllowed) {
673 BasicBlock *Exit = ParentRegion->getExit();
674 DT->changeImmediateDominator(Exit, Flow);
675 addPhiValues(Flow, Exit);
676 return Exit;
677 }
678 return getNextFlow(Flow);
679}
680
Christian Konigfc6a9852013-02-16 11:27:45 +0000681/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000682void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000683 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
684 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000685}
686
687/// \brief Does BB dominate all the predicates of Node ?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000688bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000689 BBPredicates &Preds = Predicates[Node->getEntry()];
690 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
691 PI != PE; ++PI) {
692
693 if (!DT->dominates(BB, PI->first))
694 return false;
695 }
696 return true;
697}
698
Tom Stellardf8794352012-12-19 22:10:31 +0000699/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000700bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000701 BBPredicates &Preds = Predicates[Node->getEntry()];
702 bool Dominated = false;
703
704 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000705 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000706 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000707
708 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
709 I != E; ++I) {
710
711 if (I->second != BoolTrue)
712 return false;
713
Christian Konigfc6a9852013-02-16 11:27:45 +0000714 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000715 Dominated = true;
716 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000717
718 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000719 return Dominated;
720}
721
Tom Stellard7370ede2013-02-08 22:24:38 +0000722/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000723void StructurizeCFG::wireFlow(bool ExitUseAllowed,
724 BasicBlock *LoopEnd) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000725 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000726 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000727
Christian Konigfc6a9852013-02-16 11:27:45 +0000728 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000729 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000730 if (PrevNode) {
731 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000732 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000733 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000734
735 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000736 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000737 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000738
Tom Stellard7370ede2013-02-08 22:24:38 +0000739 // Insert extra postfix node (or use exit instead)
740 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000741 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000742
743 // let it point to entry and next block
744 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
745 addPhiValues(Flow, Entry);
746 DT->changeImmediateDominator(Entry, Flow);
747
Christian Konigfc6a9852013-02-16 11:27:45 +0000748 PrevNode = Node;
749 while (!Order.empty() && !Visited.count(LoopEnd) &&
Tom Stellard7370ede2013-02-08 22:24:38 +0000750 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000751 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000752 }
753
Christian Konigfc6a9852013-02-16 11:27:45 +0000754 changeExit(PrevNode, Next, false);
755 setPrevNode(Next);
756 }
757}
758
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000759void StructurizeCFG::handleLoops(bool ExitUseAllowed,
760 BasicBlock *LoopEnd) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000761 RegionNode *Node = Order.back();
762 BasicBlock *LoopStart = Node->getEntry();
763
764 if (!Loops.count(LoopStart)) {
765 wireFlow(ExitUseAllowed, LoopEnd);
766 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000767 }
768
Christian Konigfc6a9852013-02-16 11:27:45 +0000769 if (!isPredictableTrue(Node))
770 LoopStart = needPrefix(true);
771
772 LoopEnd = Loops[Node->getEntry()];
773 wireFlow(false, LoopEnd);
774 while (!Visited.count(LoopEnd)) {
775 handleLoops(false, LoopEnd);
776 }
777
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000778 // If the start of the loop is the entry block, we can't branch to it so
779 // insert a new dummy entry block.
780 Function *LoopFunc = LoopStart->getParent();
781 if (LoopStart == &LoopFunc->getEntryBlock()) {
782 LoopStart->setName("entry.orig");
783
784 BasicBlock *NewEntry =
785 BasicBlock::Create(LoopStart->getContext(),
786 "entry",
787 LoopFunc,
788 LoopStart);
789 BranchInst::Create(LoopStart, NewEntry);
790 }
791
Christian Konigfc6a9852013-02-16 11:27:45 +0000792 // Create an extra loop end node
793 LoopEnd = needPrefix(false);
794 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
795 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
796 BoolUndef, LoopEnd));
797 addPhiValues(LoopEnd, LoopStart);
798 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000799}
800
Tom Stellardf8794352012-12-19 22:10:31 +0000801/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000802/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000803void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000804 BasicBlock *Exit = ParentRegion->getExit();
805 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
806
Tom Stellardf8794352012-12-19 22:10:31 +0000807 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000808 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000809 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000810 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000811
Craig Topperf40110f2014-04-25 05:29:35 +0000812 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000813 Visited.clear();
814
Tom Stellardf8794352012-12-19 22:10:31 +0000815 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000816 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000817 }
818
Christian Konigfc6a9852013-02-16 11:27:45 +0000819 if (PrevNode)
820 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000821 else
822 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000823}
824
Tom Stellardf8794352012-12-19 22:10:31 +0000825/// Handle a rare case where the disintegrated nodes instructions
826/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000827void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000828 SSAUpdater Updater;
Tobias Grosser4abf9d32014-03-03 13:00:39 +0000829 for (const auto &BB : ParentRegion->blocks())
Tom Stellardf8794352012-12-19 22:10:31 +0000830 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
831 II != IE; ++II) {
832
833 bool Initialized = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000834 for (auto I = II->use_begin(), E = II->use_end(); I != E;) {
835 Use &U = *I++;
836 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000837 if (User->getParent() == BB) {
838 continue;
839
840 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000841 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000842 continue;
843 }
844
845 if (DT->dominates(II, User))
846 continue;
847
848 if (!Initialized) {
849 Value *Undef = UndefValue::get(II->getType());
850 Updater.Initialize(II->getType(), "");
851 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
852 Updater.AddAvailableValue(BB, II);
853 Initialized = true;
854 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000855 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000856 }
857 }
Tom Stellardf8794352012-12-19 22:10:31 +0000858}
859
860/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000861bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000862 if (R->isTopLevelRegion())
863 return false;
864
865 Func = R->getEntry()->getParent();
866 ParentRegion = R;
867
Chandler Carruth73523022014-01-13 13:07:17 +0000868 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tom Stellard1f0dded2014-12-03 04:28:32 +0000869 LI = &getAnalysis<LoopInfo>();
Tom Stellardf8794352012-12-19 22:10:31 +0000870
871 orderNodes();
872 collectInfos();
873 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000874 insertConditions(false);
875 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000876 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000877 rebuildSSA();
878
Tom Stellard048f14f2013-02-08 22:24:37 +0000879 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000880 Order.clear();
881 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000882 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000883 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000884 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000885 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000886 Loops.clear();
887 LoopPreds.clear();
888 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000889
890 return true;
891}
892
893/// \brief Create the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000894Pass *llvm::createStructurizeCFGPass() {
895 return new StructurizeCFG();
Tom Stellardf8794352012-12-19 22:10:31 +0000896}