blob: 7d8da9b453f9fd93b4945ca1ceebe6ccf4f08781 [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);
96 ConstantInt *ExpectedValue = cast<ConstantInt>(Expect->getArgOperand(1));
97 const APInt &ExpectedPhiValue = ExpectedValue->getValue();
98
99 // Walk up in backward a list of instructions that
100 // have 'copy' semantics by 'stripping' the copies
101 // until a PHI node or an instruction of unknown kind
102 // is reached. Negation via xor is also handled.
103 //
104 // C = PHI(...);
105 // B = C;
106 // A = B;
107 // D = __builtin_expect(A, 0);
108 //
109 Value *V = &Arg;
110 SmallVector<Instruction *, 4> Operations;
111 while (!isa<PHINode>(V)) {
112 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(V)) {
113 V = ZExt->getOperand(0);
114 Operations.push_back(ZExt);
115 continue;
116 }
117
118 if (SExtInst *SExt = dyn_cast<SExtInst>(V)) {
119 V = SExt->getOperand(0);
120 Operations.push_back(SExt);
121 continue;
122 }
123
124 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(V);
125 if (!BinOp || BinOp->getOpcode() != Instruction::Xor)
126 return;
127
128 ConstantInt *CInt = dyn_cast<ConstantInt>(BinOp->getOperand(1));
129 if (!CInt)
130 return;
131
132 V = BinOp->getOperand(0);
133 Operations.push_back(BinOp);
134 }
135
136 // Executes the recorded operations on input 'Value'.
137 auto ApplyOperations = [&](const APInt &Value) {
138 APInt Result = Value;
139 for (auto Op : llvm::reverse(Operations)) {
140 switch (Op->getOpcode()) {
141 case Instruction::Xor:
142 Result ^= cast<ConstantInt>(Op->getOperand(1))->getValue();
143 break;
144 case Instruction::ZExt:
145 Result = Result.zext(Op->getType()->getIntegerBitWidth());
146 break;
147 case Instruction::SExt:
148 Result = Result.sext(Op->getType()->getIntegerBitWidth());
149 break;
150 default:
151 llvm_unreachable("Unexpected operation");
152 }
153 }
154 return Result;
155 };
156
157 auto *PhiDef = dyn_cast<PHINode>(V);
158
159 // Get the first dominating conditional branch of the operand
160 // i's incoming block.
161 auto GetDomConditional = [&](unsigned i) -> BranchInst * {
162 BasicBlock *BB = PhiDef->getIncomingBlock(i);
163 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
164 if (BI && BI->isConditional())
165 return BI;
166 BB = BB->getSinglePredecessor();
167 if (!BB)
168 return nullptr;
169 BI = dyn_cast<BranchInst>(BB->getTerminator());
170 if (!BI || BI->isUnconditional())
171 return nullptr;
172 return BI;
173 };
174
175 // Now walk through all Phi operands to find phi oprerands with values
176 // conflicting with the expected phi output value. Any such operand
177 // indicates the incoming edge to that operand is unlikely.
178 for (unsigned i = 0, e = PhiDef->getNumIncomingValues(); i != e; ++i) {
179
180 Value *PhiOpnd = PhiDef->getIncomingValue(i);
181 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
182 if (!CI)
183 continue;
184
185 // Not an interesting case when IsUnlikely is false -- we can not infer
186 // anything useful when the operand value matches the expected phi
187 // output.
188 if (ExpectedPhiValue == ApplyOperations(CI->getValue()))
189 continue;
190
191 BranchInst *BI = GetDomConditional(i);
192 if (!BI)
193 continue;
194
195 MDBuilder MDB(PhiDef->getContext());
196
197 // There are two situations in which an operand of the PhiDef comes
198 // from a given successor of a branch instruction BI.
199 // 1) When the incoming block of the operand is the successor block;
200 // 2) When the incoming block is BI's enclosing block and the
201 // successor is the PhiDef's enclosing block.
202 //
203 // Returns true if the operand which comes from OpndIncomingBB
204 // comes from outgoing edge of BI that leads to Succ block.
205 auto *OpndIncomingBB = PhiDef->getIncomingBlock(i);
206 auto IsOpndComingFromSuccessor = [&](BasicBlock *Succ) {
207 if (OpndIncomingBB == Succ)
208 // If this successor is the incoming block for this
209 // Phi operand, then this successor does lead to the Phi.
210 return true;
211 if (OpndIncomingBB == BI->getParent() && Succ == PhiDef->getParent())
212 // Otherwise, if the edge is directly from the branch
213 // to the Phi, this successor is the one feeding this
214 // Phi operand.
215 return true;
216 return false;
217 };
218
219 if (IsOpndComingFromSuccessor(BI->getSuccessor(1)))
220 BI->setMetadata(
221 LLVMContext::MD_prof,
222 MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight));
223 else if (IsOpndComingFromSuccessor(BI->getSuccessor(0)))
224 BI->setMetadata(
225 LLVMContext::MD_prof,
226 MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight));
227 }
228}
229
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000230// Handle both BranchInst and SelectInst.
231template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000232
233 // Handle non-optimized IR code like:
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000234 // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000235 // %tobool = icmp ne i64 %expval, 0
236 // br i1 %tobool, label %if.then, label %if.end
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000237 //
238 // Or the following simpler case:
239 // %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
240 // br i1 %expval, label %if.then, label %if.end
241
242 CallInst *CI;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000243
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000244 ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000245 CmpInst::Predicate Predicate;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000246 ConstantInt *CmpConstOperand = nullptr;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000247 if (!CmpI) {
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000248 CI = dyn_cast<CallInst>(BSI.getCondition());
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000249 Predicate = CmpInst::ICMP_NE;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000250 } else {
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000251 Predicate = CmpI->getPredicate();
252 if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000253 return false;
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000254
255 CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000256 if (!CmpConstOperand)
257 return false;
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000258 CI = dyn_cast<CallInst>(CmpI->getOperand(0));
259 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000260
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000261 if (!CI)
262 return false;
263
Xinliang David Lid6cfba22017-06-01 23:05:11 +0000264 uint64_t ValueComparedTo = 0;
265 if (CmpConstOperand) {
266 if (CmpConstOperand->getBitWidth() > 64)
267 return false;
268 ValueComparedTo = CmpConstOperand->getZExtValue();
269 }
270
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000271 Function *Fn = CI->getCalledFunction();
272 if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
273 return false;
274
275 Value *ArgValue = CI->getArgOperand(0);
276 ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
277 if (!ExpectedValue)
278 return false;
279
Benjamin Kramer65e75662012-05-26 13:59:43 +0000280 MDBuilder MDB(CI->getContext());
281 MDNode *Node;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000282
Xinliang David Liee8d6ac2017-06-01 19:05:55 +0000283 if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
284 (Predicate == CmpInst::ICMP_EQ))
Benjamin Kramer65e75662012-05-26 13:59:43 +0000285 Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
286 else
287 Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000288
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000289 BSI.setMetadata(LLVMContext::MD_prof, Node);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000290
Duncan P. N. Exon Smith1ff08e32014-02-02 22:43:55 +0000291 if (CmpI)
292 CmpI->setOperand(0, ArgValue);
293 else
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000294 BSI.setCondition(ArgValue);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000295 return true;
296}
297
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000298static bool handleBranchExpect(BranchInst &BI) {
299 if (BI.isUnconditional())
300 return false;
301
302 return handleBrSelExpect<BranchInst>(BI);
303}
304
Chandler Carruth43e590e2015-01-24 11:13:02 +0000305static bool lowerExpectIntrinsic(Function &F) {
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000306 bool Changed = false;
307
Chandler Carruthd12741e2015-01-24 10:57:19 +0000308 for (BasicBlock &BB : F) {
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000309 // Create "block_weights" metadata.
Chandler Carruthd12741e2015-01-24 10:57:19 +0000310 if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000311 if (handleBranchExpect(*BI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000312 ExpectIntrinsicsHandled++;
Chandler Carruthd12741e2015-01-24 10:57:19 +0000313 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
Chandler Carruth0012c772015-01-24 10:39:24 +0000314 if (handleSwitchExpect(*SI))
Chandler Carruth6eb60eb2015-01-24 10:57:25 +0000315 ExpectIntrinsicsHandled++;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000316 }
317
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000318 // Remove llvm.expect intrinsics. Iterate backwards in order
319 // to process select instructions before the intrinsic gets
320 // removed.
321 for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
322 Instruction *Inst = &*BI++;
323 CallInst *CI = dyn_cast<CallInst>(Inst);
324 if (!CI) {
325 if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
326 if (handleBrSelExpect(*SI))
327 ExpectIntrinsicsHandled++;
328 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000329 continue;
Xinliang David Li40afd5c2016-09-02 22:03:40 +0000330 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000331
332 Function *Fn = CI->getCalledFunction();
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000333 if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
Xinliang David Li621e8dc2017-06-02 02:09:31 +0000334 // Before erasing the llvm.expect, walk backward to find
335 // phi that define llvm.expect's first arg, and
336 // infer branch probability:
337 handlePhiDef(CI);
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000338 Value *Exp = CI->getArgOperand(0);
339 CI->replaceAllUsesWith(Exp);
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000340 CI->eraseFromParent();
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000341 Changed = true;
Jakub Staszaka11f7ec2011-07-06 23:50:16 +0000342 }
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000343 }
344 }
345
Chandler Carruthc3bf5bd2015-01-24 11:12:57 +0000346 return Changed;
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000347}
348
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000349PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
350 FunctionAnalysisManager &) {
Chandler Carruth43e590e2015-01-24 11:13:02 +0000351 if (lowerExpectIntrinsic(F))
352 return PreservedAnalyses::none();
353
354 return PreservedAnalyses::all();
355}
356
357namespace {
358/// \brief Legacy pass for lowering expect intrinsics out of the IR.
359///
360/// When this pass is run over a function it uses expect intrinsics which feed
361/// branches and switches to provide branch weight metadata for those
362/// terminators. It then removes the expect intrinsics from the IR so the rest
363/// of the optimizer can ignore them.
364class LowerExpectIntrinsic : public FunctionPass {
365public:
366 static char ID;
367 LowerExpectIntrinsic() : FunctionPass(ID) {
368 initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
369 }
370
371 bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
372};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000373}
Chandler Carruth43e590e2015-01-24 11:13:02 +0000374
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000375char LowerExpectIntrinsic::ID = 0;
Chandler Carruth0ea746b2015-01-24 10:30:14 +0000376INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
377 "Lower 'expect' Intrinsics", false, false)
Jakub Staszak3f158fd2011-07-06 18:22:43 +0000378
379FunctionPass *llvm::createLowerExpectIntrinsicPass() {
380 return new LowerExpectIntrinsic();
381}