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 
700012c778SChandler Carruth   SwitchInst::CaseIt 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 
743f5e7b1fSChandler 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 
86*40afd5c9SXinliang David Li // Handle both BranchInst and SelectInst.
87*40afd5c9SXinliang 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 
100*40afd5c9SXinliang David Li   ICmpInst *CmpI = dyn_cast<ICmpInst>(BSI.getCondition());
10172793727SChandler Carruth   if (!CmpI) {
102*40afd5c9SXinliang David Li     CI = dyn_cast<CallInst>(BSI.getCondition());
10372793727SChandler Carruth   } else {
10472793727SChandler Carruth     if (CmpI->getPredicate() != CmpInst::ICMP_NE)
10572793727SChandler Carruth       return false;
10672793727SChandler Carruth     CI = dyn_cast<CallInst>(CmpI->getOperand(0));
10772793727SChandler Carruth   }
10872793727SChandler Carruth 
10972793727SChandler Carruth   if (!CI)
11072793727SChandler Carruth     return false;
11172793727SChandler Carruth 
11272793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
11372793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
11472793727SChandler Carruth     return false;
11572793727SChandler Carruth 
11672793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
11772793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
11872793727SChandler Carruth   if (!ExpectedValue)
11972793727SChandler Carruth     return false;
12072793727SChandler Carruth 
12172793727SChandler Carruth   MDBuilder MDB(CI->getContext());
12272793727SChandler Carruth   MDNode *Node;
12372793727SChandler Carruth 
12472793727SChandler Carruth   // If expect value is equal to 1 it means that we are more likely to take
12572793727SChandler Carruth   // branch 0, in other case more likely is branch 1.
12672793727SChandler Carruth   if (ExpectedValue->isOne())
12772793727SChandler Carruth     Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
12872793727SChandler Carruth   else
12972793727SChandler Carruth     Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
13072793727SChandler Carruth 
131*40afd5c9SXinliang David Li   BSI.setMetadata(LLVMContext::MD_prof, Node);
13272793727SChandler Carruth 
13372793727SChandler Carruth   if (CmpI)
13472793727SChandler Carruth     CmpI->setOperand(0, ArgValue);
13572793727SChandler Carruth   else
136*40afd5c9SXinliang David Li     BSI.setCondition(ArgValue);
13772793727SChandler Carruth   return true;
13872793727SChandler Carruth }
13972793727SChandler Carruth 
140*40afd5c9SXinliang David Li static bool handleBranchExpect(BranchInst &BI) {
141*40afd5c9SXinliang David Li   if (BI.isUnconditional())
142*40afd5c9SXinliang David Li     return false;
143*40afd5c9SXinliang David Li 
144*40afd5c9SXinliang David Li   return handleBrSelExpect<BranchInst>(BI);
145*40afd5c9SXinliang David Li }
146*40afd5c9SXinliang David Li 
14743e590e5SChandler Carruth static bool lowerExpectIntrinsic(Function &F) {
148c3bf5bd8SChandler Carruth   bool Changed = false;
149c3bf5bd8SChandler Carruth 
150d12741e0SChandler Carruth   for (BasicBlock &BB : F) {
15172793727SChandler Carruth     // Create "block_weights" metadata.
152d12741e0SChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
1530012c778SChandler Carruth       if (handleBranchExpect(*BI))
1546eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
155d12741e0SChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
1560012c778SChandler Carruth       if (handleSwitchExpect(*SI))
1576eb60eb5SChandler Carruth         ExpectIntrinsicsHandled++;
15872793727SChandler Carruth     }
15972793727SChandler Carruth 
160*40afd5c9SXinliang David Li     // Remove llvm.expect intrinsics. Iterate backwards in order
161*40afd5c9SXinliang David Li     // to process select instructions before the intrinsic gets
162*40afd5c9SXinliang David Li     // removed.
163*40afd5c9SXinliang David Li     for (auto BI = BB.rbegin(), BE = BB.rend(); BI != BE;) {
164*40afd5c9SXinliang David Li       Instruction *Inst = &*BI++;
165*40afd5c9SXinliang David Li       CallInst *CI = dyn_cast<CallInst>(Inst);
166*40afd5c9SXinliang David Li       if (!CI) {
167*40afd5c9SXinliang David Li         if (SelectInst *SI = dyn_cast<SelectInst>(Inst)) {
168*40afd5c9SXinliang David Li           if (handleBrSelExpect(*SI))
169*40afd5c9SXinliang David Li             ExpectIntrinsicsHandled++;
170*40afd5c9SXinliang David Li         }
17172793727SChandler Carruth         continue;
172*40afd5c9SXinliang David Li       }
17372793727SChandler Carruth 
17472793727SChandler Carruth       Function *Fn = CI->getCalledFunction();
17572793727SChandler Carruth       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
17672793727SChandler Carruth         Value *Exp = CI->getArgOperand(0);
17772793727SChandler Carruth         CI->replaceAllUsesWith(Exp);
17872793727SChandler Carruth         CI->eraseFromParent();
179c3bf5bd8SChandler Carruth         Changed = true;
18072793727SChandler Carruth       }
18172793727SChandler Carruth     }
18272793727SChandler Carruth   }
18372793727SChandler Carruth 
184c3bf5bd8SChandler Carruth   return Changed;
18572793727SChandler Carruth }
18672793727SChandler Carruth 
187164a2aa6SChandler Carruth PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F,
188164a2aa6SChandler Carruth                                                 FunctionAnalysisManager &) {
18943e590e5SChandler Carruth   if (lowerExpectIntrinsic(F))
19043e590e5SChandler Carruth     return PreservedAnalyses::none();
19143e590e5SChandler Carruth 
19243e590e5SChandler Carruth   return PreservedAnalyses::all();
19343e590e5SChandler Carruth }
19443e590e5SChandler Carruth 
19543e590e5SChandler Carruth namespace {
19643e590e5SChandler Carruth /// \brief Legacy pass for lowering expect intrinsics out of the IR.
19743e590e5SChandler Carruth ///
19843e590e5SChandler Carruth /// When this pass is run over a function it uses expect intrinsics which feed
19943e590e5SChandler Carruth /// branches and switches to provide branch weight metadata for those
20043e590e5SChandler Carruth /// terminators. It then removes the expect intrinsics from the IR so the rest
20143e590e5SChandler Carruth /// of the optimizer can ignore them.
20243e590e5SChandler Carruth class LowerExpectIntrinsic : public FunctionPass {
20343e590e5SChandler Carruth public:
20443e590e5SChandler Carruth   static char ID;
20543e590e5SChandler Carruth   LowerExpectIntrinsic() : FunctionPass(ID) {
20643e590e5SChandler Carruth     initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
20743e590e5SChandler Carruth   }
20843e590e5SChandler Carruth 
20943e590e5SChandler Carruth   bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
21043e590e5SChandler Carruth };
211f00654e3SAlexander Kornienko }
21243e590e5SChandler Carruth 
21372793727SChandler Carruth char LowerExpectIntrinsic::ID = 0;
2140ea746bfSChandler Carruth INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
2150ea746bfSChandler Carruth                 "Lower 'expect' Intrinsics", false, false)
21672793727SChandler Carruth 
21772793727SChandler Carruth FunctionPass *llvm::createLowerExpectIntrinsicPass() {
21872793727SChandler Carruth   return new LowerExpectIntrinsic();
21972793727SChandler Carruth }
220