blob: d028edaf986c59e71ea650c6d1224a909ba7c603 [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 Stellard0f29de72015-02-05 15:32:15 +000017#include "llvm/Analysis/LoopInfo.h"
Tom Stellardb0804ec2013-06-07 20:28:43 +000018#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000019#include "llvm/IR/Dominators.h"
Tom Stellardb0804ec2013-06-07 20:28:43 +000020#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Module.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000022#include "llvm/Pass.h"
23#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tom Stellardf8794352012-12-19 22:10:31 +000024#include "llvm/Transforms/Utils/SSAUpdater.h"
25
26using namespace llvm;
27
Chandler Carruth84e68b22014-04-22 02:41:26 +000028#define DEBUG_TYPE "si-annotate-control-flow"
29
Tom Stellardf8794352012-12-19 22:10:31 +000030namespace {
31
32// Complex types used in this pass
33typedef std::pair<BasicBlock *, Value *> StackEntry;
34typedef SmallVector<StackEntry, 16> StackVector;
35
36// Intrinsic names the control flow is annotated with
Matt Arsenault7898b902016-01-22 18:42:55 +000037static const char *const IfIntrinsic = "llvm.amdgcn.if";
38static const char *const ElseIntrinsic = "llvm.amdgcn.else";
39static const char *const BreakIntrinsic = "llvm.amdgcn.break";
40static const char *const IfBreakIntrinsic = "llvm.amdgcn.if.break";
41static const char *const ElseBreakIntrinsic = "llvm.amdgcn.else.break";
42static const char *const LoopIntrinsic = "llvm.amdgcn.loop";
43static const char *const EndCfIntrinsic = "llvm.amdgcn.end.cf";
Tom Stellardf8794352012-12-19 22:10:31 +000044
45class SIAnnotateControlFlow : public FunctionPass {
46
Tom Stellardf8794352012-12-19 22:10:31 +000047 Type *Boolean;
48 Type *Void;
49 Type *Int64;
50 Type *ReturnStruct;
51
52 ConstantInt *BoolTrue;
53 ConstantInt *BoolFalse;
54 UndefValue *BoolUndef;
55 Constant *Int64Zero;
56
57 Constant *If;
58 Constant *Else;
59 Constant *Break;
60 Constant *IfBreak;
61 Constant *ElseBreak;
62 Constant *Loop;
63 Constant *EndCf;
64
65 DominatorTree *DT;
66 StackVector Stack;
Tom Stellardf8794352012-12-19 22:10:31 +000067
Tom Stellard0f29de72015-02-05 15:32:15 +000068 LoopInfo *LI;
69
Tom Stellardf8794352012-12-19 22:10:31 +000070 bool isTopOfStack(BasicBlock *BB);
71
72 Value *popSaved();
73
74 void push(BasicBlock *BB, Value *Saved);
75
76 bool isElse(PHINode *Phi);
77
78 void eraseIfUnused(PHINode *Phi);
79
80 void openIf(BranchInst *Term);
81
82 void insertElse(BranchInst *Term);
83
Changpeng Fange07f1aa2016-02-12 17:11:04 +000084 Value *handleLoopCondition(Value *Cond, PHINode *Broken,
85 llvm::Loop *L, BranchInst *Term);
Tom Stellardf8794352012-12-19 22:10:31 +000086
87 void handleLoop(BranchInst *Term);
88
89 void closeControlFlow(BasicBlock *BB);
90
91public:
Tom Stellard77a17772016-01-20 15:48:27 +000092 static char ID;
93
Tom Stellardf8794352012-12-19 22:10:31 +000094 SIAnnotateControlFlow():
95 FunctionPass(ID) { }
96
Craig Topper5656db42014-04-29 07:57:24 +000097 bool doInitialization(Module &M) override;
Tom Stellardf8794352012-12-19 22:10:31 +000098
Craig Topper5656db42014-04-29 07:57:24 +000099 bool runOnFunction(Function &F) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000100
Craig Topper5656db42014-04-29 07:57:24 +0000101 const char *getPassName() const override {
Tom Stellardf8794352012-12-19 22:10:31 +0000102 return "SI annotate control flow";
103 }
104
Craig Topper5656db42014-04-29 07:57:24 +0000105 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard0f29de72015-02-05 15:32:15 +0000106 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000107 AU.addRequired<DominatorTreeWrapperPass>();
108 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000109 FunctionPass::getAnalysisUsage(AU);
110 }
111
112};
113
114} // end anonymous namespace
115
Tom Stellard77a17772016-01-20 15:48:27 +0000116INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
117 "Annotate SI Control Flow", false, false)
118INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
119 "Annotate SI Control Flow", false, false)
120
Tom Stellardf8794352012-12-19 22:10:31 +0000121char SIAnnotateControlFlow::ID = 0;
122
123/// \brief Initialize all the types and constants used in the pass
124bool SIAnnotateControlFlow::doInitialization(Module &M) {
Tom Stellardf8794352012-12-19 22:10:31 +0000125 LLVMContext &Context = M.getContext();
126
127 Void = Type::getVoidTy(Context);
128 Boolean = Type::getInt1Ty(Context);
129 Int64 = Type::getInt64Ty(Context);
Craig Topper062a2ba2014-04-25 05:30:21 +0000130 ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000131
132 BoolTrue = ConstantInt::getTrue(Context);
133 BoolFalse = ConstantInt::getFalse(Context);
134 BoolUndef = UndefValue::get(Boolean);
135 Int64Zero = ConstantInt::get(Int64, 0);
136
137 If = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000138 IfIntrinsic, ReturnStruct, Boolean, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000139
140 Else = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000141 ElseIntrinsic, ReturnStruct, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000142
143 Break = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000144 BreakIntrinsic, Int64, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000145
146 IfBreak = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000147 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000148
149 ElseBreak = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000150 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000151
152 Loop = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000153 LoopIntrinsic, Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000154
155 EndCf = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000156 EndCfIntrinsic, Void, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000157
158 return false;
159}
160
161/// \brief Is BB the last block saved on the stack ?
162bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
Michel Danzerae0a4032013-02-14 08:00:33 +0000163 return !Stack.empty() && Stack.back().first == BB;
Tom Stellardf8794352012-12-19 22:10:31 +0000164}
165
166/// \brief Pop the last saved value from the control flow stack
167Value *SIAnnotateControlFlow::popSaved() {
168 return Stack.pop_back_val().second;
169}
170
171/// \brief Push a BB and saved value to the control flow stack
172void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
173 Stack.push_back(std::make_pair(BB, Saved));
174}
175
176/// \brief Can the condition represented by this PHI node treated like
177/// an "Else" block?
178bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
Tom Stellardf8794352012-12-19 22:10:31 +0000179 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
180 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
181 if (Phi->getIncomingBlock(i) == IDom) {
182
183 if (Phi->getIncomingValue(i) != BoolTrue)
184 return false;
185
186 } else {
187 if (Phi->getIncomingValue(i) != BoolFalse)
188 return false;
Tom Stellardde16a2e2014-06-20 17:06:02 +0000189
Tom Stellardf8794352012-12-19 22:10:31 +0000190 }
191 }
192 return true;
193}
194
195// \brief Erase "Phi" if it is not used any more
196void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
197 if (!Phi->hasNUsesOrMore(1))
198 Phi->eraseFromParent();
199}
200
201/// \brief Open a new "If" block
202void SIAnnotateControlFlow::openIf(BranchInst *Term) {
203 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
204 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
205 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
206}
207
208/// \brief Close the last "If" block and open a new "Else" block
209void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
210 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
211 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
212 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
213}
214
215/// \brief Recursively handle the condition leading to a loop
Tom Stellardd4a19502015-04-14 14:36:45 +0000216Value *SIAnnotateControlFlow::handleLoopCondition(Value *Cond, PHINode *Broken,
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000217 llvm::Loop *L, BranchInst *Term) {
Tom Stellard0b7feb12015-05-01 03:44:08 +0000218
219 // Only search through PHI nodes which are inside the loop. If we try this
220 // with PHI nodes that are outside of the loop, we end up inserting new PHI
221 // nodes outside of the loop which depend on values defined inside the loop.
222 // This will break the module with
223 // 'Instruction does not dominate all users!' errors.
224 PHINode *Phi = nullptr;
225 if ((Phi = dyn_cast<PHINode>(Cond)) && L->contains(Phi)) {
226
Tom Stellardde16a2e2014-06-20 17:06:02 +0000227 BasicBlock *Parent = Phi->getParent();
228 PHINode *NewPhi = PHINode::Create(Int64, 0, "", &Parent->front());
229 Value *Ret = NewPhi;
Tom Stellardf8794352012-12-19 22:10:31 +0000230
Alp Tokerf907b892013-12-05 05:44:44 +0000231 // Handle all non-constant incoming values first
Tom Stellardf8794352012-12-19 22:10:31 +0000232 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
233 Value *Incoming = Phi->getIncomingValue(i);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000234 BasicBlock *From = Phi->getIncomingBlock(i);
235 if (isa<ConstantInt>(Incoming)) {
236 NewPhi->addIncoming(Broken, From);
Tom Stellardf8794352012-12-19 22:10:31 +0000237 continue;
Tom Stellardde16a2e2014-06-20 17:06:02 +0000238 }
Tom Stellardf8794352012-12-19 22:10:31 +0000239
240 Phi->setIncomingValue(i, BoolFalse);
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000241 Value *PhiArg = handleLoopCondition(Incoming, Broken, L, Term);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000242 NewPhi->addIncoming(PhiArg, From);
Tom Stellardf8794352012-12-19 22:10:31 +0000243 }
244
Tom Stellardf8794352012-12-19 22:10:31 +0000245 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
246
247 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
248
249 Value *Incoming = Phi->getIncomingValue(i);
250 if (Incoming != BoolTrue)
251 continue;
252
253 BasicBlock *From = Phi->getIncomingBlock(i);
254 if (From == IDom) {
255 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
256 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
Tom Stellardde16a2e2014-06-20 17:06:02 +0000257 Value *Args[] = { OldEnd->getArgOperand(0), NewPhi };
258 Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000259 continue;
260 }
261 }
Tom Stellardf8794352012-12-19 22:10:31 +0000262 TerminatorInst *Insert = From->getTerminator();
Tom Stellardde16a2e2014-06-20 17:06:02 +0000263 Value *PhiArg = CallInst::Create(Break, Broken, "", Insert);
264 NewPhi->setIncomingValue(i, PhiArg);
Tom Stellardf8794352012-12-19 22:10:31 +0000265 }
266 eraseIfUnused(Phi);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000267 return Ret;
Tom Stellardf8794352012-12-19 22:10:31 +0000268
269 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
270 BasicBlock *Parent = Inst->getParent();
Tom Stellardd4a19502015-04-14 14:36:45 +0000271 Instruction *Insert;
272 if (L->contains(Inst)) {
273 Insert = Parent->getTerminator();
274 } else {
275 Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
276 }
Tom Stellardde16a2e2014-06-20 17:06:02 +0000277 Value *Args[] = { Cond, Broken };
278 return CallInst::Create(IfBreak, Args, "", Insert);
Tom Stellardf8794352012-12-19 22:10:31 +0000279
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000280 // Insert IfBreak before TERM for constant COND.
281 } else if (isa<ConstantInt>(Cond)) {
282 Value *Args[] = { Cond, Broken };
283 return CallInst::Create(IfBreak, Args, "", Term);
284
Tom Stellardf8794352012-12-19 22:10:31 +0000285 } else {
Matt Arsenaulteaa3a7e2013-12-10 21:37:42 +0000286 llvm_unreachable("Unhandled loop condition!");
Tom Stellardf8794352012-12-19 22:10:31 +0000287 }
Tom Stellardde16a2e2014-06-20 17:06:02 +0000288 return 0;
Tom Stellardf8794352012-12-19 22:10:31 +0000289}
290
291/// \brief Handle a back edge (loop)
292void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
Tom Stellardd4a19502015-04-14 14:36:45 +0000293 BasicBlock *BB = Term->getParent();
294 llvm::Loop *L = LI->getLoopFor(BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000295 BasicBlock *Target = Term->getSuccessor(1);
296 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
297
Tom Stellardf8794352012-12-19 22:10:31 +0000298 Value *Cond = Term->getCondition();
299 Term->setCondition(BoolTrue);
Changpeng Fange07f1aa2016-02-12 17:11:04 +0000300 Value *Arg = handleLoopCondition(Cond, Broken, L, Term);
Tom Stellardf8794352012-12-19 22:10:31 +0000301
Tom Stellardf8794352012-12-19 22:10:31 +0000302 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
303 PI != PE; ++PI) {
304
305 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
306 }
307
308 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
309 push(Term->getSuccessor(0), Arg);
Tom Stellard0f29de72015-02-05 15:32:15 +0000310}/// \brief Close the last opened control flow
Tom Stellardf8794352012-12-19 22:10:31 +0000311void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
Tom Stellard0f29de72015-02-05 15:32:15 +0000312 llvm::Loop *L = LI->getLoopFor(BB);
313
314 if (L && L->getHeader() == BB) {
315 // We can't insert an EndCF call into a loop header, because it will
316 // get executed on every iteration of the loop, when it should be
317 // executed only once before the loop.
318 SmallVector <BasicBlock*, 8> Latches;
319 L->getLoopLatches(Latches);
320
321 std::vector<BasicBlock*> Preds;
322 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
323 if (std::find(Latches.begin(), Latches.end(), *PI) == Latches.end())
324 Preds.push_back(*PI);
325 }
Chandler Carruth96ada252015-07-22 09:52:54 +0000326 BB = llvm::SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, false);
Tom Stellard0f29de72015-02-05 15:32:15 +0000327 }
328
Duncan P. N. Exon Smitha73371a2015-10-13 20:07:10 +0000329 CallInst::Create(EndCf, popSaved(), "", &*BB->getFirstInsertionPt());
Tom Stellardf8794352012-12-19 22:10:31 +0000330}
331
332/// \brief Annotate the control flow with intrinsics so the backend can
333/// recognize if/then/else and loops.
334bool SIAnnotateControlFlow::runOnFunction(Function &F) {
Chandler Carruth73523022014-01-13 13:07:17 +0000335 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tom Stellard0f29de72015-02-05 15:32:15 +0000336 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000337
338 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
339 E = df_end(&F.getEntryBlock()); I != E; ++I) {
340
341 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
342
343 if (!Term || Term->isUnconditional()) {
344 if (isTopOfStack(*I))
345 closeControlFlow(*I);
346 continue;
347 }
348
349 if (I.nodeVisited(Term->getSuccessor(1))) {
350 if (isTopOfStack(*I))
351 closeControlFlow(*I);
352 handleLoop(Term);
353 continue;
354 }
355
356 if (isTopOfStack(*I)) {
357 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
358 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
359 insertElse(Term);
360 eraseIfUnused(Phi);
361 continue;
362 }
363 closeControlFlow(*I);
364 }
365 openIf(Term);
366 }
367
368 assert(Stack.empty());
369 return true;
370}
371
372/// \brief Create the annotation pass
373FunctionPass *llvm::createSIAnnotateControlFlowPass() {
Tom Stellardf8794352012-12-19 22:10:31 +0000374 return new SIAnnotateControlFlow();
375}