blob: b8fb80b6cc26650143cba8f252980588b256393b [file] [log] [blame]
Eugene Zelenko99241d72017-10-20 21:47:29 +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
Eugene Zelenko99241d72017-10-20 21:47:29 +000010#include "llvm/ADT/DenseMap.h"
Christian Konig90b45122013-03-26 10:24:20 +000011#include "llvm/ADT/MapVector.h"
Tom Stellard071ec902015-02-04 20:49:44 +000012#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000013#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/SmallPtrSet.h"
15#include "llvm/ADT/SmallVector.h"
Tom Stellard755a4e62016-02-10 00:39:37 +000016#include "llvm/Analysis/DivergenceAnalysis.h"
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +000017#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000018#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000019#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000020#include "llvm/Analysis/RegionPass.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000021#include "llvm/IR/Argument.h"
22#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/CFG.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000033#include "llvm/IR/Type.h"
34#include "llvm/IR/Use.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
37#include "llvm/Pass.h"
38#include "llvm/Support/Casting.h"
Tom Stellard071ec902015-02-04 20:49:44 +000039#include "llvm/Support/Debug.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000040#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include "llvm/Transforms/Scalar.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000043#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000044#include <algorithm>
45#include <cassert>
46#include <utility>
Tom Stellardf8794352012-12-19 22:10:31 +000047
48using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000049using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000050
Chandler Carruth964daaa2014-04-22 02:55:47 +000051#define DEBUG_TYPE "structurizecfg"
52
Eugene Zelenko99241d72017-10-20 21:47:29 +000053// The name for newly created blocks.
54static const char *const FlowBlockName = "Flow";
55
Tom Stellardf8794352012-12-19 22:10:31 +000056namespace {
57
58// Definition of the complex types used in this pass.
59
Eugene Zelenko99241d72017-10-20 21:47:29 +000060using BBValuePair = std::pair<BasicBlock *, Value *>;
Tom Stellardf8794352012-12-19 22:10:31 +000061
Eugene Zelenko99241d72017-10-20 21:47:29 +000062using RNVector = SmallVector<RegionNode *, 8>;
63using BBVector = SmallVector<BasicBlock *, 8>;
64using BranchVector = SmallVector<BranchInst *, 8>;
65using BBValueVector = SmallVector<BBValuePair, 2>;
Tom Stellardf8794352012-12-19 22:10:31 +000066
Eugene Zelenko99241d72017-10-20 21:47:29 +000067using BBSet = SmallPtrSet<BasicBlock *, 8>;
Tom Stellard048f14f2013-02-08 22:24:37 +000068
Eugene Zelenko99241d72017-10-20 21:47:29 +000069using PhiMap = MapVector<PHINode *, BBValueVector>;
70using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
Christian Konig90b45122013-03-26 10:24:20 +000071
Eugene Zelenko99241d72017-10-20 21:47:29 +000072using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
73using BBPredicates = DenseMap<BasicBlock *, Value *>;
74using PredMap = DenseMap<BasicBlock *, BBPredicates>;
75using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
Tom Stellardf8794352012-12-19 22:10:31 +000076
Justin Lebar62c20d82016-11-28 18:49:59 +000077/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000078///
Justin Lebar62c20d82016-11-28 18:49:59 +000079/// For every BB you add to the set, you can specify whether we "remember" the
80/// block. When you get the common dominator, you can also ask whether it's one
81/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000082class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000083 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000084 BasicBlock *Result = nullptr;
85 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000086
Justin Lebar62c20d82016-11-28 18:49:59 +000087 /// Add BB to the resulting dominator.
88 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +000089 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000090 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +000091 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +000092 return;
93 }
94
Justin Lebar62c20d82016-11-28 18:49:59 +000095 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
96 if (NewResult != Result)
97 ResultIsRemembered = false;
98 if (NewResult == BB)
99 ResultIsRemembered |= Remember;
100 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +0000101 }
102
Justin Lebar62c20d82016-11-28 18:49:59 +0000103public:
104 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
105
106 void addBlock(BasicBlock *BB) {
107 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +0000108 }
109
Justin Lebar62c20d82016-11-28 18:49:59 +0000110 void addAndRememberBlock(BasicBlock *BB) {
111 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +0000112 }
Justin Lebar62c20d82016-11-28 18:49:59 +0000113
114 /// Get the nearest common dominator of all the BBs added via addBlock() and
115 /// addAndRememberBlock().
116 BasicBlock *result() { return Result; }
117
118 /// Is the BB returned by getResult() one of the blocks we added to the set
119 /// with addAndRememberBlock()?
120 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +0000121};
122
Tom Stellardf8794352012-12-19 22:10:31 +0000123/// @brief Transforms the control flow graph on one single entry/exit region
124/// at a time.
125///
126/// After the transform all "If"/"Then"/"Else" style control flow looks like
127/// this:
128///
129/// \verbatim
130/// 1
131/// ||
132/// | |
133/// 2 |
134/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000135/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000136/// 3
137/// || Where:
138/// | | 1 = "If" block, calculates the condition
139/// 4 | 2 = "Then" subregion, runs if the condition is true
140/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
141/// |/ 4 = "Else" optional subregion, runs if the condition is false
142/// 5 5 = "End" block, also rejoins the control flow
143/// \endverbatim
144///
145/// Control flow is expressed as a branch where the true exit goes into the
146/// "Then"/"Else" region, while the false exit skips the region
147/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000148/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000149/// for the "Then" edge.
150///
151/// Additionally to that even complicated loops look like this:
152///
153/// \verbatim
154/// 1
155/// ||
156/// | |
157/// 2 ^ Where:
158/// | / 1 = "Entry" block
159/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
160/// 3 3 = "Flow" block, with back edge to entry block
161/// |
162/// \endverbatim
163///
164/// The back edge of the "Flow" block is always on the false side of the branch
165/// while the true side continues the general flow. So the loop condition
166/// consist of a network of PHI nodes where the true incoming values expresses
167/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000168class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000169 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000170
Tom Stellardf8794352012-12-19 22:10:31 +0000171 Type *Boolean;
172 ConstantInt *BoolTrue;
173 ConstantInt *BoolFalse;
174 UndefValue *BoolUndef;
175
176 Function *Func;
177 Region *ParentRegion;
178
179 DominatorTree *DT;
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000180 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000181
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000182 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000183 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000184
Tom Stellardf8794352012-12-19 22:10:31 +0000185 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000186 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000187
188 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000189 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000190
Christian Konigfc6a9852013-02-16 11:27:45 +0000191 BB2BBMap Loops;
192 PredMap LoopPreds;
193 BranchVector LoopConds;
194
195 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000196
197 void orderNodes();
198
Christian Konigfc6a9852013-02-16 11:27:45 +0000199 void analyzeLoops(RegionNode *N);
200
Christian Konigd8860992013-02-16 11:27:50 +0000201 Value *invert(Value *Condition);
202
Tom Stellard048f14f2013-02-08 22:24:37 +0000203 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000204
Christian Konigfc6a9852013-02-16 11:27:45 +0000205 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000206
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000207 void collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000208
Christian Konigfc6a9852013-02-16 11:27:45 +0000209 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000210
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000211 void delPhiValues(BasicBlock *From, BasicBlock *To);
212
213 void addPhiValues(BasicBlock *From, BasicBlock *To);
214
215 void setPhiValues();
216
Tom Stellardf8794352012-12-19 22:10:31 +0000217 void killTerminator(BasicBlock *BB);
218
Tom Stellard7370ede2013-02-08 22:24:38 +0000219 void changeExit(RegionNode *Node, BasicBlock *NewExit,
220 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000221
Tom Stellard7370ede2013-02-08 22:24:38 +0000222 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000223
Christian Konigfc6a9852013-02-16 11:27:45 +0000224 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000225
Tom Stellard7370ede2013-02-08 22:24:38 +0000226 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
227
Christian Konigfc6a9852013-02-16 11:27:45 +0000228 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000229
230 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
231
Christian Konigfc6a9852013-02-16 11:27:45 +0000232 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000233
Christian Konigfc6a9852013-02-16 11:27:45 +0000234 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
235
236 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000237
238 void createFlow();
239
Tom Stellardf8794352012-12-19 22:10:31 +0000240 void rebuildSSA();
241
242public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000243 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000244
Justin Lebar73c4baf2016-11-22 23:13:44 +0000245 explicit StructurizeCFG(bool SkipUniformRegions = false)
246 : RegionPass(ID), SkipUniformRegions(SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000247 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
248 }
249
Craig Topper3e4c6972014-03-05 09:10:37 +0000250 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000251
Craig Topper3e4c6972014-03-05 09:10:37 +0000252 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000253
Mehdi Amini117296c2016-10-01 02:56:57 +0000254 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000255
Craig Topper3e4c6972014-03-05 09:10:37 +0000256 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000257 if (SkipUniformRegions)
258 AU.addRequired<DivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000259 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000260 AU.addRequired<DominatorTreeWrapperPass>();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000261 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000262
Chandler Carruth73523022014-01-13 13:07:17 +0000263 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000264 RegionPass::getAnalysisUsage(AU);
265 }
Tom Stellardf8794352012-12-19 22:10:31 +0000266};
267
268} // end anonymous namespace
269
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000270char StructurizeCFG::ID = 0;
271
272INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
273 false, false)
Tom Stellard755a4e62016-02-10 00:39:37 +0000274INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000275INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000276INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000277INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000278INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
279 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000280
281/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000282bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000283 LLVMContext &Context = R->getEntry()->getContext();
284
285 Boolean = Type::getInt1Ty(Context);
286 BoolTrue = ConstantInt::getTrue(Context);
287 BoolFalse = ConstantInt::getFalse(Context);
288 BoolUndef = UndefValue::get(Boolean);
289
290 return false;
291}
292
293/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000294void StructurizeCFG::orderNodes() {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000295 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
296 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000297
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000298 // The reverse post-order traversal of the list gives us an ordering close
299 // to what we want. The only problem with it is that sometimes backedges
300 // for outer loops will be visited before backedges for inner loops.
301 for (RegionNode *RN : RPOT) {
302 BasicBlock *BB = RN->getEntry();
303 Loop *Loop = LI->getLoopFor(BB);
304 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000305 }
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000306
307 unsigned CurrentLoopDepth = 0;
308 Loop *CurrentLoop = nullptr;
309 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
310 BasicBlock *BB = (*I)->getEntry();
311 unsigned LoopDepth = LI->getLoopDepth(BB);
312
313 if (is_contained(Order, *I))
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 auto LoopI = I;
321 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
322 LoopI++;
323 BasicBlock *LoopBB = (*LoopI)->getEntry();
324 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
325 --BlockCount;
326 Order.push_back(*LoopI);
327 }
328 }
329 }
330
331 CurrentLoop = LI->getLoopFor(BB);
332 if (CurrentLoop)
333 LoopBlocks[CurrentLoop]--;
334
335 CurrentLoopDepth = LoopDepth;
336 Order.push_back(*I);
337 }
338
339 // This pass originally used a post-order traversal and then operated on
340 // the list in reverse. Now that we are using a reverse post-order traversal
341 // rather than re-working the whole pass to operate on the list in order,
342 // we just reverse the list and continue to operate on it in reverse.
343 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000344}
345
Christian Konigfc6a9852013-02-16 11:27:45 +0000346/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000347void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000348 if (N->isSubRegion()) {
349 // Test for exit as back edge
350 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
351 if (Visited.count(Exit))
352 Loops[Exit] = N->getEntry();
353
354 } else {
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000355 // Test for successors as back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000356 BasicBlock *BB = N->getNodeAs<BasicBlock>();
357 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
358
Pete Cooperebcd7482015-08-06 20:22:46 +0000359 for (BasicBlock *Succ : Term->successors())
360 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000361 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000362 }
363}
364
Christian Konigd8860992013-02-16 11:27:50 +0000365/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000366Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000367 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000368 if (Constant *C = dyn_cast<Constant>(Condition))
369 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000370
371 // Second: If the condition is already inverted, return the original value
372 if (match(Condition, m_Not(m_Value(Condition))))
373 return Condition;
374
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000375 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
376 // Third: Check all the users for an invert
377 BasicBlock *Parent = Inst->getParent();
Matt Arsenault44746522017-04-24 20:25:01 +0000378 for (User *U : Condition->users())
379 if (Instruction *I = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000380 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
381 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000382
383 // Last option: Create a new instruction
384 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000385 }
386
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000387 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
388 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
389 return BinaryOperator::CreateNot(Condition,
390 Arg->getName() + ".inv",
391 EntryBlock.getTerminator());
392 }
393
394 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000395}
396
Tom Stellard048f14f2013-02-08 22:24:37 +0000397/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000398Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
399 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000400 Value *Cond = Invert ? BoolFalse : BoolTrue;
401 if (Term->isConditional()) {
402 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000403
Aaron Ballman19978552013-06-04 01:03:03 +0000404 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000405 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000406 }
407 return Cond;
408}
409
Tom Stellard048f14f2013-02-08 22:24:37 +0000410/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000411void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000412 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000413 BasicBlock *BB = N->getEntry();
414 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000415 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000416
Justin Lebar3aec10c2016-11-28 18:50:03 +0000417 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000418 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000419 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000420 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000421
Justin Lebar3aec10c2016-11-28 18:50:03 +0000422 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000423 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000424 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000425 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000426 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
427 BasicBlock *Succ = Term->getSuccessor(i);
428 if (Succ != BB)
429 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000430
Justin Lebar3aec10c2016-11-28 18:50:03 +0000431 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000432 // Normal forward edge
433 if (Term->isConditional()) {
434 // Try to treat it like an ELSE block
435 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000436 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000437 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000438
Tom Stellard048f14f2013-02-08 22:24:37 +0000439 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000440 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000441 continue;
442 }
443 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000444 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000445 } else {
446 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000447 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000448 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000449 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000450 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000451 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000452 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000453 R = R->getParent();
454
455 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000456 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000457 continue;
458
459 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000460 if (Visited.count(Entry))
461 Pred[Entry] = BoolTrue;
462 else
463 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000464 }
465 }
466}
467
468/// \brief Collect various loop and predicate infos
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000469void StructurizeCFG::collectInfos() {
470 // Reset predicate
471 Predicates.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000472
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000473 // and loop infos
474 Loops.clear();
475 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000476
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000477 // Reset the visited nodes
478 Visited.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000479
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000480 for (RegionNode *RN : reverse(Order)) {
481 DEBUG(dbgs() << "Visiting: "
482 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
483 << RN->getEntry()->getName() << " Loop Depth: "
484 << LI->getLoopDepth(RN->getEntry()) << "\n");
485
486 // Analyze all the conditions leading to a node
487 gatherPredicates(RN);
488
489 // Remember that we've seen this node
490 Visited.insert(RN->getEntry());
491
492 // Find the last back edges
493 analyzeLoops(RN);
494 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000495}
496
497/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000498void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000499 BranchVector &Conds = Loops ? LoopConds : Conditions;
500 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000501 SSAUpdater PhiInserter;
502
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000503 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000504 assert(Term->isConditional());
505
Christian Konigfc6a9852013-02-16 11:27:45 +0000506 BasicBlock *Parent = Term->getParent();
507 BasicBlock *SuccTrue = Term->getSuccessor(0);
508 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000509
Christian Konigb5d88662013-02-16 11:27:40 +0000510 PhiInserter.Initialize(Boolean, "");
511 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000512 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000513
Christian Konigfc6a9852013-02-16 11:27:45 +0000514 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000515
516 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000517 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000518
Craig Topperf40110f2014-04-25 05:29:35 +0000519 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000520 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
521 BasicBlock *BB = BBAndPred.first;
522 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000523
Justin Lebar3aec10c2016-11-28 18:50:03 +0000524 if (BB == Parent) {
525 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000526 break;
527 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000528 PhiInserter.AddAvailableValue(BB, Pred);
529 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000530 }
531
Christian Konigb5d88662013-02-16 11:27:40 +0000532 if (ParentValue) {
533 Term->setCondition(ParentValue);
534 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000535 if (!Dominator.resultIsRememberedBlock())
536 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000537
Tom Stellard048f14f2013-02-08 22:24:37 +0000538 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000539 }
Tom Stellardf8794352012-12-19 22:10:31 +0000540 }
541}
542
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000543/// \brief Remove all PHI values coming from "From" into "To" and remember
544/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000545void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000546 PhiMap &Map = DeletedPhis[To];
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000547 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000548 while (Phi.getBasicBlockIndex(From) != -1) {
549 Value *Deleted = Phi.removeIncomingValue(From, false);
550 Map[&Phi].push_back(std::make_pair(From, Deleted));
551 }
552 }
553}
554
555/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000556void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000557 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000558 Value *Undef = UndefValue::get(Phi.getType());
559 Phi.addIncoming(Undef, From);
560 }
561 AddedPhis[To].push_back(From);
562}
563
564/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000565void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000566 SSAUpdater Updater;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000567 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000568 BasicBlock *To = AddedPhi.first;
569 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000570
571 if (!DeletedPhis.count(To))
572 continue;
573
574 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000575 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000576 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000577 Value *Undef = UndefValue::get(Phi->getType());
578 Updater.Initialize(Phi->getType(), "");
579 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
580 Updater.AddAvailableValue(To, Undef);
581
Christian Konig0bccf9d2013-02-16 11:27:35 +0000582 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000583 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000584 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000585 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000586 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000587 }
588
Justin Lebar62c20d82016-11-28 18:49:59 +0000589 if (!Dominator.resultIsRememberedBlock())
590 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000591
Benjamin Kramer135f7352016-06-26 12:28:59 +0000592 for (BasicBlock *FI : From) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000593 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000594 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000595 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000596 }
597 }
598
599 DeletedPhis.erase(To);
600 }
601 assert(DeletedPhis.empty());
602}
603
Tom Stellard7370ede2013-02-08 22:24:38 +0000604/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000605void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000606 TerminatorInst *Term = BB->getTerminator();
607 if (!Term)
608 return;
609
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000610 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000611 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000612 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000613
614 Term->eraseFromParent();
615}
616
Tom Stellard7370ede2013-02-08 22:24:38 +0000617/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000618void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
619 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000620 if (Node->isSubRegion()) {
621 Region *SubRegion = Node->getNodeAs<Region>();
622 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000623 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000624
Tom Stellard7370ede2013-02-08 22:24:38 +0000625 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000626 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
627 // Incrememt BBI before mucking with BB's terminator.
628 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000629
Tom Stellard7370ede2013-02-08 22:24:38 +0000630 if (!SubRegion->contains(BB))
631 continue;
632
633 // Modify the edges to point to the new exit
634 delPhiValues(BB, OldExit);
635 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
636 addPhiValues(BB, NewExit);
637
638 // Find the new dominator (if requested)
639 if (IncludeDominator) {
640 if (!Dominator)
641 Dominator = BB;
642 else
643 Dominator = DT->findNearestCommonDominator(Dominator, BB);
644 }
Tom Stellardf8794352012-12-19 22:10:31 +0000645 }
646
Tom Stellard7370ede2013-02-08 22:24:38 +0000647 // Change the dominator (if requested)
648 if (Dominator)
649 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000650
Tom Stellard7370ede2013-02-08 22:24:38 +0000651 // Update the region info
652 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000653 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000654 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
655 killTerminator(BB);
656 BranchInst::Create(NewExit, BB);
657 addPhiValues(BB, NewExit);
658 if (IncludeDominator)
659 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000660 }
Tom Stellardf8794352012-12-19 22:10:31 +0000661}
662
Tom Stellardf8794352012-12-19 22:10:31 +0000663/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000664BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000665 LLVMContext &Context = Func->getContext();
666 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000667 Order.back()->getEntry();
Tom Stellardf8794352012-12-19 22:10:31 +0000668 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
669 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000670 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000671 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000672 return Flow;
673}
674
Tom Stellard7370ede2013-02-08 22:24:38 +0000675/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000676BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000677 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000678
Christian Konigfc6a9852013-02-16 11:27:45 +0000679 if (!PrevNode->isSubRegion()) {
680 killTerminator(Entry);
681 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
682 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000683 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000684
Christian Konigfc6a9852013-02-16 11:27:45 +0000685 // create a new flow node
686 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000687
Christian Konigfc6a9852013-02-16 11:27:45 +0000688 // and wire it up
689 changeExit(PrevNode, Flow, true);
690 PrevNode = ParentRegion->getBBNode(Flow);
691 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000692}
693
694/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000695BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
696 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000697 if (!Order.empty() || !ExitUseAllowed)
698 return getNextFlow(Flow);
699
700 BasicBlock *Exit = ParentRegion->getExit();
701 DT->changeImmediateDominator(Exit, Flow);
702 addPhiValues(Flow, Exit);
703 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000704}
705
Christian Konigfc6a9852013-02-16 11:27:45 +0000706/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000707void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000708 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
709 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000710}
711
Justin Lebar3aec10c2016-11-28 18:50:03 +0000712/// \brief Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000713bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000714 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000715 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
716 return DT->dominates(BB, Pred.first);
717 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000718}
719
Tom Stellardf8794352012-12-19 22:10:31 +0000720/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000721bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000722 BBPredicates &Preds = Predicates[Node->getEntry()];
723 bool Dominated = false;
724
725 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000726 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000727 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000728
Justin Lebar3aec10c2016-11-28 18:50:03 +0000729 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
730 BasicBlock *BB = Pred.first;
731 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000732
Justin Lebar3aec10c2016-11-28 18:50:03 +0000733 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000734 return false;
735
Justin Lebar3aec10c2016-11-28 18:50:03 +0000736 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000737 Dominated = true;
738 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000739
740 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000741 return Dominated;
742}
743
Tom Stellard7370ede2013-02-08 22:24:38 +0000744/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000745void StructurizeCFG::wireFlow(bool ExitUseAllowed,
746 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000747 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000748 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000749
Christian Konigfc6a9852013-02-16 11:27:45 +0000750 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000751 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000752 if (PrevNode) {
753 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000754 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000755 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000756 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000757 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000758 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000759
Tom Stellard7370ede2013-02-08 22:24:38 +0000760 // Insert extra postfix node (or use exit instead)
761 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000762 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000763
764 // let it point to entry and next block
765 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
766 addPhiValues(Flow, Entry);
767 DT->changeImmediateDominator(Entry, Flow);
768
Christian Konigfc6a9852013-02-16 11:27:45 +0000769 PrevNode = Node;
770 while (!Order.empty() && !Visited.count(LoopEnd) &&
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000771 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000772 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000773 }
774
Christian Konigfc6a9852013-02-16 11:27:45 +0000775 changeExit(PrevNode, Next, false);
776 setPrevNode(Next);
777 }
778}
779
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000780void StructurizeCFG::handleLoops(bool ExitUseAllowed,
781 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000782 RegionNode *Node = Order.back();
Christian Konigfc6a9852013-02-16 11:27:45 +0000783 BasicBlock *LoopStart = Node->getEntry();
784
785 if (!Loops.count(LoopStart)) {
786 wireFlow(ExitUseAllowed, LoopEnd);
787 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000788 }
789
Christian Konigfc6a9852013-02-16 11:27:45 +0000790 if (!isPredictableTrue(Node))
791 LoopStart = needPrefix(true);
792
793 LoopEnd = Loops[Node->getEntry()];
794 wireFlow(false, LoopEnd);
795 while (!Visited.count(LoopEnd)) {
796 handleLoops(false, LoopEnd);
797 }
798
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000799 // If the start of the loop is the entry block, we can't branch to it so
800 // insert a new dummy entry block.
801 Function *LoopFunc = LoopStart->getParent();
802 if (LoopStart == &LoopFunc->getEntryBlock()) {
803 LoopStart->setName("entry.orig");
804
805 BasicBlock *NewEntry =
806 BasicBlock::Create(LoopStart->getContext(),
807 "entry",
808 LoopFunc,
809 LoopStart);
810 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000811 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000812 }
813
Christian Konigfc6a9852013-02-16 11:27:45 +0000814 // Create an extra loop end node
815 LoopEnd = needPrefix(false);
816 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
817 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
818 BoolUndef, LoopEnd));
819 addPhiValues(LoopEnd, LoopStart);
820 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000821}
822
Tom Stellardf8794352012-12-19 22:10:31 +0000823/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000824/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000825void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000826 BasicBlock *Exit = ParentRegion->getExit();
827 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
828
Tom Stellardf8794352012-12-19 22:10:31 +0000829 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000830 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000831 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000832 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000833
Craig Topperf40110f2014-04-25 05:29:35 +0000834 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000835 Visited.clear();
836
Tom Stellardf8794352012-12-19 22:10:31 +0000837 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000838 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000839 }
840
Christian Konigfc6a9852013-02-16 11:27:45 +0000841 if (PrevNode)
842 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000843 else
844 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000845}
846
Tom Stellardf8794352012-12-19 22:10:31 +0000847/// Handle a rare case where the disintegrated nodes instructions
848/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000849void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000850 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000851 for (BasicBlock *BB : ParentRegion->blocks())
852 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000853 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000854 // We may modify the use list as we iterate over it, so be careful to
855 // compute the next element in the use list at the top of the loop.
856 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
857 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000858 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000859 if (User->getParent() == BB) {
860 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000861 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000862 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000863 continue;
864 }
865
Justin Lebar3aec10c2016-11-28 18:50:03 +0000866 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000867 continue;
868
869 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000870 Value *Undef = UndefValue::get(I.getType());
871 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000872 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000873 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000874 Initialized = true;
875 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000876 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000877 }
878 }
Tom Stellardf8794352012-12-19 22:10:31 +0000879}
880
Justin Lebarc7445d52016-11-22 23:13:33 +0000881static bool hasOnlyUniformBranches(const Region *R,
882 const DivergenceAnalysis &DA) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000883 for (const BasicBlock *BB : R->blocks()) {
884 const BranchInst *Br = dyn_cast<BranchInst>(BB->getTerminator());
885 if (!Br || !Br->isConditional())
886 continue;
887
Justin Lebarc7445d52016-11-22 23:13:33 +0000888 if (!DA.isUniform(Br->getCondition()))
Tom Stellard755a4e62016-02-10 00:39:37 +0000889 return false;
890 DEBUG(dbgs() << "BB: " << BB->getName() << " has uniform terminator\n");
891 }
892 return true;
893}
894
Tom Stellardf8794352012-12-19 22:10:31 +0000895/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000896bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000897 if (R->isTopLevelRegion())
898 return false;
899
Tom Stellard755a4e62016-02-10 00:39:37 +0000900 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000901 // TODO: We could probably be smarter here with how we handle sub-regions.
Justin Lebarc7445d52016-11-22 23:13:33 +0000902 auto &DA = getAnalysis<DivergenceAnalysis>();
903 if (hasOnlyUniformBranches(R, DA)) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000904 DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000905
906 // Mark all direct child block terminators as having been treated as
907 // uniform. To account for a possible future in which non-uniform
908 // sub-regions are treated more cleverly, indirect children are not
909 // marked as uniform.
910 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000911 for (RegionNode *E : R->elements()) {
912 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000913 continue;
914
Justin Lebar1b60d702016-11-22 23:13:37 +0000915 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000916 Term->setMetadata("structurizecfg.uniform", MD);
917 }
918
Tom Stellard755a4e62016-02-10 00:39:37 +0000919 return false;
920 }
921 }
922
Tom Stellardf8794352012-12-19 22:10:31 +0000923 Func = R->getEntry()->getParent();
924 ParentRegion = R;
925
Chandler Carruth73523022014-01-13 13:07:17 +0000926 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000927 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000928
929 orderNodes();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000930 collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000931 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000932 insertConditions(false);
933 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000934 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000935 rebuildSSA();
936
Tom Stellard048f14f2013-02-08 22:24:37 +0000937 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000938 Order.clear();
939 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000940 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000941 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000942 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000943 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000944 Loops.clear();
945 LoopPreds.clear();
946 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000947
948 return true;
949}
950
Tom Stellard755a4e62016-02-10 00:39:37 +0000951Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
952 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +0000953}