LowerExpectIntrinsic.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/IR/BasicBlock.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/Intrinsics.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/IR/MDBuilder.h"
  23. #include "llvm/IR/Metadata.h"
  24. #include "llvm/Pass.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Transforms/Scalar.h"
  28. using namespace llvm;
  29. #define DEBUG_TYPE "lower-expect-intrinsic"
  30. STATISTIC(ExpectIntrinsicsHandled,
  31. "Number of 'expect' intrinsic instructions handled");
  32. static cl::opt<uint32_t>
  33. LikelyBranchWeight("likely-branch-weight", cl::Hidden, cl::init(64),
  34. cl::desc("Weight of the branch likely to be taken (default = 64)"));
  35. static cl::opt<uint32_t>
  36. UnlikelyBranchWeight("unlikely-branch-weight", cl::Hidden, cl::init(4),
  37. cl::desc("Weight of the branch unlikely to be taken (default = 4)"));
  38. static bool handleSwitchExpect(SwitchInst &SI) {
  39. CallInst *CI = dyn_cast<CallInst>(SI.getCondition());
  40. if (!CI)
  41. return false;
  42. Function *Fn = CI->getCalledFunction();
  43. if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
  44. return false;
  45. Value *ArgValue = CI->getArgOperand(0);
  46. ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  47. if (!ExpectedValue)
  48. return false;
  49. SwitchInst::CaseIt Case = SI.findCaseValue(ExpectedValue);
  50. unsigned n = SI.getNumCases(); // +1 for default case.
  51. SmallVector<uint32_t, 16> Weights(n + 1, UnlikelyBranchWeight);
  52. if (Case == SI.case_default())
  53. Weights[0] = LikelyBranchWeight;
  54. else
  55. Weights[Case.getCaseIndex() + 1] = LikelyBranchWeight;
  56. SI.setMetadata(LLVMContext::MD_prof,
  57. MDBuilder(CI->getContext()).createBranchWeights(Weights));
  58. SI.setCondition(ArgValue);
  59. return true;
  60. }
  61. static bool handleBranchExpect(BranchInst &BI) {
  62. if (BI.isUnconditional())
  63. return false;
  64. // Handle non-optimized IR code like:
  65. // %expval = call i64 @llvm.expect.i64(i64 %conv1, i64 1)
  66. // %tobool = icmp ne i64 %expval, 0
  67. // br i1 %tobool, label %if.then, label %if.end
  68. //
  69. // Or the following simpler case:
  70. // %expval = call i1 @llvm.expect.i1(i1 %cmp, i1 1)
  71. // br i1 %expval, label %if.then, label %if.end
  72. CallInst *CI;
  73. ICmpInst *CmpI = dyn_cast<ICmpInst>(BI.getCondition());
  74. if (!CmpI) {
  75. CI = dyn_cast<CallInst>(BI.getCondition());
  76. } else {
  77. if (CmpI->getPredicate() != CmpInst::ICMP_NE)
  78. return false;
  79. CI = dyn_cast<CallInst>(CmpI->getOperand(0));
  80. }
  81. if (!CI)
  82. return false;
  83. Function *Fn = CI->getCalledFunction();
  84. if (!Fn || Fn->getIntrinsicID() != Intrinsic::expect)
  85. return false;
  86. Value *ArgValue = CI->getArgOperand(0);
  87. ConstantInt *ExpectedValue = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  88. if (!ExpectedValue)
  89. return false;
  90. MDBuilder MDB(CI->getContext());
  91. MDNode *Node;
  92. // If expect value is equal to 1 it means that we are more likely to take
  93. // branch 0, in other case more likely is branch 1.
  94. if (ExpectedValue->isOne())
  95. Node = MDB.createBranchWeights(LikelyBranchWeight, UnlikelyBranchWeight);
  96. else
  97. Node = MDB.createBranchWeights(UnlikelyBranchWeight, LikelyBranchWeight);
  98. BI.setMetadata(LLVMContext::MD_prof, Node);
  99. if (CmpI)
  100. CmpI->setOperand(0, ArgValue);
  101. else
  102. BI.setCondition(ArgValue);
  103. return true;
  104. }
  105. static bool lowerExpectIntrinsic(Function &F) {
  106. bool Changed = false;
  107. for (BasicBlock &BB : F) {
  108. // Create "block_weights" metadata.
  109. if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
  110. if (handleBranchExpect(*BI))
  111. ExpectIntrinsicsHandled++;
  112. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
  113. if (handleSwitchExpect(*SI))
  114. ExpectIntrinsicsHandled++;
  115. }
  116. // remove llvm.expect intrinsics.
  117. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  118. CallInst *CI = dyn_cast<CallInst>(BI++);
  119. if (!CI)
  120. continue;
  121. Function *Fn = CI->getCalledFunction();
  122. if (Fn && Fn->getIntrinsicID() == Intrinsic::expect) {
  123. Value *Exp = CI->getArgOperand(0);
  124. CI->replaceAllUsesWith(Exp);
  125. CI->eraseFromParent();
  126. Changed = true;
  127. }
  128. }
  129. }
  130. return Changed;
  131. }
  132. PreservedAnalyses LowerExpectIntrinsicPass::run(Function &F) {
  133. if (lowerExpectIntrinsic(F))
  134. return PreservedAnalyses::none();
  135. return PreservedAnalyses::all();
  136. }
  137. namespace {
  138. /// \brief Legacy pass for lowering expect intrinsics out of the IR.
  139. ///
  140. /// When this pass is run over a function it uses expect intrinsics which feed
  141. /// branches and switches to provide branch weight metadata for those
  142. /// terminators. It then removes the expect intrinsics from the IR so the rest
  143. /// of the optimizer can ignore them.
  144. class LowerExpectIntrinsic : public FunctionPass {
  145. public:
  146. static char ID;
  147. LowerExpectIntrinsic() : FunctionPass(ID) {
  148. initializeLowerExpectIntrinsicPass(*PassRegistry::getPassRegistry());
  149. }
  150. bool runOnFunction(Function &F) override { return lowerExpectIntrinsic(F); }
  151. };
  152. }
  153. char LowerExpectIntrinsic::ID = 0;
  154. INITIALIZE_PASS(LowerExpectIntrinsic, "lower-expect",
  155. "Lower 'expect' Intrinsics", false, false)
  156. FunctionPass *llvm::createLowerExpectIntrinsicPass() {
  157. return new LowerExpectIntrinsic();
  158. }