blob: dc4d1f73f87dcb30a477f1a8a2c9670b29cd6ee7 [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
Nicolai Haehnle43c11152018-02-23 10:45:46 +000058static cl::opt<bool> ForceSkipUniformRegions(
59 "structurizecfg-skip-uniform-regions",
60 cl::Hidden,
61 cl::desc("Force whether the StructurizeCFG pass skips uniform regions"),
62 cl::init(false));
63
Tom Stellardf8794352012-12-19 22:10:31 +000064// Definition of the complex types used in this pass.
65
Eugene Zelenko99241d72017-10-20 21:47:29 +000066using BBValuePair = std::pair<BasicBlock *, Value *>;
Tom Stellardf8794352012-12-19 22:10:31 +000067
Eugene Zelenko99241d72017-10-20 21:47:29 +000068using RNVector = SmallVector<RegionNode *, 8>;
69using BBVector = SmallVector<BasicBlock *, 8>;
70using BranchVector = SmallVector<BranchInst *, 8>;
71using BBValueVector = SmallVector<BBValuePair, 2>;
Tom Stellardf8794352012-12-19 22:10:31 +000072
Eugene Zelenko99241d72017-10-20 21:47:29 +000073using BBSet = SmallPtrSet<BasicBlock *, 8>;
Tom Stellard048f14f2013-02-08 22:24:37 +000074
Eugene Zelenko99241d72017-10-20 21:47:29 +000075using PhiMap = MapVector<PHINode *, BBValueVector>;
76using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
Christian Konig90b45122013-03-26 10:24:20 +000077
Eugene Zelenko99241d72017-10-20 21:47:29 +000078using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
79using BBPredicates = DenseMap<BasicBlock *, Value *>;
80using PredMap = DenseMap<BasicBlock *, BBPredicates>;
81using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
Tom Stellardf8794352012-12-19 22:10:31 +000082
Justin Lebar62c20d82016-11-28 18:49:59 +000083/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000084///
Justin Lebar62c20d82016-11-28 18:49:59 +000085/// For every BB you add to the set, you can specify whether we "remember" the
86/// block. When you get the common dominator, you can also ask whether it's one
87/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000088class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000089 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000090 BasicBlock *Result = nullptr;
91 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000092
Justin Lebar62c20d82016-11-28 18:49:59 +000093 /// Add BB to the resulting dominator.
94 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +000095 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000096 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +000097 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +000098 return;
99 }
100
Justin Lebar62c20d82016-11-28 18:49:59 +0000101 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
102 if (NewResult != Result)
103 ResultIsRemembered = false;
104 if (NewResult == BB)
105 ResultIsRemembered |= Remember;
106 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +0000107 }
108
Justin Lebar62c20d82016-11-28 18:49:59 +0000109public:
110 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
111
112 void addBlock(BasicBlock *BB) {
113 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +0000114 }
115
Justin Lebar62c20d82016-11-28 18:49:59 +0000116 void addAndRememberBlock(BasicBlock *BB) {
117 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +0000118 }
Justin Lebar62c20d82016-11-28 18:49:59 +0000119
120 /// Get the nearest common dominator of all the BBs added via addBlock() and
121 /// addAndRememberBlock().
122 BasicBlock *result() { return Result; }
123
124 /// Is the BB returned by getResult() one of the blocks we added to the set
125 /// with addAndRememberBlock()?
126 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +0000127};
128
Tom Stellardf8794352012-12-19 22:10:31 +0000129/// @brief Transforms the control flow graph on one single entry/exit region
130/// at a time.
131///
132/// After the transform all "If"/"Then"/"Else" style control flow looks like
133/// this:
134///
135/// \verbatim
136/// 1
137/// ||
138/// | |
139/// 2 |
140/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000141/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000142/// 3
143/// || Where:
144/// | | 1 = "If" block, calculates the condition
145/// 4 | 2 = "Then" subregion, runs if the condition is true
146/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
147/// |/ 4 = "Else" optional subregion, runs if the condition is false
148/// 5 5 = "End" block, also rejoins the control flow
149/// \endverbatim
150///
151/// Control flow is expressed as a branch where the true exit goes into the
152/// "Then"/"Else" region, while the false exit skips the region
153/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000154/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000155/// for the "Then" edge.
156///
157/// Additionally to that even complicated loops look like this:
158///
159/// \verbatim
160/// 1
161/// ||
162/// | |
163/// 2 ^ Where:
164/// | / 1 = "Entry" block
165/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
166/// 3 3 = "Flow" block, with back edge to entry block
167/// |
168/// \endverbatim
169///
170/// The back edge of the "Flow" block is always on the false side of the branch
171/// while the true side continues the general flow. So the loop condition
172/// consist of a network of PHI nodes where the true incoming values expresses
173/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000174class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000175 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000176
Tom Stellardf8794352012-12-19 22:10:31 +0000177 Type *Boolean;
178 ConstantInt *BoolTrue;
179 ConstantInt *BoolFalse;
180 UndefValue *BoolUndef;
181
182 Function *Func;
183 Region *ParentRegion;
184
185 DominatorTree *DT;
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000186 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000187
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000188 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000189 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000190
Tom Stellardf8794352012-12-19 22:10:31 +0000191 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000192 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000193
194 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000195 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000196
Christian Konigfc6a9852013-02-16 11:27:45 +0000197 BB2BBMap Loops;
198 PredMap LoopPreds;
199 BranchVector LoopConds;
200
201 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000202
203 void orderNodes();
204
Christian Konigfc6a9852013-02-16 11:27:45 +0000205 void analyzeLoops(RegionNode *N);
206
Christian Konigd8860992013-02-16 11:27:50 +0000207 Value *invert(Value *Condition);
208
Tom Stellard048f14f2013-02-08 22:24:37 +0000209 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000210
Christian Konigfc6a9852013-02-16 11:27:45 +0000211 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000212
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000213 void collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000214
Christian Konigfc6a9852013-02-16 11:27:45 +0000215 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000216
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000217 void delPhiValues(BasicBlock *From, BasicBlock *To);
218
219 void addPhiValues(BasicBlock *From, BasicBlock *To);
220
221 void setPhiValues();
222
Tom Stellardf8794352012-12-19 22:10:31 +0000223 void killTerminator(BasicBlock *BB);
224
Tom Stellard7370ede2013-02-08 22:24:38 +0000225 void changeExit(RegionNode *Node, BasicBlock *NewExit,
226 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000227
Tom Stellard7370ede2013-02-08 22:24:38 +0000228 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000229
Christian Konigfc6a9852013-02-16 11:27:45 +0000230 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000231
Tom Stellard7370ede2013-02-08 22:24:38 +0000232 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
233
Christian Konigfc6a9852013-02-16 11:27:45 +0000234 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000235
236 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
237
Christian Konigfc6a9852013-02-16 11:27:45 +0000238 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000239
Christian Konigfc6a9852013-02-16 11:27:45 +0000240 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
241
242 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000243
244 void createFlow();
245
Tom Stellardf8794352012-12-19 22:10:31 +0000246 void rebuildSSA();
247
248public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000249 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000250
Nicolai Haehnle43c11152018-02-23 10:45:46 +0000251 explicit StructurizeCFG(bool SkipUniformRegions_ = false)
252 : RegionPass(ID),
253 SkipUniformRegions(SkipUniformRegions_) {
254 if (ForceSkipUniformRegions.getNumOccurrences())
255 SkipUniformRegions = ForceSkipUniformRegions.getValue();
Tom Stellard755a4e62016-02-10 00:39:37 +0000256 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
257 }
258
Craig Topper3e4c6972014-03-05 09:10:37 +0000259 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000260
Craig Topper3e4c6972014-03-05 09:10:37 +0000261 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000262
Mehdi Amini117296c2016-10-01 02:56:57 +0000263 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000264
Craig Topper3e4c6972014-03-05 09:10:37 +0000265 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000266 if (SkipUniformRegions)
267 AU.addRequired<DivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000268 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000269 AU.addRequired<DominatorTreeWrapperPass>();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000270 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000271
Chandler Carruth73523022014-01-13 13:07:17 +0000272 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000273 RegionPass::getAnalysisUsage(AU);
274 }
Tom Stellardf8794352012-12-19 22:10:31 +0000275};
276
277} // end anonymous namespace
278
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000279char StructurizeCFG::ID = 0;
280
281INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
282 false, false)
Tom Stellard755a4e62016-02-10 00:39:37 +0000283INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000284INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000285INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000286INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000287INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
288 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000289
290/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000291bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000292 LLVMContext &Context = R->getEntry()->getContext();
293
294 Boolean = Type::getInt1Ty(Context);
295 BoolTrue = ConstantInt::getTrue(Context);
296 BoolFalse = ConstantInt::getFalse(Context);
297 BoolUndef = UndefValue::get(Boolean);
298
299 return false;
300}
301
302/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000303void StructurizeCFG::orderNodes() {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000304 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
305 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000306
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000307 // The reverse post-order traversal of the list gives us an ordering close
308 // to what we want. The only problem with it is that sometimes backedges
309 // for outer loops will be visited before backedges for inner loops.
310 for (RegionNode *RN : RPOT) {
311 BasicBlock *BB = RN->getEntry();
312 Loop *Loop = LI->getLoopFor(BB);
313 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000314 }
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000315
316 unsigned CurrentLoopDepth = 0;
317 Loop *CurrentLoop = nullptr;
318 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
319 BasicBlock *BB = (*I)->getEntry();
320 unsigned LoopDepth = LI->getLoopDepth(BB);
321
322 if (is_contained(Order, *I))
323 continue;
324
325 if (LoopDepth < CurrentLoopDepth) {
326 // Make sure we have visited all blocks in this loop before moving back to
327 // the outer loop.
328
329 auto LoopI = I;
330 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
331 LoopI++;
332 BasicBlock *LoopBB = (*LoopI)->getEntry();
333 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
334 --BlockCount;
335 Order.push_back(*LoopI);
336 }
337 }
338 }
339
340 CurrentLoop = LI->getLoopFor(BB);
341 if (CurrentLoop)
342 LoopBlocks[CurrentLoop]--;
343
344 CurrentLoopDepth = LoopDepth;
345 Order.push_back(*I);
346 }
347
348 // This pass originally used a post-order traversal and then operated on
349 // the list in reverse. Now that we are using a reverse post-order traversal
350 // rather than re-working the whole pass to operate on the list in order,
351 // we just reverse the list and continue to operate on it in reverse.
352 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000353}
354
Christian Konigfc6a9852013-02-16 11:27:45 +0000355/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000356void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000357 if (N->isSubRegion()) {
358 // Test for exit as back edge
359 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
360 if (Visited.count(Exit))
361 Loops[Exit] = N->getEntry();
362
363 } else {
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000364 // Test for successors as back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000365 BasicBlock *BB = N->getNodeAs<BasicBlock>();
366 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
367
Pete Cooperebcd7482015-08-06 20:22:46 +0000368 for (BasicBlock *Succ : Term->successors())
369 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000370 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000371 }
372}
373
Christian Konigd8860992013-02-16 11:27:50 +0000374/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000375Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000376 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000377 if (Constant *C = dyn_cast<Constant>(Condition))
378 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000379
380 // Second: If the condition is already inverted, return the original value
381 if (match(Condition, m_Not(m_Value(Condition))))
382 return Condition;
383
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000384 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
385 // Third: Check all the users for an invert
386 BasicBlock *Parent = Inst->getParent();
Matt Arsenault44746522017-04-24 20:25:01 +0000387 for (User *U : Condition->users())
388 if (Instruction *I = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000389 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
390 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000391
392 // Last option: Create a new instruction
393 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000394 }
395
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000396 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
397 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
398 return BinaryOperator::CreateNot(Condition,
399 Arg->getName() + ".inv",
400 EntryBlock.getTerminator());
401 }
402
403 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000404}
405
Tom Stellard048f14f2013-02-08 22:24:37 +0000406/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000407Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
408 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000409 Value *Cond = Invert ? BoolFalse : BoolTrue;
410 if (Term->isConditional()) {
411 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000412
Aaron Ballman19978552013-06-04 01:03:03 +0000413 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000414 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000415 }
416 return Cond;
417}
418
Tom Stellard048f14f2013-02-08 22:24:37 +0000419/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000420void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000421 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000422 BasicBlock *BB = N->getEntry();
423 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000424 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000425
Justin Lebar3aec10c2016-11-28 18:50:03 +0000426 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000427 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000428 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000429 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000430
Justin Lebar3aec10c2016-11-28 18:50:03 +0000431 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000432 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000433 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000434 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000435 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
436 BasicBlock *Succ = Term->getSuccessor(i);
437 if (Succ != BB)
438 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000439
Justin Lebar3aec10c2016-11-28 18:50:03 +0000440 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000441 // Normal forward edge
442 if (Term->isConditional()) {
443 // Try to treat it like an ELSE block
444 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000445 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000446 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000447
Tom Stellard048f14f2013-02-08 22:24:37 +0000448 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000449 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000450 continue;
451 }
452 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000453 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000454 } else {
455 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000456 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000457 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000458 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000459 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000460 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000461 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000462 R = R->getParent();
463
464 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000465 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000466 continue;
467
468 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000469 if (Visited.count(Entry))
470 Pred[Entry] = BoolTrue;
471 else
472 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000473 }
474 }
475}
476
477/// \brief Collect various loop and predicate infos
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000478void StructurizeCFG::collectInfos() {
479 // Reset predicate
480 Predicates.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000481
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000482 // and loop infos
483 Loops.clear();
484 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000485
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000486 // Reset the visited nodes
487 Visited.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000488
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000489 for (RegionNode *RN : reverse(Order)) {
490 DEBUG(dbgs() << "Visiting: "
491 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
492 << RN->getEntry()->getName() << " Loop Depth: "
493 << LI->getLoopDepth(RN->getEntry()) << "\n");
494
495 // Analyze all the conditions leading to a node
496 gatherPredicates(RN);
497
498 // Remember that we've seen this node
499 Visited.insert(RN->getEntry());
500
501 // Find the last back edges
502 analyzeLoops(RN);
503 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000504}
505
506/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000507void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000508 BranchVector &Conds = Loops ? LoopConds : Conditions;
509 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000510 SSAUpdater PhiInserter;
511
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000512 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000513 assert(Term->isConditional());
514
Christian Konigfc6a9852013-02-16 11:27:45 +0000515 BasicBlock *Parent = Term->getParent();
516 BasicBlock *SuccTrue = Term->getSuccessor(0);
517 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000518
Christian Konigb5d88662013-02-16 11:27:40 +0000519 PhiInserter.Initialize(Boolean, "");
520 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000521 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000522
Christian Konigfc6a9852013-02-16 11:27:45 +0000523 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000524
525 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000526 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000527
Craig Topperf40110f2014-04-25 05:29:35 +0000528 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000529 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
530 BasicBlock *BB = BBAndPred.first;
531 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000532
Justin Lebar3aec10c2016-11-28 18:50:03 +0000533 if (BB == Parent) {
534 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000535 break;
536 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000537 PhiInserter.AddAvailableValue(BB, Pred);
538 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000539 }
540
Christian Konigb5d88662013-02-16 11:27:40 +0000541 if (ParentValue) {
542 Term->setCondition(ParentValue);
543 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000544 if (!Dominator.resultIsRememberedBlock())
545 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000546
Tom Stellard048f14f2013-02-08 22:24:37 +0000547 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000548 }
Tom Stellardf8794352012-12-19 22:10:31 +0000549 }
550}
551
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000552/// \brief Remove all PHI values coming from "From" into "To" and remember
553/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000554void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000555 PhiMap &Map = DeletedPhis[To];
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000556 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000557 while (Phi.getBasicBlockIndex(From) != -1) {
558 Value *Deleted = Phi.removeIncomingValue(From, false);
559 Map[&Phi].push_back(std::make_pair(From, Deleted));
560 }
561 }
562}
563
564/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000565void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000566 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000567 Value *Undef = UndefValue::get(Phi.getType());
568 Phi.addIncoming(Undef, From);
569 }
570 AddedPhis[To].push_back(From);
571}
572
573/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000574void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000575 SSAUpdater Updater;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000576 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000577 BasicBlock *To = AddedPhi.first;
578 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000579
580 if (!DeletedPhis.count(To))
581 continue;
582
583 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000584 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000585 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000586 Value *Undef = UndefValue::get(Phi->getType());
587 Updater.Initialize(Phi->getType(), "");
588 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
589 Updater.AddAvailableValue(To, Undef);
590
Christian Konig0bccf9d2013-02-16 11:27:35 +0000591 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000592 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000593 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000594 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000595 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000596 }
597
Justin Lebar62c20d82016-11-28 18:49:59 +0000598 if (!Dominator.resultIsRememberedBlock())
599 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000600
Benjamin Kramer135f7352016-06-26 12:28:59 +0000601 for (BasicBlock *FI : From) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000602 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000603 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000604 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000605 }
606 }
607
608 DeletedPhis.erase(To);
609 }
610 assert(DeletedPhis.empty());
611}
612
Tom Stellard7370ede2013-02-08 22:24:38 +0000613/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000614void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000615 TerminatorInst *Term = BB->getTerminator();
616 if (!Term)
617 return;
618
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000619 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000620 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000621 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000622
623 Term->eraseFromParent();
624}
625
Tom Stellard7370ede2013-02-08 22:24:38 +0000626/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000627void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
628 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000629 if (Node->isSubRegion()) {
630 Region *SubRegion = Node->getNodeAs<Region>();
631 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000632 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000633
Tom Stellard7370ede2013-02-08 22:24:38 +0000634 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000635 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
636 // Incrememt BBI before mucking with BB's terminator.
637 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000638
Tom Stellard7370ede2013-02-08 22:24:38 +0000639 if (!SubRegion->contains(BB))
640 continue;
641
642 // Modify the edges to point to the new exit
643 delPhiValues(BB, OldExit);
644 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
645 addPhiValues(BB, NewExit);
646
647 // Find the new dominator (if requested)
648 if (IncludeDominator) {
649 if (!Dominator)
650 Dominator = BB;
651 else
652 Dominator = DT->findNearestCommonDominator(Dominator, BB);
653 }
Tom Stellardf8794352012-12-19 22:10:31 +0000654 }
655
Tom Stellard7370ede2013-02-08 22:24:38 +0000656 // Change the dominator (if requested)
657 if (Dominator)
658 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000659
Tom Stellard7370ede2013-02-08 22:24:38 +0000660 // Update the region info
661 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000662 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000663 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
664 killTerminator(BB);
665 BranchInst::Create(NewExit, BB);
666 addPhiValues(BB, NewExit);
667 if (IncludeDominator)
668 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000669 }
Tom Stellardf8794352012-12-19 22:10:31 +0000670}
671
Tom Stellardf8794352012-12-19 22:10:31 +0000672/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000673BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000674 LLVMContext &Context = Func->getContext();
675 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000676 Order.back()->getEntry();
Tom Stellardf8794352012-12-19 22:10:31 +0000677 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
678 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000679 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000680 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000681 return Flow;
682}
683
Tom Stellard7370ede2013-02-08 22:24:38 +0000684/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000685BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000686 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000687
Christian Konigfc6a9852013-02-16 11:27:45 +0000688 if (!PrevNode->isSubRegion()) {
689 killTerminator(Entry);
690 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
691 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000692 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000693
Christian Konigfc6a9852013-02-16 11:27:45 +0000694 // create a new flow node
695 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000696
Christian Konigfc6a9852013-02-16 11:27:45 +0000697 // and wire it up
698 changeExit(PrevNode, Flow, true);
699 PrevNode = ParentRegion->getBBNode(Flow);
700 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000701}
702
703/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000704BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
705 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000706 if (!Order.empty() || !ExitUseAllowed)
707 return getNextFlow(Flow);
708
709 BasicBlock *Exit = ParentRegion->getExit();
710 DT->changeImmediateDominator(Exit, Flow);
711 addPhiValues(Flow, Exit);
712 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000713}
714
Christian Konigfc6a9852013-02-16 11:27:45 +0000715/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000716void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000717 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
718 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000719}
720
Justin Lebar3aec10c2016-11-28 18:50:03 +0000721/// \brief Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000722bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000723 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000724 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
725 return DT->dominates(BB, Pred.first);
726 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000727}
728
Tom Stellardf8794352012-12-19 22:10:31 +0000729/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000730bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000731 BBPredicates &Preds = Predicates[Node->getEntry()];
732 bool Dominated = false;
733
734 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000735 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000736 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000737
Justin Lebar3aec10c2016-11-28 18:50:03 +0000738 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
739 BasicBlock *BB = Pred.first;
740 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000741
Justin Lebar3aec10c2016-11-28 18:50:03 +0000742 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000743 return false;
744
Justin Lebar3aec10c2016-11-28 18:50:03 +0000745 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000746 Dominated = true;
747 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000748
749 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000750 return Dominated;
751}
752
Tom Stellard7370ede2013-02-08 22:24:38 +0000753/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000754void StructurizeCFG::wireFlow(bool ExitUseAllowed,
755 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000756 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000757 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000758
Christian Konigfc6a9852013-02-16 11:27:45 +0000759 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000760 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000761 if (PrevNode) {
762 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000763 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000764 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000765 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000766 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000767 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000768
Tom Stellard7370ede2013-02-08 22:24:38 +0000769 // Insert extra postfix node (or use exit instead)
770 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000771 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000772
773 // let it point to entry and next block
774 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
775 addPhiValues(Flow, Entry);
776 DT->changeImmediateDominator(Entry, Flow);
777
Christian Konigfc6a9852013-02-16 11:27:45 +0000778 PrevNode = Node;
779 while (!Order.empty() && !Visited.count(LoopEnd) &&
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000780 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000781 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000782 }
783
Christian Konigfc6a9852013-02-16 11:27:45 +0000784 changeExit(PrevNode, Next, false);
785 setPrevNode(Next);
786 }
787}
788
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000789void StructurizeCFG::handleLoops(bool ExitUseAllowed,
790 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000791 RegionNode *Node = Order.back();
Christian Konigfc6a9852013-02-16 11:27:45 +0000792 BasicBlock *LoopStart = Node->getEntry();
793
794 if (!Loops.count(LoopStart)) {
795 wireFlow(ExitUseAllowed, LoopEnd);
796 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000797 }
798
Christian Konigfc6a9852013-02-16 11:27:45 +0000799 if (!isPredictableTrue(Node))
800 LoopStart = needPrefix(true);
801
802 LoopEnd = Loops[Node->getEntry()];
803 wireFlow(false, LoopEnd);
804 while (!Visited.count(LoopEnd)) {
805 handleLoops(false, LoopEnd);
806 }
807
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000808 // If the start of the loop is the entry block, we can't branch to it so
809 // insert a new dummy entry block.
810 Function *LoopFunc = LoopStart->getParent();
811 if (LoopStart == &LoopFunc->getEntryBlock()) {
812 LoopStart->setName("entry.orig");
813
814 BasicBlock *NewEntry =
815 BasicBlock::Create(LoopStart->getContext(),
816 "entry",
817 LoopFunc,
818 LoopStart);
819 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000820 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000821 }
822
Christian Konigfc6a9852013-02-16 11:27:45 +0000823 // Create an extra loop end node
824 LoopEnd = needPrefix(false);
825 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
826 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
827 BoolUndef, LoopEnd));
828 addPhiValues(LoopEnd, LoopStart);
829 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000830}
831
Tom Stellardf8794352012-12-19 22:10:31 +0000832/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000833/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000834void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000835 BasicBlock *Exit = ParentRegion->getExit();
836 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
837
Tom Stellardf8794352012-12-19 22:10:31 +0000838 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000839 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000840 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000841 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000842
Craig Topperf40110f2014-04-25 05:29:35 +0000843 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000844 Visited.clear();
845
Tom Stellardf8794352012-12-19 22:10:31 +0000846 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000847 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000848 }
849
Christian Konigfc6a9852013-02-16 11:27:45 +0000850 if (PrevNode)
851 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000852 else
853 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000854}
855
Tom Stellardf8794352012-12-19 22:10:31 +0000856/// Handle a rare case where the disintegrated nodes instructions
857/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000858void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000859 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000860 for (BasicBlock *BB : ParentRegion->blocks())
861 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000862 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000863 // We may modify the use list as we iterate over it, so be careful to
864 // compute the next element in the use list at the top of the loop.
865 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
866 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000867 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000868 if (User->getParent() == BB) {
869 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000870 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000871 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000872 continue;
873 }
874
Justin Lebar3aec10c2016-11-28 18:50:03 +0000875 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000876 continue;
877
878 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000879 Value *Undef = UndefValue::get(I.getType());
880 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000881 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000882 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000883 Initialized = true;
884 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000885 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000886 }
887 }
Tom Stellardf8794352012-12-19 22:10:31 +0000888}
889
Justin Lebarc7445d52016-11-22 23:13:33 +0000890static bool hasOnlyUniformBranches(const Region *R,
891 const DivergenceAnalysis &DA) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000892 for (const BasicBlock *BB : R->blocks()) {
893 const BranchInst *Br = dyn_cast<BranchInst>(BB->getTerminator());
894 if (!Br || !Br->isConditional())
895 continue;
896
Nicolai Haehnle43c11152018-02-23 10:45:46 +0000897 if (!DA.isUniform(Br))
Tom Stellard755a4e62016-02-10 00:39:37 +0000898 return false;
899 DEBUG(dbgs() << "BB: " << BB->getName() << " has uniform terminator\n");
900 }
901 return true;
902}
903
Tom Stellardf8794352012-12-19 22:10:31 +0000904/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000905bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000906 if (R->isTopLevelRegion())
907 return false;
908
Tom Stellard755a4e62016-02-10 00:39:37 +0000909 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000910 // TODO: We could probably be smarter here with how we handle sub-regions.
Justin Lebarc7445d52016-11-22 23:13:33 +0000911 auto &DA = getAnalysis<DivergenceAnalysis>();
912 if (hasOnlyUniformBranches(R, DA)) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000913 DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000914
915 // Mark all direct child block terminators as having been treated as
916 // uniform. To account for a possible future in which non-uniform
917 // sub-regions are treated more cleverly, indirect children are not
918 // marked as uniform.
919 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000920 for (RegionNode *E : R->elements()) {
921 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000922 continue;
923
Justin Lebar1b60d702016-11-22 23:13:37 +0000924 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000925 Term->setMetadata("structurizecfg.uniform", MD);
926 }
927
Tom Stellard755a4e62016-02-10 00:39:37 +0000928 return false;
929 }
930 }
931
Tom Stellardf8794352012-12-19 22:10:31 +0000932 Func = R->getEntry()->getParent();
933 ParentRegion = R;
934
Chandler Carruth73523022014-01-13 13:07:17 +0000935 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000936 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000937
938 orderNodes();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000939 collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000940 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000941 insertConditions(false);
942 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000943 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000944 rebuildSSA();
945
Tom Stellard048f14f2013-02-08 22:24:37 +0000946 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000947 Order.clear();
948 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000949 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000950 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000951 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000952 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000953 Loops.clear();
954 LoopPreds.clear();
955 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000956
957 return true;
958}
959
Tom Stellard755a4e62016-02-10 00:39:37 +0000960Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
961 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +0000962}