172793727SChandler Carruth //===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
272793727SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
672793727SChandler Carruth //
772793727SChandler Carruth //===----------------------------------------------------------------------===//
872793727SChandler Carruth //
972793727SChandler Carruth // This pass lowers the 'expect' intrinsic to LLVM metadata.
1072793727SChandler Carruth //
1172793727SChandler Carruth //===----------------------------------------------------------------------===//
1272793727SChandler Carruth
1343e590e5SChandler Carruth #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
143f5e7b1fSChandler Carruth #include "llvm/ADT/SmallVector.h"
1572793727SChandler Carruth #include "llvm/ADT/Statistic.h"
16621e8dcfSXinliang David Li #include "llvm/ADT/iterator_range.h"
1772793727SChandler Carruth #include "llvm/IR/BasicBlock.h"
1872793727SChandler Carruth #include "llvm/IR/Constants.h"
1972793727SChandler Carruth #include "llvm/IR/Function.h"
2072793727SChandler Carruth #include "llvm/IR/Instructions.h"
2172793727SChandler Carruth #include "llvm/IR/Intrinsics.h"
2272793727SChandler Carruth #include "llvm/IR/LLVMContext.h"
2372793727SChandler Carruth #include "llvm/IR/MDBuilder.h"
2405da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
2572793727SChandler Carruth #include "llvm/Pass.h"
26e3a47016SRoman Lebedev #include "llvm/Support/CommandLine.h"
2743e590e5SChandler Carruth #include "llvm/Transforms/Scalar.h"
28*bac6cd5bSPaul Kirth #include "llvm/Transforms/Utils/MisExpect.h"
2972793727SChandler Carruth
3072793727SChandler Carruth using namespace llvm;
3172793727SChandler Carruth
3272793727SChandler Carruth #define DEBUG_TYPE "lower-expect-intrinsic"
3372793727SChandler Carruth
346eb60eb5SChandler Carruth STATISTIC(ExpectIntrinsicsHandled,
356eb60eb5SChandler Carruth "Number of 'expect' intrinsic instructions handled");
3672793727SChandler Carruth
3737d6be90SRoman Lebedev // These default values are chosen to represent an extremely skewed outcome for
3837d6be90SRoman Lebedev // a condition, but they leave some room for interpretation by later passes.
3937d6be90SRoman Lebedev //
4037d6be90SRoman Lebedev // If the documentation for __builtin_expect() was made explicit that it should
4137d6be90SRoman Lebedev // only be used in extreme cases, we could make this ratio higher. As it stands,
4237d6be90SRoman Lebedev // programmers may be using __builtin_expect() / llvm.expect to annotate that a
4337d6be90SRoman Lebedev // branch is likely or unlikely to be taken.
4437d6be90SRoman Lebedev
45e3a47016SRoman Lebedev // WARNING: these values are internal implementation detail of the pass.
46e3a47016SRoman Lebedev // They should not be exposed to the outside of the pass, front-end codegen
47e3a47016SRoman Lebedev // should emit @llvm.expect intrinsics instead of using these weights directly.
48664d0c05SSanjay Patel // Transforms should use TargetTransformInfo's getPredictableBranchThreshold().
49e3a47016SRoman Lebedev static cl::opt<uint32_t> LikelyBranchWeight(
5037d6be90SRoman Lebedev "likely-branch-weight", cl::Hidden, cl::init(2000),
5137d6be90SRoman Lebedev cl::desc("Weight of the branch likely to be taken (default = 2000)"));
52e3a47016SRoman Lebedev static cl::opt<uint32_t> UnlikelyBranchWeight(
5337d6be90SRoman Lebedev "unlikely-branch-weight", cl::Hidden, cl::init(1),
5437d6be90SRoman Lebedev cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
5537d6be90SRoman Lebedev
565c31b8b9SArthur Eubanks static std::tuple<uint32_t, uint32_t>
getBranchWeight(Intrinsic::ID IntrinsicID,CallInst * CI,int BranchCount)57b4447054SBenjamin Kramer getBranchWeight(Intrinsic::ID IntrinsicID, CallInst *CI, int BranchCount) {
5837fb8603SZhi Zhuang if (IntrinsicID == Intrinsic::expect) {
5937fb8603SZhi Zhuang // __builtin_expect
60315bd964SLei Zhang return std::make_tuple(LikelyBranchWeight.getValue(),
61315bd964SLei Zhang UnlikelyBranchWeight.getValue());
6237fb8603SZhi Zhuang } else {
6337fb8603SZhi Zhuang // __builtin_expect_with_probability
6437fb8603SZhi Zhuang assert(CI->getNumOperands() >= 3 &&
6537fb8603SZhi Zhuang "expect with probability must have 3 arguments");
66353484d1SSimon Pilgrim auto *Confidence = cast<ConstantFP>(CI->getArgOperand(2));
6737fb8603SZhi Zhuang double TrueProb = Confidence->getValueAPF().convertToDouble();
6837fb8603SZhi Zhuang assert((TrueProb >= 0.0 && TrueProb <= 1.0) &&
6937fb8603SZhi Zhuang "probability value must be in the range [0.0, 1.0]");
7037fb8603SZhi Zhuang double FalseProb = (1.0 - TrueProb) / (BranchCount - 1);
715c31b8b9SArthur Eubanks uint32_t LikelyBW = ceil((TrueProb * (double)(INT32_MAX - 1)) + 1.0);
725c31b8b9SArthur Eubanks uint32_t UnlikelyBW = ceil((FalseProb * (double)(INT32_MAX - 1)) + 1.0);
73315bd964SLei Zhang return std::make_tuple(LikelyBW, UnlikelyBW);
7437fb8603SZhi Zhuang }
7537fb8603SZhi Zhuang }
7637fb8603SZhi Zhuang
handleSwitchExpect(SwitchInst & SI)770012c778SChandler Carruth static bool handleSwitchExpect(SwitchInst &SI) {
780012c778SChandler Carruth CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
7972793727SChandler Carruth if (!CI)
8072793727SChandler Carruth return false;
8172793727SChandler Carruth
8272793727SChandler Carruth Function *Fn = CI->getCalledFunction();
8337fb8603SZhi Zhuang if (!Fn || (Fn->getIntrinsicID() != Intrinsic::expect &&
8437fb8603SZhi Zhuang Fn->getIntrinsicID() != Intrinsic::expect_with_probability))
8572793727SChandler Carruth return false;
8672793727SChandler Carruth
8772793727SChandler Carruth Value *ArgValue = CI->getArgOperand(0);
8872793727SChandler Carruth ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
8972793727SChandler Carruth if (!ExpectedValue)
9072793727SChandler Carruth return false;
9172793727SChandler Carruth
92927d8e61SChandler Carruth SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
930012c778SChandler Carruth unsigned n = SI.getNumCases(); // +1 for default case.
945c31b8b9SArthur Eubanks uint32_t LikelyBranchWeightVal, UnlikelyBranchWeightVal;
9537fb8603SZhi Zhuang std::tie(LikelyBranchWeightVal, UnlikelyBranchWeightVal) =
9637fb8603SZhi Zhuang getBranchWeight(Fn->getIntrinsicID(), CI, n + 1);
9737fb8603SZhi Zhuang
985c31b8b9SArthur Eubanks SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeightVal);
9972793727SChandler Carruth
1007bdad084SPetr Hosek uint64_t Index = (Case == *SI.case_default()) ? 0 : Case.getCaseIndex() + 1;
10137fb8603SZhi Zhuang Weights[Index] = LikelyBranchWeightVal;
1027bdad084SPetr Hosek
103*bac6cd5bSPaul Kirth misexpect::checkExpectAnnotations(SI, Weights, /*IsFrontend=*/true);
104*bac6cd5bSPaul Kirth
1057bdad084SPetr Hosek SI.setCondition(ArgValue);
10672793727SChandler Carruth
1070012c778SChandler Carruth SI.setMetadata(LLVMContext::MD_prof,
10872793727SChandler Carruth MDBuilder(CI->getContext()).createBranchWeights(Weights));
10972793727SChandler Carruth
11072793727SChandler Carruth return true;
11172793727SChandler Carruth }
11272793727SChandler Carruth
113621e8dcfSXinliang David Li /// Handler for PHINodes that define the value argument to an
114621e8dcfSXinliang David Li /// @llvm.expect call.
115621e8dcfSXinliang David Li ///
116621e8dcfSXinliang David Li /// If the operand of the phi has a constant value and it 'contradicts'
117621e8dcfSXinliang David Li /// with the expected value of phi def, then the corresponding incoming
118621e8dcfSXinliang David Li /// edge of the phi is unlikely to be taken. Using that information,
119621e8dcfSXinliang David Li /// the branch probability info for the originating branch can be inferred.
handlePhiDef(CallInst * Expect)120621e8dcfSXinliang David Li static void handlePhiDef(CallInst *Expect) {
121621e8dcfSXinliang David Li Value &Arg = *Expect->getArgOperand(0);
1224f49bee7SXinliang David Li ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(Expect->getArgOperand(1));
1234f49bee7SXinliang David Li if (!ExpectedValue)
1244f49bee7SXinliang David Li return;
125621e8dcfSXinliang David Li const APInt &ExpectedPhiValue = ExpectedValue->getValue();
126621e8dcfSXinliang David Li
127621e8dcfSXinliang David Li // Walk up in backward a list of instructions that
128621e8dcfSXinliang David Li // have 'copy' semantics by 'stripping' the copies
129621e8dcfSXinliang David Li // until a PHI node or an instruction of unknown kind
130621e8dcfSXinliang David Li // is reached. Negation via xor is also handled.
131621e8dcfSXinliang David Li //
132621e8dcfSXinliang David Li // C = PHI(...);
133621e8dcfSXinliang David Li // B = C;
134621e8dcfSXinliang David Li // A = B;
135621e8dcfSXinliang David Li // D = __builtin_expect(A, 0);
136621e8dcfSXinliang David Li //
137621e8dcfSXinliang David Li Value *V = &Arg;
138621e8dcfSXinliang David Li SmallVector<Instruction *, 4> Operations;
139621e8dcfSXinliang David Li while (!isa<PHINode>(V)) {
140621e8dcfSXinliang David Li if (ZExtInst *ZExt = dyn_cast<ZExtInst>(V)) {
141621e8dcfSXinliang David Li V = ZExt->getOperand(0);
142621e8dcfSXinliang David Li Operations.push_back(ZExt);
143621e8dcfSXinliang David Li continue;
144621e8dcfSXinliang David Li }
145621e8dcfSXinliang David Li
146621e8dcfSXinliang David Li if (SExtInst *SExt = dyn_cast<SExtInst>(V)) {
147621e8dcfSXinliang David Li V = SExt->getOperand(0);
148621e8dcfSXinliang David Li Operations.push_back(SExt);
149621e8dcfSXinliang David Li continue;
150621e8dcfSXinliang David Li }
151621e8dcfSXinliang David Li
152621e8dcfSXinliang David Li BinaryOperator *BinOp = dyn_cast<BinaryOperator>(V);
153621e8dcfSXinliang David Li if (!BinOp || BinOp->getOpcode() != Instruction::Xor)
154621e8dcfSXinliang David Li return;
155621e8dcfSXinliang David Li
156621e8dcfSXinliang David Li ConstantInt *CInt = dyn_cast<ConstantInt>(BinOp->getOperand(1));
157621e8dcfSXinliang David Li if (!CInt)
158621e8dcfSXinliang David Li return;
159621e8dcfSXinliang David Li
160621e8dcfSXinliang David Li V = BinOp->getOperand(0);
161621e8dcfSXinliang David Li Operations.push_back(BinOp);
162621e8dcfSXinliang David Li }
163621e8dcfSXinliang David Li
164621e8dcfSXinliang David Li // Executes the recorded operations on input 'Value'.
165621e8dcfSXinliang David Li auto ApplyOperations = [&](const APInt &Value) {
166621e8dcfSXinliang David Li APInt Result = Value;
167621e8dcfSXinliang David Li for (auto Op : llvm::reverse(Operations)) {
168621e8dcfSXinliang David Li switch (Op->getOpcode()) {
169621e8dcfSXinliang David Li case Instruction::Xor:
170621e8dcfSXinliang David Li Result ^= cast<ConstantInt>(Op->getOperand(1))->getValue();
171621e8dcfSXinliang David Li break;
172621e8dcfSXinliang David Li case Instruction::ZExt:
173621e8dcfSXinliang David Li Result = Result.zext(Op->getType()->getIntegerBitWidth());
174621e8dcfSXinliang David Li break;
175621e8dcfSXinliang David Li case Instruction::SExt:
176621e8dcfSXinliang David Li Result = Result.sext(Op->getType()->getIntegerBitWidth());
177621e8dcfSXinliang David Li break;
178621e8dcfSXinliang David Li default:
179621e8dcfSXinliang David Li llvm_unreachable("Unexpected operation");
180621e8dcfSXinliang David Li }
181621e8dcfSXinliang David Li }
182621e8dcfSXinliang David Li return Result;
183621e8dcfSXinliang David Li };
184621e8dcfSXinliang David Li
18591b4085bSSimon Pilgrim auto *PhiDef = cast<PHINode>(V);
186621e8dcfSXinliang David Li
187621e8dcfSXinliang David Li // Get the first dominating conditional branch of the operand
188621e8dcfSXinliang David Li // i's incoming block.
189621e8dcfSXinliang David Li auto GetDomConditional = [&](unsigned i) -> BranchInst * {
190621e8dcfSXinliang David Li BasicBlock *BB = PhiDef->getIncomingBlock(i);
191621e8dcfSXinliang David Li BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
192621e8dcfSXinliang David Li if (BI && BI->isConditional())
193621e8dcfSXinliang David Li return BI;
194621e8dcfSXinliang David Li BB = BB->getSinglePredecessor();
195621e8dcfSXinliang David Li if (!BB)
196621e8dcfSXinliang David Li return nullptr;
197621e8dcfSXinliang David Li BI = dyn_cast<BranchInst>(BB->getTerminator());
198621e8dcfSXinliang David Li if (!BI || BI->isUnconditional())
199621e8dcfSXinliang David Li return nullptr;
200621e8dcfSXinliang David Li return BI;
201621e8dcfSXinliang David Li };
202621e8dcfSXinliang David Li
203621e8dcfSXinliang David Li // Now walk through all Phi operands to find phi oprerands with values
204621e8dcfSXinliang David Li // conflicting with the expected phi output value. Any such operand
205621e8dcfSXinliang David Li // indicates the incoming edge to that operand is unlikely.
206621e8dcfSXinliang David Li for (unsigned i = 0, e = PhiDef->getNumIncomingValues(); i != e; ++i) {
207621e8dcfSXinliang David Li
208621e8dcfSXinliang David Li Value *PhiOpnd = PhiDef->getIncomingValue(i);
209621e8dcfSXinliang David Li ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
210621e8dcfSXinliang David Li if (!CI)
211621e8dcfSXinliang David Li continue;
212621e8dcfSXinliang David Li
213621e8dcfSXinliang David Li // Not an interesting case when IsUnlikely is false -- we can not infer
214621e8dcfSXinliang David Li // anything useful when the operand value matches the expected phi
215621e8dcfSXinliang David Li // output.
216621e8dcfSXinliang David Li if (ExpectedPhiValue == ApplyOperations(CI->getValue()))
217621e8dcfSXinliang David Li continue;
218621e8dcfSXinliang David Li
219621e8dcfSXinliang David Li BranchInst *BI = GetDomConditional(i);
220621e8dcfSXinliang David Li if (!BI)
221621e8dcfSXinliang David Li continue;
222621e8dcfSXinliang David Li
223621e8dcfSXinliang David Li MDBuilder MDB(PhiDef->getContext());
224621e8dcfSXinliang David Li
225621e8dcfSXinliang David Li // There are two situations in which an operand of the PhiDef comes
226621e8dcfSXinliang David Li // from a given successor of a branch instruction BI.
227621e8dcfSXinliang David Li // 1) When the incoming block of the operand is the successor block;
228621e8dcfSXinliang David Li // 2) When the incoming block is BI's enclosing block and the
229621e8dcfSXinliang David Li // successor is the PhiDef's enclosing block.
230621e8dcfSXinliang David Li //
231621e8dcfSXinliang David Li // Returns true if the operand which comes from OpndIncomingBB
232621e8dcfSXinliang David Li // comes from outgoing edge of BI that leads to Succ block.
233621e8dcfSXinliang David Li auto *OpndIncomingBB = PhiDef->getIncomingBlock(i);
234621e8dcfSXinliang David Li auto IsOpndComingFromSuccessor = [&](BasicBlock *Succ) {
235621e8dcfSXinliang David Li if (OpndIncomingBB == Succ)
236621e8dcfSXinliang David Li // If this successor is the incoming block for this
237621e8dcfSXinliang David Li // Phi operand, then this successor does lead to the Phi.
238621e8dcfSXinliang David Li return true;
239621e8dcfSXinliang David Li if (OpndIncomingBB == BI->getParent() && Succ == PhiDef->getParent())
240621e8dcfSXinliang David Li // Otherwise, if the edge is directly from the branch
241621e8dcfSXinliang David Li // to the Phi, this successor is the one feeding this
242621e8dcfSXinliang David Li // Phi operand.
243621e8dcfSXinliang David Li return true;
244621e8dcfSXinliang David Li return false;
245621e8dcfSXinliang David Li };
2465c31b8b9SArthur Eubanks uint32_t LikelyBranchWeightVal, UnlikelyBranchWeightVal;
24737fb8603SZhi Zhuang std::tie(LikelyBranchWeightVal, UnlikelyBranchWeightVal) = getBranchWeight(
24837fb8603SZhi Zhuang Expect->getCalledFunction()->getIntrinsicID(), Expect, 2);
249621e8dcfSXinliang David Li
250621e8dcfSXinliang David Li if (IsOpndComingFromSuccessor(BI->getSuccessor(1)))
25137fb8603SZhi Zhuang BI->setMetadata(LLVMContext::MD_prof,
25237fb8603SZhi Zhuang MDB.createBranchWeights(LikelyBranchWeightVal,
25337fb8603SZhi Zhuang UnlikelyBranchWeightVal));
254621e8dcfSXinliang David Li else if (IsOpndComingFromSuccessor(BI->getSuccessor(0)))
25537fb8603SZhi Zhuang BI->setMetadata(LLVMContext::MD_prof,
25637fb8603SZhi Zhuang MDB.createBranchWeights(UnlikelyBranchWeightVal,
25737fb8603SZhi Zhuang LikelyBranchWeightVal));
258621e8dcfSXinliang David Li }
259621e8dcfSXinliang David Li }
260621e8dcfSXinliang David Li
26140afd5c9SXinliang David Li // Handle both BranchInst and SelectInst.
handleBrSelExpect(BrSelInst & BSI)26240afd5c9SXinliang David Li template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
26372793727SChandler Carruth
26472793727SChandler Carruth // Handle non-optimized IR code like:
26572793727SChandler Carruth // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
26672793727SChandler Carruth // %tobool = icmp ne i64 %expval, 0
26772793727SChandler Carruth // br i1 %tobool, label %if.then, label %if.end
26872793727SChandler Carruth //
26972793727SChandler Carruth // Or the following simpler case:
27072793727SChandler Carruth // %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
27172793727SChandler Carruth // br i1 %expval, label %if.then, label %if.end
27272793727SChandler Carruth
27372793727SChandler Carruth CallInst *CI;
27472793727SChandler Carruth
27540afd5c9SXinliang David Li ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
276ee8d6acbSXinliang David Li CmpInst::Predicate Predicate;
277d6cfba2aSXinliang David Li ConstantInt *CmpConstOperand = nullptr;
27872793727SChandler Carruth if (!CmpI) {
27940afd5c9SXinliang David Li CI = dyn_cast<CallInst>(BSI.getCondition());
280ee8d6acbSXinliang David Li Predicate = CmpInst::ICMP_NE;
28172793727SChandler Carruth } else {
282ee8d6acbSXinliang David Li Predicate = CmpI->getPredicate();
283ee8d6acbSXinliang David Li if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
28472793727SChandler Carruth return false;
285d6cfba2aSXinliang David Li
286d6cfba2aSXinliang David Li CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
287ee8d6acbSXinliang David Li if (!CmpConstOperand)
288ee8d6acbSXinliang David Li return false;
28972793727SChandler Carruth CI = dyn_cast<CallInst>(CmpI->getOperand(0));
29072793727SChandler Carruth }
29172793727SChandler Carruth
29272793727SChandler Carruth if (!CI)
29372793727SChandler Carruth return false;
29472793727SChandler Carruth
295d6cfba2aSXinliang David Li uint64_t ValueComparedTo = 0;
296d6cfba2aSXinliang David Li if (CmpConstOperand) {
297d6cfba2aSXinliang David Li if (CmpConstOperand->getBitWidth() > 64)
298d6cfba2aSXinliang David Li return false;
299d6cfba2aSXinliang David Li ValueComparedTo = CmpConstOperand->getZExtValue();
300d6cfba2aSXinliang David Li }
301d6cfba2aSXinliang David Li
30272793727SChandler Carruth Function *Fn = CI->getCalledFunction();
30337fb8603SZhi Zhuang if (!Fn || (Fn->getIntrinsicID() != Intrinsic::expect &&
30437fb8603SZhi Zhuang Fn->getIntrinsicID() != Intrinsic::expect_with_probability))
30572793727SChandler Carruth return false;
30672793727SChandler Carruth
30772793727SChandler Carruth Value *ArgValue = CI->getArgOperand(0);
30872793727SChandler Carruth ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
30972793727SChandler Carruth if (!ExpectedValue)
31072793727SChandler Carruth return false;
31172793727SChandler Carruth
31272793727SChandler Carruth MDBuilder MDB(CI->getContext());
31372793727SChandler Carruth MDNode *Node;
31472793727SChandler Carruth
3155c31b8b9SArthur Eubanks uint32_t LikelyBranchWeightVal, UnlikelyBranchWeightVal;
31637fb8603SZhi Zhuang std::tie(LikelyBranchWeightVal, UnlikelyBranchWeightVal) =
31737fb8603SZhi Zhuang getBranchWeight(Fn->getIntrinsicID(), CI, 2);
31837fb8603SZhi Zhuang
319*bac6cd5bSPaul Kirth SmallVector<uint32_t, 4> ExpectedWeights;
320ee8d6acbSXinliang David Li if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
3217bdad084SPetr Hosek (Predicate == CmpInst::ICMP_EQ)) {
32237fb8603SZhi Zhuang Node =
32337fb8603SZhi Zhuang MDB.createBranchWeights(LikelyBranchWeightVal, UnlikelyBranchWeightVal);
324*bac6cd5bSPaul Kirth ExpectedWeights = {LikelyBranchWeightVal, UnlikelyBranchWeightVal};
3257bdad084SPetr Hosek } else {
32637fb8603SZhi Zhuang Node =
32737fb8603SZhi Zhuang MDB.createBranchWeights(UnlikelyBranchWeightVal, LikelyBranchWeightVal);
328*bac6cd5bSPaul Kirth ExpectedWeights = {UnlikelyBranchWeightVal, LikelyBranchWeightVal};
3297bdad084SPetr Hosek }
33072793727SChandler Carruth
33172793727SChandler Carruth if (CmpI)
33272793727SChandler Carruth CmpI->setOperand(0, ArgValue);
33372793727SChandler Carruth else
33440afd5c9SXinliang David Li BSI.setCondition(ArgValue);
3357bdad084SPetr Hosek
336*bac6cd5bSPaul Kirth misexpect::checkFrontendInstrumentation(BSI, ExpectedWeights);
337*bac6cd5bSPaul Kirth
3387bdad084SPetr Hosek BSI.setMetadata(LLVMContext::MD_prof, Node);
3397bdad084SPetr Hosek
34072793727SChandler Carruth return true;
34172793727SChandler Carruth }
34272793727SChandler Carruth
handleBranchExpect(BranchInst & BI)34340afd5c9SXinliang David Li static bool handleBranchExpect(BranchInst &BI) {
34440afd5c9SXinliang David Li if (BI.isUnconditional())
34540afd5c9SXinliang David Li return false;
34640afd5c9SXinliang David Li
34740afd5c9SXinliang David Li return handleBrSelExpect<BranchInst>(BI);
34840afd5c9SXinliang David Li }
34940afd5c9SXinliang David Li
lowerExpectIntrinsic(Function & F)35043e590e5SChandler Carruth static bool lowerExpectIntrinsic(Function &F) {
351c3bf5bd8SChandler Carruth bool Changed = false;
352c3bf5bd8SChandler Carruth
353d12741e0SChandler Carruth for (BasicBlock &BB : F) {
35472793727SChandler Carruth // Create "block_weights" metadata.
355d12741e0SChandler Carruth if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
3560012c778SChandler Carruth if (handleBranchExpect(*BI))
3576eb60eb5SChandler Carruth ExpectIntrinsicsHandled++;
358d12741e0SChandler Carruth } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
3590012c778SChandler Carruth if (handleSwitchExpect(*SI))
3606eb60eb5SChandler Carruth ExpectIntrinsicsHandled++;
36172793727SChandler Carruth }
36272793727SChandler Carruth
36340afd5c9SXinliang David Li // Remove llvm.expect intrinsics. Iterate backwards in order
36440afd5c9SXinliang David Li // to process select instructions before the intrinsic gets
36540afd5c9SXinliang David Li // removed.
3661b108ab9SKazu Hirata for (Instruction &Inst : llvm::make_early_inc_range(llvm::reverse(BB))) {
3671b108ab9SKazu Hirata CallInst *CI = dyn_cast<CallInst>(&Inst);
36840afd5c9SXinliang David Li if (!CI) {
3691b108ab9SKazu Hirata if (SelectInst *SI = dyn_cast<SelectInst>(&Inst)) {
37040afd5c9SXinliang David Li if (handleBrSelExpect(*SI))
37140afd5c9SXinliang David Li ExpectIntrinsicsHandled++;
37240afd5c9SXinliang David Li }
37372793727SChandler Carruth continue;
37440afd5c9SXinliang David Li }
37572793727SChandler Carruth
37672793727SChandler Carruth Function *Fn = CI->getCalledFunction();
37737fb8603SZhi Zhuang if (Fn && (Fn->getIntrinsicID() == Intrinsic::expect ||
37837fb8603SZhi Zhuang Fn->getIntrinsicID() == Intrinsic::expect_with_probability)) {
379621e8dcfSXinliang David Li // Before erasing the llvm.expect, walk backward to find
380621e8dcfSXinliang David Li // phi that define llvm.expect's first arg, and
381621e8dcfSXinliang David Li // infer branch probability:
382621e8dcfSXinliang David Li handlePhiDef(CI);
38372793727SChandler Carruth Value *Exp = CI->getArgOperand(0);
38472793727SChandler Carruth CI->replaceAllUsesWith(Exp);
38572793727SChandler Carruth CI->eraseFromParent();
386c3bf5bd8SChandler Carruth Changed = true;
38772793727SChandler Carruth }
38872793727SChandler Carruth }
38972793727SChandler Carruth }
39072793727SChandler Carruth
391c3bf5bd8SChandler Carruth return Changed;
39272793727SChandler Carruth }
39372793727SChandler Carruth
run(Function & F,FunctionAnalysisManager &)394164a2aa6SChandler Carruth PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
395164a2aa6SChandler Carruth FunctionAnalysisManager &) {
39643e590e5SChandler Carruth if (lowerExpectIntrinsic(F))
39743e590e5SChandler Carruth return PreservedAnalyses::none();
39843e590e5SChandler Carruth
39943e590e5SChandler Carruth return PreservedAnalyses::all();
40043e590e5SChandler Carruth }
40143e590e5SChandler Carruth
40243e590e5SChandler Carruth namespace {
4035f8f34e4SAdrian Prantl /// Legacy pass for lowering expect intrinsics out of the IR.
40443e590e5SChandler Carruth ///
40543e590e5SChandler Carruth /// When this pass is run over a function it uses expect intrinsics which feed
40643e590e5SChandler Carruth /// branches and switches to provide branch weight metadata for those
40743e590e5SChandler Carruth /// terminators. It then removes the expect intrinsics from the IR so the rest
40843e590e5SChandler Carruth /// of the optimizer can ignore them.
40943e590e5SChandler Carruth class LowerExpectIntrinsic : public FunctionPass {
41043e590e5SChandler Carruth public:
41143e590e5SChandler Carruth static char ID;
LowerExpectIntrinsic()41243e590e5SChandler Carruth LowerExpectIntrinsic() : FunctionPass(ID) {
41343e590e5SChandler Carruth initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
41443e590e5SChandler Carruth }
41543e590e5SChandler Carruth
runOnFunction(Function & F)41643e590e5SChandler Carruth bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
41743e590e5SChandler Carruth };
418*bac6cd5bSPaul Kirth } // namespace
41943e590e5SChandler Carruth
42072793727SChandler Carruth char LowerExpectIntrinsic::ID = 0;
4210ea746bfSChandler Carruth INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
4220ea746bfSChandler Carruth "Lower 'expect' Intrinsics", false, false)
42372793727SChandler Carruth
createLowerExpectIntrinsicPass()42472793727SChandler Carruth FunctionPass *llvm::createLowerExpectIntrinsicPass() {
42572793727SChandler Carruth return new LowerExpectIntrinsic();
42672793727SChandler Carruth }
427