llvm.org GIT mirror llvm / 40288f7
[BPI] Replace weights by probabilities in BPI. This patch removes all weight-related interfaces from BPI and replace them by probability versions. With this patch, we won't use edge weight anymore in either IR or MC passes. Edge probabilitiy is a better representation in terms of CFG update and validation. Differential revision: http://reviews.llvm.org/D15519 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@256263 91177308-0d34-0410-b5e6-96231b3b80d8 Cong Hou 4 years ago
8 changed file(s) with 175 addition(s) and 290 deletion(s). Raw diff Collapse all Expand all
8383 raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
8484 const BasicBlock *Dst) const;
8585
86 /// \brief Get the raw edge weight calculated for the edge.
86 /// \brief Set the raw edge probability for the given edge.
8787 ///
88 /// This returns the raw edge weight. It is guaranteed to fall between 1 and
89 /// UINT32_MAX. Note that the raw edge weight is not meaningful in isolation.
90 /// This interface should be very carefully, and primarily by routines that
91 /// are updating the analysis by later calling setEdgeWeight.
92 uint32_t getEdgeWeight(const BasicBlock *Src,
93 unsigned IndexInSuccessors) const;
94
95 /// \brief Get the raw edge weight calculated for the block pair.
96 ///
97 /// This returns the sum of all raw edge weights from Src to Dst.
98 /// It is guaranteed to fall between 1 and UINT32_MAX.
99 uint32_t getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const;
100
101 uint32_t getEdgeWeight(const BasicBlock *Src,
102 succ_const_iterator Dst) const;
103
104 /// \brief Set the raw edge weight for a given edge.
105 ///
106 /// This allows a pass to explicitly set the edge weight for an edge. It can
107 /// be used when updating the CFG to update and preserve the branch
88 /// This allows a pass to explicitly set the edge probability for an edge. It
89 /// can be used when updating the CFG to update and preserve the branch
10890 /// probability information. Read the implementation of how these edge
109 /// weights are calculated carefully before using!
110 void setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors,
111 uint32_t Weight);
112
113 static uint32_t getBranchWeightStackProtector(bool IsLikely) {
114 return IsLikely ? (1u << 20) - 1 : 1;
115 }
91 /// probabilities are calculated carefully before using!
92 void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors,
93 BranchProbability Prob);
11694
11795 static BranchProbability getBranchProbStackProtector(bool IsLikely) {
11896 static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
134112 // weight to just "inherit" the non-zero weight of an adjacent successor.
135113 static const uint32_t DEFAULT_WEIGHT = 16;
136114
137 DenseMapuint32_t> Weights;
115 DenseMapBranchProbability> Probs;
138116
139117 /// \brief Track the last function we run over for printing.
140118 Function *LastF;
144122
145123 /// \brief Track the set of blocks that always lead to a cold call.
146124 SmallPtrSet PostDominatedByColdCall;
147
148 /// \brief Get sum of the block successors' weights.
149 uint32_t getSumForBlock(const BasicBlock *BB) const;
150125
151126 bool calcUnreachableHeuristics(BasicBlock *BB);
152127 bool calcMetadataWeights(BasicBlock *BB);
6262 static void normalizeProbabilities(ProbabilityIter Begin,
6363 ProbabilityIter End);
6464
65 // Normalize a list of weights by scaling them down so that the sum of them
66 // doesn't exceed UINT32_MAX.
67 template
68 static void normalizeEdgeWeights(WeightListIter Begin, WeightListIter End);
69
7065 uint32_t getNumerator() const { return N; }
7166 static uint32_t getDenominator() { return D; }
7267
218213 I->N = (I->N * uint64_t(D) + Sum / 2) / Sum;
219214 }
220215
221 template
222 void BranchProbability::normalizeEdgeWeights(WeightListIter Begin,
223 WeightListIter End) {
224 // First we compute the sum with 64-bits of precision.
225 uint64_t Sum = std::accumulate(Begin, End, uint64_t(0));
226
227 if (Sum > UINT32_MAX) {
228 // Compute the scale necessary to cause the weights to fit, and re-sum with
229 // that scale applied.
230 assert(Sum / UINT32_MAX < UINT32_MAX &&
231 "The sum of weights exceeds UINT32_MAX^2!");
232 uint32_t Scale = Sum / UINT32_MAX + 1;
233 for (auto I = Begin; I != End; ++I)
234 *I /= Scale;
235 Sum = std::accumulate(Begin, End, uint64_t(0));
236 }
237
238 // Eliminate zero weights.
239 auto ZeroWeightNum = std::count(Begin, End, 0u);
240 if (ZeroWeightNum > 0) {
241 // If all weights are zeros, replace them by 1.
242 if (Sum == 0)
243 std::fill(Begin, End, 1u);
244 else {
245 // We are converting zeros into ones, and here we need to make sure that
246 // after this the sum won't exceed UINT32_MAX.
247 if (Sum + ZeroWeightNum > UINT32_MAX) {
248 for (auto I = Begin; I != End; ++I)
249 *I /= 2;
250 ZeroWeightNum = std::count(Begin, End, 0u);
251 Sum = std::accumulate(Begin, End, uint64_t(0));
252 }
253 // Scale up non-zero weights and turn zero weights into ones.
254 uint64_t ScalingFactor = (UINT32_MAX - ZeroWeightNum) / Sum;
255 assert(ScalingFactor >= 1);
256 if (ScalingFactor > 1)
257 for (auto I = Begin; I != End; ++I)
258 *I *= ScalingFactor;
259 std::replace(Begin, End, 0u, 1u);
260 }
261 }
262216 }
263217
264 }
265
266218 #endif
107107 /// instruction. This is essentially never taken.
108108 static const uint32_t IH_NONTAKEN_WEIGHT = 1;
109109
110 // Standard weight value. Used when none of the heuristics set weight for
111 // the edge.
112 static const uint32_t NORMAL_WEIGHT = 16;
113
114 // Minimum weight of an edge. Please note, that weight is NEVER 0.
115 static const uint32_t MIN_WEIGHT = 1;
116
117110 /// \brief Calculate edge weights for successors lead to unreachable.
118111 ///
119112 /// Predict that a successor which leads necessarily to an
156149 return false;
157150 }
158151
159 uint32_t UnreachableWeight =
160 std::max(UR_TAKEN_WEIGHT / (unsigned)UnreachableEdges.size(), MIN_WEIGHT);
161 for (SmallVectorImpl::iterator I = UnreachableEdges.begin(),
162 E = UnreachableEdges.end();
163 I != E; ++I)
164 setEdgeWeight(BB, *I, UnreachableWeight);
165
166 if (ReachableEdges.empty())
152 if (ReachableEdges.empty()) {
153 BranchProbability Prob(1, UnreachableEdges.size());
154 for (unsigned SuccIdx : UnreachableEdges)
155 setEdgeProbability(BB, SuccIdx, Prob);
167156 return true;
168 uint32_t ReachableWeight =
169 std::max(UR_NONTAKEN_WEIGHT / (unsigned)ReachableEdges.size(),
170 NORMAL_WEIGHT);
171 for (SmallVectorImpl::iterator I = ReachableEdges.begin(),
172 E = ReachableEdges.end();
173 I != E; ++I)
174 setEdgeWeight(BB, *I, ReachableWeight);
157 }
158
159 BranchProbability UnreachableProb(UR_TAKEN_WEIGHT,
160 (UR_TAKEN_WEIGHT + UR_NONTAKEN_WEIGHT) *
161 UnreachableEdges.size());
162 BranchProbability ReachableProb(UR_NONTAKEN_WEIGHT,
163 (UR_TAKEN_WEIGHT + UR_NONTAKEN_WEIGHT) *
164 ReachableEdges.size());
165
166 for (unsigned SuccIdx : UnreachableEdges)
167 setEdgeProbability(BB, SuccIdx, UnreachableProb);
168 for (unsigned SuccIdx : ReachableEdges)
169 setEdgeProbability(BB, SuccIdx, ReachableProb);
175170
176171 return true;
177172 }
222217
223218 WeightSum = 0;
224219 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
225 uint32_t W = Weights[i] / ScalingFactor;
226 WeightSum += W;
227 setEdgeWeight(BB, i, W);
228 }
220 Weights[i] /= ScalingFactor;
221 WeightSum += Weights[i];
222 }
223 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
224 setEdgeProbability(BB, i, {Weights[i], static_cast(WeightSum)});
225
229226 assert(WeightSum <= UINT32_MAX &&
230227 "Expected weights to scale down to 32 bits");
231228
274271 if (TI->getNumSuccessors() == 1 || ColdEdges.empty())
275272 return false;
276273
277 uint32_t ColdWeight =
278 std::max(CC_TAKEN_WEIGHT / (unsigned) ColdEdges.size(), MIN_WEIGHT);
279 for (SmallVectorImpl::iterator I = ColdEdges.begin(),
280 E = ColdEdges.end();
281 I != E; ++I)
282 setEdgeWeight(BB, *I, ColdWeight);
283
284 if (NormalEdges.empty())
274 if (NormalEdges.empty()) {
275 BranchProbability Prob(1, ColdEdges.size());
276 for (unsigned SuccIdx : ColdEdges)
277 setEdgeProbability(BB, SuccIdx, Prob);
285278 return true;
286 uint32_t NormalWeight = std::max(
287 CC_NONTAKEN_WEIGHT / (unsigned) NormalEdges.size(), NORMAL_WEIGHT);
288 for (SmallVectorImpl::iterator I = NormalEdges.begin(),
289 E = NormalEdges.end();
290 I != E; ++I)
291 setEdgeWeight(BB, *I, NormalWeight);
279 }
280
281 BranchProbability ColdProb(CC_TAKEN_WEIGHT,
282 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) *
283 ColdEdges.size());
284 BranchProbability NormalProb(CC_NONTAKEN_WEIGHT,
285 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) *
286 NormalEdges.size());
287
288 for (unsigned SuccIdx : ColdEdges)
289 setEdgeProbability(BB, SuccIdx, ColdProb);
290 for (unsigned SuccIdx : NormalEdges)
291 setEdgeProbability(BB, SuccIdx, NormalProb);
292292
293293 return true;
294294 }
321321 if (!isProb)
322322 std::swap(TakenIdx, NonTakenIdx);
323323
324 setEdgeWeight(BB, TakenIdx, PH_TAKEN_WEIGHT);
325 setEdgeWeight(BB, NonTakenIdx, PH_NONTAKEN_WEIGHT);
324 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
325 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
326 setEdgeProbability(BB, TakenIdx, TakenProb);
327 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
326328 return true;
327329 }
328330
350352 if (BackEdges.empty() && ExitingEdges.empty())
351353 return false;
352354
355 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
356 // normalize them so that they sum up to one.
357 SmallVector Probs(3, BranchProbability::getZero());
358 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
359 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
360 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
361 if (!BackEdges.empty())
362 Probs[0] = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
363 if (!InEdges.empty())
364 Probs[1] = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
365 if (!ExitingEdges.empty())
366 Probs[2] = BranchProbability(LBH_NONTAKEN_WEIGHT, Denom);
367
353368 if (uint32_t numBackEdges = BackEdges.size()) {
354 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
355 if (backWeight < NORMAL_WEIGHT)
356 backWeight = NORMAL_WEIGHT;
357
358 for (SmallVectorImpl::iterator EI = BackEdges.begin(),
359 EE = BackEdges.end(); EI != EE; ++EI) {
360 setEdgeWeight(BB, *EI, backWeight);
361 }
369 auto Prob = Probs[0] / numBackEdges;
370 for (unsigned SuccIdx : BackEdges)
371 setEdgeProbability(BB, SuccIdx, Prob);
362372 }
363373
364374 if (uint32_t numInEdges = InEdges.size()) {
365 uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
366 if (inWeight < NORMAL_WEIGHT)
367 inWeight = NORMAL_WEIGHT;
368
369 for (SmallVectorImpl::iterator EI = InEdges.begin(),
370 EE = InEdges.end(); EI != EE; ++EI) {
371 setEdgeWeight(BB, *EI, inWeight);
372 }
375 auto Prob = Probs[1] / numInEdges;
376 for (unsigned SuccIdx : InEdges)
377 setEdgeProbability(BB, SuccIdx, Prob);
373378 }
374379
375380 if (uint32_t numExitingEdges = ExitingEdges.size()) {
376 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numExitingEdges;
377 if (exitWeight < MIN_WEIGHT)
378 exitWeight = MIN_WEIGHT;
379
380 for (SmallVectorImpl::iterator EI = ExitingEdges.begin(),
381 EE = ExitingEdges.end(); EI != EE; ++EI) {
382 setEdgeWeight(BB, *EI, exitWeight);
383 }
381 auto Prob = Probs[2] / numExitingEdges;
382 for (unsigned SuccIdx : ExitingEdges)
383 setEdgeProbability(BB, SuccIdx, Prob);
384384 }
385385
386386 return true;
462462 if (!isProb)
463463 std::swap(TakenIdx, NonTakenIdx);
464464
465 setEdgeWeight(BB, TakenIdx, ZH_TAKEN_WEIGHT);
466 setEdgeWeight(BB, NonTakenIdx, ZH_NONTAKEN_WEIGHT);
467
465 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
466 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
467 setEdgeProbability(BB, TakenIdx, TakenProb);
468 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
468469 return true;
469470 }
470471
498499 if (!isProb)
499500 std::swap(TakenIdx, NonTakenIdx);
500501
501 setEdgeWeight(BB, TakenIdx, FPH_TAKEN_WEIGHT);
502 setEdgeWeight(BB, NonTakenIdx, FPH_NONTAKEN_WEIGHT);
503
502 BranchProbability TakenProb(FPH_TAKEN_WEIGHT,
503 FPH_TAKEN_WEIGHT + FPH_NONTAKEN_WEIGHT);
504 setEdgeProbability(BB, TakenIdx, TakenProb);
505 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
504506 return true;
505507 }
506508
509511 if (!II)
510512 return false;
511513
512 setEdgeWeight(BB, 0/*Index for Normal*/, IH_TAKEN_WEIGHT);
513 setEdgeWeight(BB, 1/*Index for Unwind*/, IH_NONTAKEN_WEIGHT);
514 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
515 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
516 setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
517 setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
514518 return true;
515519 }
516520
517521 void BranchProbabilityInfo::releaseMemory() {
518 Weights.clear();
522 Probs.clear();
519523 }
520524
521525 void BranchProbabilityInfo::print(raw_ostream &OS) const {
531535 }
532536 }
533537
534 uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const {
535 uint32_t Sum = 0;
536
537 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
538 uint32_t Weight = getEdgeWeight(BB, I.getSuccessorIndex());
539 uint32_t PrevSum = Sum;
540
541 Sum += Weight;
542 assert(Sum >= PrevSum); (void) PrevSum;
543 }
544
545 return Sum;
546 }
547
548538 bool BranchProbabilityInfo::
549539 isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
550540 // Hot probability is at least 4/5 = 80%
553543 }
554544
555545 BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
556 uint32_t Sum = 0;
557 uint32_t MaxWeight = 0;
546 auto MaxProb = BranchProbability::getZero();
558547 BasicBlock *MaxSucc = nullptr;
559548
560549 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
561550 BasicBlock *Succ = *I;
562 uint32_t Weight = getEdgeWeight(BB, Succ);
563 uint32_t PrevSum = Sum;
564
565 Sum += Weight;
566 assert(Sum > PrevSum); (void) PrevSum;
567
568 if (Weight > MaxWeight) {
569 MaxWeight = Weight;
551 auto Prob = getEdgeProbability(BB, Succ);
552 if (Prob > MaxProb) {
553 MaxProb = Prob;
570554 MaxSucc = Succ;
571555 }
572556 }
573557
574558 // Hot probability is at least 4/5 = 80%
575 if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
559 if (MaxProb > BranchProbability(4, 5))
576560 return MaxSucc;
577561
578562 return nullptr;
579563 }
580564
581 /// Get the raw edge weight for the edge. If can't find it, return
582 /// DEFAULT_WEIGHT value. Here an edge is specified using PredBlock and an index
583 /// to the successors.
584 uint32_t BranchProbabilityInfo::
585 getEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors) const {
586 DenseMap::const_iterator I =
587 Weights.find(std::make_pair(Src, IndexInSuccessors));
588
589 if (I != Weights.end())
565 /// Get the raw edge probability for the edge. If can't find it, return a
566 /// default probability 1/N where N is the number of successors. Here an edge is
567 /// specified using PredBlock and an
568 /// index to the successors.
569 BranchProbability
570 BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
571 unsigned IndexInSuccessors) const {
572 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
573
574 if (I != Probs.end())
590575 return I->second;
591576
592 return DEFAULT_WEIGHT;
593 }
594
595 uint32_t BranchProbabilityInfo::getEdgeWeight(const BasicBlock *Src,
596 succ_const_iterator Dst) const {
597 return getEdgeWeight(Src, Dst.getSuccessorIndex());
598 }
599
600 /// Get the raw edge weight calculated for the block pair. This returns the sum
601 /// of all raw edge weights from Src to Dst.
602 uint32_t BranchProbabilityInfo::
603 getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const {
604 uint32_t Weight = 0;
605 bool FoundWeight = false;
606 DenseMap::const_iterator MapI;
607 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
608 if (*I == Dst) {
609 MapI = Weights.find(std::make_pair(Src, I.getSuccessorIndex()));
610 if (MapI != Weights.end()) {
611 FoundWeight = true;
612 Weight += MapI->second;
613 }
614 }
615 return (!FoundWeight) ? DEFAULT_WEIGHT : Weight;
616 }
617
618 /// Set the edge weight for a given edge specified by PredBlock and an index
619 /// to the successors.
620 void BranchProbabilityInfo::
621 setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors,
622 uint32_t Weight) {
623 Weights[std::make_pair(Src, IndexInSuccessors)] = Weight;
624 DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
625 << IndexInSuccessors << " successor weight to "
626 << Weight << "\n");
627 }
628
629 /// Get an edge's probability, relative to other out-edges from Src.
630 BranchProbability BranchProbabilityInfo::
631 getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const {
632 uint32_t N = getEdgeWeight(Src, IndexInSuccessors);
633 uint32_t D = getSumForBlock(Src);
634
635 // It is possible that the edge weight on the only successor edge of Src is
636 // zero, in which case we return 100%.
637 if (N == 0 && D == 0)
638 return BranchProbability::getOne();
639
640 return BranchProbability(N, D);
641 }
642
643 /// Get the probability of going from Src to Dst. It returns the sum of all
644 /// probabilities for edges from Src to Dst.
645 BranchProbability BranchProbabilityInfo::
646 getEdgeProbability(const BasicBlock *Src, const BasicBlock *Dst) const {
647
648 uint32_t N = getEdgeWeight(Src, Dst);
649 uint32_t D = getSumForBlock(Src);
650
651 // It is possible that the edge weight on the only successor edge of Src is
652 // zero, in which case we return 100%.
653 if (N == 0 && D == 0)
654 return BranchProbability::getOne();
655
656 return BranchProbability(N, D);
577 return {1,
578 static_cast(std::distance(succ_begin(Src), succ_end(Src)))};
657579 }
658580
659581 BranchProbability
660582 BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
661583 succ_const_iterator Dst) const {
662584 return getEdgeProbability(Src, Dst.getSuccessorIndex());
585 }
586
587 /// Get the raw edge probability calculated for the block pair. This returns the
588 /// sum of all raw edge probabilities from Src to Dst.
589 BranchProbability
590 BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
591 const BasicBlock *Dst) const {
592 auto Prob = BranchProbability::getZero();
593 bool FoundProb = false;
594 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
595 if (*I == Dst) {
596 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
597 if (MapI != Probs.end()) {
598 FoundProb = true;
599 Prob += MapI->second;
600 }
601 }
602 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
603 return FoundProb ? Prob : BranchProbability(1, succ_num);
604 }
605
606 /// Set the edge probability for a given edge specified by PredBlock and an
607 /// index to the successors.
608 void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
609 unsigned IndexInSuccessors,
610 BranchProbability Prob) {
611 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
612 DEBUG(dbgs() << "set edge " << Src->getName() << " -> " << IndexInSuccessors
613 << " successor probability to " << Prob << "\n");
663614 }
664615
665616 raw_ostream &
452452 LoadInst *LI1 = B.CreateLoad(StackGuardVar);
453453 LoadInst *LI2 = B.CreateLoad(AI);
454454 Value *Cmp = B.CreateICmpEQ(LI1, LI2);
455 unsigned SuccessWeight =
456 BranchProbabilityInfo::getBranchWeightStackProtector(true);
457 unsigned FailureWeight =
458 BranchProbabilityInfo::getBranchWeightStackProtector(false);
455 auto SuccessProb =
456 BranchProbabilityInfo::getBranchProbStackProtector(true);
457 auto FailureProb =
458 BranchProbabilityInfo::getBranchProbStackProtector(false);
459459 MDNode *Weights = MDBuilder(F->getContext())
460 .createBranchWeights(SuccessWeight, FailureWeight);
460 .createBranchWeights(SuccessProb.getNumerator(),
461 FailureProb.getNumerator());
461462 B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
462463 }
463464 }
413413 const BasicBlock *TBB = BBTerm->getSuccessor(0);
414414 const BasicBlock *FBB = BBTerm->getSuccessor(1);
415415
416 uint32_t TWeight = FuncInfo->BPI->getEdgeWeight(BB, TBB);
417 uint32_t FWeight = FuncInfo->BPI->getEdgeWeight(BB, FBB);
416 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
417 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
418418
419419 // We only want to handle cases which are easy to predict at static time, e.g.
420420 // C++ throw statement, that is very likely not taken, or calling never
431431 // 5. PH/ZH/FPH 20:12
432432 const uint32_t Threshold = 10000;
433433
434 // Minimal weight should be at least 1
435 if (std::max(TWeight, FWeight) /
436 std::max(1u, std::min(TWeight, FWeight)) < Threshold)
434 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
437435 return PPC::BR_NO_HINT;
438436
439437 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
440438 << BB->getName() << "'\n"
441 << " -> " << TBB->getName() << ": " << TWeight << "\n"
442 << " -> " << FBB->getName() << ": " << FWeight << "\n");
439 << " -> " << TBB->getName() << ": " << TProb << "\n"
440 << " -> " << FBB->getName() << ": " << FProb << "\n");
443441
444442 const BasicBlockSDNode *BBDN = cast(DestMBB);
445443
446 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch weight,
447 // because we want 'TWeight' stands for 'branch weight' to Dest BasicBlock
444 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
445 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
448446 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
449 std::swap(TWeight, FWeight);
450
451 return (TWeight > FWeight) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
447 std::swap(TProb, FProb);
448
449 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
452450 }
453451
454452 // isOpcWithIntImmediate - This method tests to see if the node is a specific
16351635 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
16361636
16371637 // Collect updated outgoing edges' frequencies from BB and use them to update
1638 // edge weights.
1638 // edge probabilities.
16391639 SmallVector BBSuccFreq;
16401640 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
16411641 auto SuccFreq = (*I == SuccBB)
16441644 BBSuccFreq.push_back(SuccFreq.getFrequency());
16451645 }
16461646
1647 // Normalize edge weights in Weights64 so that the sum of them can fit in
1648 BranchProbability::normalizeEdgeWeights(BBSuccFreq.begin(), BBSuccFreq.end());
1649
1650 SmallVector Weights;
1651 for (auto Freq : BBSuccFreq)
1652 Weights.push_back(static_cast(Freq));
1653
1654 // Update edge weights in BPI.
1655 for (int I = 0, E = Weights.size(); I < E; I++)
1656 BPI->setEdgeWeight(BB, I, Weights[I]);
1657
1658 if (Weights.size() >= 2) {
1647 uint64_t MaxBBSuccFreq =
1648 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
1649 SmallVector BBSuccProbs;
1650 for (uint64_t Freq : BBSuccFreq)
1651 BBSuccProbs.push_back(
1652 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
1653
1654 // Normalize edge probabilities so that they sum up to one.
1655 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
1656 BBSuccProbs.end());
1657
1658 // Update edge probabilities in BPI.
1659 for (int I = 0, E = BBSuccProbs.size(); I < E; I++)
1660 BPI->setEdgeProbability(BB, I, BBSuccProbs[I]);
1661
1662 if (BBSuccProbs.size() >= 2) {
1663 SmallVector Weights;
1664 for (auto Prob : BBSuccProbs)
1665 Weights.push_back(Prob.getNumerator());
1666
16591667 auto TI = BB->getTerminator();
16601668 TI->setMetadata(
16611669 LLVMContext::MD_prof,
2525 i32 2, label %case_b
2626 i32 3, label %case_c
2727 i32 4, label %case_d]
28 ; CHECK: edge entry -> exit probability is 0x7fffe000 / 0x80000000 = 100.00% [HOT edge]
29 ; CHECK: edge entry -> case_a probability is 0x00000800 / 0x80000000 = 0.00%
30 ; CHECK: edge entry -> case_b probability is 0x00000800 / 0x80000000 = 0.00%
31 ; CHECK: edge entry -> case_c probability is 0x00000800 / 0x80000000 = 0.00%
32 ; CHECK: edge entry -> case_d probability is 0x00000800 / 0x80000000 = 0.00%
28 ; CHECK: edge entry -> exit probability is 0x7ffff800 / 0x80000000 = 100.00% [HOT edge]
29 ; CHECK: edge entry -> case_a probability is 0x00000200 / 0x80000000 = 0.00%
30 ; CHECK: edge entry -> case_b probability is 0x00000200 / 0x80000000 = 0.00%
31 ; CHECK: edge entry -> case_c probability is 0x00000200 / 0x80000000 = 0.00%
32 ; CHECK: edge entry -> case_d probability is 0x00000200 / 0x80000000 = 0.00%
3333
3434 case_a:
3535 br label %case_b
11
22 ; Test if edge weights are properly updated after jump threading.
33
4 ; CHECK: !2 = !{!"branch_weights", i32 22, i32 7}
4 ; CHECK: !2 = !{!"branch_weights", i32 1629125526, i32 518358122}
55
66 define void @foo(i32 %n) !prof !0 {
77 entry: