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/LoopInfo.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "llvm/Transforms/Utils/SSAUpdater.h"
28 #define DEBUG_TYPE "si-annotate-control-flow"
32 // Complex types used in this pass
33 typedef std::pair<BasicBlock *, Value *> StackEntry;
34 typedef SmallVector<StackEntry, 16> StackVector;
36 // Intrinsic names the control flow is annotated with
37 static const char *const IfIntrinsic = "llvm.SI.if";
38 static const char *const ElseIntrinsic = "llvm.SI.else";
39 static const char *const BreakIntrinsic = "llvm.SI.break";
40 static const char *const IfBreakIntrinsic = "llvm.SI.if.break";
41 static const char *const ElseBreakIntrinsic = "llvm.SI.else.break";
42 static const char *const LoopIntrinsic = "llvm.SI.loop";
43 static const char *const EndCfIntrinsic = "llvm.SI.end.cf";
45 class SIAnnotateControlFlow : public FunctionPass {
54 ConstantInt *BoolTrue;
55 ConstantInt *BoolFalse;
56 UndefValue *BoolUndef;
72 bool isTopOfStack(BasicBlock *BB);
76 void push(BasicBlock *BB, Value *Saved);
78 bool isElse(PHINode *Phi);
80 void eraseIfUnused(PHINode *Phi);
82 void openIf(BranchInst *Term);
84 void insertElse(BranchInst *Term);
86 Value *handleLoopCondition(Value *Cond, PHINode *Broken);
88 void handleLoop(BranchInst *Term);
90 void closeControlFlow(BasicBlock *BB);
93 SIAnnotateControlFlow():
96 bool doInitialization(Module &M) override;
98 bool runOnFunction(Function &F) override;
100 const char *getPassName() const override {
101 return "SI annotate control flow";
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 AU.addRequired<LoopInfoWrapperPass>();
106 AU.addRequired<DominatorTreeWrapperPass>();
107 AU.addPreserved<DominatorTreeWrapperPass>();
108 FunctionPass::getAnalysisUsage(AU);
113 } // end anonymous namespace
115 char SIAnnotateControlFlow::ID = 0;
117 /// \brief Initialize all the types and constants used in the pass
118 bool SIAnnotateControlFlow::doInitialization(Module &M) {
119 LLVMContext &Context = M.getContext();
121 Void = Type::getVoidTy(Context);
122 Boolean = Type::getInt1Ty(Context);
123 Int64 = Type::getInt64Ty(Context);
124 ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr);
126 BoolTrue = ConstantInt::getTrue(Context);
127 BoolFalse = ConstantInt::getFalse(Context);
128 BoolUndef = UndefValue::get(Boolean);
129 Int64Zero = ConstantInt::get(Int64, 0);
131 If = M.getOrInsertFunction(
132 IfIntrinsic, ReturnStruct, Boolean, (Type *)nullptr);
134 Else = M.getOrInsertFunction(
135 ElseIntrinsic, ReturnStruct, Int64, (Type *)nullptr);
137 Break = M.getOrInsertFunction(
138 BreakIntrinsic, Int64, Int64, (Type *)nullptr);
140 IfBreak = M.getOrInsertFunction(
141 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)nullptr);
143 ElseBreak = M.getOrInsertFunction(
144 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)nullptr);
146 Loop = M.getOrInsertFunction(
147 LoopIntrinsic, Boolean, Int64, (Type *)nullptr);
149 EndCf = M.getOrInsertFunction(
150 EndCfIntrinsic, Void, Int64, (Type *)nullptr);
155 /// \brief Is BB the last block saved on the stack ?
156 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
157 return !Stack.empty() && Stack.back().first == BB;
160 /// \brief Pop the last saved value from the control flow stack
161 Value *SIAnnotateControlFlow::popSaved() {
162 return Stack.pop_back_val().second;
165 /// \brief Push a BB and saved value to the control flow stack
166 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
167 Stack.push_back(std::make_pair(BB, Saved));
170 /// \brief Can the condition represented by this PHI node treated like
172 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
173 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
174 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
175 if (Phi->getIncomingBlock(i) == IDom) {
177 if (Phi->getIncomingValue(i) != BoolTrue)
181 if (Phi->getIncomingValue(i) != BoolFalse)
189 // \brief Erase "Phi" if it is not used any more
190 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
191 if (!Phi->hasNUsesOrMore(1))
192 Phi->eraseFromParent();
195 /// \brief Open a new "If" block
196 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
197 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
198 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
199 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
202 /// \brief Close the last "If" block and open a new "Else" block
203 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
204 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
205 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
206 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
209 /// \brief Recursively handle the condition leading to a loop
210 Value *SIAnnotateControlFlow::handleLoopCondition(Value *Cond, PHINode *Broken) {
211 if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
212 BasicBlock *Parent = Phi->getParent();
213 PHINode *NewPhi = PHINode::Create(Int64, 0, "", &Parent->front());
216 // Handle all non-constant incoming values first
217 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
218 Value *Incoming = Phi->getIncomingValue(i);
219 BasicBlock *From = Phi->getIncomingBlock(i);
220 if (isa<ConstantInt>(Incoming)) {
221 NewPhi->addIncoming(Broken, From);
225 Phi->setIncomingValue(i, BoolFalse);
226 Value *PhiArg = handleLoopCondition(Incoming, Broken);
227 NewPhi->addIncoming(PhiArg, From);
230 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
232 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
234 Value *Incoming = Phi->getIncomingValue(i);
235 if (Incoming != BoolTrue)
238 BasicBlock *From = Phi->getIncomingBlock(i);
240 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
241 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
242 Value *Args[] = { OldEnd->getArgOperand(0), NewPhi };
243 Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
247 TerminatorInst *Insert = From->getTerminator();
248 Value *PhiArg = CallInst::Create(Break, Broken, "", Insert);
249 NewPhi->setIncomingValue(i, PhiArg);
254 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
255 BasicBlock *Parent = Inst->getParent();
256 TerminatorInst *Insert = Parent->getTerminator();
257 Value *Args[] = { Cond, Broken };
258 return CallInst::Create(IfBreak, Args, "", Insert);
261 llvm_unreachable("Unhandled loop condition!");
266 /// \brief Handle a back edge (loop)
267 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
268 BasicBlock *Target = Term->getSuccessor(1);
269 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
271 Value *Cond = Term->getCondition();
272 Term->setCondition(BoolTrue);
273 Value *Arg = handleLoopCondition(Cond, Broken);
275 BasicBlock *BB = Term->getParent();
276 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
279 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
282 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
283 push(Term->getSuccessor(0), Arg);
284 }/// \brief Close the last opened control flow
285 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
286 llvm::Loop *L = LI->getLoopFor(BB);
288 if (L && L->getHeader() == BB) {
289 // We can't insert an EndCF call into a loop header, because it will
290 // get executed on every iteration of the loop, when it should be
291 // executed only once before the loop.
292 SmallVector <BasicBlock*, 8> Latches;
293 L->getLoopLatches(Latches);
295 std::vector<BasicBlock*> Preds;
296 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
297 if (std::find(Latches.begin(), Latches.end(), *PI) == Latches.end())
298 Preds.push_back(*PI);
300 BB = llvm::SplitBlockPredecessors(BB, Preds, "endcf.split", nullptr, DT,
304 CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
307 /// \brief Annotate the control flow with intrinsics so the backend can
308 /// recognize if/then/else and loops.
309 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
310 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
311 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
313 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
314 E = df_end(&F.getEntryBlock()); I != E; ++I) {
316 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
318 if (!Term || Term->isUnconditional()) {
319 if (isTopOfStack(*I))
320 closeControlFlow(*I);
324 if (I.nodeVisited(Term->getSuccessor(1))) {
325 if (isTopOfStack(*I))
326 closeControlFlow(*I);
331 if (isTopOfStack(*I)) {
332 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
333 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
338 closeControlFlow(*I);
343 assert(Stack.empty());
347 /// \brief Create the annotation pass
348 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
349 return new SIAnnotateControlFlow();