blob: 46f8a356426562cd00c5ce690e2c7515e7eb52d3 [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"
Xinliang David Li621e8dc2017-06-02 02:09:31 +000017#include "llvm/ADT/iterator_range.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/Metadata.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000026#include "llvm/Pass.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
Chandler Carruth43e590e2015-01-24 11:13:02 +000029#include "llvm/Transforms/Scalar.h"
Jakub Staszak3f158fd2011-07-06 18:22:43 +000030
31using namespace llvm;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "lower-expect-intrinsic"
34
Chandler Carruth6eb60eb2015-01-24 10:57:25 +000035STATISTIC(ExpectIntrinsicsHandled,
36 "Number of 'expect' intrinsic instructions handled");
Jakub Staszak3f158fd2011-07-06 18:22:43 +000037
Sanjay Pateld2d2aa52016-04-26 22:23:38 +000038// These default values are chosen to represent an extremely skewed outcome for
39// a condition, but they leave some room for interpretation by later passes.
40//
41// If the documentation for __builtin_expect() was made explicit that it should
42// only be used in extreme cases, we could make this ratio higher. As it stands,
43// programmers may be using __builtin_expect() / llvm.expect to annotate that a
44// branch is likely or unlikely to be taken.
45//
46// There is a known dependency on this ratio in CodeGenPrepare when transforming
47// 'select' instructions. It may be worthwhile to hoist these values to some
48// shared space, so they can be used directly by other passes.
49
50static cl::opt<uint32_t> LikelyBranchWeight(
51 "likely-branch-weight", cl::Hidden, cl::init(2000),
52 cl::desc("Weight of the branch likely to be taken (default = 2000)"));
53static cl::opt<uint32_t> UnlikelyBranchWeight(
54 "unlikely-branch-weight", cl::Hidden, cl::init(1),
55 cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
Jakub Staszak3f158fd2011-07-06 18:22:43 +000056
Chandler Carruth0012c772015-01-24 10:39:24 +000057static bool handleSwitchExpect(SwitchInst &SI) {
58 CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
Jakub Staszak3f158fd2011-07-06 18:22:43 +000059 if (!CI)
60 return false;
61
62 Function *Fn = CI->getCalledFunction();
63 if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
64 return false;
65
66 Value *ArgValue = CI->getArgOperand(0);
67 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
68 if (!ExpectedValue)
69 return false;
70
Chandler Carruth927d8e62017-04-12 07:27:28 +000071 SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
Chandler Carruth0012c772015-01-24 10:39:24 +000072 unsigned n = SI.getNumCases(); // +1 for default case.
Chandler Carruth3f5e7b12015-01-24 10:47:13 +000073 SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeight);
Jakub Staszak3f158fd2011-07-06 18:22:43 +000074
Chandler Carruth927d8e62017-04-12 07:27:28 +000075 if (Case == *SI.case_default())
Chandler Carruth3f5e7b12015-01-24 10:47:13 +000076 Weights[0] = LikelyBranchWeight;
77 else
78 Weights[Case.getCaseIndex() + 1] = LikelyBranchWeight;
Jakub Staszak3f158fd2011-07-06 18:22:43 +000079
Chandler Carruth0012c772015-01-24 10:39:24 +000080 SI.setMetadata(LLVMContext::MD_prof,
81 MDBuilder(CI->getContext()).createBranchWeights(Weights));
Jakub Staszak3f158fd2011-07-06 18:22:43 +000082
Chandler Carruth0012c772015-01-24 10:39:24 +000083 SI.setCondition(ArgValue);
Jakub Staszak3f158fd2011-07-06 18:22:43 +000084 return true;
85}
86
Xinliang David Li621e8dc2017-06-02 02:09:31 +000087/// Handler for PHINodes that define the value argument to an
88/// @llvm.expect call.
89///
90/// If the operand of the phi has a constant value and it 'contradicts'
91/// with the expected value of phi def, then the corresponding incoming
92/// edge of the phi is unlikely to be taken. Using that information,
93/// the branch probability info for the originating branch can be inferred.
94static void handlePhiDef(CallInst *Expect) {
95 Value &Arg = *Expect->getArgOperand(0);
Xinliang David Li4f49bee2017-06-07 18:32:24 +000096 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(Expect->getArgOperand(1));
97 if (!ExpectedValue)
98 return;
Xinliang David Li621e8dc2017-06-02 02:09:31 +000099 const APInt &ExpectedPhiValue = ExpectedValue->getValue();
100
101 // Walk up in backward a list of instructions that
102 // have 'copy' semantics by 'stripping' the copies
103 // until a PHI node or an instruction of unknown kind
104 // is reached. Negation via xor is also handled.
105 //
106 // C = PHI(...);
107 // B = C;
108 // A = B;
109 // D = __builtin_expect(A, 0);
110 //
111 Value *V = &Arg;
112 SmallVector<Instruction *, 4> Operations;
113 while (!isa<PHINode>(V)) {
114 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(V)) {
115 V = ZExt->getOperand(0);
116 Operations.push_back(ZExt);
117 continue;
118 }
119
120 if (SExtInst *SExt = dyn_cast<SExtInst>(V)) {
121 V = SExt->getOperand(0);
122 Operations.push_back(SExt);
123 continue;
124 }
125
126 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(V);
127 if (!BinOp || BinOp->getOpcode() != Instruction::Xor)
128 return;
129
130 ConstantInt *CInt = dyn_cast<ConstantInt>(BinOp->getOperand(1));
131 if (!CInt)
132 return;
133
134 V = BinOp->getOperand(0);
135 Operations.push_back(BinOp);
136 }
137
138 // Executes the recorded operations on input 'Value'.
139 auto ApplyOperations = [&](const APInt &Value) {
140 APInt Result = Value;
141 for (auto Op : llvm::reverse(Operations)) {
142 switch (Op->getOpcode()) {
143 case Instruction::Xor:
144 Result ^= cast<ConstantInt>(Op->getOperand(1))->getValue();
145 break;
146 case Instruction::ZExt:
147 Result = Result.zext(Op->getType()->getIntegerBitWidth());
148 break;
149 case Instruction::SExt:
150 Result = Result.sext(Op->getType()->getIntegerBitWidth());
151 break;
152 default:
153 llvm_unreachable("Unexpected operation");
154 }
155 }
156 return Result;
157 };
158
159 auto *PhiDef = dyn_cast<PHINode>(V);
160
161 // Get the first dominating conditional branch of the operand
162 // i's incoming block.
163 auto GetDomConditional = [&](unsigned i) -> BranchInst * {
164 BasicBlock *BB = PhiDef->getIncomingBlock(i);
165 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
166 if (BI && BI->isConditional())
167 return BI;
168 BB = BB->getSinglePredecessor();
169 if (!BB)
170 return nullptr;
171 BI = dyn_cast<BranchInst>(BB->getTerminator());
172 if (!BI || BI->isUnconditional())
173 return nullptr;
174 return BI;
175 };
176
177 // Now walk through all Phi operands to find phi oprerands with values
178 // conflicting with the expected phi output value. Any such operand
179 // indicates the incoming edge to that operand is unlikely.
180 for (unsigned i = 0, e = PhiDef->getNumIncomingValues(); i != e; ++i) {
181
182 Value *PhiOpnd = PhiDef->getIncomingValue(i);
183 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
184 if (!CI)
185 continue;
186
187 // Not an interesting case when IsUnlikely is false -- we can not infer
188 // anything useful when the operand value matches the expected phi
189 // output.
190 if (ExpectedPhiValue == ApplyOperations(CI->getValue()))
191 continue;
192
193 BranchInst *BI = GetDomConditional(i);
194 if (!BI)
195 continue;
196
197 MDBuilder MDB(PhiDef->getContext());
198
199 // There are two situations in which an operand of the PhiDef comes
200 // from a given successor of a branch instruction BI.
201 // 1) When the incoming block of the operand is the successor block;
202 // 2) When the incoming block is BI's enclosing block and the
203 // successor is the PhiDef's enclosing block.
204 //
205 // Returns true if the operand which comes from OpndIncomingBB
206 // comes from outgoing edge of BI that leads to Succ block.
207 auto *OpndIncomingBB = PhiDef->getIncomingBlock(i);
208 auto IsOpndComingFromSuccessor = [&](BasicBlock *Succ) {
209 if (OpndIncomingBB == Succ)
210 // If this successor is the incoming block for this
211 // Phi operand, then this successor does lead to the Phi.
212 return true;
213 if (OpndIncomingBB == BI->getParent() && Succ == PhiDef->getParent())
214 // Otherwise, if the edge is directly from the branch
215 // to the Phi, this successor is the one feeding this
216 // Phi operand.
217 return true;
218 return false;
219 };
220
221 if (IsOpndComingFromSuccessor(BI->getSuccessor(1)))
222 BI->setMetadata(
223 LLVMContext::MD_prof,
224 MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight));
225 else if (IsOpndComingFromSuccessor(BI->getSuccessor(0)))
226 BI->setMetadata(
227 LLVMContext::MD_prof,
228 MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight));
229 }
230}
231
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000232// Handle both BranchInst and SelectInst.
233template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000234
235 // Handle non-optimized IR code like:
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000236 // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000237 // %tobool = icmp ne i64 %expval, 0
238 // br i1 %tobool, label %if.then, label %if.end
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000239 //
240 // Or the following simpler case:
241 // %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
242 // br i1 %expval, label %if.then, label %if.end
243
244 CallInst *CI;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000245
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000246 ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000247 CmpInst::Predicate Predicate;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000248 ConstantInt *CmpConstOperand = nullptr;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000249 if (!CmpI) {
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000250 CI = dyn_cast<CallInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000251 Predicate = CmpInst::ICMP_NE;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000252 } else {
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000253 Predicate = CmpI->getPredicate();
254 if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000255 return false;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000256
257 CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000258 if (!CmpConstOperand)
259 return false;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000260 CI = dyn_cast<CallInst>(CmpI->getOperand(0));
261 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000262
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000263 if (!CI)
264 return false;
265
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000266 uint64_t ValueComparedTo = 0;
267 if (CmpConstOperand) {
268 if (CmpConstOperand->getBitWidth() > 64)
269 return false;
270 ValueComparedTo = CmpConstOperand->getZExtValue();
271 }
272
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000273 Function *Fn = CI->getCalledFunction();
274 if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
275 return false;
276
277 Value *ArgValue = CI->getArgOperand(0);
278 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
279 if (!ExpectedValue)
280 return false;
281
Benjamin Kramer65e75662012-05-26 13:59:43 +0000282 MDBuilder MDB(CI->getContext());
283 MDNode *Node;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000284
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000285 if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
286 (Predicate == CmpInst::ICMP_EQ))
Benjamin Kramer65e75662012-05-26 13:59:43 +0000287 Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
288 else
289 Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000290
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000291 BSI.setMetadata(LLVMContext::MD_prof, Node);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000292
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000293 if (CmpI)
294 CmpI->setOperand(0, ArgValue);
295 else
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000296 BSI.setCondition(ArgValue);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000297 return true;
298}
299
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000300static bool handleBranchExpect(BranchInst &BI) {
301 if (BI.isUnconditional())
302 return false;
303
304 return handleBrSelExpect<BranchInst>(BI);
305}
306
Chandler Carruth43e590e2015-01-24 11:13:02 +0000307static bool lowerExpectIntrinsic(Function &F) {
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000308 bool Changed = false;
309
Chandler Carruthd12741e2015-01-24 10:57:19 +0000310 for (BasicBlock &BB : F) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000311 // Create "block_weights" metadata.
Chandler Carruthd12741e2015-01-24 10:57:19 +0000312 if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000313 if (handleBranchExpect(*BI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000314 ExpectIntrinsicsHandled++;
Chandler Carruthd12741e2015-01-24 10:57:19 +0000315 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000316 if (handleSwitchExpect(*SI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000317 ExpectIntrinsicsHandled++;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000318 }
319
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000320 // Remove llvm.expect intrinsics. Iterate backwards in order
321 // to process select instructions before the intrinsic gets
322 // removed.
323 for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
324 Instruction *Inst = &*BI++;
325 CallInst *CI = dyn_cast<CallInst>(Inst);
326 if (!CI) {
327 if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
328 if (handleBrSelExpect(*SI))
329 ExpectIntrinsicsHandled++;
330 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000331 continue;
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000332 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000333
334 Function *Fn = CI->getCalledFunction();
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000335 if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
Xinliang David Li621e8dc2017-06-02 02:09:31 +0000336 // Before erasing the llvm.expect, walk backward to find
337 // phi that define llvm.expect's first arg, and
338 // infer branch probability:
339 handlePhiDef(CI);
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000340 Value *Exp = CI->getArgOperand(0);
341 CI->replaceAllUsesWith(Exp);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000342 CI->eraseFromParent();
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000343 Changed = true;
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000344 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000345 }
346 }
347
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000348 return Changed;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000349}
350
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000351PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
352 FunctionAnalysisManager &) {
Chandler Carruth43e590e2015-01-24 11:13:02 +0000353 if (lowerExpectIntrinsic(F))
354 return PreservedAnalyses::none();
355
356 return PreservedAnalyses::all();
357}
358
359namespace {
360/// \brief Legacy pass for lowering expect intrinsics out of the IR.
361///
362/// When this pass is run over a function it uses expect intrinsics which feed
363/// branches and switches to provide branch weight metadata for those
364/// terminators. It then removes the expect intrinsics from the IR so the rest
365/// of the optimizer can ignore them.
366class LowerExpectIntrinsic : public FunctionPass {
367public:
368 static char ID;
369 LowerExpectIntrinsic() : FunctionPass(ID) {
370 initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
371 }
372
373 bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
374};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000375}
Chandler Carruth43e590e2015-01-24 11:13:02 +0000376
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000377char LowerExpectIntrinsic::ID = 0;
Chandler Carruth0ea746b2015-01-24 10:30:14 +0000378INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
379 "Lower 'expect' Intrinsics", false, false)
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000380
381FunctionPass *llvm::createLowerExpectIntrinsicPass() {
382 return new LowerExpectIntrinsic();
383}