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 //===----------------------------------------------------------------------===//
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"
28 // Complex types used in this pass
29 typedef std::pair<BasicBlock *, Value *> StackEntry;
30 typedef SmallVector<StackEntry, 16> StackVector;
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";
41 class SIAnnotateControlFlow : public FunctionPass {
50 ConstantInt *BoolTrue;
51 ConstantInt *BoolFalse;
52 UndefValue *BoolUndef;
65 SSAUpdater PhiInserter;
67 bool isTopOfStack(BasicBlock *BB);
71 void push(BasicBlock *BB, Value *Saved);
73 bool isElse(PHINode *Phi);
75 void eraseIfUnused(PHINode *Phi);
77 void openIf(BranchInst *Term);
79 void insertElse(BranchInst *Term);
81 void handleLoopCondition(Value *Cond);
83 void handleLoop(BranchInst *Term);
85 void closeControlFlow(BasicBlock *BB);
88 SIAnnotateControlFlow():
91 virtual bool doInitialization(Module &M);
93 virtual bool runOnFunction(Function &F);
95 virtual const char *getPassName() const {
96 return "SI annotate control flow";
99 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.addRequired<DominatorTree>();
102 AU.addPreserved<DominatorTree>();
103 FunctionPass::getAnalysisUsage(AU);
108 } // end anonymous namespace
110 char SIAnnotateControlFlow::ID = 0;
112 /// \brief Initialize all the types and constants used in the pass
113 bool SIAnnotateControlFlow::doInitialization(Module &M) {
115 LLVMContext &Context = M.getContext();
117 Void = Type::getVoidTy(Context);
118 Boolean = Type::getInt1Ty(Context);
119 Int64 = Type::getInt64Ty(Context);
120 ReturnStruct = StructType::get(Boolean, Int64, (Type *)0);
122 BoolTrue = ConstantInt::getTrue(Context);
123 BoolFalse = ConstantInt::getFalse(Context);
124 BoolUndef = UndefValue::get(Boolean);
125 Int64Zero = ConstantInt::get(Int64, 0);
127 If = M.getOrInsertFunction(
128 IfIntrinsic, ReturnStruct, Boolean, (Type *)0);
130 Else = M.getOrInsertFunction(
131 ElseIntrinsic, ReturnStruct, Int64, (Type *)0);
133 Break = M.getOrInsertFunction(
134 BreakIntrinsic, Int64, Int64, (Type *)0);
136 IfBreak = M.getOrInsertFunction(
137 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)0);
139 ElseBreak = M.getOrInsertFunction(
140 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)0);
142 Loop = M.getOrInsertFunction(
143 LoopIntrinsic, Boolean, Int64, (Type *)0);
145 EndCf = M.getOrInsertFunction(
146 EndCfIntrinsic, Void, Int64, (Type *)0);
151 /// \brief Is BB the last block saved on the stack ?
152 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
153 return Stack.back().first == BB;
156 /// \brief Pop the last saved value from the control flow stack
157 Value *SIAnnotateControlFlow::popSaved() {
158 return Stack.pop_back_val().second;
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));
166 /// \brief Can the condition represented by this PHI node treated like
168 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
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) {
174 if (Phi->getIncomingValue(i) != BoolTrue)
178 if (Phi->getIncomingValue(i) != BoolFalse)
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();
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));
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));
206 /// \brief Recursively handle the condition leading to a loop
207 void SIAnnotateControlFlow::handleLoopCondition(Value *Cond) {
209 if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
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))
217 Phi->setIncomingValue(i, BoolFalse);
218 handleLoopCondition(Incoming);
221 BasicBlock *Parent = Phi->getParent();
222 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
224 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
226 Value *Incoming = Phi->getIncomingValue(i);
227 if (Incoming != BoolTrue)
230 BasicBlock *From = Phi->getIncomingBlock(i);
232 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
233 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
235 OldEnd->getArgOperand(0),
236 PhiInserter.GetValueAtEndOfBlock(Parent)
238 Value *Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
239 PhiInserter.AddAvailableValue(Parent, Ret);
244 TerminatorInst *Insert = From->getTerminator();
245 Value *Arg = PhiInserter.GetValueAtEndOfBlock(From);
246 Value *Ret = CallInst::Create(Break, Arg, "", Insert);
247 PhiInserter.AddAvailableValue(From, Ret);
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);
259 assert(0 && "Unhandled loop condition!");
263 /// \brief Handle a back edge (loop)
264 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
266 BasicBlock *Target = Term->getSuccessor(1);
267 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
269 PhiInserter.Initialize(Int64, "");
270 PhiInserter.AddAvailableValue(Target, Broken);
272 Value *Cond = Term->getCondition();
273 Term->setCondition(BoolTrue);
274 handleLoopCondition(Cond);
276 BasicBlock *BB = Term->getParent();
277 Value *Arg = PhiInserter.GetValueAtEndOfBlock(BB);
278 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
281 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
284 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
285 push(Term->getSuccessor(0), Arg);
288 /// \brief Close the last opened control flow
289 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
290 CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
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) {
297 DT = &getAnalysis<DominatorTree>();
299 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
300 E = df_end(&F.getEntryBlock()); I != E; ++I) {
302 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
304 if (!Term || Term->isUnconditional()) {
305 if (isTopOfStack(*I))
306 closeControlFlow(*I);
310 if (I.nodeVisited(Term->getSuccessor(1))) {
311 if (isTopOfStack(*I))
312 closeControlFlow(*I);
317 if (isTopOfStack(*I)) {
318 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
319 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
324 closeControlFlow(*I);
329 assert(Stack.empty());
333 /// \brief Create the annotation pass
334 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
336 return new SIAnnotateControlFlow();