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 
1472793727SChandler Carruth #include "llvm/Transforms/Scalar.h"
1572793727SChandler Carruth #include "llvm/ADT/Statistic.h"
1672793727SChandler Carruth #include "llvm/IR/BasicBlock.h"
1772793727SChandler Carruth #include "llvm/IR/Constants.h"
1872793727SChandler Carruth #include "llvm/IR/Function.h"
1972793727SChandler Carruth #include "llvm/IR/Instructions.h"
2072793727SChandler Carruth #include "llvm/IR/Intrinsics.h"
2172793727SChandler Carruth #include "llvm/IR/LLVMContext.h"
2272793727SChandler Carruth #include "llvm/IR/MDBuilder.h"
2372793727SChandler Carruth #include "llvm/IR/Metadata.h"
2472793727SChandler Carruth #include "llvm/Pass.h"
2572793727SChandler Carruth #include "llvm/Support/CommandLine.h"
2672793727SChandler Carruth #include "llvm/Support/Debug.h"
2772793727SChandler Carruth #include <vector>
2872793727SChandler Carruth 
2972793727SChandler Carruth using namespace llvm;
3072793727SChandler Carruth 
3172793727SChandler Carruth #define DEBUG_TYPE "lower-expect-intrinsic"
3272793727SChandler Carruth 
3372793727SChandler Carruth STATISTIC(IfHandled, "Number of 'expect' intrinsic instructions handled");
3472793727SChandler Carruth 
3572793727SChandler Carruth static cl::opt<uint32_t>
3672793727SChandler Carruth LikelyBranchWeight("likely-branch-weight", cl::Hidden, cl::init(64),
3772793727SChandler Carruth                    cl::desc("Weight of the branch likely to be taken (default = 64)"));
3872793727SChandler Carruth static cl::opt<uint32_t>
3972793727SChandler Carruth UnlikelyBranchWeight("unlikely-branch-weight", cl::Hidden, cl::init(4),
4072793727SChandler Carruth                    cl::desc("Weight of the branch unlikely to be taken (default = 4)"));
4172793727SChandler Carruth 
4272793727SChandler Carruth namespace {
43*579c5c45SChandler Carruth /// \brief Legacy pass for lowering expect intrinsics out of the IR.
44*579c5c45SChandler Carruth ///
45*579c5c45SChandler Carruth /// When this pass is run over a function it uses expect intrinsics which feed
46*579c5c45SChandler Carruth /// branches and switches to provide branch weight metadata for those
47*579c5c45SChandler Carruth /// terminators. It then removes the expect intrinsics from the IR so the rest
48*579c5c45SChandler Carruth /// of the optimizer can ignore them.
4972793727SChandler Carruth class LowerExpectIntrinsic : public FunctionPass {
5072793727SChandler Carruth 
5172793727SChandler Carruth   bool HandleSwitchExpect(SwitchInst *SI);
5272793727SChandler Carruth 
5372793727SChandler Carruth   bool HandleIfExpect(BranchInst *BI);
5472793727SChandler Carruth 
5572793727SChandler Carruth public:
5672793727SChandler Carruth   static char ID;
5772793727SChandler Carruth   LowerExpectIntrinsic() : FunctionPass(ID) {
5872793727SChandler Carruth     initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
5972793727SChandler Carruth   }
6072793727SChandler Carruth 
6172793727SChandler Carruth   bool runOnFunction(Function &F) override;
6272793727SChandler Carruth };
6372793727SChandler Carruth }
6472793727SChandler Carruth 
6572793727SChandler Carruth bool LowerExpectIntrinsic::HandleSwitchExpect(SwitchInst *SI) {
6672793727SChandler Carruth   CallInst *CI = dyn_cast<CallInst>(SI->getCondition());
6772793727SChandler Carruth   if (!CI)
6872793727SChandler Carruth     return false;
6972793727SChandler Carruth 
7072793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
7172793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
7272793727SChandler Carruth     return false;
7372793727SChandler Carruth 
7472793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
7572793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
7672793727SChandler Carruth   if (!ExpectedValue)
7772793727SChandler Carruth     return false;
7872793727SChandler Carruth 
7972793727SChandler Carruth   SwitchInst::CaseIt Case = SI->findCaseValue(ExpectedValue);
8072793727SChandler Carruth   unsigned n = SI->getNumCases(); // +1 for default case.
8172793727SChandler Carruth   std::vector<uint32_t> Weights(n + 1);
8272793727SChandler Carruth 
830ea746bfSChandler Carruth   Weights[0] =
840ea746bfSChandler Carruth       Case == SI->case_default() ? LikelyBranchWeight : UnlikelyBranchWeight;
8572793727SChandler Carruth   for (unsigned i = 0; i != n; ++i)
860ea746bfSChandler Carruth     Weights[i + 1] =
870ea746bfSChandler Carruth         i == Case.getCaseIndex() ? LikelyBranchWeight : UnlikelyBranchWeight;
8872793727SChandler Carruth 
8972793727SChandler Carruth   SI->setMetadata(LLVMContext::MD_prof,
9072793727SChandler Carruth                   MDBuilder(CI->getContext()).createBranchWeights(Weights));
9172793727SChandler Carruth 
9272793727SChandler Carruth   SI->setCondition(ArgValue);
9372793727SChandler Carruth   return true;
9472793727SChandler Carruth }
9572793727SChandler Carruth 
9672793727SChandler Carruth bool LowerExpectIntrinsic::HandleIfExpect(BranchInst *BI) {
9772793727SChandler Carruth   if (BI->isUnconditional())
9872793727SChandler Carruth     return false;
9972793727SChandler Carruth 
10072793727SChandler Carruth   // Handle non-optimized IR code like:
10172793727SChandler Carruth   //   %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
10272793727SChandler Carruth   //   %tobool = icmp ne i64 %expval, 0
10372793727SChandler Carruth   //   br i1 %tobool, label %if.then, label %if.end
10472793727SChandler Carruth   //
10572793727SChandler Carruth   // Or the following simpler case:
10672793727SChandler Carruth   //   %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
10772793727SChandler Carruth   //   br i1 %expval, label %if.then, label %if.end
10872793727SChandler Carruth 
10972793727SChandler Carruth   CallInst *CI;
11072793727SChandler Carruth 
11172793727SChandler Carruth   ICmpInst *CmpI = dyn_cast<ICmpInst>(BI->getCondition());
11272793727SChandler Carruth   if (!CmpI) {
11372793727SChandler Carruth     CI = dyn_cast<CallInst>(BI->getCondition());
11472793727SChandler Carruth   } else {
11572793727SChandler Carruth     if (CmpI->getPredicate() != CmpInst::ICMP_NE)
11672793727SChandler Carruth       return false;
11772793727SChandler Carruth     CI = dyn_cast<CallInst>(CmpI->getOperand(0));
11872793727SChandler Carruth   }
11972793727SChandler Carruth 
12072793727SChandler Carruth   if (!CI)
12172793727SChandler Carruth     return false;
12272793727SChandler Carruth 
12372793727SChandler Carruth   Function *Fn = CI->getCalledFunction();
12472793727SChandler Carruth   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
12572793727SChandler Carruth     return false;
12672793727SChandler Carruth 
12772793727SChandler Carruth   Value *ArgValue = CI->getArgOperand(0);
12872793727SChandler Carruth   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
12972793727SChandler Carruth   if (!ExpectedValue)
13072793727SChandler Carruth     return false;
13172793727SChandler Carruth 
13272793727SChandler Carruth   MDBuilder MDB(CI->getContext());
13372793727SChandler Carruth   MDNode *Node;
13472793727SChandler Carruth 
13572793727SChandler Carruth   // If expect value is equal to 1 it means that we are more likely to take
13672793727SChandler Carruth   // branch 0, in other case more likely is branch 1.
13772793727SChandler Carruth   if (ExpectedValue->isOne())
13872793727SChandler Carruth     Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
13972793727SChandler Carruth   else
14072793727SChandler Carruth     Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
14172793727SChandler Carruth 
14272793727SChandler Carruth   BI->setMetadata(LLVMContext::MD_prof, Node);
14372793727SChandler Carruth 
14472793727SChandler Carruth   if (CmpI)
14572793727SChandler Carruth     CmpI->setOperand(0, ArgValue);
14672793727SChandler Carruth   else
14772793727SChandler Carruth     BI->setCondition(ArgValue);
14872793727SChandler Carruth   return true;
14972793727SChandler Carruth }
15072793727SChandler Carruth 
15172793727SChandler Carruth bool LowerExpectIntrinsic::runOnFunction(Function &F) {
15272793727SChandler Carruth   for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
15372793727SChandler Carruth     BasicBlock *BB = I++;
15472793727SChandler Carruth 
15572793727SChandler Carruth     // Create "block_weights" metadata.
15672793727SChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
15772793727SChandler Carruth       if (HandleIfExpect(BI))
15872793727SChandler Carruth         IfHandled++;
15972793727SChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
16072793727SChandler Carruth       if (HandleSwitchExpect(SI))
16172793727SChandler Carruth         IfHandled++;
16272793727SChandler Carruth     }
16372793727SChandler Carruth 
16472793727SChandler Carruth     // remove llvm.expect intrinsics.
1650ea746bfSChandler Carruth     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
16672793727SChandler Carruth       CallInst *CI = dyn_cast<CallInst>(BI++);
16772793727SChandler Carruth       if (!CI)
16872793727SChandler Carruth         continue;
16972793727SChandler Carruth 
17072793727SChandler Carruth       Function *Fn = CI->getCalledFunction();
17172793727SChandler Carruth       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
17272793727SChandler Carruth         Value *Exp = CI->getArgOperand(0);
17372793727SChandler Carruth         CI->replaceAllUsesWith(Exp);
17472793727SChandler Carruth         CI->eraseFromParent();
17572793727SChandler Carruth       }
17672793727SChandler Carruth     }
17772793727SChandler Carruth   }
17872793727SChandler Carruth 
17972793727SChandler Carruth   return false;
18072793727SChandler Carruth }
18172793727SChandler Carruth 
18272793727SChandler Carruth char LowerExpectIntrinsic::ID = 0;
1830ea746bfSChandler Carruth INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
1840ea746bfSChandler Carruth                 "Lower 'expect' Intrinsics", false, false)
18572793727SChandler Carruth 
18672793727SChandler Carruth FunctionPass *llvm::createLowerExpectIntrinsicPass() {
18772793727SChandler Carruth   return new LowerExpectIntrinsic();
18872793727SChandler Carruth }
189