1 //===--- SelectOptimize.cpp - Convert select to branches if profitable ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass converts selects to conditional jumps when profitable.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/BlockFrequencyInfo.h"
17 #include "llvm/Analysis/BranchProbabilityInfo.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
20 #include "llvm/Analysis/ProfileSummaryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/TargetLowering.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/CodeGen/TargetSchedule.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/ScaledNumber.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/Utils/SizeOpts.h"
37 #include <algorithm>
38 #include <memory>
39 #include <queue>
40 #include <stack>
41 #include <string>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "select-optimize"
46 
47 STATISTIC(NumSelectOptAnalyzed,
48           "Number of select groups considered for conversion to branch");
49 STATISTIC(NumSelectConvertedExpColdOperand,
50           "Number of select groups converted due to expensive cold operand");
51 STATISTIC(NumSelectConvertedHighPred,
52           "Number of select groups converted due to high-predictability");
53 STATISTIC(NumSelectUnPred,
54           "Number of select groups not converted due to unpredictability");
55 STATISTIC(NumSelectColdBB,
56           "Number of select groups not converted due to cold basic block");
57 STATISTIC(NumSelectConvertedLoop,
58           "Number of select groups converted due to loop-level analysis");
59 STATISTIC(NumSelectsConverted, "Number of selects converted");
60 
61 static cl::opt<unsigned> ColdOperandThreshold(
62     "cold-operand-threshold",
63     cl::desc("Maximum frequency of path for an operand to be considered cold."),
64     cl::init(20), cl::Hidden);
65 
66 static cl::opt<unsigned> ColdOperandMaxCostMultiplier(
67     "cold-operand-max-cost-multiplier",
68     cl::desc("Maximum cost multiplier of TCC_expensive for the dependence "
69              "slice of a cold operand to be considered inexpensive."),
70     cl::init(1), cl::Hidden);
71 
72 static cl::opt<unsigned>
73     GainGradientThreshold("select-opti-loop-gradient-gain-threshold",
74                           cl::desc("Gradient gain threshold (%)."),
75                           cl::init(25), cl::Hidden);
76 
77 static cl::opt<unsigned>
78     GainCycleThreshold("select-opti-loop-cycle-gain-threshold",
79                        cl::desc("Minimum gain per loop (in cycles) threshold."),
80                        cl::init(4), cl::Hidden);
81 
82 static cl::opt<unsigned> GainRelativeThreshold(
83     "select-opti-loop-relative-gain-threshold",
84     cl::desc(
85         "Minimum relative gain per loop threshold (1/X). Defaults to 12.5%"),
86     cl::init(8), cl::Hidden);
87 
88 static cl::opt<unsigned> MispredictDefaultRate(
89     "mispredict-default-rate", cl::Hidden, cl::init(25),
90     cl::desc("Default mispredict rate (initialized to 25%)."));
91 
92 static cl::opt<bool>
93     DisableLoopLevelHeuristics("disable-loop-level-heuristics", cl::Hidden,
94                                cl::init(false),
95                                cl::desc("Disable loop-level heuristics."));
96 
97 namespace {
98 
99 class SelectOptimize : public FunctionPass {
100   const TargetMachine *TM = nullptr;
101   const TargetSubtargetInfo *TSI;
102   const TargetLowering *TLI = nullptr;
103   const TargetTransformInfo *TTI = nullptr;
104   const LoopInfo *LI;
105   DominatorTree *DT;
106   std::unique_ptr<BlockFrequencyInfo> BFI;
107   std::unique_ptr<BranchProbabilityInfo> BPI;
108   ProfileSummaryInfo *PSI;
109   OptimizationRemarkEmitter *ORE;
110   TargetSchedModel TSchedModel;
111 
112 public:
113   static char ID;
114 
115   SelectOptimize() : FunctionPass(ID) {
116     initializeSelectOptimizePass(*PassRegistry::getPassRegistry());
117   }
118 
119   bool runOnFunction(Function &F) override;
120 
121   void getAnalysisUsage(AnalysisUsage &AU) const override {
122     AU.addRequired<ProfileSummaryInfoWrapperPass>();
123     AU.addRequired<TargetPassConfig>();
124     AU.addRequired<TargetTransformInfoWrapperPass>();
125     AU.addRequired<DominatorTreeWrapperPass>();
126     AU.addRequired<LoopInfoWrapperPass>();
127     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
128   }
129 
130 private:
131   // Select groups consist of consecutive select instructions with the same
132   // condition.
133   using SelectGroup = SmallVector<SelectInst *, 2>;
134   using SelectGroups = SmallVector<SelectGroup, 2>;
135 
136   using Scaled64 = ScaledNumber<uint64_t>;
137 
138   struct CostInfo {
139     /// Predicated cost (with selects as conditional moves).
140     Scaled64 PredCost;
141     /// Non-predicated cost (with selects converted to branches).
142     Scaled64 NonPredCost;
143   };
144 
145   // Converts select instructions of a function to conditional jumps when deemed
146   // profitable. Returns true if at least one select was converted.
147   bool optimizeSelects(Function &F);
148 
149   // Heuristics for determining which select instructions can be profitably
150   // conveted to branches. Separate heuristics for selects in inner-most loops
151   // and the rest of code regions (base heuristics for non-inner-most loop
152   // regions).
153   void optimizeSelectsBase(Function &F, SelectGroups &ProfSIGroups);
154   void optimizeSelectsInnerLoops(Function &F, SelectGroups &ProfSIGroups);
155 
156   // Converts to branches the select groups that were deemed
157   // profitable-to-convert.
158   void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
159 
160   // Splits selects of a given basic block into select groups.
161   void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
162 
163   // Determines for which select groups it is profitable converting to branches
164   // (base and inner-most-loop heuristics).
165   void findProfitableSIGroupsBase(SelectGroups &SIGroups,
166                                   SelectGroups &ProfSIGroups);
167   void findProfitableSIGroupsInnerLoops(const Loop *L, SelectGroups &SIGroups,
168                                         SelectGroups &ProfSIGroups);
169 
170   // Determines if a select group should be converted to a branch (base
171   // heuristics).
172   bool isConvertToBranchProfitableBase(const SmallVector<SelectInst *, 2> &ASI);
173 
174   // Returns true if there are expensive instructions in the cold value
175   // operand's (if any) dependence slice of any of the selects of the given
176   // group.
177   bool hasExpensiveColdOperand(const SmallVector<SelectInst *, 2> &ASI);
178 
179   // For a given source instruction, collect its backwards dependence slice
180   // consisting of instructions exclusively computed for producing the operands
181   // of the source instruction.
182   void getExclBackwardsSlice(Instruction *I,
183                              SmallVector<Instruction *, 2> &Slice);
184 
185   // Returns true if the condition of the select is highly predictable.
186   bool isSelectHighlyPredictable(const SelectInst *SI);
187 
188   // Loop-level checks to determine if a non-predicated version (with branches)
189   // of the given loop is more profitable than its predicated version.
190   bool checkLoopHeuristics(const Loop *L, const CostInfo LoopDepth[2]);
191 
192   // Computes instruction and loop-critical-path costs for both the predicated
193   // and non-predicated version of the given loop.
194   bool computeLoopCosts(const Loop *L, const SelectGroups &SIGroups,
195                         DenseMap<const Instruction *, CostInfo> &InstCostMap,
196                         CostInfo *LoopCost);
197 
198   // Returns a set of all the select instructions in the given select groups.
199   SmallPtrSet<const Instruction *, 2> getSIset(const SelectGroups &SIGroups);
200 
201   // Returns the latency cost of a given instruction.
202   Optional<uint64_t> computeInstCost(const Instruction *I);
203 
204   // Returns the misprediction cost of a given select when converted to branch.
205   Scaled64 getMispredictionCost(const SelectInst *SI, const Scaled64 CondCost);
206 
207   // Returns the cost of a branch when the prediction is correct.
208   Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
209                                 const SelectInst *SI);
210 
211   // Returns true if the target architecture supports lowering a given select.
212   bool isSelectKindSupported(SelectInst *SI);
213 };
214 } // namespace
215 
216 char SelectOptimize::ID = 0;
217 
218 INITIALIZE_PASS_BEGIN(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
219                       false)
220 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
221 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
222 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
223 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
224 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
225 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
226 INITIALIZE_PASS_END(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
227                     false)
228 
229 FunctionPass *llvm::createSelectOptimizePass() { return new SelectOptimize(); }
230 
231 bool SelectOptimize::runOnFunction(Function &F) {
232   TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
233   TSI = TM->getSubtargetImpl(F);
234   TLI = TSI->getTargetLowering();
235 
236   // If none of the select types is supported then skip this pass.
237   // This is an optimization pass. Legality issues will be handled by
238   // instruction selection.
239   if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) &&
240       !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) &&
241       !TLI->isSelectSupported(TargetLowering::VectorMaskSelect))
242     return false;
243 
244   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
245   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
246   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
247   BPI.reset(new BranchProbabilityInfo(F, *LI));
248   BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
249   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
250   ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
251   TSchedModel.init(TSI);
252 
253   // When optimizing for size, selects are preferable over branches.
254   if (F.hasOptSize() || llvm::shouldOptimizeForSize(&F, PSI, BFI.get()))
255     return false;
256 
257   return optimizeSelects(F);
258 }
259 
260 bool SelectOptimize::optimizeSelects(Function &F) {
261   // Determine for which select groups it is profitable converting to branches.
262   SelectGroups ProfSIGroups;
263   // Base heuristics apply only to non-loops and outer loops.
264   optimizeSelectsBase(F, ProfSIGroups);
265   // Separate heuristics for inner-most loops.
266   optimizeSelectsInnerLoops(F, ProfSIGroups);
267 
268   // Convert to branches the select groups that were deemed
269   // profitable-to-convert.
270   convertProfitableSIGroups(ProfSIGroups);
271 
272   // Code modified if at least one select group was converted.
273   return !ProfSIGroups.empty();
274 }
275 
276 void SelectOptimize::optimizeSelectsBase(Function &F,
277                                          SelectGroups &ProfSIGroups) {
278   // Collect all the select groups.
279   SelectGroups SIGroups;
280   for (BasicBlock &BB : F) {
281     // Base heuristics apply only to non-loops and outer loops.
282     Loop *L = LI->getLoopFor(&BB);
283     if (L && L->isInnermost())
284       continue;
285     collectSelectGroups(BB, SIGroups);
286   }
287 
288   // Determine for which select groups it is profitable converting to branches.
289   findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
290 }
291 
292 void SelectOptimize::optimizeSelectsInnerLoops(Function &F,
293                                                SelectGroups &ProfSIGroups) {
294   SmallVector<Loop *, 4> Loops(LI->begin(), LI->end());
295   // Need to check size on each iteration as we accumulate child loops.
296   for (unsigned long i = 0; i < Loops.size(); ++i)
297     for (Loop *ChildL : Loops[i]->getSubLoops())
298       Loops.push_back(ChildL);
299 
300   for (Loop *L : Loops) {
301     if (!L->isInnermost())
302       continue;
303 
304     SelectGroups SIGroups;
305     for (BasicBlock *BB : L->getBlocks())
306       collectSelectGroups(*BB, SIGroups);
307 
308     findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
309   }
310 }
311 
312 /// If \p isTrue is true, return the true value of \p SI, otherwise return
313 /// false value of \p SI. If the true/false value of \p SI is defined by any
314 /// select instructions in \p Selects, look through the defining select
315 /// instruction until the true/false value is not defined in \p Selects.
316 static Value *
317 getTrueOrFalseValue(SelectInst *SI, bool isTrue,
318                     const SmallPtrSet<const Instruction *, 2> &Selects) {
319   Value *V = nullptr;
320   for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
321        DefSI = dyn_cast<SelectInst>(V)) {
322     assert(DefSI->getCondition() == SI->getCondition() &&
323            "The condition of DefSI does not match with SI");
324     V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
325   }
326   assert(V && "Failed to get select true/false value");
327   return V;
328 }
329 
330 void SelectOptimize::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
331   for (SelectGroup &ASI : ProfSIGroups) {
332     // TODO: eliminate the redundancy of logic transforming selects to branches
333     // by removing CodeGenPrepare::optimizeSelectInst and optimizing here
334     // selects for all cases (with and without profile information).
335 
336     // Transform a sequence like this:
337     //    start:
338     //       %cmp = cmp uge i32 %a, %b
339     //       %sel = select i1 %cmp, i32 %c, i32 %d
340     //
341     // Into:
342     //    start:
343     //       %cmp = cmp uge i32 %a, %b
344     //       %cmp.frozen = freeze %cmp
345     //       br i1 %cmp.frozen, label %select.end, label %select.false
346     //    select.false:
347     //       br label %select.end
348     //    select.end:
349     //       %sel = phi i32 [ %c, %start ], [ %d, %select.false ]
350     //
351     // %cmp should be frozen, otherwise it may introduce undefined behavior.
352 
353     // We split the block containing the select(s) into two blocks.
354     SelectInst *SI = ASI.front();
355     SelectInst *LastSI = ASI.back();
356     BasicBlock *StartBlock = SI->getParent();
357     BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
358     BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
359     BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock).getFrequency());
360     // Delete the unconditional branch that was just created by the split.
361     StartBlock->getTerminator()->eraseFromParent();
362 
363     // Move any debug/pseudo instructions that were in-between the select
364     // group to the newly-created end block.
365     SmallVector<Instruction *, 2> DebugPseudoINS;
366     auto DIt = SI->getIterator();
367     while (&*DIt != LastSI) {
368       if (DIt->isDebugOrPseudoInst())
369         DebugPseudoINS.push_back(&*DIt);
370       DIt++;
371     }
372     for (auto DI : DebugPseudoINS) {
373       DI->moveBefore(&*EndBlock->getFirstInsertionPt());
374     }
375 
376     // These are the new basic blocks for the conditional branch.
377     // For now, no instruction sinking to the true/false blocks.
378     // Thus both True and False blocks will be empty.
379     BasicBlock *TrueBlock = nullptr, *FalseBlock = nullptr;
380 
381     // Use the 'false' side for a new input value to the PHI.
382     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
383                                     EndBlock->getParent(), EndBlock);
384     auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
385     FalseBranch->setDebugLoc(SI->getDebugLoc());
386 
387     // For the 'true' side the path originates from the start block from the
388     // point view of the new PHI.
389     TrueBlock = StartBlock;
390 
391     // Insert the real conditional branch based on the original condition.
392     BasicBlock *TT, *FT;
393     TT = EndBlock;
394     FT = FalseBlock;
395     IRBuilder<> IB(SI);
396     auto *CondFr =
397         IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
398     IB.CreateCondBr(CondFr, TT, FT, SI);
399 
400     SmallPtrSet<const Instruction *, 2> INS;
401     INS.insert(ASI.begin(), ASI.end());
402     // Use reverse iterator because later select may use the value of the
403     // earlier select, and we need to propagate value through earlier select
404     // to get the PHI operand.
405     for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
406       SelectInst *SI = *It;
407       // The select itself is replaced with a PHI Node.
408       PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
409       PN->takeName(SI);
410       PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
411       PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
412       PN->setDebugLoc(SI->getDebugLoc());
413 
414       SI->replaceAllUsesWith(PN);
415       SI->eraseFromParent();
416       INS.erase(SI);
417       ++NumSelectsConverted;
418     }
419   }
420 }
421 
422 void SelectOptimize::collectSelectGroups(BasicBlock &BB,
423                                          SelectGroups &SIGroups) {
424   BasicBlock::iterator BBIt = BB.begin();
425   while (BBIt != BB.end()) {
426     Instruction *I = &*BBIt++;
427     if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
428       SelectGroup SIGroup;
429       SIGroup.push_back(SI);
430       while (BBIt != BB.end()) {
431         Instruction *NI = &*BBIt;
432         SelectInst *NSI = dyn_cast<SelectInst>(NI);
433         if (NSI && SI->getCondition() == NSI->getCondition()) {
434           SIGroup.push_back(NSI);
435         } else if (!NI->isDebugOrPseudoInst()) {
436           // Debug/pseudo instructions should be skipped and not prevent the
437           // formation of a select group.
438           break;
439         }
440         ++BBIt;
441       }
442 
443       // If the select type is not supported, no point optimizing it.
444       // Instruction selection will take care of it.
445       if (!isSelectKindSupported(SI))
446         continue;
447 
448       SIGroups.push_back(SIGroup);
449     }
450   }
451 }
452 
453 void SelectOptimize::findProfitableSIGroupsBase(SelectGroups &SIGroups,
454                                                 SelectGroups &ProfSIGroups) {
455   for (SelectGroup &ASI : SIGroups) {
456     ++NumSelectOptAnalyzed;
457     if (isConvertToBranchProfitableBase(ASI))
458       ProfSIGroups.push_back(ASI);
459   }
460 }
461 
462 void SelectOptimize::findProfitableSIGroupsInnerLoops(
463     const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
464   NumSelectOptAnalyzed += SIGroups.size();
465   // For each select group in an inner-most loop,
466   // a branch is more preferable than a select/conditional-move if:
467   // i) conversion to branches for all the select groups of the loop satisfies
468   //    loop-level heuristics including reducing the loop's critical path by
469   //    some threshold (see SelectOptimize::checkLoopHeuristics); and
470   // ii) the total cost of the select group is cheaper with a branch compared
471   //     to its predicated version. The cost is in terms of latency and the cost
472   //     of a select group is the cost of its most expensive select instruction
473   //     (assuming infinite resources and thus fully leveraging available ILP).
474 
475   DenseMap<const Instruction *, CostInfo> InstCostMap;
476   CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
477                           {Scaled64::getZero(), Scaled64::getZero()}};
478   if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
479       !checkLoopHeuristics(L, LoopCost)) {
480     return;
481   }
482 
483   for (SelectGroup &ASI : SIGroups) {
484     // Assuming infinite resources, the cost of a group of instructions is the
485     // cost of the most expensive instruction of the group.
486     Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
487     for (SelectInst *SI : ASI) {
488       SelectCost = std::max(SelectCost, InstCostMap[SI].PredCost);
489       BranchCost = std::max(BranchCost, InstCostMap[SI].NonPredCost);
490     }
491     if (BranchCost < SelectCost) {
492       OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", ASI.front());
493       OR << "Profitable to convert to branch (loop analysis). BranchCost="
494          << BranchCost.toString() << ", SelectCost=" << SelectCost.toString()
495          << ". ";
496       ORE->emit(OR);
497       ++NumSelectConvertedLoop;
498       ProfSIGroups.push_back(ASI);
499     } else {
500       OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", ASI.front());
501       ORmiss << "Select is more profitable (loop analysis). BranchCost="
502              << BranchCost.toString()
503              << ", SelectCost=" << SelectCost.toString() << ". ";
504       ORE->emit(ORmiss);
505     }
506   }
507 }
508 
509 bool SelectOptimize::isConvertToBranchProfitableBase(
510     const SmallVector<SelectInst *, 2> &ASI) {
511   SelectInst *SI = ASI.front();
512   OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", SI);
513   OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", SI);
514 
515   // Skip cold basic blocks. Better to optimize for size for cold blocks.
516   if (PSI->isColdBlock(SI->getParent(), BFI.get())) {
517     ++NumSelectColdBB;
518     ORmiss << "Not converted to branch because of cold basic block. ";
519     ORE->emit(ORmiss);
520     return false;
521   }
522 
523   // If unpredictable, branch form is less profitable.
524   if (SI->getMetadata(LLVMContext::MD_unpredictable)) {
525     ++NumSelectUnPred;
526     ORmiss << "Not converted to branch because of unpredictable branch. ";
527     ORE->emit(ORmiss);
528     return false;
529   }
530 
531   // If highly predictable, branch form is more profitable, unless a
532   // predictable select is inexpensive in the target architecture.
533   if (isSelectHighlyPredictable(SI) && TLI->isPredictableSelectExpensive()) {
534     ++NumSelectConvertedHighPred;
535     OR << "Converted to branch because of highly predictable branch. ";
536     ORE->emit(OR);
537     return true;
538   }
539 
540   // Look for expensive instructions in the cold operand's (if any) dependence
541   // slice of any of the selects in the group.
542   if (hasExpensiveColdOperand(ASI)) {
543     ++NumSelectConvertedExpColdOperand;
544     OR << "Converted to branch because of expensive cold operand.";
545     ORE->emit(OR);
546     return true;
547   }
548 
549   ORmiss << "Not profitable to convert to branch (base heuristic).";
550   ORE->emit(ORmiss);
551   return false;
552 }
553 
554 static InstructionCost divideNearest(InstructionCost Numerator,
555                                      uint64_t Denominator) {
556   return (Numerator + (Denominator / 2)) / Denominator;
557 }
558 
559 bool SelectOptimize::hasExpensiveColdOperand(
560     const SmallVector<SelectInst *, 2> &ASI) {
561   bool ColdOperand = false;
562   uint64_t TrueWeight, FalseWeight, TotalWeight;
563   if (ASI.front()->extractProfMetadata(TrueWeight, FalseWeight)) {
564     uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
565     TotalWeight = TrueWeight + FalseWeight;
566     // Is there a path with frequency <ColdOperandThreshold% (default:20%) ?
567     ColdOperand = TotalWeight * ColdOperandThreshold > 100 * MinWeight;
568   } else if (PSI->hasProfileSummary()) {
569     OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", ASI.front());
570     ORmiss << "Profile data available but missing branch-weights metadata for "
571               "select instruction. ";
572     ORE->emit(ORmiss);
573   }
574   if (!ColdOperand)
575     return false;
576   // Check if the cold path's dependence slice is expensive for any of the
577   // selects of the group.
578   for (SelectInst *SI : ASI) {
579     Instruction *ColdI = nullptr;
580     uint64_t HotWeight;
581     if (TrueWeight < FalseWeight) {
582       ColdI = dyn_cast<Instruction>(SI->getTrueValue());
583       HotWeight = FalseWeight;
584     } else {
585       ColdI = dyn_cast<Instruction>(SI->getFalseValue());
586       HotWeight = TrueWeight;
587     }
588     if (ColdI) {
589       SmallVector<Instruction *, 2> ColdSlice;
590       getExclBackwardsSlice(ColdI, ColdSlice);
591       InstructionCost SliceCost = 0;
592       for (auto *ColdII : ColdSlice) {
593         SliceCost +=
594             TTI->getInstructionCost(ColdII, TargetTransformInfo::TCK_Latency);
595       }
596       // The colder the cold value operand of the select is the more expensive
597       // the cmov becomes for computing the cold value operand every time. Thus,
598       // the colder the cold operand is the more its cost counts.
599       // Get nearest integer cost adjusted for coldness.
600       InstructionCost AdjSliceCost =
601           divideNearest(SliceCost * HotWeight, TotalWeight);
602       if (AdjSliceCost >=
603           ColdOperandMaxCostMultiplier * TargetTransformInfo::TCC_Expensive)
604         return true;
605     }
606   }
607   return false;
608 }
609 
610 // For a given source instruction, collect its backwards dependence slice
611 // consisting of instructions exclusively computed for the purpose of producing
612 // the operands of the source instruction. As an approximation
613 // (sufficiently-accurate in practice), we populate this set with the
614 // instructions of the backwards dependence slice that only have one-use and
615 // form an one-use chain that leads to the source instruction.
616 void SelectOptimize::getExclBackwardsSlice(
617     Instruction *I, SmallVector<Instruction *, 2> &Slice) {
618   SmallPtrSet<Instruction *, 2> Visited;
619   std::queue<Instruction *> Worklist;
620   Worklist.push(I);
621   while (!Worklist.empty()) {
622     Instruction *II = Worklist.front();
623     Worklist.pop();
624 
625     // Avoid cycles.
626     if (Visited.count(II))
627       continue;
628     Visited.insert(II);
629 
630     if (!II->hasOneUse())
631       continue;
632 
633     // Avoid considering instructions with less frequency than the source
634     // instruction (i.e., avoid colder code regions of the dependence slice).
635     if (BFI->getBlockFreq(II->getParent()) < BFI->getBlockFreq(I->getParent()))
636       continue;
637 
638     // Eligible one-use instruction added to the dependence slice.
639     Slice.push_back(II);
640 
641     // Explore all the operands of the current instruction to expand the slice.
642     for (unsigned k = 0; k < II->getNumOperands(); ++k)
643       if (auto *OpI = dyn_cast<Instruction>(II->getOperand(k)))
644         Worklist.push(OpI);
645   }
646 }
647 
648 bool SelectOptimize::isSelectHighlyPredictable(const SelectInst *SI) {
649   uint64_t TrueWeight, FalseWeight;
650   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
651     uint64_t Max = std::max(TrueWeight, FalseWeight);
652     uint64_t Sum = TrueWeight + FalseWeight;
653     if (Sum != 0) {
654       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
655       if (Probability > TTI->getPredictableBranchThreshold())
656         return true;
657     }
658   }
659   return false;
660 }
661 
662 bool SelectOptimize::checkLoopHeuristics(const Loop *L,
663                                          const CostInfo LoopCost[2]) {
664   // Loop-level checks to determine if a non-predicated version (with branches)
665   // of the loop is more profitable than its predicated version.
666 
667   if (DisableLoopLevelHeuristics)
668     return true;
669 
670   OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti",
671                                    L->getHeader()->getFirstNonPHI());
672 
673   if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
674       LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
675     ORmissL << "No select conversion in the loop due to no reduction of loop's "
676                "critical path. ";
677     ORE->emit(ORmissL);
678     return false;
679   }
680 
681   Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
682                       LoopCost[1].PredCost - LoopCost[1].NonPredCost};
683 
684   // Profitably converting to branches need to reduce the loop's critical path
685   // by at least some threshold (absolute gain of GainCycleThreshold cycles and
686   // relative gain of 12.5%).
687   if (Gain[1] < Scaled64::get(GainCycleThreshold) ||
688       Gain[1] * Scaled64::get(GainRelativeThreshold) < LoopCost[1].PredCost) {
689     Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
690     ORmissL << "No select conversion in the loop due to small reduction of "
691                "loop's critical path. Gain="
692             << Gain[1].toString()
693             << ", RelativeGain=" << RelativeGain.toString() << "%. ";
694     ORE->emit(ORmissL);
695     return false;
696   }
697 
698   // If the loop's critical path involves loop-carried dependences, the gradient
699   // of the gain needs to be at least GainGradientThreshold% (defaults to 25%).
700   // This check ensures that the latency reduction for the loop's critical path
701   // keeps decreasing with sufficient rate beyond the two analyzed loop
702   // iterations.
703   if (Gain[1] > Gain[0]) {
704     Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
705                             (LoopCost[1].PredCost - LoopCost[0].PredCost);
706     if (GradientGain < Scaled64::get(GainGradientThreshold)) {
707       ORmissL << "No select conversion in the loop due to small gradient gain. "
708                  "GradientGain="
709               << GradientGain.toString() << "%. ";
710       ORE->emit(ORmissL);
711       return false;
712     }
713   }
714   // If the gain decreases it is not profitable to convert.
715   else if (Gain[1] < Gain[0]) {
716     ORmissL
717         << "No select conversion in the loop due to negative gradient gain. ";
718     ORE->emit(ORmissL);
719     return false;
720   }
721 
722   // Non-predicated version of the loop is more profitable than its
723   // predicated version.
724   return true;
725 }
726 
727 // Computes instruction and loop-critical-path costs for both the predicated
728 // and non-predicated version of the given loop.
729 // Returns false if unable to compute these costs due to invalid cost of loop
730 // instruction(s).
731 bool SelectOptimize::computeLoopCosts(
732     const Loop *L, const SelectGroups &SIGroups,
733     DenseMap<const Instruction *, CostInfo> &InstCostMap, CostInfo *LoopCost) {
734   const auto &SIset = getSIset(SIGroups);
735   // Compute instruction and loop-critical-path costs across two iterations for
736   // both predicated and non-predicated version.
737   const unsigned Iterations = 2;
738   for (unsigned Iter = 0; Iter < Iterations; ++Iter) {
739     // Cost of the loop's critical path.
740     CostInfo &MaxCost = LoopCost[Iter];
741     for (BasicBlock *BB : L->getBlocks()) {
742       for (const Instruction &I : *BB) {
743         if (I.isDebugOrPseudoInst())
744           continue;
745         // Compute the predicated and non-predicated cost of the instruction.
746         Scaled64 IPredCost = Scaled64::getZero(),
747                  INonPredCost = Scaled64::getZero();
748 
749         // Assume infinite resources that allow to fully exploit the available
750         // instruction-level parallelism.
751         // InstCost = InstLatency + max(Op1Cost, Op2Cost, … OpNCost)
752         for (const Use &U : I.operands()) {
753           auto UI = dyn_cast<Instruction>(U.get());
754           if (!UI)
755             continue;
756           if (InstCostMap.count(UI)) {
757             IPredCost = std::max(IPredCost, InstCostMap[UI].PredCost);
758             INonPredCost = std::max(INonPredCost, InstCostMap[UI].NonPredCost);
759           }
760         }
761         auto ILatency = computeInstCost(&I);
762         if (!ILatency.hasValue()) {
763           OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", &I);
764           ORmissL << "Invalid instruction cost preventing analysis and "
765                      "optimization of the inner-most loop containing this "
766                      "instruction. ";
767           ORE->emit(ORmissL);
768           return false;
769         }
770         IPredCost += Scaled64::get(ILatency.getValue());
771         INonPredCost += Scaled64::get(ILatency.getValue());
772 
773         // For a select that can be converted to branch,
774         // compute its cost as a branch (non-predicated cost).
775         //
776         // BranchCost = PredictedPathCost + MispredictCost
777         // PredictedPathCost = TrueOpCost * TrueProb + FalseOpCost * FalseProb
778         // MispredictCost = max(MispredictPenalty, CondCost) * MispredictRate
779         if (SIset.contains(&I)) {
780           auto SI = dyn_cast<SelectInst>(&I);
781 
782           Scaled64 TrueOpCost = Scaled64::getZero(),
783                    FalseOpCost = Scaled64::getZero();
784           if (auto *TI = dyn_cast<Instruction>(SI->getTrueValue()))
785             if (InstCostMap.count(TI))
786               TrueOpCost = InstCostMap[TI].NonPredCost;
787           if (auto *FI = dyn_cast<Instruction>(SI->getFalseValue()))
788             if (InstCostMap.count(FI))
789               FalseOpCost = InstCostMap[FI].NonPredCost;
790           Scaled64 PredictedPathCost =
791               getPredictedPathCost(TrueOpCost, FalseOpCost, SI);
792 
793           Scaled64 CondCost = Scaled64::getZero();
794           if (auto *CI = dyn_cast<Instruction>(SI->getCondition()))
795             if (InstCostMap.count(CI))
796               CondCost = InstCostMap[CI].NonPredCost;
797           Scaled64 MispredictCost = getMispredictionCost(SI, CondCost);
798 
799           INonPredCost = PredictedPathCost + MispredictCost;
800         }
801 
802         InstCostMap[&I] = {IPredCost, INonPredCost};
803         MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
804         MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
805       }
806     }
807   }
808   return true;
809 }
810 
811 SmallPtrSet<const Instruction *, 2>
812 SelectOptimize::getSIset(const SelectGroups &SIGroups) {
813   SmallPtrSet<const Instruction *, 2> SIset;
814   for (const SelectGroup &ASI : SIGroups)
815     for (const SelectInst *SI : ASI)
816       SIset.insert(SI);
817   return SIset;
818 }
819 
820 Optional<uint64_t> SelectOptimize::computeInstCost(const Instruction *I) {
821   InstructionCost ICost =
822       TTI->getInstructionCost(I, TargetTransformInfo::TCK_Latency);
823   if (auto OC = ICost.getValue())
824     return Optional<uint64_t>(OC.getValue());
825   return Optional<uint64_t>(None);
826 }
827 
828 ScaledNumber<uint64_t>
829 SelectOptimize::getMispredictionCost(const SelectInst *SI,
830                                      const Scaled64 CondCost) {
831   uint64_t MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
832 
833   // Account for the default misprediction rate when using a branch
834   // (conservatively set to 25% by default).
835   uint64_t MispredictRate = MispredictDefaultRate;
836   // If the select condition is obviously predictable, then the misprediction
837   // rate is zero.
838   if (isSelectHighlyPredictable(SI))
839     MispredictRate = 0;
840 
841   // CondCost is included to account for cases where the computation of the
842   // condition is part of a long dependence chain (potentially loop-carried)
843   // that would delay detection of a misprediction and increase its cost.
844   Scaled64 MispredictCost =
845       std::max(Scaled64::get(MispredictPenalty), CondCost) *
846       Scaled64::get(MispredictRate);
847   MispredictCost /= Scaled64::get(100);
848 
849   return MispredictCost;
850 }
851 
852 // Returns the cost of a branch when the prediction is correct.
853 // TrueCost * TrueProbability + FalseCost * FalseProbability.
854 ScaledNumber<uint64_t>
855 SelectOptimize::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
856                                      const SelectInst *SI) {
857   Scaled64 PredPathCost;
858   uint64_t TrueWeight, FalseWeight;
859   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
860     uint64_t SumWeight = TrueWeight + FalseWeight;
861     if (SumWeight != 0) {
862       PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
863                      FalseCost * Scaled64::get(FalseWeight);
864       PredPathCost /= Scaled64::get(SumWeight);
865       return PredPathCost;
866     }
867   }
868   // Without branch weight metadata, we assume 75% for the one path and 25% for
869   // the other, and pick the result with the biggest cost.
870   PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
871                           FalseCost * Scaled64::get(3) + TrueCost);
872   PredPathCost /= Scaled64::get(4);
873   return PredPathCost;
874 }
875 
876 bool SelectOptimize::isSelectKindSupported(SelectInst *SI) {
877   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
878   if (VectorCond)
879     return false;
880   TargetLowering::SelectSupportKind SelectKind;
881   if (SI->getType()->isVectorTy())
882     SelectKind = TargetLowering::ScalarCondVectorVal;
883   else
884     SelectKind = TargetLowering::ScalarValSelect;
885   return TLI->isSelectSupported(SelectKind);
886 }
887