ac3c9f4ac6828885e68aab8bf44f5d7f4bfa92ed
[oota-llvm.git] / lib / Transforms / Scalar / LowerExpectIntrinsic.cpp
1 //===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
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 // This pass lowers the 'expect' intrinsic to LLVM metadata.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/MDBuilder.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include <vector>
28
29 using namespace llvm;
30
31 #define DEBUG_TYPE "lower-expect-intrinsic"
32
33 STATISTIC(IfHandled, "Number of 'expect' intrinsic instructions handled");
34
35 static cl::opt<uint32_t>
36 LikelyBranchWeight("likely-branch-weight", cl::Hidden, cl::init(64),
37                    cl::desc("Weight of the branch likely to be taken (default = 64)"));
38 static cl::opt<uint32_t>
39 UnlikelyBranchWeight("unlikely-branch-weight", cl::Hidden, cl::init(4),
40                    cl::desc("Weight of the branch unlikely to be taken (default = 4)"));
41
42 namespace {
43 /// \brief Legacy pass for lowering expect intrinsics out of the IR.
44 ///
45 /// When this pass is run over a function it uses expect intrinsics which feed
46 /// branches and switches to provide branch weight metadata for those
47 /// terminators. It then removes the expect intrinsics from the IR so the rest
48 /// of the optimizer can ignore them.
49 class LowerExpectIntrinsic : public FunctionPass {
50 public:
51   static char ID;
52   LowerExpectIntrinsic() : FunctionPass(ID) {
53     initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
54   }
55
56   bool runOnFunction(Function &F) override;
57 };
58 }
59
60 static bool handleSwitchExpect(SwitchInst &SI) {
61   CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
62   if (!CI)
63     return false;
64
65   Function *Fn = CI->getCalledFunction();
66   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
67     return false;
68
69   Value *ArgValue = CI->getArgOperand(0);
70   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
71   if (!ExpectedValue)
72     return false;
73
74   SwitchInst::CaseIt Case = SI.findCaseValue(ExpectedValue);
75   unsigned n = SI.getNumCases(); // +1 for default case.
76   std::vector<uint32_t> Weights(n + 1);
77
78   Weights[0] =
79       Case == SI.case_default() ? LikelyBranchWeight : UnlikelyBranchWeight;
80   for (unsigned i = 0; i != n; ++i)
81     Weights[i + 1] =
82         i == Case.getCaseIndex() ? LikelyBranchWeight : UnlikelyBranchWeight;
83
84   SI.setMetadata(LLVMContext::MD_prof,
85                  MDBuilder(CI->getContext()).createBranchWeights(Weights));
86
87   SI.setCondition(ArgValue);
88   return true;
89 }
90
91 static bool handleBranchExpect(BranchInst &BI) {
92   if (BI.isUnconditional())
93     return false;
94
95   // Handle non-optimized IR code like:
96   //   %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
97   //   %tobool = icmp ne i64 %expval, 0
98   //   br i1 %tobool, label %if.then, label %if.end
99   //
100   // Or the following simpler case:
101   //   %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
102   //   br i1 %expval, label %if.then, label %if.end
103
104   CallInst *CI;
105
106   ICmpInst *CmpI = dyn_cast<ICmpInst>(BI.getCondition());
107   if (!CmpI) {
108     CI = dyn_cast<CallInst>(BI.getCondition());
109   } else {
110     if (CmpI->getPredicate() != CmpInst::ICMP_NE)
111       return false;
112     CI = dyn_cast<CallInst>(CmpI->getOperand(0));
113   }
114
115   if (!CI)
116     return false;
117
118   Function *Fn = CI->getCalledFunction();
119   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
120     return false;
121
122   Value *ArgValue = CI->getArgOperand(0);
123   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
124   if (!ExpectedValue)
125     return false;
126
127   MDBuilder MDB(CI->getContext());
128   MDNode *Node;
129
130   // If expect value is equal to 1 it means that we are more likely to take
131   // branch 0, in other case more likely is branch 1.
132   if (ExpectedValue->isOne())
133     Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
134   else
135     Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
136
137   BI.setMetadata(LLVMContext::MD_prof, Node);
138
139   if (CmpI)
140     CmpI->setOperand(0, ArgValue);
141   else
142     BI.setCondition(ArgValue);
143   return true;
144 }
145
146 bool LowerExpectIntrinsic::runOnFunction(Function &F) {
147   for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
148     BasicBlock *BB = I++;
149
150     // Create "block_weights" metadata.
151     if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
152       if (handleBranchExpect(*BI))
153         IfHandled++;
154     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
155       if (handleSwitchExpect(*SI))
156         IfHandled++;
157     }
158
159     // remove llvm.expect intrinsics.
160     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
161       CallInst *CI = dyn_cast<CallInst>(BI++);
162       if (!CI)
163         continue;
164
165       Function *Fn = CI->getCalledFunction();
166       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
167         Value *Exp = CI->getArgOperand(0);
168         CI->replaceAllUsesWith(Exp);
169         CI->eraseFromParent();
170       }
171     }
172   }
173
174   return false;
175 }
176
177 char LowerExpectIntrinsic::ID = 0;
178 INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
179                 "Lower 'expect' Intrinsics", false, false)
180
181 FunctionPass *llvm::createLowerExpectIntrinsicPass() {
182   return new LowerExpectIntrinsic();
183 }