blob: b3ef31cea0a8814ac7f87a61f942f11d646e2eb5 [file] [log] [blame]
Eugene Zelenko99241d72017-10-20 21:47:29 +00001//===- StructurizeCFG.cpp -------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tom Stellardf8794352012-12-19 22:10:31 +00006//
7//===----------------------------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00008
Eugene Zelenko99241d72017-10-20 21:47:29 +00009#include "llvm/ADT/DenseMap.h"
Christian Konig90b45122013-03-26 10:24:20 +000010#include "llvm/ADT/MapVector.h"
Tom Stellard071ec902015-02-04 20:49:44 +000011#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000012#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/SmallPtrSet.h"
14#include "llvm/ADT/SmallVector.h"
Nicolai Haehnle08230502018-10-17 15:37:41 +000015#include "llvm/Analysis/InstructionSimplify.h"
Nicolai Haehnle35617ed2018-08-30 14:21:36 +000016#include "llvm/Analysis/LegacyDivergenceAnalysis.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
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +000059static cl::opt<bool> ForceSkipUniformRegions(
60 "structurizecfg-skip-uniform-regions",
61 cl::Hidden,
62 cl::desc("Force whether the StructurizeCFG pass skips uniform regions"),
63 cl::init(false));
64
Tom Stellardf8794352012-12-19 22:10:31 +000065// Definition of the complex types used in this pass.
66
Eugene Zelenko99241d72017-10-20 21:47:29 +000067using BBValuePair = std::pair<BasicBlock *, Value *>;
Tom Stellardf8794352012-12-19 22:10:31 +000068
Eugene Zelenko99241d72017-10-20 21:47:29 +000069using RNVector = SmallVector<RegionNode *, 8>;
70using BBVector = SmallVector<BasicBlock *, 8>;
71using BranchVector = SmallVector<BranchInst *, 8>;
72using BBValueVector = SmallVector<BBValuePair, 2>;
Tom Stellardf8794352012-12-19 22:10:31 +000073
Eugene Zelenko99241d72017-10-20 21:47:29 +000074using BBSet = SmallPtrSet<BasicBlock *, 8>;
Tom Stellard048f14f2013-02-08 22:24:37 +000075
Eugene Zelenko99241d72017-10-20 21:47:29 +000076using PhiMap = MapVector<PHINode *, BBValueVector>;
77using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
Christian Konig90b45122013-03-26 10:24:20 +000078
Eugene Zelenko99241d72017-10-20 21:47:29 +000079using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
80using BBPredicates = DenseMap<BasicBlock *, Value *>;
81using PredMap = DenseMap<BasicBlock *, BBPredicates>;
82using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
Tom Stellardf8794352012-12-19 22:10:31 +000083
Justin Lebar62c20d82016-11-28 18:49:59 +000084/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000085///
Justin Lebar62c20d82016-11-28 18:49:59 +000086/// For every BB you add to the set, you can specify whether we "remember" the
87/// block. When you get the common dominator, you can also ask whether it's one
88/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000089class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000090 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000091 BasicBlock *Result = nullptr;
92 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000093
Justin Lebar62c20d82016-11-28 18:49:59 +000094 /// Add BB to the resulting dominator.
95 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +000096 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000097 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +000098 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +000099 return;
100 }
101
Justin Lebar62c20d82016-11-28 18:49:59 +0000102 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
103 if (NewResult != Result)
104 ResultIsRemembered = false;
105 if (NewResult == BB)
106 ResultIsRemembered |= Remember;
107 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +0000108 }
109
Justin Lebar62c20d82016-11-28 18:49:59 +0000110public:
111 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
112
113 void addBlock(BasicBlock *BB) {
114 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +0000115 }
116
Justin Lebar62c20d82016-11-28 18:49:59 +0000117 void addAndRememberBlock(BasicBlock *BB) {
118 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +0000119 }
Justin Lebar62c20d82016-11-28 18:49:59 +0000120
121 /// Get the nearest common dominator of all the BBs added via addBlock() and
122 /// addAndRememberBlock().
123 BasicBlock *result() { return Result; }
124
125 /// Is the BB returned by getResult() one of the blocks we added to the set
126 /// with addAndRememberBlock()?
127 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +0000128};
129
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000130/// Transforms the control flow graph on one single entry/exit region
Tom Stellardf8794352012-12-19 22:10:31 +0000131/// at a time.
132///
133/// After the transform all "If"/"Then"/"Else" style control flow looks like
134/// this:
135///
136/// \verbatim
137/// 1
138/// ||
139/// | |
140/// 2 |
141/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000142/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000143/// 3
144/// || Where:
145/// | | 1 = "If" block, calculates the condition
146/// 4 | 2 = "Then" subregion, runs if the condition is true
147/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
148/// |/ 4 = "Else" optional subregion, runs if the condition is false
149/// 5 5 = "End" block, also rejoins the control flow
150/// \endverbatim
151///
152/// Control flow is expressed as a branch where the true exit goes into the
153/// "Then"/"Else" region, while the false exit skips the region
154/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000155/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000156/// for the "Then" edge.
157///
158/// Additionally to that even complicated loops look like this:
159///
160/// \verbatim
161/// 1
162/// ||
163/// | |
164/// 2 ^ Where:
165/// | / 1 = "Entry" block
166/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
167/// 3 3 = "Flow" block, with back edge to entry block
168/// |
169/// \endverbatim
170///
171/// The back edge of the "Flow" block is always on the false side of the branch
172/// while the true side continues the general flow. So the loop condition
173/// consist of a network of PHI nodes where the true incoming values expresses
174/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000175class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000176 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000177
Tom Stellardf8794352012-12-19 22:10:31 +0000178 Type *Boolean;
179 ConstantInt *BoolTrue;
180 ConstantInt *BoolFalse;
181 UndefValue *BoolUndef;
182
183 Function *Func;
184 Region *ParentRegion;
185
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000186 LegacyDivergenceAnalysis *DA;
Tom Stellardf8794352012-12-19 22:10:31 +0000187 DominatorTree *DT;
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000188 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000189
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000190 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000191 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000192
Tom Stellardf8794352012-12-19 22:10:31 +0000193 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000194 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000195
196 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000197 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000198
Christian Konigfc6a9852013-02-16 11:27:45 +0000199 BB2BBMap Loops;
200 PredMap LoopPreds;
201 BranchVector LoopConds;
202
203 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000204
205 void orderNodes();
206
Changpeng Fang5f915462018-05-23 18:34:48 +0000207 Loop *getAdjustedLoop(RegionNode *RN);
208 unsigned getAdjustedLoopDepth(RegionNode *RN);
209
Christian Konigfc6a9852013-02-16 11:27:45 +0000210 void analyzeLoops(RegionNode *N);
211
Christian Konigd8860992013-02-16 11:27:50 +0000212 Value *invert(Value *Condition);
213
Tom Stellard048f14f2013-02-08 22:24:37 +0000214 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000215
Christian Konigfc6a9852013-02-16 11:27:45 +0000216 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000217
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000218 void collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000219
Christian Konigfc6a9852013-02-16 11:27:45 +0000220 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000221
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000222 void delPhiValues(BasicBlock *From, BasicBlock *To);
223
224 void addPhiValues(BasicBlock *From, BasicBlock *To);
225
226 void setPhiValues();
227
Tom Stellardf8794352012-12-19 22:10:31 +0000228 void killTerminator(BasicBlock *BB);
229
Tom Stellard7370ede2013-02-08 22:24:38 +0000230 void changeExit(RegionNode *Node, BasicBlock *NewExit,
231 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000232
Tom Stellard7370ede2013-02-08 22:24:38 +0000233 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000234
Christian Konigfc6a9852013-02-16 11:27:45 +0000235 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000236
Tom Stellard7370ede2013-02-08 22:24:38 +0000237 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
238
Christian Konigfc6a9852013-02-16 11:27:45 +0000239 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000240
241 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
242
Christian Konigfc6a9852013-02-16 11:27:45 +0000243 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000244
Christian Konigfc6a9852013-02-16 11:27:45 +0000245 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
246
247 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000248
249 void createFlow();
250
Tom Stellardf8794352012-12-19 22:10:31 +0000251 void rebuildSSA();
252
253public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000254 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000255
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000256 explicit StructurizeCFG(bool SkipUniformRegions_ = false)
257 : RegionPass(ID),
258 SkipUniformRegions(SkipUniformRegions_) {
259 if (ForceSkipUniformRegions.getNumOccurrences())
260 SkipUniformRegions = ForceSkipUniformRegions.getValue();
Tom Stellard755a4e62016-02-10 00:39:37 +0000261 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
262 }
263
Craig Topper3e4c6972014-03-05 09:10:37 +0000264 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000265
Craig Topper3e4c6972014-03-05 09:10:37 +0000266 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000267
Mehdi Amini117296c2016-10-01 02:56:57 +0000268 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000269
Craig Topper3e4c6972014-03-05 09:10:37 +0000270 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000271 if (SkipUniformRegions)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000272 AU.addRequired<LegacyDivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000273 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000274 AU.addRequired<DominatorTreeWrapperPass>();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000275 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000276
Chandler Carruth73523022014-01-13 13:07:17 +0000277 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000278 RegionPass::getAnalysisUsage(AU);
279 }
Tom Stellardf8794352012-12-19 22:10:31 +0000280};
281
282} // end anonymous namespace
283
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000284char StructurizeCFG::ID = 0;
285
286INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
287 false, false)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000288INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000289INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000290INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000291INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000292INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
293 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295/// Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000296bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000297 LLVMContext &Context = R->getEntry()->getContext();
298
299 Boolean = Type::getInt1Ty(Context);
300 BoolTrue = ConstantInt::getTrue(Context);
301 BoolFalse = ConstantInt::getFalse(Context);
302 BoolUndef = UndefValue::get(Boolean);
303
304 return false;
305}
306
Changpeng Fang5f915462018-05-23 18:34:48 +0000307/// Use the exit block to determine the loop if RN is a SubRegion.
308Loop *StructurizeCFG::getAdjustedLoop(RegionNode *RN) {
309 if (RN->isSubRegion()) {
310 Region *SubRegion = RN->getNodeAs<Region>();
311 return LI->getLoopFor(SubRegion->getExit());
312 }
313
314 return LI->getLoopFor(RN->getEntry());
315}
316
317/// Use the exit block to determine the loop depth if RN is a SubRegion.
318unsigned StructurizeCFG::getAdjustedLoopDepth(RegionNode *RN) {
319 if (RN->isSubRegion()) {
320 Region *SubR = RN->getNodeAs<Region>();
321 return LI->getLoopDepth(SubR->getExit());
322 }
323
324 return LI->getLoopDepth(RN->getEntry());
325}
326
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000327/// Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000328void StructurizeCFG::orderNodes() {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000329 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
330 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000331
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000332 // The reverse post-order traversal of the list gives us an ordering close
333 // to what we want. The only problem with it is that sometimes backedges
334 // for outer loops will be visited before backedges for inner loops.
335 for (RegionNode *RN : RPOT) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000336 Loop *Loop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000337 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000338 }
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000339
340 unsigned CurrentLoopDepth = 0;
341 Loop *CurrentLoop = nullptr;
342 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000343 RegionNode *RN = cast<RegionNode>(*I);
344 unsigned LoopDepth = getAdjustedLoopDepth(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000345
346 if (is_contained(Order, *I))
347 continue;
348
349 if (LoopDepth < CurrentLoopDepth) {
350 // Make sure we have visited all blocks in this loop before moving back to
351 // the outer loop.
352
353 auto LoopI = I;
354 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
355 LoopI++;
Changpeng Fang5f915462018-05-23 18:34:48 +0000356 if (getAdjustedLoop(cast<RegionNode>(*LoopI)) == CurrentLoop) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000357 --BlockCount;
358 Order.push_back(*LoopI);
359 }
360 }
361 }
362
Changpeng Fang5f915462018-05-23 18:34:48 +0000363 CurrentLoop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000364 if (CurrentLoop)
365 LoopBlocks[CurrentLoop]--;
366
367 CurrentLoopDepth = LoopDepth;
368 Order.push_back(*I);
369 }
370
371 // This pass originally used a post-order traversal and then operated on
372 // the list in reverse. Now that we are using a reverse post-order traversal
373 // rather than re-working the whole pass to operate on the list in order,
374 // we just reverse the list and continue to operate on it in reverse.
375 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000376}
377
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000378/// Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000379void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000380 if (N->isSubRegion()) {
381 // Test for exit as back edge
382 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
383 if (Visited.count(Exit))
384 Loops[Exit] = N->getEntry();
385
386 } else {
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000387 // Test for successors as back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000388 BasicBlock *BB = N->getNodeAs<BasicBlock>();
389 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
390
Pete Cooperebcd7482015-08-06 20:22:46 +0000391 for (BasicBlock *Succ : Term->successors())
392 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000393 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000394 }
395}
396
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000397/// Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000398Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000399 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000400 if (Constant *C = dyn_cast<Constant>(Condition))
401 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000402
403 // Second: If the condition is already inverted, return the original value
Marek Olsak3c5fd142018-05-15 21:41:55 +0000404 Value *NotCondition;
405 if (match(Condition, m_Not(m_Value(NotCondition))))
406 return NotCondition;
Christian Konigd8860992013-02-16 11:27:50 +0000407
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000408 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
409 // Third: Check all the users for an invert
410 BasicBlock *Parent = Inst->getParent();
Matt Arsenault44746522017-04-24 20:25:01 +0000411 for (User *U : Condition->users())
412 if (Instruction *I = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000413 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
414 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000415
416 // Last option: Create a new instruction
417 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000418 }
419
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000420 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
421 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
422 return BinaryOperator::CreateNot(Condition,
423 Arg->getName() + ".inv",
424 EntryBlock.getTerminator());
425 }
426
427 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000428}
429
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000430/// Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000431Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
432 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000433 Value *Cond = Invert ? BoolFalse : BoolTrue;
434 if (Term->isConditional()) {
435 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000436
Aaron Ballman19978552013-06-04 01:03:03 +0000437 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000438 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000439 }
440 return Cond;
441}
442
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000443/// Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000444void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000445 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000446 BasicBlock *BB = N->getEntry();
447 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000448 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000449
Justin Lebar3aec10c2016-11-28 18:50:03 +0000450 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000451 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000452 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000453 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000454
Justin Lebar3aec10c2016-11-28 18:50:03 +0000455 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000456 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000457 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000458 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000459 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
460 BasicBlock *Succ = Term->getSuccessor(i);
461 if (Succ != BB)
462 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000463
Justin Lebar3aec10c2016-11-28 18:50:03 +0000464 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000465 // Normal forward edge
466 if (Term->isConditional()) {
467 // Try to treat it like an ELSE block
468 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000469 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000470 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000471
Tom Stellard048f14f2013-02-08 22:24:37 +0000472 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000473 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000474 continue;
475 }
476 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000477 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000478 } else {
479 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000480 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000481 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000482 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000483 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000484 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000485 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000486 R = R->getParent();
487
488 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000489 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000490 continue;
491
492 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000493 if (Visited.count(Entry))
494 Pred[Entry] = BoolTrue;
495 else
496 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000497 }
498 }
499}
500
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000501/// Collect various loop and predicate infos
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000502void StructurizeCFG::collectInfos() {
503 // Reset predicate
504 Predicates.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000505
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000506 // and loop infos
507 Loops.clear();
508 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000509
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000510 // Reset the visited nodes
511 Visited.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000512
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000513 for (RegionNode *RN : reverse(Order)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000514 LLVM_DEBUG(dbgs() << "Visiting: "
515 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
516 << RN->getEntry()->getName() << " Loop Depth: "
517 << LI->getLoopDepth(RN->getEntry()) << "\n");
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000518
519 // Analyze all the conditions leading to a node
520 gatherPredicates(RN);
521
522 // Remember that we've seen this node
523 Visited.insert(RN->getEntry());
524
525 // Find the last back edges
526 analyzeLoops(RN);
527 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000528}
529
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000530/// Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000531void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000532 BranchVector &Conds = Loops ? LoopConds : Conditions;
533 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000534 SSAUpdater PhiInserter;
535
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000536 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000537 assert(Term->isConditional());
538
Christian Konigfc6a9852013-02-16 11:27:45 +0000539 BasicBlock *Parent = Term->getParent();
540 BasicBlock *SuccTrue = Term->getSuccessor(0);
541 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000542
Christian Konigb5d88662013-02-16 11:27:40 +0000543 PhiInserter.Initialize(Boolean, "");
544 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000545 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000546
Christian Konigfc6a9852013-02-16 11:27:45 +0000547 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000548
549 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000550 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000551
Craig Topperf40110f2014-04-25 05:29:35 +0000552 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000553 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
554 BasicBlock *BB = BBAndPred.first;
555 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000556
Justin Lebar3aec10c2016-11-28 18:50:03 +0000557 if (BB == Parent) {
558 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000559 break;
560 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000561 PhiInserter.AddAvailableValue(BB, Pred);
562 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000563 }
564
Christian Konigb5d88662013-02-16 11:27:40 +0000565 if (ParentValue) {
566 Term->setCondition(ParentValue);
567 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000568 if (!Dominator.resultIsRememberedBlock())
569 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000570
Tom Stellard048f14f2013-02-08 22:24:37 +0000571 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000572 }
Tom Stellardf8794352012-12-19 22:10:31 +0000573 }
574}
575
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000576/// Remove all PHI values coming from "From" into "To" and remember
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000577/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000578void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000579 PhiMap &Map = DeletedPhis[To];
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000580 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000581 while (Phi.getBasicBlockIndex(From) != -1) {
582 Value *Deleted = Phi.removeIncomingValue(From, false);
583 Map[&Phi].push_back(std::make_pair(From, Deleted));
584 }
585 }
586}
587
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000588/// Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000589void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000590 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000591 Value *Undef = UndefValue::get(Phi.getType());
592 Phi.addIncoming(Undef, From);
593 }
594 AddedPhis[To].push_back(From);
595}
596
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000597/// Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000598void StructurizeCFG::setPhiValues() {
Nicolai Haehnle08230502018-10-17 15:37:41 +0000599 SmallVector<PHINode *, 8> InsertedPhis;
600 SSAUpdater Updater(&InsertedPhis);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000601 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000602 BasicBlock *To = AddedPhi.first;
603 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000604
605 if (!DeletedPhis.count(To))
606 continue;
607
608 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000609 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000610 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000611 Value *Undef = UndefValue::get(Phi->getType());
612 Updater.Initialize(Phi->getType(), "");
613 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
614 Updater.AddAvailableValue(To, Undef);
615
Christian Konig0bccf9d2013-02-16 11:27:35 +0000616 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000617 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000618 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000619 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000620 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000621 }
622
Justin Lebar62c20d82016-11-28 18:49:59 +0000623 if (!Dominator.resultIsRememberedBlock())
624 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000625
Benjamin Kramer135f7352016-06-26 12:28:59 +0000626 for (BasicBlock *FI : From) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000627 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000628 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000629 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000630 }
631 }
632
633 DeletedPhis.erase(To);
634 }
635 assert(DeletedPhis.empty());
Nicolai Haehnle08230502018-10-17 15:37:41 +0000636
637 // Simplify any phis inserted by the SSAUpdater if possible
638 bool Changed;
639 do {
640 Changed = false;
641
642 SimplifyQuery Q(Func->getParent()->getDataLayout());
643 Q.DT = DT;
644 for (size_t i = 0; i < InsertedPhis.size(); ++i) {
645 PHINode *Phi = InsertedPhis[i];
646 if (Value *V = SimplifyInstruction(Phi, Q)) {
647 Phi->replaceAllUsesWith(V);
648 Phi->eraseFromParent();
649 InsertedPhis[i] = InsertedPhis.back();
650 InsertedPhis.pop_back();
651 i--;
652 Changed = true;
653 }
654 }
655 } while (Changed);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000656}
657
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000658/// Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000659void StructurizeCFG::killTerminator(BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000660 Instruction *Term = BB->getTerminator();
Tom Stellardf8794352012-12-19 22:10:31 +0000661 if (!Term)
662 return;
663
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000664 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000665 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000666 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000667
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000668 if (DA)
669 DA->removeValue(Term);
Tom Stellardf8794352012-12-19 22:10:31 +0000670 Term->eraseFromParent();
671}
672
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000673/// Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000674void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
675 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000676 if (Node->isSubRegion()) {
677 Region *SubRegion = Node->getNodeAs<Region>();
678 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000679 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000680
Tom Stellard7370ede2013-02-08 22:24:38 +0000681 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000682 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
683 // Incrememt BBI before mucking with BB's terminator.
684 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000685
Tom Stellard7370ede2013-02-08 22:24:38 +0000686 if (!SubRegion->contains(BB))
687 continue;
688
689 // Modify the edges to point to the new exit
690 delPhiValues(BB, OldExit);
691 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
692 addPhiValues(BB, NewExit);
693
694 // Find the new dominator (if requested)
695 if (IncludeDominator) {
696 if (!Dominator)
697 Dominator = BB;
698 else
699 Dominator = DT->findNearestCommonDominator(Dominator, BB);
700 }
Tom Stellardf8794352012-12-19 22:10:31 +0000701 }
702
Tom Stellard7370ede2013-02-08 22:24:38 +0000703 // Change the dominator (if requested)
704 if (Dominator)
705 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000706
Tom Stellard7370ede2013-02-08 22:24:38 +0000707 // Update the region info
708 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000709 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000710 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
711 killTerminator(BB);
712 BranchInst::Create(NewExit, BB);
713 addPhiValues(BB, NewExit);
714 if (IncludeDominator)
715 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000716 }
Tom Stellardf8794352012-12-19 22:10:31 +0000717}
718
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000719/// Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000720BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000721 LLVMContext &Context = Func->getContext();
722 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000723 Order.back()->getEntry();
Tom Stellardf8794352012-12-19 22:10:31 +0000724 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
725 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000726 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000727 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000728 return Flow;
729}
730
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000731/// Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000732BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000733 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000734
Christian Konigfc6a9852013-02-16 11:27:45 +0000735 if (!PrevNode->isSubRegion()) {
736 killTerminator(Entry);
737 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
738 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000739 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000740
Christian Konigfc6a9852013-02-16 11:27:45 +0000741 // create a new flow node
742 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000743
Christian Konigfc6a9852013-02-16 11:27:45 +0000744 // and wire it up
745 changeExit(PrevNode, Flow, true);
746 PrevNode = ParentRegion->getBBNode(Flow);
747 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000748}
749
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000750/// Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000751BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
752 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000753 if (!Order.empty() || !ExitUseAllowed)
754 return getNextFlow(Flow);
755
756 BasicBlock *Exit = ParentRegion->getExit();
757 DT->changeImmediateDominator(Exit, Flow);
758 addPhiValues(Flow, Exit);
759 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000760}
761
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000762/// Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000763void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000764 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
765 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000766}
767
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000768/// Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000769bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000770 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000771 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
772 return DT->dominates(BB, Pred.first);
773 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000774}
775
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000776/// Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000777bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000778 BBPredicates &Preds = Predicates[Node->getEntry()];
779 bool Dominated = false;
780
781 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000782 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000783 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000784
Justin Lebar3aec10c2016-11-28 18:50:03 +0000785 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
786 BasicBlock *BB = Pred.first;
787 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000788
Justin Lebar3aec10c2016-11-28 18:50:03 +0000789 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000790 return false;
791
Justin Lebar3aec10c2016-11-28 18:50:03 +0000792 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000793 Dominated = true;
794 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000795
796 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000797 return Dominated;
798}
799
Tom Stellard7370ede2013-02-08 22:24:38 +0000800/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000801void StructurizeCFG::wireFlow(bool ExitUseAllowed,
802 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000803 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000804 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000805
Christian Konigfc6a9852013-02-16 11:27:45 +0000806 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000807 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000808 if (PrevNode) {
809 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000810 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000811 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000812 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000813 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000814 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000815
Tom Stellard7370ede2013-02-08 22:24:38 +0000816 // Insert extra postfix node (or use exit instead)
817 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000818 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000819
820 // let it point to entry and next block
821 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
822 addPhiValues(Flow, Entry);
823 DT->changeImmediateDominator(Entry, Flow);
824
Christian Konigfc6a9852013-02-16 11:27:45 +0000825 PrevNode = Node;
826 while (!Order.empty() && !Visited.count(LoopEnd) &&
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000827 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000828 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000829 }
830
Christian Konigfc6a9852013-02-16 11:27:45 +0000831 changeExit(PrevNode, Next, false);
832 setPrevNode(Next);
833 }
834}
835
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000836void StructurizeCFG::handleLoops(bool ExitUseAllowed,
837 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000838 RegionNode *Node = Order.back();
Christian Konigfc6a9852013-02-16 11:27:45 +0000839 BasicBlock *LoopStart = Node->getEntry();
840
841 if (!Loops.count(LoopStart)) {
842 wireFlow(ExitUseAllowed, LoopEnd);
843 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000844 }
845
Christian Konigfc6a9852013-02-16 11:27:45 +0000846 if (!isPredictableTrue(Node))
847 LoopStart = needPrefix(true);
848
849 LoopEnd = Loops[Node->getEntry()];
850 wireFlow(false, LoopEnd);
851 while (!Visited.count(LoopEnd)) {
852 handleLoops(false, LoopEnd);
853 }
854
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000855 // If the start of the loop is the entry block, we can't branch to it so
856 // insert a new dummy entry block.
857 Function *LoopFunc = LoopStart->getParent();
858 if (LoopStart == &LoopFunc->getEntryBlock()) {
859 LoopStart->setName("entry.orig");
860
861 BasicBlock *NewEntry =
862 BasicBlock::Create(LoopStart->getContext(),
863 "entry",
864 LoopFunc,
865 LoopStart);
866 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000867 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000868 }
869
Christian Konigfc6a9852013-02-16 11:27:45 +0000870 // Create an extra loop end node
871 LoopEnd = needPrefix(false);
872 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
873 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
874 BoolUndef, LoopEnd));
875 addPhiValues(LoopEnd, LoopStart);
876 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000877}
878
Tom Stellardf8794352012-12-19 22:10:31 +0000879/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000880/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000881void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000882 BasicBlock *Exit = ParentRegion->getExit();
883 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
884
Tom Stellardf8794352012-12-19 22:10:31 +0000885 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000886 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000887 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000888 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000889
Craig Topperf40110f2014-04-25 05:29:35 +0000890 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000891 Visited.clear();
892
Tom Stellardf8794352012-12-19 22:10:31 +0000893 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000894 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000895 }
896
Christian Konigfc6a9852013-02-16 11:27:45 +0000897 if (PrevNode)
898 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000899 else
900 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000901}
902
Tom Stellardf8794352012-12-19 22:10:31 +0000903/// Handle a rare case where the disintegrated nodes instructions
Hiroshi Inouef2096492018-06-14 05:41:49 +0000904/// no longer dominate all their uses. Not sure if this is really necessary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000905void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000906 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000907 for (BasicBlock *BB : ParentRegion->blocks())
908 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000909 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000910 // We may modify the use list as we iterate over it, so be careful to
911 // compute the next element in the use list at the top of the loop.
912 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
913 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000914 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000915 if (User->getParent() == BB) {
916 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000917 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000918 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000919 continue;
920 }
921
Justin Lebar3aec10c2016-11-28 18:50:03 +0000922 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000923 continue;
924
925 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000926 Value *Undef = UndefValue::get(I.getType());
927 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000928 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000929 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000930 Initialized = true;
931 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000932 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000933 }
934 }
Tom Stellardf8794352012-12-19 22:10:31 +0000935}
936
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000937static bool hasOnlyUniformBranches(Region *R, unsigned UniformMDKindID,
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000938 const LegacyDivergenceAnalysis &DA) {
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000939 for (auto E : R->elements()) {
940 if (!E->isSubRegion()) {
941 auto Br = dyn_cast<BranchInst>(E->getEntry()->getTerminator());
942 if (!Br || !Br->isConditional())
943 continue;
Tom Stellard755a4e62016-02-10 00:39:37 +0000944
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000945 if (!DA.isUniform(Br))
946 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000947 LLVM_DEBUG(dbgs() << "BB: " << Br->getParent()->getName()
948 << " has uniform terminator\n");
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000949 } else {
950 // Explicitly refuse to treat regions as uniform if they have non-uniform
951 // subregions. We cannot rely on DivergenceAnalysis for branches in
952 // subregions because those branches may have been removed and re-created,
953 // so we look for our metadata instead.
954 //
955 // Warning: It would be nice to treat regions as uniform based only on
956 // their direct child basic blocks' terminators, regardless of whether
957 // subregions are uniform or not. However, this requires a very careful
958 // look at SIAnnotateControlFlow to make sure nothing breaks there.
959 for (auto BB : E->getNodeAs<Region>()->blocks()) {
960 auto Br = dyn_cast<BranchInst>(BB->getTerminator());
961 if (!Br || !Br->isConditional())
962 continue;
963
964 if (!Br->getMetadata(UniformMDKindID))
965 return false;
966 }
967 }
Tom Stellard755a4e62016-02-10 00:39:37 +0000968 }
969 return true;
970}
971
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000972/// Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000973bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000974 if (R->isTopLevelRegion())
975 return false;
976
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000977 DA = nullptr;
978
Tom Stellard755a4e62016-02-10 00:39:37 +0000979 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000980 // TODO: We could probably be smarter here with how we handle sub-regions.
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000981 // We currently rely on the fact that metadata is set by earlier invocations
982 // of the pass on sub-regions, and that this metadata doesn't get lost --
983 // but we shouldn't rely on metadata for correctness!
984 unsigned UniformMDKindID =
985 R->getEntry()->getContext().getMDKindID("structurizecfg.uniform");
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000986 DA = &getAnalysis<LegacyDivergenceAnalysis>();
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000987
988 if (hasOnlyUniformBranches(R, UniformMDKindID, *DA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000989 LLVM_DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R
990 << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000991
992 // Mark all direct child block terminators as having been treated as
993 // uniform. To account for a possible future in which non-uniform
994 // sub-regions are treated more cleverly, indirect children are not
995 // marked as uniform.
996 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000997 for (RegionNode *E : R->elements()) {
998 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000999 continue;
1000
Justin Lebar1b60d702016-11-22 23:13:37 +00001001 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +00001002 Term->setMetadata(UniformMDKindID, MD);
Nicolai Haehnle05b127d2016-04-14 17:42:35 +00001003 }
1004
Tom Stellard755a4e62016-02-10 00:39:37 +00001005 return false;
1006 }
1007 }
1008
Tom Stellardf8794352012-12-19 22:10:31 +00001009 Func = R->getEntry()->getParent();
1010 ParentRegion = R;
1011
Chandler Carruth73523022014-01-13 13:07:17 +00001012 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +00001013 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +00001014
1015 orderNodes();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +00001016 collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +00001017 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +00001018 insertConditions(false);
1019 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +00001020 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +00001021 rebuildSSA();
1022
Tom Stellard048f14f2013-02-08 22:24:37 +00001023 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +00001024 Order.clear();
1025 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001026 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +00001027 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001028 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +00001029 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001030 Loops.clear();
1031 LoopPreds.clear();
1032 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001033
1034 return true;
1035}
1036
Tom Stellard755a4e62016-02-10 00:39:37 +00001037Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
1038 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +00001039}