R600: New control flow for SI v2
[oota-llvm.git] / lib / Target / R600 / SIAnnotateControlFlow.cpp
1 //===-- 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"
16
17 #include "llvm/Pass.h"
18 #include "llvm/Module.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/Transforms/Utils/SSAUpdater.h"
23
24 using namespace llvm;
25
26 namespace {
27
28 // Complex types used in this pass
29 typedef std::pair<BasicBlock *, Value *> StackEntry;
30 typedef SmallVector<StackEntry, 16> StackVector;
31
32 // Intrinsic names the control flow is annotated with
33 static const char *IfIntrinsic = "llvm.SI.if";
34 static const char *ElseIntrinsic = "llvm.SI.else";
35 static const char *BreakIntrinsic = "llvm.SI.break";
36 static const char *IfBreakIntrinsic = "llvm.SI.if.break";
37 static const char *ElseBreakIntrinsic = "llvm.SI.else.break";
38 static const char *LoopIntrinsic = "llvm.SI.loop";
39 static const char *EndCfIntrinsic = "llvm.SI.end.cf";
40
41 class SIAnnotateControlFlow : public FunctionPass {
42
43   static char ID;
44
45   Type *Boolean;
46   Type *Void;
47   Type *Int64;
48   Type *ReturnStruct;
49
50   ConstantInt *BoolTrue;
51   ConstantInt *BoolFalse;
52   UndefValue *BoolUndef;
53   Constant *Int64Zero;
54
55   Constant *If;
56   Constant *Else;
57   Constant *Break;
58   Constant *IfBreak;
59   Constant *ElseBreak;
60   Constant *Loop;
61   Constant *EndCf;
62
63   DominatorTree *DT;
64   StackVector Stack;
65   SSAUpdater PhiInserter;
66
67   bool isTopOfStack(BasicBlock *BB);
68
69   Value *popSaved();
70
71   void push(BasicBlock *BB, Value *Saved);
72
73   bool isElse(PHINode *Phi);
74
75   void eraseIfUnused(PHINode *Phi);
76
77   void openIf(BranchInst *Term);
78
79   void insertElse(BranchInst *Term);
80
81   void handleLoopCondition(Value *Cond);
82
83   void handleLoop(BranchInst *Term);
84
85   void closeControlFlow(BasicBlock *BB);
86
87 public:
88   SIAnnotateControlFlow():
89     FunctionPass(ID) { }
90
91   virtual bool doInitialization(Module &M);
92
93   virtual bool runOnFunction(Function &F);
94
95   virtual const char *getPassName() const {
96     return "SI annotate control flow";
97   }
98
99   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100
101     AU.addRequired<DominatorTree>();
102     AU.addPreserved<DominatorTree>();
103     FunctionPass::getAnalysisUsage(AU);
104   }
105
106 };
107
108 } // end anonymous namespace
109
110 char SIAnnotateControlFlow::ID = 0;
111
112 /// \brief Initialize all the types and constants used in the pass
113 bool SIAnnotateControlFlow::doInitialization(Module &M) {
114
115   LLVMContext &Context = M.getContext();
116
117   Void = Type::getVoidTy(Context);
118   Boolean = Type::getInt1Ty(Context);
119   Int64 = Type::getInt64Ty(Context);
120   ReturnStruct = StructType::get(Boolean, Int64, (Type *)0);
121
122   BoolTrue = ConstantInt::getTrue(Context);
123   BoolFalse = ConstantInt::getFalse(Context);
124   BoolUndef = UndefValue::get(Boolean);
125   Int64Zero = ConstantInt::get(Int64, 0);
126
127   If = M.getOrInsertFunction(
128     IfIntrinsic, ReturnStruct, Boolean, (Type *)0);
129
130   Else = M.getOrInsertFunction(
131     ElseIntrinsic, ReturnStruct, Int64, (Type *)0);
132
133   Break = M.getOrInsertFunction(
134     BreakIntrinsic, Int64, Int64, (Type *)0);
135
136   IfBreak = M.getOrInsertFunction(
137     IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)0);
138
139   ElseBreak = M.getOrInsertFunction(
140     ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)0);
141
142   Loop = M.getOrInsertFunction(
143     LoopIntrinsic, Boolean, Int64, (Type *)0);
144
145   EndCf = M.getOrInsertFunction(
146     EndCfIntrinsic, Void, Int64, (Type *)0);
147
148   return false;
149 }
150
151 /// \brief Is BB the last block saved on the stack ?
152 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
153   return Stack.back().first == BB;
154 }
155
156 /// \brief Pop the last saved value from the control flow stack
157 Value *SIAnnotateControlFlow::popSaved() {
158   return Stack.pop_back_val().second;
159 }
160
161 /// \brief Push a BB and saved value to the control flow stack
162 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
163   Stack.push_back(std::make_pair(BB, Saved));
164 }
165
166 /// \brief Can the condition represented by this PHI node treated like
167 /// an "Else" block?
168 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
169
170   BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
171   for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
172     if (Phi->getIncomingBlock(i) == IDom) {
173
174       if (Phi->getIncomingValue(i) != BoolTrue)
175         return false;
176
177     } else {
178       if (Phi->getIncomingValue(i) != BoolFalse)
179         return false;
180  
181     }
182   }
183   return true;
184 }
185
186 // \brief Erase "Phi" if it is not used any more
187 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
188   if (!Phi->hasNUsesOrMore(1))
189     Phi->eraseFromParent();
190 }
191
192 /// \brief Open a new "If" block
193 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
194   Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
195   Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
196   push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
197 }
198
199 /// \brief Close the last "If" block and open a new "Else" block
200 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
201   Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
202   Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
203   push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
204 }
205
206 /// \brief Recursively handle the condition leading to a loop
207 void SIAnnotateControlFlow::handleLoopCondition(Value *Cond) {
208
209   if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
210
211     // Handle all non constant incoming values first
212     for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
213       Value *Incoming = Phi->getIncomingValue(i);
214       if (isa<ConstantInt>(Incoming))
215         continue;
216
217       Phi->setIncomingValue(i, BoolFalse);
218       handleLoopCondition(Incoming);
219     }
220
221     BasicBlock *Parent = Phi->getParent();
222     BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
223
224     for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
225
226       Value *Incoming = Phi->getIncomingValue(i);
227       if (Incoming != BoolTrue)
228         continue;
229
230       BasicBlock *From = Phi->getIncomingBlock(i);
231       if (From == IDom) {
232         CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
233         if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
234           Value *Args[] = {
235             OldEnd->getArgOperand(0),
236             PhiInserter.GetValueAtEndOfBlock(Parent)
237           };
238           Value *Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
239           PhiInserter.AddAvailableValue(Parent, Ret);
240           continue;
241         }
242       }
243
244       TerminatorInst *Insert = From->getTerminator();
245       Value *Arg = PhiInserter.GetValueAtEndOfBlock(From);
246       Value *Ret = CallInst::Create(Break, Arg, "", Insert);
247       PhiInserter.AddAvailableValue(From, Ret);
248     }
249     eraseIfUnused(Phi);
250
251   } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
252     BasicBlock *Parent = Inst->getParent();
253     TerminatorInst *Insert = Parent->getTerminator();
254     Value *Args[] = { Cond, PhiInserter.GetValueAtEndOfBlock(Parent) };
255     Value *Ret = CallInst::Create(IfBreak, Args, "", Insert);
256     PhiInserter.AddAvailableValue(Parent, Ret);
257
258   } else {
259     assert(0 && "Unhandled loop condition!");
260   }
261 }
262
263 /// \brief Handle a back edge (loop)
264 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
265
266   BasicBlock *Target = Term->getSuccessor(1);
267   PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
268
269   PhiInserter.Initialize(Int64, "");
270   PhiInserter.AddAvailableValue(Target, Broken);
271
272   Value *Cond = Term->getCondition();
273   Term->setCondition(BoolTrue);
274   handleLoopCondition(Cond);
275
276   BasicBlock *BB = Term->getParent();
277   Value *Arg = PhiInserter.GetValueAtEndOfBlock(BB);
278   for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
279        PI != PE; ++PI) {
280
281     Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
282   }
283
284   Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
285   push(Term->getSuccessor(0), Arg);
286 }
287
288 /// \brief Close the last opened control flow
289 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
290   CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
291 }
292
293 /// \brief Annotate the control flow with intrinsics so the backend can
294 /// recognize if/then/else and loops.
295 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
296
297   DT = &getAnalysis<DominatorTree>();
298
299   for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
300        E = df_end(&F.getEntryBlock()); I != E; ++I) {
301
302     BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
303
304     if (!Term || Term->isUnconditional()) {
305       if (isTopOfStack(*I))
306         closeControlFlow(*I);
307       continue;
308     }
309
310     if (I.nodeVisited(Term->getSuccessor(1))) {
311       if (isTopOfStack(*I))
312         closeControlFlow(*I);
313       handleLoop(Term);
314       continue;
315     }
316
317     if (isTopOfStack(*I)) {
318       PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
319       if (Phi && Phi->getParent() == *I && isElse(Phi)) {
320         insertElse(Term);
321         eraseIfUnused(Phi);
322         continue;
323       }
324       closeControlFlow(*I);
325     }
326     openIf(Term);
327   }
328
329   assert(Stack.empty());
330   return true;
331 }
332
333 /// \brief Create the annotation pass
334 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
335
336   return new SIAnnotateControlFlow();
337 }