Home | History | Annotate | Download | only in Utils
      1 //===- 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 
     14 #define DEBUG_TYPE "lower-expect-intrinsic"
     15 #include "llvm/Constants.h"
     16 #include "llvm/Function.h"
     17 #include "llvm/BasicBlock.h"
     18 #include "llvm/LLVMContext.h"
     19 #include "llvm/Instructions.h"
     20 #include "llvm/Intrinsics.h"
     21 #include "llvm/Metadata.h"
     22 #include "llvm/Pass.h"
     23 #include "llvm/Transforms/Scalar.h"
     24 #include "llvm/Support/CommandLine.h"
     25 #include "llvm/Support/Debug.h"
     26 #include "llvm/ADT/Statistic.h"
     27 #include <vector>
     28 
     29 using namespace llvm;
     30 
     31 STATISTIC(IfHandled, "Number of 'expect' intrinsic intructions handled");
     32 
     33 static cl::opt<uint32_t>
     34 LikelyBranchWeight("likely-branch-weight", cl::Hidden, cl::init(64),
     35                    cl::desc("Weight of the branch likely to be taken (default = 64)"));
     36 static cl::opt<uint32_t>
     37 UnlikelyBranchWeight("unlikely-branch-weight", cl::Hidden, cl::init(4),
     38                    cl::desc("Weight of the branch unlikely to be taken (default = 4)"));
     39 
     40 namespace {
     41 
     42   class LowerExpectIntrinsic : public FunctionPass {
     43 
     44     bool HandleSwitchExpect(SwitchInst *SI);
     45 
     46     bool HandleIfExpect(BranchInst *BI);
     47 
     48   public:
     49     static char ID;
     50     LowerExpectIntrinsic() : FunctionPass(ID) {
     51       initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
     52     }
     53 
     54     bool runOnFunction(Function &F);
     55   };
     56 }
     57 
     58 
     59 bool LowerExpectIntrinsic::HandleSwitchExpect(SwitchInst *SI) {
     60   CallInst *CI = dyn_cast<CallInst>(SI->getCondition());
     61   if (!CI)
     62     return false;
     63 
     64   Function *Fn = CI->getCalledFunction();
     65   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
     66     return false;
     67 
     68   Value *ArgValue = CI->getArgOperand(0);
     69   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
     70   if (!ExpectedValue)
     71     return false;
     72 
     73   LLVMContext &Context = CI->getContext();
     74   Type *Int32Ty = Type::getInt32Ty(Context);
     75 
     76   unsigned caseNo = SI->findCaseValue(ExpectedValue);
     77   std::vector<Value *> Vec;
     78   unsigned n = SI->getNumCases();
     79   Vec.resize(n + 1); // +1 for MDString
     80 
     81   Vec[0] = MDString::get(Context, "branch_weights");
     82   for (unsigned i = 0; i < n; ++i) {
     83     Vec[i + 1] = ConstantInt::get(Int32Ty, i == caseNo ? LikelyBranchWeight : UnlikelyBranchWeight);
     84   }
     85 
     86   MDNode *WeightsNode = llvm::MDNode::get(Context, Vec);
     87   SI->setMetadata(LLVMContext::MD_prof, WeightsNode);
     88 
     89   SI->setCondition(ArgValue);
     90   return true;
     91 }
     92 
     93 
     94 bool LowerExpectIntrinsic::HandleIfExpect(BranchInst *BI) {
     95   if (BI->isUnconditional())
     96     return false;
     97 
     98   // Handle non-optimized IR code like:
     99   //   %expval = call i64 @llvm.expect.i64.i64(i64 %conv1, i64 1)
    100   //   %tobool = icmp ne i64 %expval, 0
    101   //   br i1 %tobool, label %if.then, label %if.end
    102 
    103   ICmpInst *CmpI = dyn_cast<ICmpInst>(BI->getCondition());
    104   if (!CmpI || CmpI->getPredicate() != CmpInst::ICMP_NE)
    105     return false;
    106 
    107   CallInst *CI = dyn_cast<CallInst>(CmpI->getOperand(0));
    108   if (!CI)
    109     return false;
    110 
    111   Function *Fn = CI->getCalledFunction();
    112   if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
    113     return false;
    114 
    115   Value *ArgValue = CI->getArgOperand(0);
    116   ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
    117   if (!ExpectedValue)
    118     return false;
    119 
    120   LLVMContext &Context = CI->getContext();
    121   Type *Int32Ty = Type::getInt32Ty(Context);
    122   bool Likely = ExpectedValue->isOne();
    123 
    124   // If expect value is equal to 1 it means that we are more likely to take
    125   // branch 0, in other case more likely is branch 1.
    126   Value *Ops[] = {
    127     MDString::get(Context, "branch_weights"),
    128     ConstantInt::get(Int32Ty, Likely ? LikelyBranchWeight : UnlikelyBranchWeight),
    129     ConstantInt::get(Int32Ty, Likely ? UnlikelyBranchWeight : LikelyBranchWeight)
    130   };
    131 
    132   MDNode *WeightsNode = MDNode::get(Context, Ops);
    133   BI->setMetadata(LLVMContext::MD_prof, WeightsNode);
    134 
    135   CmpI->setOperand(0, ArgValue);
    136   return true;
    137 }
    138 
    139 
    140 bool LowerExpectIntrinsic::runOnFunction(Function &F) {
    141   for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
    142     BasicBlock *BB = I++;
    143 
    144     // Create "block_weights" metadata.
    145     if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
    146       if (HandleIfExpect(BI))
    147         IfHandled++;
    148     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
    149       if (HandleSwitchExpect(SI))
    150         IfHandled++;
    151     }
    152 
    153     // remove llvm.expect intrinsics.
    154     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
    155          BI != BE; ) {
    156       CallInst *CI = dyn_cast<CallInst>(BI++);
    157       if (!CI)
    158         continue;
    159 
    160       Function *Fn = CI->getCalledFunction();
    161       if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
    162         Value *Exp = CI->getArgOperand(0);
    163         CI->replaceAllUsesWith(Exp);
    164         CI->eraseFromParent();
    165       }
    166     }
    167   }
    168 
    169   return false;
    170 }
    171 
    172 
    173 char LowerExpectIntrinsic::ID = 0;
    174 INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect", "Lower 'expect' "
    175                 "Intrinsics", false, false)
    176 
    177 FunctionPass *llvm::createLowerExpectIntrinsicPass() {
    178   return new LowerExpectIntrinsic();
    179 }
    180