1 //===-- SIAnnotateControlFlow.cpp - ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Annotates the control flow with hardware specific intrinsics.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/SSAUpdater.h"
27 // Complex types used in this pass
28 typedef std::pair<BasicBlock *, Value *> StackEntry;
29 typedef SmallVector<StackEntry, 16> StackVector;
31 // Intrinsic names the control flow is annotated with
32 static const char *IfIntrinsic = "llvm.SI.if";
33 static const char *ElseIntrinsic = "llvm.SI.else";
34 static const char *BreakIntrinsic = "llvm.SI.break";
35 static const char *IfBreakIntrinsic = "llvm.SI.if.break";
36 static const char *ElseBreakIntrinsic = "llvm.SI.else.break";
37 static const char *LoopIntrinsic = "llvm.SI.loop";
38 static const char *EndCfIntrinsic = "llvm.SI.end.cf";
40 class SIAnnotateControlFlow : public FunctionPass {
49 ConstantInt *BoolTrue;
50 ConstantInt *BoolFalse;
51 UndefValue *BoolUndef;
64 SSAUpdater PhiInserter;
66 bool isTopOfStack(BasicBlock *BB);
70 void push(BasicBlock *BB, Value *Saved);
72 bool isElse(PHINode *Phi);
74 void eraseIfUnused(PHINode *Phi);
76 void openIf(BranchInst *Term);
78 void insertElse(BranchInst *Term);
80 void handleLoopCondition(Value *Cond);
82 void handleLoop(BranchInst *Term);
84 void closeControlFlow(BasicBlock *BB);
87 SIAnnotateControlFlow():
90 virtual bool doInitialization(Module &M);
92 virtual bool runOnFunction(Function &F);
94 virtual const char *getPassName() const {
95 return "SI annotate control flow";
98 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<DominatorTree>();
100 AU.addPreserved<DominatorTree>();
101 FunctionPass::getAnalysisUsage(AU);
106 } // end anonymous namespace
108 char SIAnnotateControlFlow::ID = 0;
110 /// \brief Initialize all the types and constants used in the pass
111 bool SIAnnotateControlFlow::doInitialization(Module &M) {
112 LLVMContext &Context = M.getContext();
114 Void = Type::getVoidTy(Context);
115 Boolean = Type::getInt1Ty(Context);
116 Int64 = Type::getInt64Ty(Context);
117 ReturnStruct = StructType::get(Boolean, Int64, (Type *)0);
119 BoolTrue = ConstantInt::getTrue(Context);
120 BoolFalse = ConstantInt::getFalse(Context);
121 BoolUndef = UndefValue::get(Boolean);
122 Int64Zero = ConstantInt::get(Int64, 0);
124 If = M.getOrInsertFunction(
125 IfIntrinsic, ReturnStruct, Boolean, (Type *)0);
127 Else = M.getOrInsertFunction(
128 ElseIntrinsic, ReturnStruct, Int64, (Type *)0);
130 Break = M.getOrInsertFunction(
131 BreakIntrinsic, Int64, Int64, (Type *)0);
133 IfBreak = M.getOrInsertFunction(
134 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)0);
136 ElseBreak = M.getOrInsertFunction(
137 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)0);
139 Loop = M.getOrInsertFunction(
140 LoopIntrinsic, Boolean, Int64, (Type *)0);
142 EndCf = M.getOrInsertFunction(
143 EndCfIntrinsic, Void, Int64, (Type *)0);
148 /// \brief Is BB the last block saved on the stack ?
149 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
150 return !Stack.empty() && Stack.back().first == BB;
153 /// \brief Pop the last saved value from the control flow stack
154 Value *SIAnnotateControlFlow::popSaved() {
155 return Stack.pop_back_val().second;
158 /// \brief Push a BB and saved value to the control flow stack
159 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
160 Stack.push_back(std::make_pair(BB, Saved));
163 /// \brief Can the condition represented by this PHI node treated like
165 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
166 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
167 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
168 if (Phi->getIncomingBlock(i) == IDom) {
170 if (Phi->getIncomingValue(i) != BoolTrue)
174 if (Phi->getIncomingValue(i) != BoolFalse)
182 // \brief Erase "Phi" if it is not used any more
183 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
184 if (!Phi->hasNUsesOrMore(1))
185 Phi->eraseFromParent();
188 /// \brief Open a new "If" block
189 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
190 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
191 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
192 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
195 /// \brief Close the last "If" block and open a new "Else" block
196 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
197 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
198 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
199 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
202 /// \brief Recursively handle the condition leading to a loop
203 void SIAnnotateControlFlow::handleLoopCondition(Value *Cond) {
204 if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
206 // Handle all non constant incoming values first
207 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
208 Value *Incoming = Phi->getIncomingValue(i);
209 if (isa<ConstantInt>(Incoming))
212 Phi->setIncomingValue(i, BoolFalse);
213 handleLoopCondition(Incoming);
216 BasicBlock *Parent = Phi->getParent();
217 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
219 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
221 Value *Incoming = Phi->getIncomingValue(i);
222 if (Incoming != BoolTrue)
225 BasicBlock *From = Phi->getIncomingBlock(i);
227 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
228 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
230 OldEnd->getArgOperand(0),
231 PhiInserter.GetValueAtEndOfBlock(Parent)
233 Value *Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
234 PhiInserter.AddAvailableValue(Parent, Ret);
239 TerminatorInst *Insert = From->getTerminator();
240 Value *Arg = PhiInserter.GetValueAtEndOfBlock(From);
241 Value *Ret = CallInst::Create(Break, Arg, "", Insert);
242 PhiInserter.AddAvailableValue(From, Ret);
246 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
247 BasicBlock *Parent = Inst->getParent();
248 TerminatorInst *Insert = Parent->getTerminator();
249 Value *Args[] = { Cond, PhiInserter.GetValueAtEndOfBlock(Parent) };
250 Value *Ret = CallInst::Create(IfBreak, Args, "", Insert);
251 PhiInserter.AddAvailableValue(Parent, Ret);
254 assert(0 && "Unhandled loop condition!");
258 /// \brief Handle a back edge (loop)
259 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
260 BasicBlock *Target = Term->getSuccessor(1);
261 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
263 PhiInserter.Initialize(Int64, "");
264 PhiInserter.AddAvailableValue(Target, Broken);
266 Value *Cond = Term->getCondition();
267 Term->setCondition(BoolTrue);
268 handleLoopCondition(Cond);
270 BasicBlock *BB = Term->getParent();
271 Value *Arg = PhiInserter.GetValueAtEndOfBlock(BB);
272 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
275 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
278 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
279 push(Term->getSuccessor(0), Arg);
282 /// \brief Close the last opened control flow
283 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
284 CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
287 /// \brief Annotate the control flow with intrinsics so the backend can
288 /// recognize if/then/else and loops.
289 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
290 DT = &getAnalysis<DominatorTree>();
292 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
293 E = df_end(&F.getEntryBlock()); I != E; ++I) {
295 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
297 if (!Term || Term->isUnconditional()) {
298 if (isTopOfStack(*I))
299 closeControlFlow(*I);
303 if (I.nodeVisited(Term->getSuccessor(1))) {
304 if (isTopOfStack(*I))
305 closeControlFlow(*I);
310 if (isTopOfStack(*I)) {
311 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
312 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
317 closeControlFlow(*I);
322 assert(Stack.empty());
326 /// \brief Create the annotation pass
327 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
328 return new SIAnnotateControlFlow();