blob: b0f438721751155d7bf1430b9aeb6e0203429d62 [file] [log] [blame]
Chandler Carruth47e1db12011-10-16 22:15:07 +00001//===- 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
Chandler Carruth43e590e2015-01-24 11:13:02 +000014#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
Chandler Carruth3f5e7b12015-01-24 10:47:13 +000015#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/BasicBlock.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/MDBuilder.h"
24#include "llvm/IR/Metadata.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000025#include "llvm/Pass.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +000028#include "llvm/Transforms/Scalar.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000029
30using namespace llvm;
31
Chandler Carruth964daaa2014-04-22 02:55:47 +000032#define DEBUG_TYPE "lower-expect-intrinsic"
33
Chandler Carruth6eb60eb2015-01-24 10:57:25 +000034STATISTIC(ExpectIntrinsicsHandled,
35 "Number of 'expect' intrinsic instructions handled");
Jakub Staszak3f158fd2011-07-06 18:22:43 +000036
Sanjay Pateld2d2aa52016-04-26 22:23:38 +000037// These default values are chosen to represent an extremely skewed outcome for
38// a condition, but they leave some room for interpretation by later passes.
39//
40// If the documentation for __builtin_expect() was made explicit that it should
41// only be used in extreme cases, we could make this ratio higher. As it stands,
42// programmers may be using __builtin_expect() / llvm.expect to annotate that a
43// branch is likely or unlikely to be taken.
44//
45// There is a known dependency on this ratio in CodeGenPrepare when transforming
46// 'select' instructions. It may be worthwhile to hoist these values to some
47// shared space, so they can be used directly by other passes.
48
49static cl::opt<uint32_t> LikelyBranchWeight(
50 "likely-branch-weight", cl::Hidden, cl::init(2000),
51 cl::desc("Weight of the branch likely to be taken (default = 2000)"));
52static cl::opt<uint32_t> UnlikelyBranchWeight(
53 "unlikely-branch-weight", cl::Hidden, cl::init(1),
54 cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
Jakub Staszak3f158fd2011-07-06 18:22:43 +000055
Chandler Carruth0012c772015-01-24 10:39:24 +000056static bool handleSwitchExpect(SwitchInst &SI) {
57 CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
Jakub Staszak3f158fd2011-07-06 18:22:43 +000058 if (!CI)
59 return false;
60
61 Function *Fn = CI->getCalledFunction();
62 if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
63 return false;
64
65 Value *ArgValue = CI->getArgOperand(0);
66 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
67 if (!ExpectedValue)
68 return false;
69
Chandler Carruth927d8e62017-04-12 07:27:28 +000070 SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
Chandler Carruth0012c772015-01-24 10:39:24 +000071 unsigned n = SI.getNumCases(); // +1 for default case.
Chandler Carruth3f5e7b12015-01-24 10:47:13 +000072 SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeight);
Jakub Staszak3f158fd2011-07-06 18:22:43 +000073
Chandler Carruth927d8e62017-04-12 07:27:28 +000074 if (Case == *SI.case_default())
Chandler Carruth3f5e7b12015-01-24 10:47:13 +000075 Weights[0] = LikelyBranchWeight;
76 else
77 Weights[Case.getCaseIndex() + 1] = LikelyBranchWeight;
Jakub Staszak3f158fd2011-07-06 18:22:43 +000078
Chandler Carruth0012c772015-01-24 10:39:24 +000079 SI.setMetadata(LLVMContext::MD_prof,
80 MDBuilder(CI->getContext()).createBranchWeights(Weights));
Jakub Staszak3f158fd2011-07-06 18:22:43 +000081
Chandler Carruth0012c772015-01-24 10:39:24 +000082 SI.setCondition(ArgValue);
Jakub Staszak3f158fd2011-07-06 18:22:43 +000083 return true;
84}
85
Xinliang David Li40afd5c2016-09-02 22:03:40 +000086// Handle both BranchInst and SelectInst.
87template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +000088
89 // Handle non-optimized IR code like:
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +000090 // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
Jakub Staszak3f158fd2011-07-06 18:22:43 +000091 // %tobool = icmp ne i64 %expval, 0
92 // br i1 %tobool, label %if.then, label %if.end
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +000093 //
94 // Or the following simpler case:
95 // %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
96 // br i1 %expval, label %if.then, label %if.end
97
98 CallInst *CI;
Jakub Staszak3f158fd2011-07-06 18:22:43 +000099
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000100 ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000101 CmpInst::Predicate Predicate;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000102 ConstantInt *CmpConstOperand = nullptr;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000103 if (!CmpI) {
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000104 CI = dyn_cast<CallInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000105 Predicate = CmpInst::ICMP_NE;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000106 } else {
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000107 Predicate = CmpI->getPredicate();
108 if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000109 return false;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000110
111 CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000112 if (!CmpConstOperand)
113 return false;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000114 CI = dyn_cast<CallInst>(CmpI->getOperand(0));
115 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000116
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000117 if (!CI)
118 return false;
119
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000120 uint64_t ValueComparedTo = 0;
121 if (CmpConstOperand) {
122 if (CmpConstOperand->getBitWidth() > 64)
123 return false;
124 ValueComparedTo = CmpConstOperand->getZExtValue();
125 }
126
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000127 Function *Fn = CI->getCalledFunction();
128 if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
129 return false;
130
131 Value *ArgValue = CI->getArgOperand(0);
132 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
133 if (!ExpectedValue)
134 return false;
135
Benjamin Kramer65e75662012-05-26 13:59:43 +0000136 MDBuilder MDB(CI->getContext());
137 MDNode *Node;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000138
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000139 if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
140 (Predicate == CmpInst::ICMP_EQ))
Benjamin Kramer65e75662012-05-26 13:59:43 +0000141 Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
142 else
143 Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000144
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000145 BSI.setMetadata(LLVMContext::MD_prof, Node);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000146
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000147 if (CmpI)
148 CmpI->setOperand(0, ArgValue);
149 else
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000150 BSI.setCondition(ArgValue);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000151 return true;
152}
153
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000154static bool handleBranchExpect(BranchInst &BI) {
155 if (BI.isUnconditional())
156 return false;
157
158 return handleBrSelExpect<BranchInst>(BI);
159}
160
Chandler Carruth43e590e2015-01-24 11:13:02 +0000161static bool lowerExpectIntrinsic(Function &F) {
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000162 bool Changed = false;
163
Chandler Carruthd12741e2015-01-24 10:57:19 +0000164 for (BasicBlock &BB : F) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000165 // Create "block_weights" metadata.
Chandler Carruthd12741e2015-01-24 10:57:19 +0000166 if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000167 if (handleBranchExpect(*BI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000168 ExpectIntrinsicsHandled++;
Chandler Carruthd12741e2015-01-24 10:57:19 +0000169 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000170 if (handleSwitchExpect(*SI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000171 ExpectIntrinsicsHandled++;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000172 }
173
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000174 // Remove llvm.expect intrinsics. Iterate backwards in order
175 // to process select instructions before the intrinsic gets
176 // removed.
177 for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
178 Instruction *Inst = &*BI++;
179 CallInst *CI = dyn_cast<CallInst>(Inst);
180 if (!CI) {
181 if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
182 if (handleBrSelExpect(*SI))
183 ExpectIntrinsicsHandled++;
184 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000185 continue;
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000186 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000187
188 Function *Fn = CI->getCalledFunction();
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000189 if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
190 Value *Exp = CI->getArgOperand(0);
191 CI->replaceAllUsesWith(Exp);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000192 CI->eraseFromParent();
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000193 Changed = true;
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000194 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000195 }
196 }
197
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000198 return Changed;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000199}
200
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000201PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
202 FunctionAnalysisManager &) {
Chandler Carruth43e590e2015-01-24 11:13:02 +0000203 if (lowerExpectIntrinsic(F))
204 return PreservedAnalyses::none();
205
206 return PreservedAnalyses::all();
207}
208
209namespace {
210/// \brief Legacy pass for lowering expect intrinsics out of the IR.
211///
212/// When this pass is run over a function it uses expect intrinsics which feed
213/// branches and switches to provide branch weight metadata for those
214/// terminators. It then removes the expect intrinsics from the IR so the rest
215/// of the optimizer can ignore them.
216class LowerExpectIntrinsic : public FunctionPass {
217public:
218 static char ID;
219 LowerExpectIntrinsic() : FunctionPass(ID) {
220 initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
221 }
222
223 bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
224};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000225}
Chandler Carruth43e590e2015-01-24 11:13:02 +0000226
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000227char LowerExpectIntrinsic::ID = 0;
Chandler Carruth0ea746b2015-01-24 10:30:14 +0000228INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
229 "Lower 'expect' Intrinsics", false, false)
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000230
231FunctionPass *llvm::createLowerExpectIntrinsicPass() {
232 return new LowerExpectIntrinsic();
233}