172793727SChandler Carruth //===- LowerExpectIntrinsic.cpp - Lower expect intrinsic ------------------===//
272793727SChandler Carruth //
372793727SChandler Carruth //                     The LLVM Compiler Infrastructure
472793727SChandler Carruth //
572793727SChandler Carruth // This file is distributed under the University of Illinois Open Source
672793727SChandler Carruth // License. See LICENSE.TXT for details.
772793727SChandler Carruth //
872793727SChandler Carruth //===----------------------------------------------------------------------===//
972793727SChandler Carruth //
1072793727SChandler Carruth // This pass lowers the 'expect' intrinsic to LLVM metadata.
1172793727SChandler Carruth //
1272793727SChandler Carruth //===----------------------------------------------------------------------===//
1372793727SChandler Carruth 
1443e590e5SChandler Carruth #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
153f5e7b1fSChandler Carruth #include "llvm/ADT/SmallVector.h"
1672793727SChandler Carruth #include "llvm/ADT/Statistic.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"
2472793727SChandler Carruth #include "llvm/IR/Metadata.h"
2572793727SChandler Carruth #include "llvm/Pass.h"
2672793727SChandler Carruth #include "llvm/Support/CommandLine.h"
2772793727SChandler Carruth #include "llvm/Support/Debug.h"
2843e590e5SChandler Carruth #include "llvm/Transforms/Scalar.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 
37d2d2aa52SSanjay Patel // These default values are chosen to represent an extremely skewed outcome for
38d2d2aa52SSanjay Patel // a condition, but they leave some room for interpretation by later passes.
39d2d2aa52SSanjay Patel //
40d2d2aa52SSanjay Patel // If the documentation for __builtin_expect() was made explicit that it should
41d2d2aa52SSanjay Patel // only be used in extreme cases, we could make this ratio higher. As it stands,
42d2d2aa52SSanjay Patel // programmers may be using __builtin_expect() / llvm.expect to annotate that a
43d2d2aa52SSanjay Patel // branch is likely or unlikely to be taken.
44d2d2aa52SSanjay Patel //
45d2d2aa52SSanjay Patel // There is a known dependency on this ratio in CodeGenPrepare when transforming
46d2d2aa52SSanjay Patel // 'select' instructions. It may be worthwhile to hoist these values to some
47d2d2aa52SSanjay Patel // shared space, so they can be used directly by other passes.
48d2d2aa52SSanjay Patel 
49d2d2aa52SSanjay Patel static cl::opt<uint32_t> LikelyBranchWeight(
50d2d2aa52SSanjay Patel     "likely-branch-weight", cl::Hidden, cl::init(2000),
51d2d2aa52SSanjay Patel     cl::desc("Weight of the branch likely to be taken (default = 2000)"));
52d2d2aa52SSanjay Patel static cl::opt<uint32_t> UnlikelyBranchWeight(
53d2d2aa52SSanjay Patel     "unlikely-branch-weight", cl::Hidden, cl::init(1),
54d2d2aa52SSanjay Patel     cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
5572793727SChandler Carruth 
560012c778SChandler Carruth static bool handleSwitchExpect(SwitchInst &SI) {
570012c778SChandler Carruth   CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
5872793727SChandler Carruth   if (!CI)
5972793727SChandler Carruth     return false;
6072793727SChandler Carruth 
6172793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
6272793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
6372793727SChandler Carruth     return false;
6472793727SChandler Carruth 
6572793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
6672793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
6772793727SChandler Carruth   if (!ExpectedValue)
6872793727SChandler Carruth     return false;
6972793727SChandler Carruth 
70927d8e61SChandler Carruth   SwitchInst::CaseHandle Case = *SI.findCaseValue(ExpectedValue);
710012c778SChandler Carruth   unsigned n = SI.getNumCases(); // +1 for default case.
723f5e7b1fSChandler Carruth   SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeight);
7372793727SChandler Carruth 
74927d8e61SChandler Carruth   if (Case == *SI.case_default())
753f5e7b1fSChandler Carruth     Weights[0] = LikelyBranchWeight;
763f5e7b1fSChandler Carruth   else
773f5e7b1fSChandler Carruth     Weights[Case.getCaseIndex() + 1] = LikelyBranchWeight;
7872793727SChandler Carruth 
790012c778SChandler Carruth   SI.setMetadata(LLVMContext::MD_prof,
8072793727SChandler Carruth                  MDBuilder(CI->getContext()).createBranchWeights(Weights));
8172793727SChandler Carruth 
820012c778SChandler Carruth   SI.setCondition(ArgValue);
8372793727SChandler Carruth   return true;
8472793727SChandler Carruth }
8572793727SChandler Carruth 
8640afd5c9SXinliang David Li // Handle both BranchInst and SelectInst.
8740afd5c9SXinliang David Li template <class BrSelInst> static bool handleBrSelExpect(BrSelInst &BSI) {
8872793727SChandler Carruth 
8972793727SChandler Carruth   // Handle non-optimized IR code like:
9072793727SChandler Carruth   //   %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
9172793727SChandler Carruth   //   %tobool = icmp ne i64 %expval, 0
9272793727SChandler Carruth   //   br i1 %tobool, label %if.then, label %if.end
9372793727SChandler Carruth   //
9472793727SChandler Carruth   // Or the following simpler case:
9572793727SChandler Carruth   //   %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
9672793727SChandler Carruth   //   br i1 %expval, label %if.then, label %if.end
9772793727SChandler Carruth 
9872793727SChandler Carruth   CallInst *CI;
9972793727SChandler Carruth 
10040afd5c9SXinliang David Li   ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
101*ee8d6acbSXinliang David Li   CmpInst::Predicate Predicate;
102*ee8d6acbSXinliang David Li   uint64_t ValueComparedTo = 0;
10372793727SChandler Carruth   if (!CmpI) {
10440afd5c9SXinliang David Li     CI = dyn_cast<CallInst>(BSI.getCondition());
105*ee8d6acbSXinliang David Li     Predicate = CmpInst::ICMP_NE;
106*ee8d6acbSXinliang David Li     ValueComparedTo = 0;
10772793727SChandler Carruth   } else {
108*ee8d6acbSXinliang David Li     Predicate = CmpI->getPredicate();
109*ee8d6acbSXinliang David Li     if (Predicate != CmpInst::ICMP_NE && Predicate != CmpInst::ICMP_EQ)
11072793727SChandler Carruth       return false;
111*ee8d6acbSXinliang David Li     ConstantInt *CmpConstOperand = dyn_cast<ConstantInt>(CmpI->getOperand(1));
112*ee8d6acbSXinliang David Li     if (!CmpConstOperand)
113*ee8d6acbSXinliang David Li       return false;
114*ee8d6acbSXinliang David Li     ValueComparedTo = CmpConstOperand->getZExtValue();
11572793727SChandler Carruth     CI = dyn_cast<CallInst>(CmpI->getOperand(0));
11672793727SChandler Carruth   }
11772793727SChandler Carruth 
11872793727SChandler Carruth   if (!CI)
11972793727SChandler Carruth     return false;
12072793727SChandler Carruth 
12172793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
12272793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
12372793727SChandler Carruth     return false;
12472793727SChandler Carruth 
12572793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
12672793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
12772793727SChandler Carruth   if (!ExpectedValue)
12872793727SChandler Carruth     return false;
12972793727SChandler Carruth 
13072793727SChandler Carruth   MDBuilder MDB(CI->getContext());
13172793727SChandler Carruth   MDNode *Node;
13272793727SChandler Carruth 
133*ee8d6acbSXinliang David Li   if ((ExpectedValue->getZExtValue() == ValueComparedTo) ==
134*ee8d6acbSXinliang David Li       (Predicate == CmpInst::ICMP_EQ))
13572793727SChandler Carruth     Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
13672793727SChandler Carruth   else
13772793727SChandler Carruth     Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
13872793727SChandler Carruth 
13940afd5c9SXinliang David Li   BSI.setMetadata(LLVMContext::MD_prof, Node);
14072793727SChandler Carruth 
14172793727SChandler Carruth   if (CmpI)
14272793727SChandler Carruth     CmpI->setOperand(0, ArgValue);
14372793727SChandler Carruth   else
14440afd5c9SXinliang David Li     BSI.setCondition(ArgValue);
14572793727SChandler Carruth   return true;
14672793727SChandler Carruth }
14772793727SChandler Carruth 
14840afd5c9SXinliang David Li static bool handleBranchExpect(BranchInst &BI) {
14940afd5c9SXinliang David Li   if (BI.isUnconditional())
15040afd5c9SXinliang David Li     return false;
15140afd5c9SXinliang David Li 
15240afd5c9SXinliang David Li   return handleBrSelExpect<BranchInst>(BI);
15340afd5c9SXinliang David Li }
15440afd5c9SXinliang David Li 
15543e590e5SChandler Carruth static bool lowerExpectIntrinsic(Function &F) {
156c3bf5bd8SChandler Carruth   bool Changed = false;
157c3bf5bd8SChandler Carruth 
158d12741e0SChandler Carruth   for (BasicBlock &BB : F) {
15972793727SChandler Carruth     // Create "block_weights" metadata.
160d12741e0SChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
1610012c778SChandler Carruth       if (handleBranchExpect(*BI))
1626eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
163d12741e0SChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
1640012c778SChandler Carruth       if (handleSwitchExpect(*SI))
1656eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
16672793727SChandler Carruth     }
16772793727SChandler Carruth 
16840afd5c9SXinliang David Li     // Remove llvm.expect intrinsics. Iterate backwards in order
16940afd5c9SXinliang David Li     // to process select instructions before the intrinsic gets
17040afd5c9SXinliang David Li     // removed.
17140afd5c9SXinliang David Li     for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
17240afd5c9SXinliang David Li       Instruction *Inst = &*BI++;
17340afd5c9SXinliang David Li       CallInst *CI = dyn_cast<CallInst>(Inst);
17440afd5c9SXinliang David Li       if (!CI) {
17540afd5c9SXinliang David Li         if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
17640afd5c9SXinliang David Li           if (handleBrSelExpect(*SI))
17740afd5c9SXinliang David Li             ExpectIntrinsicsHandled++;
17840afd5c9SXinliang David Li         }
17972793727SChandler Carruth         continue;
18040afd5c9SXinliang David Li       }
18172793727SChandler Carruth 
18272793727SChandler Carruth       Function *Fn = CI->getCalledFunction();
18372793727SChandler Carruth       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
18472793727SChandler Carruth         Value *Exp = CI->getArgOperand(0);
18572793727SChandler Carruth         CI->replaceAllUsesWith(Exp);
18672793727SChandler Carruth         CI->eraseFromParent();
187c3bf5bd8SChandler Carruth         Changed = true;
18872793727SChandler Carruth       }
18972793727SChandler Carruth     }
19072793727SChandler Carruth   }
19172793727SChandler Carruth 
192c3bf5bd8SChandler Carruth   return Changed;
19372793727SChandler Carruth }
19472793727SChandler Carruth 
195164a2aa6SChandler Carruth PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
196164a2aa6SChandler Carruth                                                 FunctionAnalysisManager &) {
19743e590e5SChandler Carruth   if (lowerExpectIntrinsic(F))
19843e590e5SChandler Carruth     return PreservedAnalyses::none();
19943e590e5SChandler Carruth 
20043e590e5SChandler Carruth   return PreservedAnalyses::all();
20143e590e5SChandler Carruth }
20243e590e5SChandler Carruth 
20343e590e5SChandler Carruth namespace {
20443e590e5SChandler Carruth /// \brief Legacy pass for lowering expect intrinsics out of the IR.
20543e590e5SChandler Carruth ///
20643e590e5SChandler Carruth /// When this pass is run over a function it uses expect intrinsics which feed
20743e590e5SChandler Carruth /// branches and switches to provide branch weight metadata for those
20843e590e5SChandler Carruth /// terminators. It then removes the expect intrinsics from the IR so the rest
20943e590e5SChandler Carruth /// of the optimizer can ignore them.
21043e590e5SChandler Carruth class LowerExpectIntrinsic : public FunctionPass {
21143e590e5SChandler Carruth public:
21243e590e5SChandler Carruth   static char ID;
21343e590e5SChandler Carruth   LowerExpectIntrinsic() : FunctionPass(ID) {
21443e590e5SChandler Carruth     initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
21543e590e5SChandler Carruth   }
21643e590e5SChandler Carruth 
21743e590e5SChandler Carruth   bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
21843e590e5SChandler Carruth };
219f00654e3SAlexander Kornienko }
22043e590e5SChandler Carruth 
22172793727SChandler Carruth char LowerExpectIntrinsic::ID = 0;
2220ea746bfSChandler Carruth INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
2230ea746bfSChandler Carruth                 "Lower 'expect' Intrinsics", false, false)
22472793727SChandler Carruth 
22572793727SChandler Carruth FunctionPass *llvm::createLowerExpectIntrinsicPass() {
22672793727SChandler Carruth   return new LowerExpectIntrinsic();
22772793727SChandler Carruth }
228