blob: 3009564f85431e44e5f517204b0c82de52d5dbcf [file] [log] [blame]
Tom Stellardf8794352012-12-19 22:10:31 +00001//===-- SIAnnotateControlFlow.cpp - ------------------===//
2//
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//===----------------------------------------------------------------------===//
9//
10/// \file
11/// Annotates the control flow with hardware specific intrinsics.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AMDGPU.h"
Tom Stellardf8794352012-12-19 22:10:31 +000016#include "llvm/ADT/DepthFirstIterator.h"
Tom Stellardbc4497b2016-02-12 23:45:29 +000017#include "llvm/Analysis/DivergenceAnalysis.h"
Tom Stellard0f29de72015-02-05 15:32:15 +000018#include "llvm/Analysis/LoopInfo.h"
Tom Stellardb0804ec2013-06-07 20:28:43 +000019#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000020#include "llvm/IR/Dominators.h"
Tom Stellardb0804ec2013-06-07 20:28:43 +000021#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Module.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000023#include "llvm/Pass.h"
24#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tom Stellardf8794352012-12-19 22:10:31 +000025#include "llvm/Transforms/Utils/SSAUpdater.h"
26
27using namespace llvm;
28
Chandler Carruth84e68b22014-04-22 02:41:26 +000029#define DEBUG_TYPE "si-annotate-control-flow"
30
Tom Stellardf8794352012-12-19 22:10:31 +000031namespace {
32
33// Complex types used in this pass
34typedef std::pair<BasicBlock *, Value *> StackEntry;
35typedef SmallVector<StackEntry, 16> StackVector;
36
37// Intrinsic names the control flow is annotated with
Matt Arsenault7898b902016-01-22 18:42:55 +000038static const char *const IfIntrinsic = "llvm.amdgcn.if";
39static const char *const ElseIntrinsic = "llvm.amdgcn.else";
40static const char *const BreakIntrinsic = "llvm.amdgcn.break";
41static const char *const IfBreakIntrinsic = "llvm.amdgcn.if.break";
42static const char *const ElseBreakIntrinsic = "llvm.amdgcn.else.break";
43static const char *const LoopIntrinsic = "llvm.amdgcn.loop";
44static const char *const EndCfIntrinsic = "llvm.amdgcn.end.cf";
Tom Stellardf8794352012-12-19 22:10:31 +000045
46class SIAnnotateControlFlow : public FunctionPass {
Tom Stellardbc4497b2016-02-12 23:45:29 +000047 DivergenceAnalysis *DA;
Tom Stellardf8794352012-12-19 22:10:31 +000048
Tom Stellardf8794352012-12-19 22:10:31 +000049 Type *Boolean;
50 Type *Void;
51 Type *Int64;
52 Type *ReturnStruct;
53
54 ConstantInt *BoolTrue;
55 ConstantInt *BoolFalse;
56 UndefValue *BoolUndef;
57 Constant *Int64Zero;
58
59 Constant *If;
60 Constant *Else;
61 Constant *Break;
62 Constant *IfBreak;
63 Constant *ElseBreak;
64 Constant *Loop;
65 Constant *EndCf;
66
67 DominatorTree *DT;
68 StackVector Stack;
Tom Stellardf8794352012-12-19 22:10:31 +000069
Tom Stellard0f29de72015-02-05 15:32:15 +000070 LoopInfo *LI;
71
Tom Stellardf8794352012-12-19 22:10:31 +000072 bool isTopOfStack(BasicBlock *BB);
73
74 Value *popSaved();
75
76 void push(BasicBlock *BB, Value *Saved);
77
78 bool isElse(PHINode *Phi);
79
80 void eraseIfUnused(PHINode *Phi);
81
82 void openIf(BranchInst *Term);
83
84 void insertElse(BranchInst *Term);
85
Changpeng Fange07f1aa2016-02-12 17:11:04 +000086 Value *handleLoopCondition(Value *Cond, PHINode *Broken,
87 llvm::Loop *L, BranchInst *Term);
Tom Stellardf8794352012-12-19 22:10:31 +000088
89 void handleLoop(BranchInst *Term);
90
91 void closeControlFlow(BasicBlock *BB);
92
93public:
Tom Stellard77a17772016-01-20 15:48:27 +000094 static char ID;
95
Tom Stellardf8794352012-12-19 22:10:31 +000096 SIAnnotateControlFlow():
97 FunctionPass(ID) { }
98
Craig Topper5656db42014-04-29 07:57:24 +000099 bool doInitialization(Module &M) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000100
Craig Topper5656db42014-04-29 07:57:24 +0000101 bool runOnFunction(Function &F) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000102
Craig Topper5656db42014-04-29 07:57:24 +0000103 const char *getPassName() const override {
Tom Stellardf8794352012-12-19 22:10:31 +0000104 return "SI annotate control flow";
105 }
106
Craig Topper5656db42014-04-29 07:57:24 +0000107 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard0f29de72015-02-05 15:32:15 +0000108 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000109 AU.addRequired<DominatorTreeWrapperPass>();
Tom Stellardbc4497b2016-02-12 23:45:29 +0000110 AU.addRequired<DivergenceAnalysis>();
Chandler Carruth73523022014-01-13 13:07:17 +0000111 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000112 FunctionPass::getAnalysisUsage(AU);
113 }
114
115};
116
117} // end anonymous namespace
118
Tom Stellard77a17772016-01-20 15:48:27 +0000119INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
120 "Annotate SI Control Flow", false, false)
Tom Stellardbc4497b2016-02-12 23:45:29 +0000121INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
Tom Stellard77a17772016-01-20 15:48:27 +0000122INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
123 "Annotate SI Control Flow", false, false)
124
Tom Stellardf8794352012-12-19 22:10:31 +0000125char SIAnnotateControlFlow::ID = 0;
126
127/// \brief Initialize all the types and constants used in the pass
128bool SIAnnotateControlFlow::doInitialization(Module &M) {
Tom Stellardf8794352012-12-19 22:10:31 +0000129 LLVMContext &Context = M.getContext();
130
131 Void = Type::getVoidTy(Context);
132 Boolean = Type::getInt1Ty(Context);
133 Int64 = Type::getInt64Ty(Context);
Craig Topper062a2ba2014-04-25 05:30:21 +0000134 ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000135
136 BoolTrue = ConstantInt::getTrue(Context);
137 BoolFalse = ConstantInt::getFalse(Context);
138 BoolUndef = UndefValue::get(Boolean);
139 Int64Zero = ConstantInt::get(Int64, 0);
140
141 If = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000142 IfIntrinsic, ReturnStruct, Boolean, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000143
144 Else = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000145 ElseIntrinsic, ReturnStruct, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000146
147 Break = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000148 BreakIntrinsic, Int64, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000149
150 IfBreak = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000151 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000152
153 ElseBreak = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000154 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000155
156 Loop = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000157 LoopIntrinsic, Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000158
159 EndCf = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000160 EndCfIntrinsic, Void, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000161
162 return false;
163}
164
165/// \brief Is BB the last block saved on the stack ?
166bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
Michel Danzerae0a4032013-02-14 08:00:33 +0000167 return !Stack.empty() && Stack.back().first == BB;
Tom Stellardf8794352012-12-19 22:10:31 +0000168}
169
170/// \brief Pop the last saved value from the control flow stack
171Value *SIAnnotateControlFlow::popSaved() {
172 return Stack.pop_back_val().second;
173}
174
175/// \brief Push a BB and saved value to the control flow stack
176void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
177 Stack.push_back(std::make_pair(BB, Saved));
178}
179
180/// \brief Can the condition represented by this PHI node treated like
181/// an "Else" block?
182bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
Tom Stellardf8794352012-12-19 22:10:31 +0000183 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
184 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
185 if (Phi->getIncomingBlock(i) == IDom) {
186
187 if (Phi->getIncomingValue(i) != BoolTrue)
188 return false;
189
190 } else {
191 if (Phi->getIncomingValue(i) != BoolFalse)
192 return false;
Tom Stellardde16a2e2014-06-20 17:06:02 +0000193
Tom Stellardf8794352012-12-19 22:10:31 +0000194 }
195 }
196 return true;
197}
198
199// \brief Erase "Phi" if it is not used any more
200void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
201 if (!Phi->hasNUsesOrMore(1))
202 Phi->eraseFromParent();
203}
204
205/// \brief Open a new "If" block
206void SIAnnotateControlFlow::openIf(BranchInst *Term) {
Tom Stellardbc4497b2016-02-12 23:45:29 +0000207 if (DA->isUniform(Term->getCondition())) {
208 return;
209 }
Tom Stellardf8794352012-12-19 22:10:31 +0000210 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
211 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
212 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
213}
214
215/// \brief Close the last "If" block and open a new "Else" block
216void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
Tom Stellardbc4497b2016-02-12 23:45:29 +0000217 if (DA->isUniform(Term->getCondition())) {
218 return;
219 }
Tom Stellardf8794352012-12-19 22:10:31 +0000220 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
221 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
222 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
223}
224
225/// \brief Recursively handle the condition leading to a loop
Tom Stellardd4a19502015-04-14 14:36:45 +0000226Value *SIAnnotateControlFlow::handleLoopCondition(Value *Cond, PHINode *Broken,
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000227 llvm::Loop *L, BranchInst *Term) {
Tom Stellard0b7feb12015-05-01 03:44:08 +0000228
229 // Only search through PHI nodes which are inside the loop. If we try this
230 // with PHI nodes that are outside of the loop, we end up inserting new PHI
231 // nodes outside of the loop which depend on values defined inside the loop.
232 // This will break the module with
233 // 'Instruction does not dominate all users!' errors.
234 PHINode *Phi = nullptr;
235 if ((Phi = dyn_cast<PHINode>(Cond)) && L->contains(Phi)) {
236
Tom Stellardde16a2e2014-06-20 17:06:02 +0000237 BasicBlock *Parent = Phi->getParent();
238 PHINode *NewPhi = PHINode::Create(Int64, 0, "", &Parent->front());
239 Value *Ret = NewPhi;
Tom Stellardf8794352012-12-19 22:10:31 +0000240
Alp Tokerf907b892013-12-05 05:44:44 +0000241 // Handle all non-constant incoming values first
Tom Stellardf8794352012-12-19 22:10:31 +0000242 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
243 Value *Incoming = Phi->getIncomingValue(i);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000244 BasicBlock *From = Phi->getIncomingBlock(i);
245 if (isa<ConstantInt>(Incoming)) {
246 NewPhi->addIncoming(Broken, From);
Tom Stellardf8794352012-12-19 22:10:31 +0000247 continue;
Tom Stellardde16a2e2014-06-20 17:06:02 +0000248 }
Tom Stellardf8794352012-12-19 22:10:31 +0000249
250 Phi->setIncomingValue(i, BoolFalse);
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000251 Value *PhiArg = handleLoopCondition(Incoming, Broken, L, Term);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000252 NewPhi->addIncoming(PhiArg, From);
Tom Stellardf8794352012-12-19 22:10:31 +0000253 }
254
Tom Stellardf8794352012-12-19 22:10:31 +0000255 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
256
257 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
258
259 Value *Incoming = Phi->getIncomingValue(i);
260 if (Incoming != BoolTrue)
261 continue;
262
263 BasicBlock *From = Phi->getIncomingBlock(i);
264 if (From == IDom) {
Nicolai Haehnle279970c2016-04-12 16:10:38 +0000265 // We're in the following situation:
266 // IDom/From
267 // | \
268 // | If-block
269 // | /
270 // Parent
271 // where we want to break out of the loop if the If-block is not taken.
272 // Due to the depth-first traversal, there should be an end.cf
273 // intrinsic in Parent, and we insert an else.break before it.
274 //
275 // Note that the end.cf need not be the first non-phi instruction
276 // of parent, particularly when we're dealing with a multi-level
277 // break, but it should occur within a group of intrinsic calls
278 // at the beginning of the block.
Tom Stellardf8794352012-12-19 22:10:31 +0000279 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
Nicolai Haehnle279970c2016-04-12 16:10:38 +0000280 while (OldEnd && OldEnd->getCalledFunction() != EndCf)
281 OldEnd = dyn_cast<CallInst>(OldEnd->getNextNode());
Tom Stellardf8794352012-12-19 22:10:31 +0000282 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
Tom Stellardde16a2e2014-06-20 17:06:02 +0000283 Value *Args[] = { OldEnd->getArgOperand(0), NewPhi };
284 Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000285 continue;
286 }
287 }
Tom Stellardf8794352012-12-19 22:10:31 +0000288 TerminatorInst *Insert = From->getTerminator();
Tom Stellardde16a2e2014-06-20 17:06:02 +0000289 Value *PhiArg = CallInst::Create(Break, Broken, "", Insert);
290 NewPhi->setIncomingValue(i, PhiArg);
Tom Stellardf8794352012-12-19 22:10:31 +0000291 }
292 eraseIfUnused(Phi);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000293 return Ret;
Tom Stellardf8794352012-12-19 22:10:31 +0000294
295 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
296 BasicBlock *Parent = Inst->getParent();
Tom Stellardd4a19502015-04-14 14:36:45 +0000297 Instruction *Insert;
298 if (L->contains(Inst)) {
299 Insert = Parent->getTerminator();
300 } else {
301 Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
302 }
Tom Stellardde16a2e2014-06-20 17:06:02 +0000303 Value *Args[] = { Cond, Broken };
304 return CallInst::Create(IfBreak, Args, "", Insert);
Tom Stellardf8794352012-12-19 22:10:31 +0000305
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000306 // Insert IfBreak before TERM for constant COND.
307 } else if (isa<ConstantInt>(Cond)) {
308 Value *Args[] = { Cond, Broken };
309 return CallInst::Create(IfBreak, Args, "", Term);
310
Tom Stellardf8794352012-12-19 22:10:31 +0000311 } else {
Matt Arsenaulteaa3a7e2013-12-10 21:37:42 +0000312 llvm_unreachable("Unhandled loop condition!");
Tom Stellardf8794352012-12-19 22:10:31 +0000313 }
Tom Stellardde16a2e2014-06-20 17:06:02 +0000314 return 0;
Tom Stellardf8794352012-12-19 22:10:31 +0000315}
316
317/// \brief Handle a back edge (loop)
318void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
Tom Stellardbc4497b2016-02-12 23:45:29 +0000319 if (DA->isUniform(Term->getCondition())) {
320 return;
321 }
322
Tom Stellardd4a19502015-04-14 14:36:45 +0000323 BasicBlock *BB = Term->getParent();
324 llvm::Loop *L = LI->getLoopFor(BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000325 BasicBlock *Target = Term->getSuccessor(1);
326 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
327
Tom Stellardf8794352012-12-19 22:10:31 +0000328 Value *Cond = Term->getCondition();
329 Term->setCondition(BoolTrue);
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000330 Value *Arg = handleLoopCondition(Cond, Broken, L, Term);
Tom Stellardf8794352012-12-19 22:10:31 +0000331
Tom Stellardf8794352012-12-19 22:10:31 +0000332 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
333 PI != PE; ++PI) {
334
335 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
336 }
337
338 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
339 push(Term->getSuccessor(0), Arg);
Tom Stellard0f29de72015-02-05 15:32:15 +0000340}/// \brief Close the last opened control flow
Tom Stellardf8794352012-12-19 22:10:31 +0000341void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
Tom Stellard0f29de72015-02-05 15:32:15 +0000342 llvm::Loop *L = LI->getLoopFor(BB);
343
Nicolai Haehnle19f0f512016-04-14 17:42:18 +0000344 assert(Stack.back().first == BB);
Tom Stellardbc4497b2016-02-12 23:45:29 +0000345
Tom Stellard0f29de72015-02-05 15:32:15 +0000346 if (L && L->getHeader() == BB) {
347 // We can't insert an EndCF call into a loop header, because it will
348 // get executed on every iteration of the loop, when it should be
349 // executed only once before the loop.
350 SmallVector <BasicBlock*, 8> Latches;
351 L->getLoopLatches(Latches);
352
353 std::vector<BasicBlock*> Preds;
354 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
355 if (std::find(Latches.begin(), Latches.end(), *PI) == Latches.end())
356 Preds.push_back(*PI);
357 }
Chandler Carruth96ada252015-07-22 09:52:54 +0000358 BB = llvm::SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, false);
Tom Stellard0f29de72015-02-05 15:32:15 +0000359 }
360
Tom Stellardbc4497b2016-02-12 23:45:29 +0000361 Value *Exec = popSaved();
362 if (!isa<UndefValue>(Exec))
363 CallInst::Create(EndCf, Exec, "", &*BB->getFirstInsertionPt());
Tom Stellardf8794352012-12-19 22:10:31 +0000364}
365
366/// \brief Annotate the control flow with intrinsics so the backend can
367/// recognize if/then/else and loops.
368bool SIAnnotateControlFlow::runOnFunction(Function &F) {
Tom Stellardbc4497b2016-02-12 23:45:29 +0000369
Chandler Carruth73523022014-01-13 13:07:17 +0000370 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tom Stellard0f29de72015-02-05 15:32:15 +0000371 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardbc4497b2016-02-12 23:45:29 +0000372 DA = &getAnalysis<DivergenceAnalysis>();
Tom Stellardf8794352012-12-19 22:10:31 +0000373
374 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
375 E = df_end(&F.getEntryBlock()); I != E; ++I) {
376
377 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
378
379 if (!Term || Term->isUnconditional()) {
380 if (isTopOfStack(*I))
381 closeControlFlow(*I);
Tom Stellardbc4497b2016-02-12 23:45:29 +0000382
Tom Stellardf8794352012-12-19 22:10:31 +0000383 continue;
384 }
385
386 if (I.nodeVisited(Term->getSuccessor(1))) {
387 if (isTopOfStack(*I))
388 closeControlFlow(*I);
Tom Stellardbc4497b2016-02-12 23:45:29 +0000389
Tom Stellardf8794352012-12-19 22:10:31 +0000390 handleLoop(Term);
391 continue;
392 }
393
394 if (isTopOfStack(*I)) {
395 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
396 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
397 insertElse(Term);
398 eraseIfUnused(Phi);
399 continue;
400 }
401 closeControlFlow(*I);
402 }
403 openIf(Term);
404 }
405
406 assert(Stack.empty());
407 return true;
408}
409
410/// \brief Create the annotation pass
411FunctionPass *llvm::createSIAnnotateControlFlowPass() {
Tom Stellardf8794352012-12-19 22:10:31 +0000412 return new SIAnnotateControlFlow();
413}