blob: 7e4177c3507cba62df5891ff5bb83b4a38d71f23 [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"
David Blaikiea373d182018-03-28 17:44:36 +000043#include "llvm/Transforms/Utils.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000044#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000045#include <algorithm>
46#include <cassert>
47#include <utility>
Tom Stellardf8794352012-12-19 22:10:31 +000048
49using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000050using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000051
Chandler Carruth964daaa2014-04-22 02:55:47 +000052#define DEBUG_TYPE "structurizecfg"
53
Eugene Zelenko99241d72017-10-20 21:47:29 +000054// The name for newly created blocks.
55static const char *const FlowBlockName = "Flow";
56
Tom Stellardf8794352012-12-19 22:10:31 +000057namespace {
58
59// Definition of the complex types used in this pass.
60
Eugene Zelenko99241d72017-10-20 21:47:29 +000061using BBValuePair = std::pair<BasicBlock *, Value *>;
Tom Stellardf8794352012-12-19 22:10:31 +000062
Eugene Zelenko99241d72017-10-20 21:47:29 +000063using RNVector = SmallVector<RegionNode *, 8>;
64using BBVector = SmallVector<BasicBlock *, 8>;
65using BranchVector = SmallVector<BranchInst *, 8>;
66using BBValueVector = SmallVector<BBValuePair, 2>;
Tom Stellardf8794352012-12-19 22:10:31 +000067
Eugene Zelenko99241d72017-10-20 21:47:29 +000068using BBSet = SmallPtrSet<BasicBlock *, 8>;
Tom Stellard048f14f2013-02-08 22:24:37 +000069
Eugene Zelenko99241d72017-10-20 21:47:29 +000070using PhiMap = MapVector<PHINode *, BBValueVector>;
71using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
Christian Konig90b45122013-03-26 10:24:20 +000072
Eugene Zelenko99241d72017-10-20 21:47:29 +000073using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
74using BBPredicates = DenseMap<BasicBlock *, Value *>;
75using PredMap = DenseMap<BasicBlock *, BBPredicates>;
76using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
Tom Stellardf8794352012-12-19 22:10:31 +000077
Justin Lebar62c20d82016-11-28 18:49:59 +000078/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000079///
Justin Lebar62c20d82016-11-28 18:49:59 +000080/// For every BB you add to the set, you can specify whether we "remember" the
81/// block. When you get the common dominator, you can also ask whether it's one
82/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000083class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000084 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000085 BasicBlock *Result = nullptr;
86 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000087
Justin Lebar62c20d82016-11-28 18:49:59 +000088 /// Add BB to the resulting dominator.
89 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +000090 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000091 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +000092 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +000093 return;
94 }
95
Justin Lebar62c20d82016-11-28 18:49:59 +000096 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
97 if (NewResult != Result)
98 ResultIsRemembered = false;
99 if (NewResult == BB)
100 ResultIsRemembered |= Remember;
101 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +0000102 }
103
Justin Lebar62c20d82016-11-28 18:49:59 +0000104public:
105 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
106
107 void addBlock(BasicBlock *BB) {
108 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +0000109 }
110
Justin Lebar62c20d82016-11-28 18:49:59 +0000111 void addAndRememberBlock(BasicBlock *BB) {
112 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +0000113 }
Justin Lebar62c20d82016-11-28 18:49:59 +0000114
115 /// Get the nearest common dominator of all the BBs added via addBlock() and
116 /// addAndRememberBlock().
117 BasicBlock *result() { return Result; }
118
119 /// Is the BB returned by getResult() one of the blocks we added to the set
120 /// with addAndRememberBlock()?
121 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +0000122};
123
Tom Stellardf8794352012-12-19 22:10:31 +0000124/// @brief Transforms the control flow graph on one single entry/exit region
125/// at a time.
126///
127/// After the transform all "If"/"Then"/"Else" style control flow looks like
128/// this:
129///
130/// \verbatim
131/// 1
132/// ||
133/// | |
134/// 2 |
135/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000136/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000137/// 3
138/// || Where:
139/// | | 1 = "If" block, calculates the condition
140/// 4 | 2 = "Then" subregion, runs if the condition is true
141/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
142/// |/ 4 = "Else" optional subregion, runs if the condition is false
143/// 5 5 = "End" block, also rejoins the control flow
144/// \endverbatim
145///
146/// Control flow is expressed as a branch where the true exit goes into the
147/// "Then"/"Else" region, while the false exit skips the region
148/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000149/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000150/// for the "Then" edge.
151///
152/// Additionally to that even complicated loops look like this:
153///
154/// \verbatim
155/// 1
156/// ||
157/// | |
158/// 2 ^ Where:
159/// | / 1 = "Entry" block
160/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
161/// 3 3 = "Flow" block, with back edge to entry block
162/// |
163/// \endverbatim
164///
165/// The back edge of the "Flow" block is always on the false side of the branch
166/// while the true side continues the general flow. So the loop condition
167/// consist of a network of PHI nodes where the true incoming values expresses
168/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000169class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000170 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000171
Tom Stellardf8794352012-12-19 22:10:31 +0000172 Type *Boolean;
173 ConstantInt *BoolTrue;
174 ConstantInt *BoolFalse;
175 UndefValue *BoolUndef;
176
177 Function *Func;
178 Region *ParentRegion;
179
180 DominatorTree *DT;
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000181 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000182
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000183 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000184 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000185
Tom Stellardf8794352012-12-19 22:10:31 +0000186 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000187 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000188
189 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000190 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000191
Christian Konigfc6a9852013-02-16 11:27:45 +0000192 BB2BBMap Loops;
193 PredMap LoopPreds;
194 BranchVector LoopConds;
195
196 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000197
198 void orderNodes();
199
Christian Konigfc6a9852013-02-16 11:27:45 +0000200 void analyzeLoops(RegionNode *N);
201
Christian Konigd8860992013-02-16 11:27:50 +0000202 Value *invert(Value *Condition);
203
Tom Stellard048f14f2013-02-08 22:24:37 +0000204 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000205
Christian Konigfc6a9852013-02-16 11:27:45 +0000206 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000207
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000208 void collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000209
Christian Konigfc6a9852013-02-16 11:27:45 +0000210 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000211
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000212 void delPhiValues(BasicBlock *From, BasicBlock *To);
213
214 void addPhiValues(BasicBlock *From, BasicBlock *To);
215
216 void setPhiValues();
217
Tom Stellardf8794352012-12-19 22:10:31 +0000218 void killTerminator(BasicBlock *BB);
219
Tom Stellard7370ede2013-02-08 22:24:38 +0000220 void changeExit(RegionNode *Node, BasicBlock *NewExit,
221 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000222
Tom Stellard7370ede2013-02-08 22:24:38 +0000223 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000224
Christian Konigfc6a9852013-02-16 11:27:45 +0000225 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000226
Tom Stellard7370ede2013-02-08 22:24:38 +0000227 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
228
Christian Konigfc6a9852013-02-16 11:27:45 +0000229 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000230
231 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
232
Christian Konigfc6a9852013-02-16 11:27:45 +0000233 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000234
Christian Konigfc6a9852013-02-16 11:27:45 +0000235 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
236
237 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000238
239 void createFlow();
240
Tom Stellardf8794352012-12-19 22:10:31 +0000241 void rebuildSSA();
242
243public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000244 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000245
Adam Nemete4e1de62018-02-24 17:29:09 +0000246 explicit StructurizeCFG(bool SkipUniformRegions = false)
247 : RegionPass(ID), SkipUniformRegions(SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000248 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
249 }
250
Craig Topper3e4c6972014-03-05 09:10:37 +0000251 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000252
Craig Topper3e4c6972014-03-05 09:10:37 +0000253 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000254
Mehdi Amini117296c2016-10-01 02:56:57 +0000255 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000256
Craig Topper3e4c6972014-03-05 09:10:37 +0000257 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000258 if (SkipUniformRegions)
259 AU.addRequired<DivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000260 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000261 AU.addRequired<DominatorTreeWrapperPass>();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000262 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000263
Chandler Carruth73523022014-01-13 13:07:17 +0000264 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000265 RegionPass::getAnalysisUsage(AU);
266 }
Tom Stellardf8794352012-12-19 22:10:31 +0000267};
268
269} // end anonymous namespace
270
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000271char StructurizeCFG::ID = 0;
272
273INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
274 false, false)
Tom Stellard755a4e62016-02-10 00:39:37 +0000275INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000276INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000277INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000278INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000279INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
280 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000281
282/// \brief Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000283bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000284 LLVMContext &Context = R->getEntry()->getContext();
285
286 Boolean = Type::getInt1Ty(Context);
287 BoolTrue = ConstantInt::getTrue(Context);
288 BoolFalse = ConstantInt::getFalse(Context);
289 BoolUndef = UndefValue::get(Boolean);
290
291 return false;
292}
293
294/// \brief Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000295void StructurizeCFG::orderNodes() {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000296 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
297 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000298
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000299 // The reverse post-order traversal of the list gives us an ordering close
300 // to what we want. The only problem with it is that sometimes backedges
301 // for outer loops will be visited before backedges for inner loops.
302 for (RegionNode *RN : RPOT) {
303 BasicBlock *BB = RN->getEntry();
304 Loop *Loop = LI->getLoopFor(BB);
305 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000306 }
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000307
308 unsigned CurrentLoopDepth = 0;
309 Loop *CurrentLoop = nullptr;
310 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
311 BasicBlock *BB = (*I)->getEntry();
312 unsigned LoopDepth = LI->getLoopDepth(BB);
313
314 if (is_contained(Order, *I))
315 continue;
316
317 if (LoopDepth < CurrentLoopDepth) {
318 // Make sure we have visited all blocks in this loop before moving back to
319 // the outer loop.
320
321 auto LoopI = I;
322 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
323 LoopI++;
324 BasicBlock *LoopBB = (*LoopI)->getEntry();
325 if (LI->getLoopFor(LoopBB) == CurrentLoop) {
326 --BlockCount;
327 Order.push_back(*LoopI);
328 }
329 }
330 }
331
332 CurrentLoop = LI->getLoopFor(BB);
333 if (CurrentLoop)
334 LoopBlocks[CurrentLoop]--;
335
336 CurrentLoopDepth = LoopDepth;
337 Order.push_back(*I);
338 }
339
340 // This pass originally used a post-order traversal and then operated on
341 // the list in reverse. Now that we are using a reverse post-order traversal
342 // rather than re-working the whole pass to operate on the list in order,
343 // we just reverse the list and continue to operate on it in reverse.
344 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000345}
346
Christian Konigfc6a9852013-02-16 11:27:45 +0000347/// \brief Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000348void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000349 if (N->isSubRegion()) {
350 // Test for exit as back edge
351 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
352 if (Visited.count(Exit))
353 Loops[Exit] = N->getEntry();
354
355 } else {
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000356 // Test for successors as back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000357 BasicBlock *BB = N->getNodeAs<BasicBlock>();
358 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
359
Pete Cooperebcd7482015-08-06 20:22:46 +0000360 for (BasicBlock *Succ : Term->successors())
361 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000362 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000363 }
364}
365
Christian Konigd8860992013-02-16 11:27:50 +0000366/// \brief Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000367Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000368 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000369 if (Constant *C = dyn_cast<Constant>(Condition))
370 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000371
372 // Second: If the condition is already inverted, return the original value
373 if (match(Condition, m_Not(m_Value(Condition))))
374 return Condition;
375
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000376 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
377 // Third: Check all the users for an invert
378 BasicBlock *Parent = Inst->getParent();
Matt Arsenault44746522017-04-24 20:25:01 +0000379 for (User *U : Condition->users())
380 if (Instruction *I = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000381 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
382 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000383
384 // Last option: Create a new instruction
385 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000386 }
387
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000388 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
389 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
390 return BinaryOperator::CreateNot(Condition,
391 Arg->getName() + ".inv",
392 EntryBlock.getTerminator());
393 }
394
395 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000396}
397
Tom Stellard048f14f2013-02-08 22:24:37 +0000398/// \brief Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000399Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
400 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000401 Value *Cond = Invert ? BoolFalse : BoolTrue;
402 if (Term->isConditional()) {
403 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000404
Aaron Ballman19978552013-06-04 01:03:03 +0000405 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000406 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000407 }
408 return Cond;
409}
410
Tom Stellard048f14f2013-02-08 22:24:37 +0000411/// \brief Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000412void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000413 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000414 BasicBlock *BB = N->getEntry();
415 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000416 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000417
Justin Lebar3aec10c2016-11-28 18:50:03 +0000418 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000419 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000420 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000421 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000422
Justin Lebar3aec10c2016-11-28 18:50:03 +0000423 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000424 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000425 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000426 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000427 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
428 BasicBlock *Succ = Term->getSuccessor(i);
429 if (Succ != BB)
430 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000431
Justin Lebar3aec10c2016-11-28 18:50:03 +0000432 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000433 // Normal forward edge
434 if (Term->isConditional()) {
435 // Try to treat it like an ELSE block
436 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000437 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000438 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000439
Tom Stellard048f14f2013-02-08 22:24:37 +0000440 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000441 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000442 continue;
443 }
444 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000445 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000446 } else {
447 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000448 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000449 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000450 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000451 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000452 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000453 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000454 R = R->getParent();
455
456 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000457 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000458 continue;
459
460 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000461 if (Visited.count(Entry))
462 Pred[Entry] = BoolTrue;
463 else
464 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000465 }
466 }
467}
468
469/// \brief Collect various loop and predicate infos
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000470void StructurizeCFG::collectInfos() {
471 // Reset predicate
472 Predicates.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000473
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000474 // and loop infos
475 Loops.clear();
476 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000477
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000478 // Reset the visited nodes
479 Visited.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000480
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000481 for (RegionNode *RN : reverse(Order)) {
482 DEBUG(dbgs() << "Visiting: "
483 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
484 << RN->getEntry()->getName() << " Loop Depth: "
485 << LI->getLoopDepth(RN->getEntry()) << "\n");
486
487 // Analyze all the conditions leading to a node
488 gatherPredicates(RN);
489
490 // Remember that we've seen this node
491 Visited.insert(RN->getEntry());
492
493 // Find the last back edges
494 analyzeLoops(RN);
495 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000496}
497
498/// \brief Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000499void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000500 BranchVector &Conds = Loops ? LoopConds : Conditions;
501 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000502 SSAUpdater PhiInserter;
503
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000504 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000505 assert(Term->isConditional());
506
Christian Konigfc6a9852013-02-16 11:27:45 +0000507 BasicBlock *Parent = Term->getParent();
508 BasicBlock *SuccTrue = Term->getSuccessor(0);
509 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000510
Christian Konigb5d88662013-02-16 11:27:40 +0000511 PhiInserter.Initialize(Boolean, "");
512 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000513 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000514
Christian Konigfc6a9852013-02-16 11:27:45 +0000515 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000516
517 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000518 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000519
Craig Topperf40110f2014-04-25 05:29:35 +0000520 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000521 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
522 BasicBlock *BB = BBAndPred.first;
523 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000524
Justin Lebar3aec10c2016-11-28 18:50:03 +0000525 if (BB == Parent) {
526 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000527 break;
528 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000529 PhiInserter.AddAvailableValue(BB, Pred);
530 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000531 }
532
Christian Konigb5d88662013-02-16 11:27:40 +0000533 if (ParentValue) {
534 Term->setCondition(ParentValue);
535 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000536 if (!Dominator.resultIsRememberedBlock())
537 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000538
Tom Stellard048f14f2013-02-08 22:24:37 +0000539 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000540 }
Tom Stellardf8794352012-12-19 22:10:31 +0000541 }
542}
543
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000544/// \brief Remove all PHI values coming from "From" into "To" and remember
545/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000546void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000547 PhiMap &Map = DeletedPhis[To];
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000548 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000549 while (Phi.getBasicBlockIndex(From) != -1) {
550 Value *Deleted = Phi.removeIncomingValue(From, false);
551 Map[&Phi].push_back(std::make_pair(From, Deleted));
552 }
553 }
554}
555
556/// \brief Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000557void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000558 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000559 Value *Undef = UndefValue::get(Phi.getType());
560 Phi.addIncoming(Undef, From);
561 }
562 AddedPhis[To].push_back(From);
563}
564
565/// \brief Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000566void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000567 SSAUpdater Updater;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000568 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000569 BasicBlock *To = AddedPhi.first;
570 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000571
572 if (!DeletedPhis.count(To))
573 continue;
574
575 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000576 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000577 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000578 Value *Undef = UndefValue::get(Phi->getType());
579 Updater.Initialize(Phi->getType(), "");
580 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
581 Updater.AddAvailableValue(To, Undef);
582
Christian Konig0bccf9d2013-02-16 11:27:35 +0000583 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000584 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000585 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000586 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000587 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000588 }
589
Justin Lebar62c20d82016-11-28 18:49:59 +0000590 if (!Dominator.resultIsRememberedBlock())
591 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000592
Benjamin Kramer135f7352016-06-26 12:28:59 +0000593 for (BasicBlock *FI : From) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000594 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000595 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000596 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000597 }
598 }
599
600 DeletedPhis.erase(To);
601 }
602 assert(DeletedPhis.empty());
603}
604
Tom Stellard7370ede2013-02-08 22:24:38 +0000605/// \brief Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000606void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000607 TerminatorInst *Term = BB->getTerminator();
608 if (!Term)
609 return;
610
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000611 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000612 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000613 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000614
615 Term->eraseFromParent();
616}
617
Tom Stellard7370ede2013-02-08 22:24:38 +0000618/// \brief Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000619void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
620 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000621 if (Node->isSubRegion()) {
622 Region *SubRegion = Node->getNodeAs<Region>();
623 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000624 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000625
Tom Stellard7370ede2013-02-08 22:24:38 +0000626 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000627 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
628 // Incrememt BBI before mucking with BB's terminator.
629 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000630
Tom Stellard7370ede2013-02-08 22:24:38 +0000631 if (!SubRegion->contains(BB))
632 continue;
633
634 // Modify the edges to point to the new exit
635 delPhiValues(BB, OldExit);
636 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
637 addPhiValues(BB, NewExit);
638
639 // Find the new dominator (if requested)
640 if (IncludeDominator) {
641 if (!Dominator)
642 Dominator = BB;
643 else
644 Dominator = DT->findNearestCommonDominator(Dominator, BB);
645 }
Tom Stellardf8794352012-12-19 22:10:31 +0000646 }
647
Tom Stellard7370ede2013-02-08 22:24:38 +0000648 // Change the dominator (if requested)
649 if (Dominator)
650 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000651
Tom Stellard7370ede2013-02-08 22:24:38 +0000652 // Update the region info
653 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000654 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000655 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
656 killTerminator(BB);
657 BranchInst::Create(NewExit, BB);
658 addPhiValues(BB, NewExit);
659 if (IncludeDominator)
660 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000661 }
Tom Stellardf8794352012-12-19 22:10:31 +0000662}
663
Tom Stellardf8794352012-12-19 22:10:31 +0000664/// \brief Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000665BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000666 LLVMContext &Context = Func->getContext();
667 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000668 Order.back()->getEntry();
Tom Stellardf8794352012-12-19 22:10:31 +0000669 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
670 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000671 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000672 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000673 return Flow;
674}
675
Tom Stellard7370ede2013-02-08 22:24:38 +0000676/// \brief Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000677BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000678 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000679
Christian Konigfc6a9852013-02-16 11:27:45 +0000680 if (!PrevNode->isSubRegion()) {
681 killTerminator(Entry);
682 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
683 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000684 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000685
Christian Konigfc6a9852013-02-16 11:27:45 +0000686 // create a new flow node
687 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000688
Christian Konigfc6a9852013-02-16 11:27:45 +0000689 // and wire it up
690 changeExit(PrevNode, Flow, true);
691 PrevNode = ParentRegion->getBBNode(Flow);
692 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000693}
694
695/// \brief Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000696BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
697 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000698 if (!Order.empty() || !ExitUseAllowed)
699 return getNextFlow(Flow);
700
701 BasicBlock *Exit = ParentRegion->getExit();
702 DT->changeImmediateDominator(Exit, Flow);
703 addPhiValues(Flow, Exit);
704 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000705}
706
Christian Konigfc6a9852013-02-16 11:27:45 +0000707/// \brief Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000708void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000709 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
710 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000711}
712
Justin Lebar3aec10c2016-11-28 18:50:03 +0000713/// \brief Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000714bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000715 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000716 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
717 return DT->dominates(BB, Pred.first);
718 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000719}
720
Tom Stellardf8794352012-12-19 22:10:31 +0000721/// \brief Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000722bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000723 BBPredicates &Preds = Predicates[Node->getEntry()];
724 bool Dominated = false;
725
726 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000727 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000728 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000729
Justin Lebar3aec10c2016-11-28 18:50:03 +0000730 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
731 BasicBlock *BB = Pred.first;
732 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000733
Justin Lebar3aec10c2016-11-28 18:50:03 +0000734 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000735 return false;
736
Justin Lebar3aec10c2016-11-28 18:50:03 +0000737 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000738 Dominated = true;
739 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000740
741 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000742 return Dominated;
743}
744
Tom Stellard7370ede2013-02-08 22:24:38 +0000745/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000746void StructurizeCFG::wireFlow(bool ExitUseAllowed,
747 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000748 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000749 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000750
Christian Konigfc6a9852013-02-16 11:27:45 +0000751 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000752 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000753 if (PrevNode) {
754 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000755 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000756 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000757 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000758 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000759 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000760
Tom Stellard7370ede2013-02-08 22:24:38 +0000761 // Insert extra postfix node (or use exit instead)
762 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000763 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000764
765 // let it point to entry and next block
766 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
767 addPhiValues(Flow, Entry);
768 DT->changeImmediateDominator(Entry, Flow);
769
Christian Konigfc6a9852013-02-16 11:27:45 +0000770 PrevNode = Node;
771 while (!Order.empty() && !Visited.count(LoopEnd) &&
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000772 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000773 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000774 }
775
Christian Konigfc6a9852013-02-16 11:27:45 +0000776 changeExit(PrevNode, Next, false);
777 setPrevNode(Next);
778 }
779}
780
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000781void StructurizeCFG::handleLoops(bool ExitUseAllowed,
782 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000783 RegionNode *Node = Order.back();
Christian Konigfc6a9852013-02-16 11:27:45 +0000784 BasicBlock *LoopStart = Node->getEntry();
785
786 if (!Loops.count(LoopStart)) {
787 wireFlow(ExitUseAllowed, LoopEnd);
788 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000789 }
790
Christian Konigfc6a9852013-02-16 11:27:45 +0000791 if (!isPredictableTrue(Node))
792 LoopStart = needPrefix(true);
793
794 LoopEnd = Loops[Node->getEntry()];
795 wireFlow(false, LoopEnd);
796 while (!Visited.count(LoopEnd)) {
797 handleLoops(false, LoopEnd);
798 }
799
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000800 // If the start of the loop is the entry block, we can't branch to it so
801 // insert a new dummy entry block.
802 Function *LoopFunc = LoopStart->getParent();
803 if (LoopStart == &LoopFunc->getEntryBlock()) {
804 LoopStart->setName("entry.orig");
805
806 BasicBlock *NewEntry =
807 BasicBlock::Create(LoopStart->getContext(),
808 "entry",
809 LoopFunc,
810 LoopStart);
811 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000812 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000813 }
814
Christian Konigfc6a9852013-02-16 11:27:45 +0000815 // Create an extra loop end node
816 LoopEnd = needPrefix(false);
817 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
818 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
819 BoolUndef, LoopEnd));
820 addPhiValues(LoopEnd, LoopStart);
821 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000822}
823
Tom Stellardf8794352012-12-19 22:10:31 +0000824/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000825/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000826void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000827 BasicBlock *Exit = ParentRegion->getExit();
828 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
829
Tom Stellardf8794352012-12-19 22:10:31 +0000830 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000831 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000832 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000833 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000834
Craig Topperf40110f2014-04-25 05:29:35 +0000835 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000836 Visited.clear();
837
Tom Stellardf8794352012-12-19 22:10:31 +0000838 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000839 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000840 }
841
Christian Konigfc6a9852013-02-16 11:27:45 +0000842 if (PrevNode)
843 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000844 else
845 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000846}
847
Tom Stellardf8794352012-12-19 22:10:31 +0000848/// Handle a rare case where the disintegrated nodes instructions
849/// no longer dominate all their uses. Not sure if this is really nessasary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000850void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000851 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000852 for (BasicBlock *BB : ParentRegion->blocks())
853 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000854 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000855 // We may modify the use list as we iterate over it, so be careful to
856 // compute the next element in the use list at the top of the loop.
857 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
858 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000859 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000860 if (User->getParent() == BB) {
861 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000862 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000863 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000864 continue;
865 }
866
Justin Lebar3aec10c2016-11-28 18:50:03 +0000867 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000868 continue;
869
870 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000871 Value *Undef = UndefValue::get(I.getType());
872 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000873 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000874 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000875 Initialized = true;
876 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000877 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000878 }
879 }
Tom Stellardf8794352012-12-19 22:10:31 +0000880}
881
Justin Lebarc7445d52016-11-22 23:13:33 +0000882static bool hasOnlyUniformBranches(const Region *R,
883 const DivergenceAnalysis &DA) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000884 for (const BasicBlock *BB : R->blocks()) {
885 const BranchInst *Br = dyn_cast<BranchInst>(BB->getTerminator());
886 if (!Br || !Br->isConditional())
887 continue;
888
Adam Nemete4e1de62018-02-24 17:29:09 +0000889 if (!DA.isUniform(Br->getCondition()))
Tom Stellard755a4e62016-02-10 00:39:37 +0000890 return false;
891 DEBUG(dbgs() << "BB: " << BB->getName() << " has uniform terminator\n");
892 }
893 return true;
894}
895
Tom Stellardf8794352012-12-19 22:10:31 +0000896/// \brief Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000897bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000898 if (R->isTopLevelRegion())
899 return false;
900
Tom Stellard755a4e62016-02-10 00:39:37 +0000901 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000902 // TODO: We could probably be smarter here with how we handle sub-regions.
Justin Lebarc7445d52016-11-22 23:13:33 +0000903 auto &DA = getAnalysis<DivergenceAnalysis>();
904 if (hasOnlyUniformBranches(R, DA)) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000905 DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000906
907 // Mark all direct child block terminators as having been treated as
908 // uniform. To account for a possible future in which non-uniform
909 // sub-regions are treated more cleverly, indirect children are not
910 // marked as uniform.
911 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000912 for (RegionNode *E : R->elements()) {
913 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000914 continue;
915
Justin Lebar1b60d702016-11-22 23:13:37 +0000916 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000917 Term->setMetadata("structurizecfg.uniform", MD);
918 }
919
Tom Stellard755a4e62016-02-10 00:39:37 +0000920 return false;
921 }
922 }
923
Tom Stellardf8794352012-12-19 22:10:31 +0000924 Func = R->getEntry()->getParent();
925 ParentRegion = R;
926
Chandler Carruth73523022014-01-13 13:07:17 +0000927 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000928 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000929
930 orderNodes();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000931 collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000932 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000933 insertConditions(false);
934 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000935 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +0000936 rebuildSSA();
937
Tom Stellard048f14f2013-02-08 22:24:37 +0000938 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +0000939 Order.clear();
940 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000941 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000942 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000943 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000944 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000945 Loops.clear();
946 LoopPreds.clear();
947 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000948
949 return true;
950}
951
Tom Stellard755a4e62016-02-10 00:39:37 +0000952Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
953 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +0000954}