blob: aaf6f9a0a73b4e3f525640f579d05885a0c855af [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 Stellard071ec902015-02-04 20:49:44 +000013#include "llvm/ADT/PostOrderIterator.h"
Tom Stellard1f0dded2014-12-03 04:28:32 +000014#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000015#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000016#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000017#include "llvm/Analysis/RegionPass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Module.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Tom Stellard071ec902015-02-04 20:49:44 +000020#include "llvm/Support/Debug.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000021#include "llvm/Transforms/Utils/SSAUpdater.h"
Tom Stellardf8794352012-12-19 22:10:31 +000022
23using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000024using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000025
Chandler Carruth964daaa2014-04-22 02:55:47 +000026#define DEBUG_TYPE "structurizecfg"
27
Tom Stellardf8794352012-12-19 22:10:31 +000028namespace {
29
30// Definition of the complex types used in this pass.
31
32typedef std::pair<BasicBlock *, Value *> BBValuePair;
Tom Stellardf8794352012-12-19 22:10:31 +000033
34typedef SmallVector<RegionNode*, 8> RNVector;
35typedef SmallVector<BasicBlock*, 8> BBVector;
Tom Stellard048f14f2013-02-08 22:24:37 +000036typedef SmallVector<BranchInst*, 8> BranchVector;
Tom Stellardf8794352012-12-19 22:10:31 +000037typedef SmallVector<BBValuePair, 2> BBValueVector;
38
Tom Stellard048f14f2013-02-08 22:24:37 +000039typedef SmallPtrSet<BasicBlock *, 8> BBSet;
40
Christian Konig90b45122013-03-26 10:24:20 +000041typedef MapVector<PHINode *, BBValueVector> PhiMap;
42typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap;
43
Christian Konigd08e3d72013-02-16 11:27:29 +000044typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
Tom Stellardf8794352012-12-19 22:10:31 +000045typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
46typedef DenseMap<BasicBlock *, Value *> BBPredicates;
47typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
Christian Konigfc6a9852013-02-16 11:27:45 +000048typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
Tom Stellardf8794352012-12-19 22:10:31 +000049
50// The name for newly created blocks.
51
Craig Topperd3a34f82013-07-16 01:17:10 +000052static const char *const FlowBlockName = "Flow";
Tom Stellardf8794352012-12-19 22:10:31 +000053
Christian Konigd08e3d72013-02-16 11:27:29 +000054/// @brief Find the nearest common dominator for multiple BasicBlocks
55///
Matt Arsenaultd46fce12013-06-19 20:18:24 +000056/// Helper class for StructurizeCFG
Christian Konigd08e3d72013-02-16 11:27:29 +000057/// TODO: Maybe move into common code
58class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000059 DominatorTree *DT;
60
61 DTN2UnsignedMap IndexMap;
62
63 BasicBlock *Result;
64 unsigned ResultIndex;
65 bool ExplicitMentioned;
66
67public:
68 /// \brief Start a new query
69 NearestCommonDominator(DominatorTree *DomTree) {
70 DT = DomTree;
Craig Topperf40110f2014-04-25 05:29:35 +000071 Result = nullptr;
Christian Konigd08e3d72013-02-16 11:27:29 +000072 }
73
74 /// \brief Add BB to the resulting dominator
75 void addBlock(BasicBlock *BB, bool Remember = true) {
Christian Konigd08e3d72013-02-16 11:27:29 +000076 DomTreeNode *Node = DT->getNode(BB);
77
Craig Topperf40110f2014-04-25 05:29:35 +000078 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000079 unsigned Numbering = 0;
80 for (;Node;Node = Node->getIDom())
81 IndexMap[Node] = ++Numbering;
82 Result = BB;
83 ResultIndex = 1;
84 ExplicitMentioned = Remember;
85 return;
86 }
87
88 for (;Node;Node = Node->getIDom())
89 if (IndexMap.count(Node))
90 break;
91 else
92 IndexMap[Node] = 0;
93
94 assert(Node && "Dominator tree invalid!");
95
96 unsigned Numbering = IndexMap[Node];
97 if (Numbering > ResultIndex) {
98 Result = Node->getBlock();
99 ResultIndex = Numbering;
100 ExplicitMentioned = Remember && (Result == BB);
101 } else if (Numbering == ResultIndex) {
102 ExplicitMentioned |= Remember;
103 }
104 }
105
106 /// \brief Is "Result" one of the BBs added with "Remember" = True?
107 bool wasResultExplicitMentioned() {
108 return ExplicitMentioned;
109 }
110
111 /// \brief Get the query result
112 BasicBlock *getResult() {
113 return Result;
114 }
115};
116
Tom Stellardf8794352012-12-19 22:10:31 +0000117/// @brief Transforms the control flow graph on one single entry/exit region
118/// at a time.
119///
120/// After the transform all "If"/"Then"/"Else" style control flow looks like
121/// this:
122///
123/// \verbatim
124/// 1
125/// ||
126/// | |
127/// 2 |
128/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000129/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000130/// 3
131/// || Where:
132/// | | 1 = "If" block, calculates the condition
133/// 4 | 2 = "Then" subregion, runs if the condition is true
134/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
135/// |/ 4 = "Else" optional subregion, runs if the condition is false
136/// 5 5 = "End" block, also rejoins the control flow
137/// \endverbatim
138///
139/// Control flow is expressed as a branch where the true exit goes into the
140/// "Then"/"Else" region, while the false exit skips the region
141/// The condition for the optional "Else" region is expressed as a PHI node.
142/// The incomming values of the PHI node are true for the "If" edge and false
143/// for the "Then" edge.
144///
145/// Additionally to that even complicated loops look like this:
146///
147/// \verbatim
148/// 1
149/// ||
150/// | |
151/// 2 ^ Where:
152/// | / 1 = "Entry" block
153/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
154/// 3 3 = "Flow" block, with back edge to entry block
155/// |
156/// \endverbatim
157///
158/// The back edge of the "Flow" block is always on the false side of the branch
159/// while the true side continues the general flow. So the loop condition
160/// consist of a network of PHI nodes where the true incoming values expresses
161/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000162class StructurizeCFG : public RegionPass {
Tom Stellardf8794352012-12-19 22:10:31 +0000163 Type *Boolean;
164 ConstantInt *BoolTrue;
165 ConstantInt *BoolFalse;
166 UndefValue *BoolUndef;
167
168 Function *Func;
169 Region *ParentRegion;
170
171 DominatorTree *DT;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000172 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000173
174 RNVector Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000175 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000176
Tom Stellardf8794352012-12-19 22:10:31 +0000177 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000178 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000179
180 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000181 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000182
Christian Konigfc6a9852013-02-16 11:27:45 +0000183 BB2BBMap Loops;
184 PredMap LoopPreds;
185 BranchVector LoopConds;
186
187 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000188
189 void orderNodes();
190
Christian Konigfc6a9852013-02-16 11:27:45 +0000191 void analyzeLoops(RegionNode *N);
192
Christian Konigd8860992013-02-16 11:27:50 +0000193 Value *invert(Value *Condition);
194
Tom Stellard048f14f2013-02-08 22:24:37 +0000195 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000196
Christian Konigfc6a9852013-02-16 11:27:45 +0000197 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000198
199 void collectInfos();
200
Christian Konigfc6a9852013-02-16 11:27:45 +0000201 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000202
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000203 void delPhiValues(BasicBlock *From, BasicBlock *To);
204
205 void addPhiValues(BasicBlock *From, BasicBlock *To);
206
207 void setPhiValues();
208
Tom Stellardf8794352012-12-19 22:10:31 +0000209 void killTerminator(BasicBlock *BB);
210
Tom Stellard7370ede2013-02-08 22:24:38 +0000211 void changeExit(RegionNode *Node, BasicBlock *NewExit,
212 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000213
Tom Stellard7370ede2013-02-08 22:24:38 +0000214 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000215
Christian Konigfc6a9852013-02-16 11:27:45 +0000216 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000217
Tom Stellard7370ede2013-02-08 22:24:38 +0000218 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
219
Christian Konigfc6a9852013-02-16 11:27:45 +0000220 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000221
222 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
223
Christian Konigfc6a9852013-02-16 11:27:45 +0000224 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000225
Christian Konigfc6a9852013-02-16 11:27:45 +0000226 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
227
228 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000229
230 void createFlow();
231
Tom Stellardf8794352012-12-19 22:10:31 +0000232 void rebuildSSA();
233
234public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000235 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000236
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000237 StructurizeCFG() :
238 RegionPass(ID) {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000239 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
Tom Stellardf8794352012-12-19 22:10:31 +0000240 }
241
Christian Konig01fd1f62013-03-01 09:46:11 +0000242 using Pass::doInitialization;
Craig Topper3e4c6972014-03-05 09:10:37 +0000243 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000244
Craig Topper3e4c6972014-03-05 09:10:37 +0000245 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000246
Craig Topper3e4c6972014-03-05 09:10:37 +0000247 const char *getPassName() const override {
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000248 return "Structurize control flow";
Tom Stellardf8794352012-12-19 22:10:31 +0000249 }
250
Craig Topper3e4c6972014-03-05 09:10:37 +0000251 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellardd3e916e2013-10-02 17:04:59 +0000252 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000253 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000254 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000255 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000256 RegionPass::getAnalysisUsage(AU);
257 }
Tom Stellardf8794352012-12-19 22:10:31 +0000258};
259
260} // end anonymous namespace
261
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000262char StructurizeCFG::ID = 0;
263
264INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
265 false, false)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000266INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000267INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000268INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000269INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
270 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000271
272/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000273bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000274 LLVMContext &Context = R->getEntry()->getContext();
275
276 Boolean = Type::getInt1Ty(Context);
277 BoolTrue = ConstantInt::getTrue(Context);
278 BoolFalse = ConstantInt::getFalse(Context);
279 BoolUndef = UndefValue::get(Boolean);
280
281 return false;
282}
283
284/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000285void StructurizeCFG::orderNodes() {
Tom Stellard071ec902015-02-04 20:49:44 +0000286 RNVector TempOrder;
287 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
288 TempOrder.append(RPOT.begin(), RPOT.end());
289
290 std::map<Loop*, unsigned> LoopBlocks;
291
292
293 // The reverse post-order traversal of the list gives us an ordering close
294 // to what we want. The only problem with it is that sometimes backedges
295 // for outer loops will be visited before backedges for inner loops.
296 for (RegionNode *RN : TempOrder) {
297 BasicBlock *BB = RN->getEntry();
298 Loop *Loop = LI->getLoopFor(BB);
299 if (!LoopBlocks.count(Loop)) {
300 LoopBlocks[Loop] = 1;
301 continue;
302 }
303 LoopBlocks[Loop]++;
Tom Stellardf8794352012-12-19 22:10:31 +0000304 }
Tom Stellard071ec902015-02-04 20:49:44 +0000305
306 unsigned CurrentLoopDepth = 0;
307 Loop *CurrentLoop = nullptr;
308 BBSet TempVisited;
309 for (RNVector::iterator I = TempOrder.begin(), E = TempOrder.end(); I != E; ++I) {
310 BasicBlock *BB = (*I)->getEntry();
311 unsigned LoopDepth = LI->getLoopDepth(BB);
312
313 if (std::find(Order.begin(), Order.end(), *I) != Order.end())
314 continue;
315
316 if (LoopDepth < CurrentLoopDepth) {
317 // Make sure we have visited all blocks in this loop before moving back to
318 // the outer loop.
319
320 RNVector::iterator LoopI = I;
321 while(LoopBlocks[CurrentLoop]) {
322 LoopI++;
323 BasicBlock *LoopBB = (*LoopI)->getEntry();
324 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
325 LoopBlocks[CurrentLoop]--;
326 Order.push_back(*LoopI);
327 }
328 }
329 }
330
331 CurrentLoop = LI->getLoopFor(BB);
332 if (CurrentLoop) {
333 LoopBlocks[CurrentLoop]--;
334 }
335
336 CurrentLoopDepth = LoopDepth;
337 Order.push_back(*I);
338 }
339
340 // This pass originally used a post-order traversal and then operated on
341 // the list in reverse. Now that we are using a reverse post-order traversal
342 // rather than re-working the whole pass to operate on the list in order,
343 // we just reverse the list and continue to operate on it in reverse.
344 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000345}
346
Christian Konigfc6a9852013-02-16 11:27:45 +0000347/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000348void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000349 if (N->isSubRegion()) {
350 // Test for exit as back edge
351 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
352 if (Visited.count(Exit))
353 Loops[Exit] = N->getEntry();
354
355 } else {
356 // Test for sucessors as back edge
357 BasicBlock *BB = N->getNodeAs<BasicBlock>();
358 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
359
360 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
361 BasicBlock *Succ = Term->getSuccessor(i);
362
Tom Stellard080209d2015-02-04 20:49:47 +0000363 if (Visited.count(Succ)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000364 Loops[Succ] = BB;
Tom Stellard1f0dded2014-12-03 04:28:32 +0000365 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000366 }
367 }
368}
369
Christian Konigd8860992013-02-16 11:27:50 +0000370/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000371Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000372 // First: Check if it's a constant
373 if (Condition == BoolTrue)
374 return BoolFalse;
375
376 if (Condition == BoolFalse)
377 return BoolTrue;
378
379 if (Condition == BoolUndef)
380 return BoolUndef;
381
382 // Second: If the condition is already inverted, return the original value
383 if (match(Condition, m_Not(m_Value(Condition))))
384 return Condition;
385
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000386 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
387 // Third: Check all the users for an invert
388 BasicBlock *Parent = Inst->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000389 for (User *U : Condition->users())
390 if (Instruction *I = dyn_cast<Instruction>(U))
391 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
392 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000393
394 // Last option: Create a new instruction
395 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000396 }
397
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000398 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
399 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
400 return BinaryOperator::CreateNot(Condition,
401 Arg->getName() + ".inv",
402 EntryBlock.getTerminator());
403 }
404
405 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000406}
407
Tom Stellard048f14f2013-02-08 22:24:37 +0000408/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000409Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
410 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000411 Value *Cond = Invert ? BoolFalse : BoolTrue;
412 if (Term->isConditional()) {
413 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000414
Aaron Ballman19978552013-06-04 01:03:03 +0000415 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000416 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000417 }
418 return Cond;
419}
420
Tom Stellard048f14f2013-02-08 22:24:37 +0000421/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000422void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000423 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000424 BasicBlock *BB = N->getEntry();
425 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000426 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000427
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000428 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
429 PI != PE; ++PI) {
430
Christian Konigfc6a9852013-02-16 11:27:45 +0000431 // Ignore it if it's a branch from outside into our region entry
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000432 if (!ParentRegion->contains(*PI))
Tom Stellard048f14f2013-02-08 22:24:37 +0000433 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000434
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000435 Region *R = RI->getRegionFor(*PI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000436 if (R == ParentRegion) {
Tom Stellardf8794352012-12-19 22:10:31 +0000437
Tom Stellard048f14f2013-02-08 22:24:37 +0000438 // It's a top level block in our region
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000439 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000440 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
441 BasicBlock *Succ = Term->getSuccessor(i);
442 if (Succ != BB)
443 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000444
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000445 if (Visited.count(*PI)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000446 // Normal forward edge
447 if (Term->isConditional()) {
448 // Try to treat it like an ELSE block
449 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000450 if (Visited.count(Other) && !Loops.count(Other) &&
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000451 !Pred.count(Other) && !Pred.count(*PI)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000452
Tom Stellard048f14f2013-02-08 22:24:37 +0000453 Pred[Other] = BoolFalse;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000454 Pred[*PI] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000455 continue;
456 }
457 }
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000458 Pred[*PI] = buildCondition(Term, i, false);
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000459
Tom Stellard048f14f2013-02-08 22:24:37 +0000460 } else {
461 // Back edge
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000462 LPred[*PI] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000463 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000464 }
465
466 } else {
467
468 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000469 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000470 R = R->getParent();
471
472 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000473 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000474 continue;
475
476 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000477 if (Visited.count(Entry))
478 Pred[Entry] = BoolTrue;
479 else
480 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000481 }
482 }
483}
484
485/// \brief Collect various loop and predicate infos
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000486void StructurizeCFG::collectInfos() {
Tom Stellardf8794352012-12-19 22:10:31 +0000487 // Reset predicate
488 Predicates.clear();
489
490 // and loop infos
Christian Konigfc6a9852013-02-16 11:27:45 +0000491 Loops.clear();
492 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000493
Tom Stellard048f14f2013-02-08 22:24:37 +0000494 // Reset the visited nodes
495 Visited.clear();
496
497 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
498 OI != OE; ++OI) {
Tom Stellardf8794352012-12-19 22:10:31 +0000499
Tom Stellard071ec902015-02-04 20:49:44 +0000500 DEBUG(dbgs() << "Visiting: " <<
501 ((*OI)->isSubRegion() ? "SubRegion with entry: " : "") <<
502 (*OI)->getEntry()->getName() << " Loop Depth: " << LI->getLoopDepth((*OI)->getEntry()) << "\n");
503
Tom Stellardf8794352012-12-19 22:10:31 +0000504 // Analyze all the conditions leading to a node
Christian Konigfc6a9852013-02-16 11:27:45 +0000505 gatherPredicates(*OI);
Tom Stellardf8794352012-12-19 22:10:31 +0000506
Tom Stellard048f14f2013-02-08 22:24:37 +0000507 // Remember that we've seen this node
Tom Stellard7370ede2013-02-08 22:24:38 +0000508 Visited.insert((*OI)->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000509
Christian Konigfc6a9852013-02-16 11:27:45 +0000510 // Find the last back edges
511 analyzeLoops(*OI);
Tom Stellard048f14f2013-02-08 22:24:37 +0000512 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000513}
514
515/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000516void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000517 BranchVector &Conds = Loops ? LoopConds : Conditions;
518 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000519 SSAUpdater PhiInserter;
520
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000521 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000522 assert(Term->isConditional());
523
Christian Konigfc6a9852013-02-16 11:27:45 +0000524 BasicBlock *Parent = Term->getParent();
525 BasicBlock *SuccTrue = Term->getSuccessor(0);
526 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000527
Christian Konigb5d88662013-02-16 11:27:40 +0000528 PhiInserter.Initialize(Boolean, "");
529 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000530 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000531
Christian Konigfc6a9852013-02-16 11:27:45 +0000532 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000533
534 NearestCommonDominator Dominator(DT);
535 Dominator.addBlock(Parent, false);
536
Craig Topperf40110f2014-04-25 05:29:35 +0000537 Value *ParentValue = nullptr;
Tom Stellard048f14f2013-02-08 22:24:37 +0000538 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
539 PI != PE; ++PI) {
540
Christian Konigb5d88662013-02-16 11:27:40 +0000541 if (PI->first == Parent) {
542 ParentValue = PI->second;
543 break;
544 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000545 PhiInserter.AddAvailableValue(PI->first, PI->second);
Christian Konigb5d88662013-02-16 11:27:40 +0000546 Dominator.addBlock(PI->first);
Tom Stellard048f14f2013-02-08 22:24:37 +0000547 }
548
Christian Konigb5d88662013-02-16 11:27:40 +0000549 if (ParentValue) {
550 Term->setCondition(ParentValue);
551 } else {
552 if (!Dominator.wasResultExplicitMentioned())
553 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
554
Tom Stellard048f14f2013-02-08 22:24:37 +0000555 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000556 }
Tom Stellardf8794352012-12-19 22:10:31 +0000557 }
558}
559
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000560/// \brief Remove all PHI values coming from "From" into "To" and remember
561/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000562void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000563 PhiMap &Map = DeletedPhis[To];
564 for (BasicBlock::iterator I = To->begin(), E = To->end();
565 I != E && isa<PHINode>(*I);) {
566
567 PHINode &Phi = cast<PHINode>(*I++);
568 while (Phi.getBasicBlockIndex(From) != -1) {
569 Value *Deleted = Phi.removeIncomingValue(From, false);
570 Map[&Phi].push_back(std::make_pair(From, Deleted));
571 }
572 }
573}
574
575/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000576void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000577 for (BasicBlock::iterator I = To->begin(), E = To->end();
578 I != E && isa<PHINode>(*I);) {
579
580 PHINode &Phi = cast<PHINode>(*I++);
581 Value *Undef = UndefValue::get(Phi.getType());
582 Phi.addIncoming(Undef, From);
583 }
584 AddedPhis[To].push_back(From);
585}
586
587/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000588void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000589 SSAUpdater Updater;
590 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
591 AI != AE; ++AI) {
592
593 BasicBlock *To = AI->first;
594 BBVector &From = AI->second;
595
596 if (!DeletedPhis.count(To))
597 continue;
598
599 PhiMap &Map = DeletedPhis[To];
600 for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
601 PI != PE; ++PI) {
602
603 PHINode *Phi = PI->first;
604 Value *Undef = UndefValue::get(Phi->getType());
605 Updater.Initialize(Phi->getType(), "");
606 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
607 Updater.AddAvailableValue(To, Undef);
608
Christian Konig0bccf9d2013-02-16 11:27:35 +0000609 NearestCommonDominator Dominator(DT);
610 Dominator.addBlock(To, false);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000611 for (BBValueVector::iterator VI = PI->second.begin(),
612 VE = PI->second.end(); VI != VE; ++VI) {
613
614 Updater.AddAvailableValue(VI->first, VI->second);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000615 Dominator.addBlock(VI->first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000616 }
617
Christian Konig0bccf9d2013-02-16 11:27:35 +0000618 if (!Dominator.wasResultExplicitMentioned())
619 Updater.AddAvailableValue(Dominator.getResult(), Undef);
620
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000621 for (BBVector::iterator FI = From.begin(), FE = From.end();
622 FI != FE; ++FI) {
623
624 int Idx = Phi->getBasicBlockIndex(*FI);
625 assert(Idx != -1);
626 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
627 }
628 }
629
630 DeletedPhis.erase(To);
631 }
632 assert(DeletedPhis.empty());
633}
634
Tom Stellard7370ede2013-02-08 22:24:38 +0000635/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000636void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000637 TerminatorInst *Term = BB->getTerminator();
638 if (!Term)
639 return;
640
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000641 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
642 SI != SE; ++SI) {
643
644 delPhiValues(BB, *SI);
645 }
Tom Stellardf8794352012-12-19 22:10:31 +0000646
647 Term->eraseFromParent();
648}
649
Tom Stellard7370ede2013-02-08 22:24:38 +0000650/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000651void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
652 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000653 if (Node->isSubRegion()) {
654 Region *SubRegion = Node->getNodeAs<Region>();
655 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000656 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000657
Tom Stellard7370ede2013-02-08 22:24:38 +0000658 // Find all the edges from the sub region to the exit
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000659 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
660 I != E;) {
661
662 BasicBlock *BB = *I++;
Tom Stellard7370ede2013-02-08 22:24:38 +0000663 if (!SubRegion->contains(BB))
664 continue;
665
666 // Modify the edges to point to the new exit
667 delPhiValues(BB, OldExit);
668 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
669 addPhiValues(BB, NewExit);
670
671 // Find the new dominator (if requested)
672 if (IncludeDominator) {
673 if (!Dominator)
674 Dominator = BB;
675 else
676 Dominator = DT->findNearestCommonDominator(Dominator, BB);
677 }
Tom Stellardf8794352012-12-19 22:10:31 +0000678 }
679
Tom Stellard7370ede2013-02-08 22:24:38 +0000680 // Change the dominator (if requested)
681 if (Dominator)
682 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000683
Tom Stellard7370ede2013-02-08 22:24:38 +0000684 // Update the region info
685 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000686
Tom Stellardf8794352012-12-19 22:10:31 +0000687 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000688 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
689 killTerminator(BB);
690 BranchInst::Create(NewExit, BB);
691 addPhiValues(BB, NewExit);
692 if (IncludeDominator)
693 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000694 }
Tom Stellardf8794352012-12-19 22:10:31 +0000695}
696
Tom Stellardf8794352012-12-19 22:10:31 +0000697/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000698BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000699 LLVMContext &Context = Func->getContext();
700 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
701 Order.back()->getEntry();
702 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
703 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000704 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000705 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000706 return Flow;
707}
708
Tom Stellard7370ede2013-02-08 22:24:38 +0000709/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000710BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000711 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000712
Christian Konigfc6a9852013-02-16 11:27:45 +0000713 if (!PrevNode->isSubRegion()) {
714 killTerminator(Entry);
715 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
716 return Entry;
Tom Stellard7370ede2013-02-08 22:24:38 +0000717
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000718 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000719
Christian Konigfc6a9852013-02-16 11:27:45 +0000720 // create a new flow node
721 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000722
Christian Konigfc6a9852013-02-16 11:27:45 +0000723 // and wire it up
724 changeExit(PrevNode, Flow, true);
725 PrevNode = ParentRegion->getBBNode(Flow);
726 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000727}
728
729/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000730BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
731 bool ExitUseAllowed) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000732 if (Order.empty() && ExitUseAllowed) {
733 BasicBlock *Exit = ParentRegion->getExit();
734 DT->changeImmediateDominator(Exit, Flow);
735 addPhiValues(Flow, Exit);
736 return Exit;
737 }
738 return getNextFlow(Flow);
739}
740
Christian Konigfc6a9852013-02-16 11:27:45 +0000741/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000742void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000743 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
744 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000745}
746
747/// \brief Does BB dominate all the predicates of Node ?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000748bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000749 BBPredicates &Preds = Predicates[Node->getEntry()];
750 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
751 PI != PE; ++PI) {
752
753 if (!DT->dominates(BB, PI->first))
754 return false;
755 }
756 return true;
757}
758
Tom Stellardf8794352012-12-19 22:10:31 +0000759/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000760bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000761 BBPredicates &Preds = Predicates[Node->getEntry()];
762 bool Dominated = false;
763
764 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000765 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000766 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000767
768 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
769 I != E; ++I) {
770
771 if (I->second != BoolTrue)
772 return false;
773
Christian Konigfc6a9852013-02-16 11:27:45 +0000774 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000775 Dominated = true;
776 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000777
778 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000779 return Dominated;
780}
781
Tom Stellard7370ede2013-02-08 22:24:38 +0000782/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000783void StructurizeCFG::wireFlow(bool ExitUseAllowed,
784 BasicBlock *LoopEnd) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000785 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000786 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000787
Christian Konigfc6a9852013-02-16 11:27:45 +0000788 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000789 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000790 if (PrevNode) {
791 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000792 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000793 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000794
795 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000796 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000797 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000798
Tom Stellard7370ede2013-02-08 22:24:38 +0000799 // Insert extra postfix node (or use exit instead)
800 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000801 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000802
803 // let it point to entry and next block
804 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
805 addPhiValues(Flow, Entry);
806 DT->changeImmediateDominator(Entry, Flow);
807
Christian Konigfc6a9852013-02-16 11:27:45 +0000808 PrevNode = Node;
809 while (!Order.empty() && !Visited.count(LoopEnd) &&
Tom Stellard7370ede2013-02-08 22:24:38 +0000810 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000811 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000812 }
813
Christian Konigfc6a9852013-02-16 11:27:45 +0000814 changeExit(PrevNode, Next, false);
815 setPrevNode(Next);
816 }
817}
818
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000819void StructurizeCFG::handleLoops(bool ExitUseAllowed,
820 BasicBlock *LoopEnd) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000821 RegionNode *Node = Order.back();
822 BasicBlock *LoopStart = Node->getEntry();
823
824 if (!Loops.count(LoopStart)) {
825 wireFlow(ExitUseAllowed, LoopEnd);
826 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000827 }
828
Christian Konigfc6a9852013-02-16 11:27:45 +0000829 if (!isPredictableTrue(Node))
830 LoopStart = needPrefix(true);
831
832 LoopEnd = Loops[Node->getEntry()];
833 wireFlow(false, LoopEnd);
834 while (!Visited.count(LoopEnd)) {
835 handleLoops(false, LoopEnd);
836 }
837
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000838 // If the start of the loop is the entry block, we can't branch to it so
839 // insert a new dummy entry block.
840 Function *LoopFunc = LoopStart->getParent();
841 if (LoopStart == &LoopFunc->getEntryBlock()) {
842 LoopStart->setName("entry.orig");
843
844 BasicBlock *NewEntry =
845 BasicBlock::Create(LoopStart->getContext(),
846 "entry",
847 LoopFunc,
848 LoopStart);
849 BranchInst::Create(LoopStart, NewEntry);
850 }
851
Christian Konigfc6a9852013-02-16 11:27:45 +0000852 // Create an extra loop end node
853 LoopEnd = needPrefix(false);
854 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
855 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
856 BoolUndef, LoopEnd));
857 addPhiValues(LoopEnd, LoopStart);
858 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000859}
860
Tom Stellardf8794352012-12-19 22:10:31 +0000861/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000862/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000863void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000864 BasicBlock *Exit = ParentRegion->getExit();
865 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
866
Tom Stellardf8794352012-12-19 22:10:31 +0000867 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000868 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000869 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000870 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000871
Craig Topperf40110f2014-04-25 05:29:35 +0000872 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000873 Visited.clear();
874
Tom Stellardf8794352012-12-19 22:10:31 +0000875 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000876 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000877 }
878
Christian Konigfc6a9852013-02-16 11:27:45 +0000879 if (PrevNode)
880 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000881 else
882 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000883}
884
Tom Stellardf8794352012-12-19 22:10:31 +0000885/// Handle a rare case where the disintegrated nodes instructions
886/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000887void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000888 SSAUpdater Updater;
Tobias Grosser4abf9d32014-03-03 13:00:39 +0000889 for (const auto &BB : ParentRegion->blocks())
Tom Stellardf8794352012-12-19 22:10:31 +0000890 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
891 II != IE; ++II) {
892
893 bool Initialized = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000894 for (auto I = II->use_begin(), E = II->use_end(); I != E;) {
895 Use &U = *I++;
896 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000897 if (User->getParent() == BB) {
898 continue;
899
900 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000901 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000902 continue;
903 }
904
905 if (DT->dominates(II, User))
906 continue;
907
908 if (!Initialized) {
909 Value *Undef = UndefValue::get(II->getType());
910 Updater.Initialize(II->getType(), "");
911 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
912 Updater.AddAvailableValue(BB, II);
913 Initialized = true;
914 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000915 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000916 }
917 }
Tom Stellardf8794352012-12-19 22:10:31 +0000918}
919
920/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000921bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000922 if (R->isTopLevelRegion())
923 return false;
924
925 Func = R->getEntry()->getParent();
926 ParentRegion = R;
927
Chandler Carruth73523022014-01-13 13:07:17 +0000928 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000929 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000930
931 orderNodes();
932 collectInfos();
933 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000934 insertConditions(false);
935 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000936 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000937 rebuildSSA();
938
Tom Stellard048f14f2013-02-08 22:24:37 +0000939 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000940 Order.clear();
941 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000942 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000943 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000944 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000945 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000946 Loops.clear();
947 LoopPreds.clear();
948 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000949
950 return true;
951}
952
953/// \brief Create the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000954Pass *llvm::createStructurizeCFGPass() {
955 return new StructurizeCFG();
Tom Stellardf8794352012-12-19 22:10:31 +0000956}