BranchProbabilityInfo.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. //===-- BranchProbabilityInfo.cpp - Branch Probability Analysis -----------===//
  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. // Loops should be simplified before this analysis.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/BranchProbabilityInfo.h"
  14. #include "llvm/ADT/PostOrderIterator.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/IR/CFG.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/IR/Metadata.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. using namespace llvm;
  25. #define DEBUG_TYPE "branch-prob"
  26. INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
  27. "Branch Probability Analysis", false, true)
  28. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  29. INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
  30. "Branch Probability Analysis", false, true)
  31. char BranchProbabilityInfo::ID = 0;
  32. // Weights are for internal use only. They are used by heuristics to help to
  33. // estimate edges' probability. Example:
  34. //
  35. // Using "Loop Branch Heuristics" we predict weights of edges for the
  36. // block BB2.
  37. // ...
  38. // |
  39. // V
  40. // BB1<-+
  41. // | |
  42. // | | (Weight = 124)
  43. // V |
  44. // BB2--+
  45. // |
  46. // | (Weight = 4)
  47. // V
  48. // BB3
  49. //
  50. // Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
  51. // Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
  52. static const uint32_t LBH_TAKEN_WEIGHT = 124;
  53. static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
  54. /// \brief Unreachable-terminating branch taken weight.
  55. ///
  56. /// This is the weight for a branch being taken to a block that terminates
  57. /// (eventually) in unreachable. These are predicted as unlikely as possible.
  58. static const uint32_t UR_TAKEN_WEIGHT = 1;
  59. /// \brief Unreachable-terminating branch not-taken weight.
  60. ///
  61. /// This is the weight for a branch not being taken toward a block that
  62. /// terminates (eventually) in unreachable. Such a branch is essentially never
  63. /// taken. Set the weight to an absurdly high value so that nested loops don't
  64. /// easily subsume it.
  65. static const uint32_t UR_NONTAKEN_WEIGHT = 1024*1024 - 1;
  66. /// \brief Weight for a branch taken going into a cold block.
  67. ///
  68. /// This is the weight for a branch taken toward a block marked
  69. /// cold. A block is marked cold if it's postdominated by a
  70. /// block containing a call to a cold function. Cold functions
  71. /// are those marked with attribute 'cold'.
  72. static const uint32_t CC_TAKEN_WEIGHT = 4;
  73. /// \brief Weight for a branch not-taken into a cold block.
  74. ///
  75. /// This is the weight for a branch not taken toward a block marked
  76. /// cold.
  77. static const uint32_t CC_NONTAKEN_WEIGHT = 64;
  78. static const uint32_t PH_TAKEN_WEIGHT = 20;
  79. static const uint32_t PH_NONTAKEN_WEIGHT = 12;
  80. static const uint32_t ZH_TAKEN_WEIGHT = 20;
  81. static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
  82. static const uint32_t FPH_TAKEN_WEIGHT = 20;
  83. static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
  84. /// \brief Invoke-terminating normal branch taken weight
  85. ///
  86. /// This is the weight for branching to the normal destination of an invoke
  87. /// instruction. We expect this to happen most of the time. Set the weight to an
  88. /// absurdly high value so that nested loops subsume it.
  89. static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
  90. /// \brief Invoke-terminating normal branch not-taken weight.
  91. ///
  92. /// This is the weight for branching to the unwind destination of an invoke
  93. /// instruction. This is essentially never taken.
  94. static const uint32_t IH_NONTAKEN_WEIGHT = 1;
  95. // Standard weight value. Used when none of the heuristics set weight for
  96. // the edge.
  97. static const uint32_t NORMAL_WEIGHT = 16;
  98. // Minimum weight of an edge. Please note, that weight is NEVER 0.
  99. static const uint32_t MIN_WEIGHT = 1;
  100. /// \brief Calculate edge weights for successors lead to unreachable.
  101. ///
  102. /// Predict that a successor which leads necessarily to an
  103. /// unreachable-terminated block as extremely unlikely.
  104. bool BranchProbabilityInfo::calcUnreachableHeuristics(BasicBlock *BB) {
  105. TerminatorInst *TI = BB->getTerminator();
  106. if (TI->getNumSuccessors() == 0) {
  107. if (isa<UnreachableInst>(TI))
  108. PostDominatedByUnreachable.insert(BB);
  109. return false;
  110. }
  111. SmallVector<unsigned, 4> UnreachableEdges;
  112. SmallVector<unsigned, 4> ReachableEdges;
  113. for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
  114. if (PostDominatedByUnreachable.count(*I))
  115. UnreachableEdges.push_back(I.getSuccessorIndex());
  116. else
  117. ReachableEdges.push_back(I.getSuccessorIndex());
  118. }
  119. // If all successors are in the set of blocks post-dominated by unreachable,
  120. // this block is too.
  121. if (UnreachableEdges.size() == TI->getNumSuccessors())
  122. PostDominatedByUnreachable.insert(BB);
  123. // Skip probabilities if this block has a single successor or if all were
  124. // reachable.
  125. if (TI->getNumSuccessors() == 1 || UnreachableEdges.empty())
  126. return false;
  127. uint32_t UnreachableWeight =
  128. std::max(UR_TAKEN_WEIGHT / (unsigned)UnreachableEdges.size(), MIN_WEIGHT);
  129. for (SmallVectorImpl<unsigned>::iterator I = UnreachableEdges.begin(),
  130. E = UnreachableEdges.end();
  131. I != E; ++I)
  132. setEdgeWeight(BB, *I, UnreachableWeight);
  133. if (ReachableEdges.empty())
  134. return true;
  135. uint32_t ReachableWeight =
  136. std::max(UR_NONTAKEN_WEIGHT / (unsigned)ReachableEdges.size(),
  137. NORMAL_WEIGHT);
  138. for (SmallVectorImpl<unsigned>::iterator I = ReachableEdges.begin(),
  139. E = ReachableEdges.end();
  140. I != E; ++I)
  141. setEdgeWeight(BB, *I, ReachableWeight);
  142. return true;
  143. }
  144. // Propagate existing explicit probabilities from either profile data or
  145. // 'expect' intrinsic processing.
  146. bool BranchProbabilityInfo::calcMetadataWeights(BasicBlock *BB) {
  147. TerminatorInst *TI = BB->getTerminator();
  148. if (TI->getNumSuccessors() == 1)
  149. return false;
  150. if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
  151. return false;
  152. MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
  153. if (!WeightsNode)
  154. return false;
  155. // Check that the number of successors is manageable.
  156. assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
  157. // Ensure there are weights for all of the successors. Note that the first
  158. // operand to the metadata node is a name, not a weight.
  159. if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
  160. return false;
  161. // Build up the final weights that will be used in a temporary buffer.
  162. // Compute the sum of all weights to later decide whether they need to
  163. // be scaled to fit in 32 bits.
  164. uint64_t WeightSum = 0;
  165. SmallVector<uint32_t, 2> Weights;
  166. Weights.reserve(TI->getNumSuccessors());
  167. for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
  168. ConstantInt *Weight =
  169. mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
  170. if (!Weight)
  171. return false;
  172. assert(Weight->getValue().getActiveBits() <= 32 &&
  173. "Too many bits for uint32_t");
  174. Weights.push_back(Weight->getZExtValue());
  175. WeightSum += Weights.back();
  176. }
  177. assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
  178. // If the sum of weights does not fit in 32 bits, scale every weight down
  179. // accordingly.
  180. uint64_t ScalingFactor =
  181. (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
  182. WeightSum = 0;
  183. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
  184. uint32_t W = Weights[i] / ScalingFactor;
  185. WeightSum += W;
  186. setEdgeWeight(BB, i, W);
  187. }
  188. assert(WeightSum <= UINT32_MAX &&
  189. "Expected weights to scale down to 32 bits");
  190. return true;
  191. }
  192. /// \brief Calculate edge weights for edges leading to cold blocks.
  193. ///
  194. /// A cold block is one post-dominated by a block with a call to a
  195. /// cold function. Those edges are unlikely to be taken, so we give
  196. /// them relatively low weight.
  197. ///
  198. /// Return true if we could compute the weights for cold edges.
  199. /// Return false, otherwise.
  200. bool BranchProbabilityInfo::calcColdCallHeuristics(BasicBlock *BB) {
  201. TerminatorInst *TI = BB->getTerminator();
  202. if (TI->getNumSuccessors() == 0)
  203. return false;
  204. // Determine which successors are post-dominated by a cold block.
  205. SmallVector<unsigned, 4> ColdEdges;
  206. SmallVector<unsigned, 4> NormalEdges;
  207. for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
  208. if (PostDominatedByColdCall.count(*I))
  209. ColdEdges.push_back(I.getSuccessorIndex());
  210. else
  211. NormalEdges.push_back(I.getSuccessorIndex());
  212. // If all successors are in the set of blocks post-dominated by cold calls,
  213. // this block is in the set post-dominated by cold calls.
  214. if (ColdEdges.size() == TI->getNumSuccessors())
  215. PostDominatedByColdCall.insert(BB);
  216. else {
  217. // Otherwise, if the block itself contains a cold function, add it to the
  218. // set of blocks postdominated by a cold call.
  219. assert(!PostDominatedByColdCall.count(BB));
  220. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  221. if (CallInst *CI = dyn_cast<CallInst>(I))
  222. if (CI->hasFnAttr(Attribute::Cold)) {
  223. PostDominatedByColdCall.insert(BB);
  224. break;
  225. }
  226. }
  227. // Skip probabilities if this block has a single successor.
  228. if (TI->getNumSuccessors() == 1 || ColdEdges.empty())
  229. return false;
  230. uint32_t ColdWeight =
  231. std::max(CC_TAKEN_WEIGHT / (unsigned) ColdEdges.size(), MIN_WEIGHT);
  232. for (SmallVectorImpl<unsigned>::iterator I = ColdEdges.begin(),
  233. E = ColdEdges.end();
  234. I != E; ++I)
  235. setEdgeWeight(BB, *I, ColdWeight);
  236. if (NormalEdges.empty())
  237. return true;
  238. uint32_t NormalWeight = std::max(
  239. CC_NONTAKEN_WEIGHT / (unsigned) NormalEdges.size(), NORMAL_WEIGHT);
  240. for (SmallVectorImpl<unsigned>::iterator I = NormalEdges.begin(),
  241. E = NormalEdges.end();
  242. I != E; ++I)
  243. setEdgeWeight(BB, *I, NormalWeight);
  244. return true;
  245. }
  246. // Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
  247. // between two pointer or pointer and NULL will fail.
  248. bool BranchProbabilityInfo::calcPointerHeuristics(BasicBlock *BB) {
  249. BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
  250. if (!BI || !BI->isConditional())
  251. return false;
  252. Value *Cond = BI->getCondition();
  253. ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
  254. if (!CI || !CI->isEquality())
  255. return false;
  256. Value *LHS = CI->getOperand(0);
  257. if (!LHS->getType()->isPointerTy())
  258. return false;
  259. assert(CI->getOperand(1)->getType()->isPointerTy());
  260. // p != 0 -> isProb = true
  261. // p == 0 -> isProb = false
  262. // p != q -> isProb = true
  263. // p == q -> isProb = false;
  264. unsigned TakenIdx = 0, NonTakenIdx = 1;
  265. bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
  266. if (!isProb)
  267. std::swap(TakenIdx, NonTakenIdx);
  268. setEdgeWeight(BB, TakenIdx, PH_TAKEN_WEIGHT);
  269. setEdgeWeight(BB, NonTakenIdx, PH_NONTAKEN_WEIGHT);
  270. return true;
  271. }
  272. // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
  273. // as taken, exiting edges as not-taken.
  274. bool BranchProbabilityInfo::calcLoopBranchHeuristics(BasicBlock *BB) {
  275. Loop *L = LI->getLoopFor(BB);
  276. if (!L)
  277. return false;
  278. SmallVector<unsigned, 8> BackEdges;
  279. SmallVector<unsigned, 8> ExitingEdges;
  280. SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
  281. for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
  282. if (!L->contains(*I))
  283. ExitingEdges.push_back(I.getSuccessorIndex());
  284. else if (L->getHeader() == *I)
  285. BackEdges.push_back(I.getSuccessorIndex());
  286. else
  287. InEdges.push_back(I.getSuccessorIndex());
  288. }
  289. if (BackEdges.empty() && ExitingEdges.empty())
  290. return false;
  291. if (uint32_t numBackEdges = BackEdges.size()) {
  292. uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
  293. if (backWeight < NORMAL_WEIGHT)
  294. backWeight = NORMAL_WEIGHT;
  295. for (SmallVectorImpl<unsigned>::iterator EI = BackEdges.begin(),
  296. EE = BackEdges.end(); EI != EE; ++EI) {
  297. setEdgeWeight(BB, *EI, backWeight);
  298. }
  299. }
  300. if (uint32_t numInEdges = InEdges.size()) {
  301. uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
  302. if (inWeight < NORMAL_WEIGHT)
  303. inWeight = NORMAL_WEIGHT;
  304. for (SmallVectorImpl<unsigned>::iterator EI = InEdges.begin(),
  305. EE = InEdges.end(); EI != EE; ++EI) {
  306. setEdgeWeight(BB, *EI, inWeight);
  307. }
  308. }
  309. if (uint32_t numExitingEdges = ExitingEdges.size()) {
  310. uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numExitingEdges;
  311. if (exitWeight < MIN_WEIGHT)
  312. exitWeight = MIN_WEIGHT;
  313. for (SmallVectorImpl<unsigned>::iterator EI = ExitingEdges.begin(),
  314. EE = ExitingEdges.end(); EI != EE; ++EI) {
  315. setEdgeWeight(BB, *EI, exitWeight);
  316. }
  317. }
  318. return true;
  319. }
  320. bool BranchProbabilityInfo::calcZeroHeuristics(BasicBlock *BB) {
  321. BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
  322. if (!BI || !BI->isConditional())
  323. return false;
  324. Value *Cond = BI->getCondition();
  325. ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
  326. if (!CI)
  327. return false;
  328. Value *RHS = CI->getOperand(1);
  329. ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
  330. if (!CV)
  331. return false;
  332. // If the LHS is the result of AND'ing a value with a single bit bitmask,
  333. // we don't have information about probabilities.
  334. if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
  335. if (LHS->getOpcode() == Instruction::And)
  336. if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
  337. if (AndRHS->getUniqueInteger().isPowerOf2())
  338. return false;
  339. bool isProb;
  340. if (CV->isZero()) {
  341. switch (CI->getPredicate()) {
  342. case CmpInst::ICMP_EQ:
  343. // X == 0 -> Unlikely
  344. isProb = false;
  345. break;
  346. case CmpInst::ICMP_NE:
  347. // X != 0 -> Likely
  348. isProb = true;
  349. break;
  350. case CmpInst::ICMP_SLT:
  351. // X < 0 -> Unlikely
  352. isProb = false;
  353. break;
  354. case CmpInst::ICMP_SGT:
  355. // X > 0 -> Likely
  356. isProb = true;
  357. break;
  358. default:
  359. return false;
  360. }
  361. } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
  362. // InstCombine canonicalizes X <= 0 into X < 1.
  363. // X <= 0 -> Unlikely
  364. isProb = false;
  365. } else if (CV->isAllOnesValue()) {
  366. switch (CI->getPredicate()) {
  367. case CmpInst::ICMP_EQ:
  368. // X == -1 -> Unlikely
  369. isProb = false;
  370. break;
  371. case CmpInst::ICMP_NE:
  372. // X != -1 -> Likely
  373. isProb = true;
  374. break;
  375. case CmpInst::ICMP_SGT:
  376. // InstCombine canonicalizes X >= 0 into X > -1.
  377. // X >= 0 -> Likely
  378. isProb = true;
  379. break;
  380. default:
  381. return false;
  382. }
  383. } else {
  384. return false;
  385. }
  386. unsigned TakenIdx = 0, NonTakenIdx = 1;
  387. if (!isProb)
  388. std::swap(TakenIdx, NonTakenIdx);
  389. setEdgeWeight(BB, TakenIdx, ZH_TAKEN_WEIGHT);
  390. setEdgeWeight(BB, NonTakenIdx, ZH_NONTAKEN_WEIGHT);
  391. return true;
  392. }
  393. bool BranchProbabilityInfo::calcFloatingPointHeuristics(BasicBlock *BB) {
  394. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  395. if (!BI || !BI->isConditional())
  396. return false;
  397. Value *Cond = BI->getCondition();
  398. FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
  399. if (!FCmp)
  400. return false;
  401. bool isProb;
  402. if (FCmp->isEquality()) {
  403. // f1 == f2 -> Unlikely
  404. // f1 != f2 -> Likely
  405. isProb = !FCmp->isTrueWhenEqual();
  406. } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
  407. // !isnan -> Likely
  408. isProb = true;
  409. } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
  410. // isnan -> Unlikely
  411. isProb = false;
  412. } else {
  413. return false;
  414. }
  415. unsigned TakenIdx = 0, NonTakenIdx = 1;
  416. if (!isProb)
  417. std::swap(TakenIdx, NonTakenIdx);
  418. setEdgeWeight(BB, TakenIdx, FPH_TAKEN_WEIGHT);
  419. setEdgeWeight(BB, NonTakenIdx, FPH_NONTAKEN_WEIGHT);
  420. return true;
  421. }
  422. bool BranchProbabilityInfo::calcInvokeHeuristics(BasicBlock *BB) {
  423. InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
  424. if (!II)
  425. return false;
  426. setEdgeWeight(BB, 0/*Index for Normal*/, IH_TAKEN_WEIGHT);
  427. setEdgeWeight(BB, 1/*Index for Unwind*/, IH_NONTAKEN_WEIGHT);
  428. return true;
  429. }
  430. void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
  431. AU.addRequired<LoopInfoWrapperPass>();
  432. AU.setPreservesAll();
  433. }
  434. bool BranchProbabilityInfo::runOnFunction(Function &F) {
  435. DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
  436. << " ----\n\n");
  437. LastF = &F; // Store the last function we ran on for printing.
  438. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  439. assert(PostDominatedByUnreachable.empty());
  440. assert(PostDominatedByColdCall.empty());
  441. // Walk the basic blocks in post-order so that we can build up state about
  442. // the successors of a block iteratively.
  443. for (auto BB : post_order(&F.getEntryBlock())) {
  444. DEBUG(dbgs() << "Computing probabilities for " << BB->getName() << "\n");
  445. if (calcUnreachableHeuristics(BB))
  446. continue;
  447. if (calcMetadataWeights(BB))
  448. continue;
  449. if (calcColdCallHeuristics(BB))
  450. continue;
  451. if (calcLoopBranchHeuristics(BB))
  452. continue;
  453. if (calcPointerHeuristics(BB))
  454. continue;
  455. if (calcZeroHeuristics(BB))
  456. continue;
  457. if (calcFloatingPointHeuristics(BB))
  458. continue;
  459. calcInvokeHeuristics(BB);
  460. }
  461. PostDominatedByUnreachable.clear();
  462. PostDominatedByColdCall.clear();
  463. return false;
  464. }
  465. void BranchProbabilityInfo::releaseMemory() {
  466. Weights.clear();
  467. }
  468. void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const {
  469. OS << "---- Branch Probabilities ----\n";
  470. // We print the probabilities from the last function the analysis ran over,
  471. // or the function it is currently running over.
  472. assert(LastF && "Cannot print prior to running over a function");
  473. for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
  474. BI != BE; ++BI) {
  475. for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
  476. SI != SE; ++SI) {
  477. printEdgeProbability(OS << " ", BI, *SI);
  478. }
  479. }
  480. }
  481. uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const {
  482. uint32_t Sum = 0;
  483. for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
  484. uint32_t Weight = getEdgeWeight(BB, I.getSuccessorIndex());
  485. uint32_t PrevSum = Sum;
  486. Sum += Weight;
  487. assert(Sum >= PrevSum); (void) PrevSum;
  488. }
  489. return Sum;
  490. }
  491. bool BranchProbabilityInfo::
  492. isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
  493. // Hot probability is at least 4/5 = 80%
  494. // FIXME: Compare against a static "hot" BranchProbability.
  495. return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
  496. }
  497. BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
  498. uint32_t Sum = 0;
  499. uint32_t MaxWeight = 0;
  500. BasicBlock *MaxSucc = nullptr;
  501. for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
  502. BasicBlock *Succ = *I;
  503. uint32_t Weight = getEdgeWeight(BB, Succ);
  504. uint32_t PrevSum = Sum;
  505. Sum += Weight;
  506. assert(Sum > PrevSum); (void) PrevSum;
  507. if (Weight > MaxWeight) {
  508. MaxWeight = Weight;
  509. MaxSucc = Succ;
  510. }
  511. }
  512. // Hot probability is at least 4/5 = 80%
  513. if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
  514. return MaxSucc;
  515. return nullptr;
  516. }
  517. /// Get the raw edge weight for the edge. If can't find it, return
  518. /// DEFAULT_WEIGHT value. Here an edge is specified using PredBlock and an index
  519. /// to the successors.
  520. uint32_t BranchProbabilityInfo::
  521. getEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors) const {
  522. DenseMap<Edge, uint32_t>::const_iterator I =
  523. Weights.find(std::make_pair(Src, IndexInSuccessors));
  524. if (I != Weights.end())
  525. return I->second;
  526. return DEFAULT_WEIGHT;
  527. }
  528. uint32_t BranchProbabilityInfo::getEdgeWeight(const BasicBlock *Src,
  529. succ_const_iterator Dst) const {
  530. return getEdgeWeight(Src, Dst.getSuccessorIndex());
  531. }
  532. /// Get the raw edge weight calculated for the block pair. This returns the sum
  533. /// of all raw edge weights from Src to Dst.
  534. uint32_t BranchProbabilityInfo::
  535. getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const {
  536. uint32_t Weight = 0;
  537. bool FoundWeight = false;
  538. DenseMap<Edge, uint32_t>::const_iterator MapI;
  539. for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
  540. if (*I == Dst) {
  541. MapI = Weights.find(std::make_pair(Src, I.getSuccessorIndex()));
  542. if (MapI != Weights.end()) {
  543. FoundWeight = true;
  544. Weight += MapI->second;
  545. }
  546. }
  547. return (!FoundWeight) ? DEFAULT_WEIGHT : Weight;
  548. }
  549. /// Set the edge weight for a given edge specified by PredBlock and an index
  550. /// to the successors.
  551. void BranchProbabilityInfo::
  552. setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors,
  553. uint32_t Weight) {
  554. Weights[std::make_pair(Src, IndexInSuccessors)] = Weight;
  555. DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
  556. << IndexInSuccessors << " successor weight to "
  557. << Weight << "\n");
  558. }
  559. /// Get an edge's probability, relative to other out-edges from Src.
  560. BranchProbability BranchProbabilityInfo::
  561. getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const {
  562. uint32_t N = getEdgeWeight(Src, IndexInSuccessors);
  563. uint32_t D = getSumForBlock(Src);
  564. return BranchProbability(N, D);
  565. }
  566. /// Get the probability of going from Src to Dst. It returns the sum of all
  567. /// probabilities for edges from Src to Dst.
  568. BranchProbability BranchProbabilityInfo::
  569. getEdgeProbability(const BasicBlock *Src, const BasicBlock *Dst) const {
  570. uint32_t N = getEdgeWeight(Src, Dst);
  571. uint32_t D = getSumForBlock(Src);
  572. return BranchProbability(N, D);
  573. }
  574. raw_ostream &
  575. BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
  576. const BasicBlock *Src,
  577. const BasicBlock *Dst) const {
  578. const BranchProbability Prob = getEdgeProbability(Src, Dst);
  579. OS << "edge " << Src->getName() << " -> " << Dst->getName()
  580. << " probability is " << Prob
  581. << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
  582. return OS;
  583. }