xref: /src/contrib/llvm-project/llvm/lib/CodeGen/SelectOptimize.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1145449b1SDimitry Andric //===--- SelectOptimize.cpp - Convert select to branches if profitable ---===//
2145449b1SDimitry Andric //
3145449b1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4145449b1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5145449b1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6145449b1SDimitry Andric //
7145449b1SDimitry Andric //===----------------------------------------------------------------------===//
8145449b1SDimitry Andric //
9145449b1SDimitry Andric // This pass converts selects to conditional jumps when profitable.
10145449b1SDimitry Andric //
11145449b1SDimitry Andric //===----------------------------------------------------------------------===//
12145449b1SDimitry Andric 
13312c0ed1SDimitry Andric #include "llvm/CodeGen/SelectOptimize.h"
14145449b1SDimitry Andric #include "llvm/ADT/SmallVector.h"
15145449b1SDimitry Andric #include "llvm/ADT/Statistic.h"
16145449b1SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
17145449b1SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
18145449b1SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
19145449b1SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
20145449b1SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
21145449b1SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
22145449b1SDimitry Andric #include "llvm/CodeGen/Passes.h"
23145449b1SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
24145449b1SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
25145449b1SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
26145449b1SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
27145449b1SDimitry Andric #include "llvm/IR/BasicBlock.h"
28145449b1SDimitry Andric #include "llvm/IR/Dominators.h"
29145449b1SDimitry Andric #include "llvm/IR/Function.h"
30145449b1SDimitry Andric #include "llvm/IR/IRBuilder.h"
31145449b1SDimitry Andric #include "llvm/IR/Instruction.h"
327fa27ce4SDimitry Andric #include "llvm/IR/PatternMatch.h"
33e3b55780SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
34145449b1SDimitry Andric #include "llvm/InitializePasses.h"
35145449b1SDimitry Andric #include "llvm/Pass.h"
36145449b1SDimitry Andric #include "llvm/Support/ScaledNumber.h"
37145449b1SDimitry Andric #include "llvm/Target/TargetMachine.h"
38145449b1SDimitry Andric #include "llvm/Transforms/Utils/SizeOpts.h"
39145449b1SDimitry Andric #include <algorithm>
40145449b1SDimitry Andric #include <memory>
41145449b1SDimitry Andric #include <queue>
42145449b1SDimitry Andric #include <stack>
43145449b1SDimitry Andric 
44145449b1SDimitry Andric using namespace llvm;
454df029ccSDimitry Andric using namespace llvm::PatternMatch;
46145449b1SDimitry Andric 
47145449b1SDimitry Andric #define DEBUG_TYPE "select-optimize"
48145449b1SDimitry Andric 
49145449b1SDimitry Andric STATISTIC(NumSelectOptAnalyzed,
50145449b1SDimitry Andric           "Number of select groups considered for conversion to branch");
51145449b1SDimitry Andric STATISTIC(NumSelectConvertedExpColdOperand,
52145449b1SDimitry Andric           "Number of select groups converted due to expensive cold operand");
53145449b1SDimitry Andric STATISTIC(NumSelectConvertedHighPred,
54145449b1SDimitry Andric           "Number of select groups converted due to high-predictability");
55145449b1SDimitry Andric STATISTIC(NumSelectUnPred,
56145449b1SDimitry Andric           "Number of select groups not converted due to unpredictability");
57145449b1SDimitry Andric STATISTIC(NumSelectColdBB,
58145449b1SDimitry Andric           "Number of select groups not converted due to cold basic block");
59145449b1SDimitry Andric STATISTIC(NumSelectConvertedLoop,
60145449b1SDimitry Andric           "Number of select groups converted due to loop-level analysis");
61145449b1SDimitry Andric STATISTIC(NumSelectsConverted, "Number of selects converted");
62145449b1SDimitry Andric 
63145449b1SDimitry Andric static cl::opt<unsigned> ColdOperandThreshold(
64145449b1SDimitry Andric     "cold-operand-threshold",
65145449b1SDimitry Andric     cl::desc("Maximum frequency of path for an operand to be considered cold."),
66145449b1SDimitry Andric     cl::init(20), cl::Hidden);
67145449b1SDimitry Andric 
68145449b1SDimitry Andric static cl::opt<unsigned> ColdOperandMaxCostMultiplier(
69145449b1SDimitry Andric     "cold-operand-max-cost-multiplier",
70145449b1SDimitry Andric     cl::desc("Maximum cost multiplier of TCC_expensive for the dependence "
71145449b1SDimitry Andric              "slice of a cold operand to be considered inexpensive."),
72145449b1SDimitry Andric     cl::init(1), cl::Hidden);
73145449b1SDimitry Andric 
74145449b1SDimitry Andric static cl::opt<unsigned>
75145449b1SDimitry Andric     GainGradientThreshold("select-opti-loop-gradient-gain-threshold",
76145449b1SDimitry Andric                           cl::desc("Gradient gain threshold (%)."),
77145449b1SDimitry Andric                           cl::init(25), cl::Hidden);
78145449b1SDimitry Andric 
79145449b1SDimitry Andric static cl::opt<unsigned>
80145449b1SDimitry Andric     GainCycleThreshold("select-opti-loop-cycle-gain-threshold",
81145449b1SDimitry Andric                        cl::desc("Minimum gain per loop (in cycles) threshold."),
82145449b1SDimitry Andric                        cl::init(4), cl::Hidden);
83145449b1SDimitry Andric 
84145449b1SDimitry Andric static cl::opt<unsigned> GainRelativeThreshold(
85145449b1SDimitry Andric     "select-opti-loop-relative-gain-threshold",
86145449b1SDimitry Andric     cl::desc(
87145449b1SDimitry Andric         "Minimum relative gain per loop threshold (1/X). Defaults to 12.5%"),
88145449b1SDimitry Andric     cl::init(8), cl::Hidden);
89145449b1SDimitry Andric 
90145449b1SDimitry Andric static cl::opt<unsigned> MispredictDefaultRate(
91145449b1SDimitry Andric     "mispredict-default-rate", cl::Hidden, cl::init(25),
92145449b1SDimitry Andric     cl::desc("Default mispredict rate (initialized to 25%)."));
93145449b1SDimitry Andric 
94145449b1SDimitry Andric static cl::opt<bool>
95145449b1SDimitry Andric     DisableLoopLevelHeuristics("disable-loop-level-heuristics", cl::Hidden,
96145449b1SDimitry Andric                                cl::init(false),
97145449b1SDimitry Andric                                cl::desc("Disable loop-level heuristics."));
98145449b1SDimitry Andric 
99145449b1SDimitry Andric namespace {
100145449b1SDimitry Andric 
101312c0ed1SDimitry Andric class SelectOptimizeImpl {
102145449b1SDimitry Andric   const TargetMachine *TM = nullptr;
1037fa27ce4SDimitry Andric   const TargetSubtargetInfo *TSI = nullptr;
104145449b1SDimitry Andric   const TargetLowering *TLI = nullptr;
105145449b1SDimitry Andric   const TargetTransformInfo *TTI = nullptr;
1067fa27ce4SDimitry Andric   const LoopInfo *LI = nullptr;
107312c0ed1SDimitry Andric   BlockFrequencyInfo *BFI;
1087fa27ce4SDimitry Andric   ProfileSummaryInfo *PSI = nullptr;
1097fa27ce4SDimitry Andric   OptimizationRemarkEmitter *ORE = nullptr;
110145449b1SDimitry Andric   TargetSchedModel TSchedModel;
111145449b1SDimitry Andric 
112145449b1SDimitry Andric public:
113312c0ed1SDimitry Andric   SelectOptimizeImpl() = default;
SelectOptimizeImpl(const TargetMachine * TM)114312c0ed1SDimitry Andric   SelectOptimizeImpl(const TargetMachine *TM) : TM(TM){};
115312c0ed1SDimitry Andric   PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
116312c0ed1SDimitry Andric   bool runOnFunction(Function &F, Pass &P);
117145449b1SDimitry Andric 
118145449b1SDimitry Andric   using Scaled64 = ScaledNumber<uint64_t>;
119145449b1SDimitry Andric 
120145449b1SDimitry Andric   struct CostInfo {
121145449b1SDimitry Andric     /// Predicated cost (with selects as conditional moves).
122145449b1SDimitry Andric     Scaled64 PredCost;
123145449b1SDimitry Andric     /// Non-predicated cost (with selects converted to branches).
124145449b1SDimitry Andric     Scaled64 NonPredCost;
125145449b1SDimitry Andric   };
126145449b1SDimitry Andric 
1274df029ccSDimitry Andric   /// SelectLike is an abstraction over SelectInst and other operations that can
1284df029ccSDimitry Andric   /// act like selects. For example Or(Zext(icmp), X) can be treated like
1294df029ccSDimitry Andric   /// select(icmp, X|1, X).
1304df029ccSDimitry Andric   class SelectLike {
SelectLike(Instruction * I)1314df029ccSDimitry Andric     SelectLike(Instruction *I) : I(I) {}
1324df029ccSDimitry Andric 
133ac9a064cSDimitry Andric     /// The select (/or) instruction.
1344df029ccSDimitry Andric     Instruction *I;
135ac9a064cSDimitry Andric     /// Whether this select is inverted, "not(cond), FalseVal, TrueVal", as
136ac9a064cSDimitry Andric     /// opposed to the original condition.
137ac9a064cSDimitry Andric     bool Inverted = false;
1384df029ccSDimitry Andric 
1394df029ccSDimitry Andric   public:
1404df029ccSDimitry Andric     /// Match a select or select-like instruction, returning a SelectLike.
match(Instruction * I)1414df029ccSDimitry Andric     static SelectLike match(Instruction *I) {
1424df029ccSDimitry Andric       // Select instruction are what we are usually looking for.
1434df029ccSDimitry Andric       if (isa<SelectInst>(I))
1444df029ccSDimitry Andric         return SelectLike(I);
1454df029ccSDimitry Andric 
1464df029ccSDimitry Andric       // An Or(zext(i1 X), Y) can also be treated like a select, with condition
1474df029ccSDimitry Andric       // C and values Y|1 and Y.
1484df029ccSDimitry Andric       Value *X;
1494df029ccSDimitry Andric       if (PatternMatch::match(
1504df029ccSDimitry Andric               I, m_c_Or(m_OneUse(m_ZExt(m_Value(X))), m_Value())) &&
1514df029ccSDimitry Andric           X->getType()->isIntegerTy(1))
1524df029ccSDimitry Andric         return SelectLike(I);
1534df029ccSDimitry Andric 
1544df029ccSDimitry Andric       return SelectLike(nullptr);
1554df029ccSDimitry Andric     }
1564df029ccSDimitry Andric 
isValid()1574df029ccSDimitry Andric     bool isValid() { return I; }
operator bool()1584df029ccSDimitry Andric     operator bool() { return isValid(); }
1594df029ccSDimitry Andric 
160ac9a064cSDimitry Andric     /// Invert the select by inverting the condition and switching the operands.
setInverted()161ac9a064cSDimitry Andric     void setInverted() {
162ac9a064cSDimitry Andric       assert(!Inverted && "Trying to invert an inverted SelectLike");
163ac9a064cSDimitry Andric       assert(isa<Instruction>(getCondition()) &&
164ac9a064cSDimitry Andric              cast<Instruction>(getCondition())->getOpcode() ==
165ac9a064cSDimitry Andric                  Instruction::Xor);
166ac9a064cSDimitry Andric       Inverted = true;
167ac9a064cSDimitry Andric     }
isInverted() const168ac9a064cSDimitry Andric     bool isInverted() const { return Inverted; }
169ac9a064cSDimitry Andric 
getI()1704df029ccSDimitry Andric     Instruction *getI() { return I; }
getI() const1714df029ccSDimitry Andric     const Instruction *getI() const { return I; }
1724df029ccSDimitry Andric 
getType() const1734df029ccSDimitry Andric     Type *getType() const { return I->getType(); }
1744df029ccSDimitry Andric 
getNonInvertedCondition() const175ac9a064cSDimitry Andric     Value *getNonInvertedCondition() const {
1764df029ccSDimitry Andric       if (auto *Sel = dyn_cast<SelectInst>(I))
1774df029ccSDimitry Andric         return Sel->getCondition();
1784df029ccSDimitry Andric       // Or(zext) case
1794df029ccSDimitry Andric       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
1804df029ccSDimitry Andric         Value *X;
1814df029ccSDimitry Andric         if (PatternMatch::match(BO->getOperand(0),
1824df029ccSDimitry Andric                                 m_OneUse(m_ZExt(m_Value(X)))))
1834df029ccSDimitry Andric           return X;
1844df029ccSDimitry Andric         if (PatternMatch::match(BO->getOperand(1),
1854df029ccSDimitry Andric                                 m_OneUse(m_ZExt(m_Value(X)))))
1864df029ccSDimitry Andric           return X;
1874df029ccSDimitry Andric       }
1884df029ccSDimitry Andric 
1894df029ccSDimitry Andric       llvm_unreachable("Unhandled case in getCondition");
1904df029ccSDimitry Andric     }
1914df029ccSDimitry Andric 
192ac9a064cSDimitry Andric     /// Return the condition for the SelectLike instruction. For example the
193ac9a064cSDimitry Andric     /// condition of a select or c in `or(zext(c), x)`
getCondition() const194ac9a064cSDimitry Andric     Value *getCondition() const {
195ac9a064cSDimitry Andric       Value *CC = getNonInvertedCondition();
196ac9a064cSDimitry Andric       // For inverted conditions the CC is checked when created to be a not
197ac9a064cSDimitry Andric       // (xor) instruction.
198ac9a064cSDimitry Andric       if (Inverted)
199ac9a064cSDimitry Andric         return cast<Instruction>(CC)->getOperand(0);
200ac9a064cSDimitry Andric       return CC;
201ac9a064cSDimitry Andric     }
202ac9a064cSDimitry Andric 
2034df029ccSDimitry Andric     /// Return the true value for the SelectLike instruction. Note this may not
2044df029ccSDimitry Andric     /// exist for all SelectLike instructions. For example, for `or(zext(c), x)`
2054df029ccSDimitry Andric     /// the true value would be `or(x,1)`. As this value does not exist, nullptr
2064df029ccSDimitry Andric     /// is returned.
getTrueValue(bool HonorInverts=true) const207ac9a064cSDimitry Andric     Value *getTrueValue(bool HonorInverts = true) const {
208ac9a064cSDimitry Andric       if (Inverted && HonorInverts)
209ac9a064cSDimitry Andric         return getFalseValue(/*HonorInverts=*/false);
2104df029ccSDimitry Andric       if (auto *Sel = dyn_cast<SelectInst>(I))
2114df029ccSDimitry Andric         return Sel->getTrueValue();
2124df029ccSDimitry Andric       // Or(zext) case - The true value is Or(X), so return nullptr as the value
2134df029ccSDimitry Andric       // does not yet exist.
2144df029ccSDimitry Andric       if (isa<BinaryOperator>(I))
2154df029ccSDimitry Andric         return nullptr;
2164df029ccSDimitry Andric 
2174df029ccSDimitry Andric       llvm_unreachable("Unhandled case in getTrueValue");
2184df029ccSDimitry Andric     }
2194df029ccSDimitry Andric 
2204df029ccSDimitry Andric     /// Return the false value for the SelectLike instruction. For example the
2214df029ccSDimitry Andric     /// getFalseValue of a select or `x` in `or(zext(c), x)` (which is
2224df029ccSDimitry Andric     /// `select(c, x|1, x)`)
getFalseValue(bool HonorInverts=true) const223ac9a064cSDimitry Andric     Value *getFalseValue(bool HonorInverts = true) const {
224ac9a064cSDimitry Andric       if (Inverted && HonorInverts)
225ac9a064cSDimitry Andric         return getTrueValue(/*HonorInverts=*/false);
2264df029ccSDimitry Andric       if (auto *Sel = dyn_cast<SelectInst>(I))
2274df029ccSDimitry Andric         return Sel->getFalseValue();
2284df029ccSDimitry Andric       // Or(zext) case - return the operand which is not the zext.
2294df029ccSDimitry Andric       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
2304df029ccSDimitry Andric         Value *X;
2314df029ccSDimitry Andric         if (PatternMatch::match(BO->getOperand(0),
2324df029ccSDimitry Andric                                 m_OneUse(m_ZExt(m_Value(X)))))
2334df029ccSDimitry Andric           return BO->getOperand(1);
2344df029ccSDimitry Andric         if (PatternMatch::match(BO->getOperand(1),
2354df029ccSDimitry Andric                                 m_OneUse(m_ZExt(m_Value(X)))))
2364df029ccSDimitry Andric           return BO->getOperand(0);
2374df029ccSDimitry Andric       }
2384df029ccSDimitry Andric 
2394df029ccSDimitry Andric       llvm_unreachable("Unhandled case in getFalseValue");
2404df029ccSDimitry Andric     }
2414df029ccSDimitry Andric 
2424df029ccSDimitry Andric     /// Return the NonPredCost cost of the true op, given the costs in
2434df029ccSDimitry Andric     /// InstCostMap. This may need to be generated for select-like instructions.
getTrueOpCost(DenseMap<const Instruction *,CostInfo> & InstCostMap,const TargetTransformInfo * TTI)2444df029ccSDimitry Andric     Scaled64 getTrueOpCost(DenseMap<const Instruction *, CostInfo> &InstCostMap,
2454df029ccSDimitry Andric                            const TargetTransformInfo *TTI) {
246ac9a064cSDimitry Andric       if (isa<SelectInst>(I))
247ac9a064cSDimitry Andric         if (auto *I = dyn_cast<Instruction>(getTrueValue()))
2484df029ccSDimitry Andric           return InstCostMap.contains(I) ? InstCostMap[I].NonPredCost
2494df029ccSDimitry Andric                                          : Scaled64::getZero();
2504df029ccSDimitry Andric 
2514df029ccSDimitry Andric       // Or case - add the cost of an extra Or to the cost of the False case.
2524df029ccSDimitry Andric       if (isa<BinaryOperator>(I))
2534df029ccSDimitry Andric         if (auto I = dyn_cast<Instruction>(getFalseValue()))
2544df029ccSDimitry Andric           if (InstCostMap.contains(I)) {
2554df029ccSDimitry Andric             InstructionCost OrCost = TTI->getArithmeticInstrCost(
2564df029ccSDimitry Andric                 Instruction::Or, I->getType(), TargetTransformInfo::TCK_Latency,
2574df029ccSDimitry Andric                 {TargetTransformInfo::OK_AnyValue,
2584df029ccSDimitry Andric                  TargetTransformInfo::OP_None},
2594df029ccSDimitry Andric                 {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2});
2604df029ccSDimitry Andric             return InstCostMap[I].NonPredCost +
2614df029ccSDimitry Andric                    Scaled64::get(*OrCost.getValue());
2624df029ccSDimitry Andric           }
2634df029ccSDimitry Andric 
2644df029ccSDimitry Andric       return Scaled64::getZero();
2654df029ccSDimitry Andric     }
2664df029ccSDimitry Andric 
2674df029ccSDimitry Andric     /// Return the NonPredCost cost of the false op, given the costs in
2684df029ccSDimitry Andric     /// InstCostMap. This may need to be generated for select-like instructions.
2694df029ccSDimitry Andric     Scaled64
getFalseOpCost(DenseMap<const Instruction *,CostInfo> & InstCostMap,const TargetTransformInfo * TTI)2704df029ccSDimitry Andric     getFalseOpCost(DenseMap<const Instruction *, CostInfo> &InstCostMap,
2714df029ccSDimitry Andric                    const TargetTransformInfo *TTI) {
272ac9a064cSDimitry Andric       if (isa<SelectInst>(I))
273ac9a064cSDimitry Andric         if (auto *I = dyn_cast<Instruction>(getFalseValue()))
2744df029ccSDimitry Andric           return InstCostMap.contains(I) ? InstCostMap[I].NonPredCost
2754df029ccSDimitry Andric                                          : Scaled64::getZero();
2764df029ccSDimitry Andric 
2774df029ccSDimitry Andric       // Or case - return the cost of the false case
2784df029ccSDimitry Andric       if (isa<BinaryOperator>(I))
2794df029ccSDimitry Andric         if (auto I = dyn_cast<Instruction>(getFalseValue()))
2804df029ccSDimitry Andric           if (InstCostMap.contains(I))
2814df029ccSDimitry Andric             return InstCostMap[I].NonPredCost;
2824df029ccSDimitry Andric 
2834df029ccSDimitry Andric       return Scaled64::getZero();
2844df029ccSDimitry Andric     }
2854df029ccSDimitry Andric   };
2864df029ccSDimitry Andric 
2874df029ccSDimitry Andric private:
2884df029ccSDimitry Andric   // Select groups consist of consecutive select instructions with the same
2894df029ccSDimitry Andric   // condition.
2904df029ccSDimitry Andric   using SelectGroup = SmallVector<SelectLike, 2>;
2914df029ccSDimitry Andric   using SelectGroups = SmallVector<SelectGroup, 2>;
2924df029ccSDimitry Andric 
293145449b1SDimitry Andric   // Converts select instructions of a function to conditional jumps when deemed
294145449b1SDimitry Andric   // profitable. Returns true if at least one select was converted.
295145449b1SDimitry Andric   bool optimizeSelects(Function &F);
296145449b1SDimitry Andric 
297145449b1SDimitry Andric   // Heuristics for determining which select instructions can be profitably
298145449b1SDimitry Andric   // conveted to branches. Separate heuristics for selects in inner-most loops
299145449b1SDimitry Andric   // and the rest of code regions (base heuristics for non-inner-most loop
300145449b1SDimitry Andric   // regions).
301145449b1SDimitry Andric   void optimizeSelectsBase(Function &F, SelectGroups &ProfSIGroups);
302145449b1SDimitry Andric   void optimizeSelectsInnerLoops(Function &F, SelectGroups &ProfSIGroups);
303145449b1SDimitry Andric 
304145449b1SDimitry Andric   // Converts to branches the select groups that were deemed
305145449b1SDimitry Andric   // profitable-to-convert.
306145449b1SDimitry Andric   void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
307145449b1SDimitry Andric 
308145449b1SDimitry Andric   // Splits selects of a given basic block into select groups.
309145449b1SDimitry Andric   void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
310145449b1SDimitry Andric 
311145449b1SDimitry Andric   // Determines for which select groups it is profitable converting to branches
312145449b1SDimitry Andric   // (base and inner-most-loop heuristics).
313145449b1SDimitry Andric   void findProfitableSIGroupsBase(SelectGroups &SIGroups,
314145449b1SDimitry Andric                                   SelectGroups &ProfSIGroups);
315145449b1SDimitry Andric   void findProfitableSIGroupsInnerLoops(const Loop *L, SelectGroups &SIGroups,
316145449b1SDimitry Andric                                         SelectGroups &ProfSIGroups);
317145449b1SDimitry Andric 
318145449b1SDimitry Andric   // Determines if a select group should be converted to a branch (base
319145449b1SDimitry Andric   // heuristics).
3204df029ccSDimitry Andric   bool isConvertToBranchProfitableBase(const SelectGroup &ASI);
321145449b1SDimitry Andric 
322145449b1SDimitry Andric   // Returns true if there are expensive instructions in the cold value
323145449b1SDimitry Andric   // operand's (if any) dependence slice of any of the selects of the given
324145449b1SDimitry Andric   // group.
3254df029ccSDimitry Andric   bool hasExpensiveColdOperand(const SelectGroup &ASI);
326145449b1SDimitry Andric 
327145449b1SDimitry Andric   // For a given source instruction, collect its backwards dependence slice
328145449b1SDimitry Andric   // consisting of instructions exclusively computed for producing the operands
329145449b1SDimitry Andric   // of the source instruction.
330145449b1SDimitry Andric   void getExclBackwardsSlice(Instruction *I, std::stack<Instruction *> &Slice,
331e3b55780SDimitry Andric                              Instruction *SI, bool ForSinking = false);
332145449b1SDimitry Andric 
333145449b1SDimitry Andric   // Returns true if the condition of the select is highly predictable.
3344df029ccSDimitry Andric   bool isSelectHighlyPredictable(const SelectLike SI);
335145449b1SDimitry Andric 
336145449b1SDimitry Andric   // Loop-level checks to determine if a non-predicated version (with branches)
337145449b1SDimitry Andric   // of the given loop is more profitable than its predicated version.
338145449b1SDimitry Andric   bool checkLoopHeuristics(const Loop *L, const CostInfo LoopDepth[2]);
339145449b1SDimitry Andric 
340145449b1SDimitry Andric   // Computes instruction and loop-critical-path costs for both the predicated
341145449b1SDimitry Andric   // and non-predicated version of the given loop.
342145449b1SDimitry Andric   bool computeLoopCosts(const Loop *L, const SelectGroups &SIGroups,
343145449b1SDimitry Andric                         DenseMap<const Instruction *, CostInfo> &InstCostMap,
344145449b1SDimitry Andric                         CostInfo *LoopCost);
345145449b1SDimitry Andric 
346145449b1SDimitry Andric   // Returns a set of all the select instructions in the given select groups.
3474df029ccSDimitry Andric   SmallDenseMap<const Instruction *, SelectLike, 2>
3484df029ccSDimitry Andric   getSImap(const SelectGroups &SIGroups);
349145449b1SDimitry Andric 
350145449b1SDimitry Andric   // Returns the latency cost of a given instruction.
351e3b55780SDimitry Andric   std::optional<uint64_t> computeInstCost(const Instruction *I);
352145449b1SDimitry Andric 
353145449b1SDimitry Andric   // Returns the misprediction cost of a given select when converted to branch.
3544df029ccSDimitry Andric   Scaled64 getMispredictionCost(const SelectLike SI, const Scaled64 CondCost);
355145449b1SDimitry Andric 
356145449b1SDimitry Andric   // Returns the cost of a branch when the prediction is correct.
357145449b1SDimitry Andric   Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
3584df029ccSDimitry Andric                                 const SelectLike SI);
359145449b1SDimitry Andric 
360145449b1SDimitry Andric   // Returns true if the target architecture supports lowering a given select.
3614df029ccSDimitry Andric   bool isSelectKindSupported(const SelectLike SI);
362145449b1SDimitry Andric };
363312c0ed1SDimitry Andric 
364312c0ed1SDimitry Andric class SelectOptimize : public FunctionPass {
365312c0ed1SDimitry Andric   SelectOptimizeImpl Impl;
366312c0ed1SDimitry Andric 
367312c0ed1SDimitry Andric public:
368312c0ed1SDimitry Andric   static char ID;
369312c0ed1SDimitry Andric 
SelectOptimize()370312c0ed1SDimitry Andric   SelectOptimize() : FunctionPass(ID) {
371312c0ed1SDimitry Andric     initializeSelectOptimizePass(*PassRegistry::getPassRegistry());
372312c0ed1SDimitry Andric   }
373312c0ed1SDimitry Andric 
runOnFunction(Function & F)374312c0ed1SDimitry Andric   bool runOnFunction(Function &F) override {
375312c0ed1SDimitry Andric     return Impl.runOnFunction(F, *this);
376312c0ed1SDimitry Andric   }
377312c0ed1SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const378312c0ed1SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
379312c0ed1SDimitry Andric     AU.addRequired<ProfileSummaryInfoWrapperPass>();
380312c0ed1SDimitry Andric     AU.addRequired<TargetPassConfig>();
381312c0ed1SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
382312c0ed1SDimitry Andric     AU.addRequired<LoopInfoWrapperPass>();
383312c0ed1SDimitry Andric     AU.addRequired<BlockFrequencyInfoWrapperPass>();
384312c0ed1SDimitry Andric     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
385312c0ed1SDimitry Andric   }
386312c0ed1SDimitry Andric };
387312c0ed1SDimitry Andric 
388145449b1SDimitry Andric } // namespace
389145449b1SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)390312c0ed1SDimitry Andric PreservedAnalyses SelectOptimizePass::run(Function &F,
391312c0ed1SDimitry Andric                                           FunctionAnalysisManager &FAM) {
392312c0ed1SDimitry Andric   SelectOptimizeImpl Impl(TM);
393312c0ed1SDimitry Andric   return Impl.run(F, FAM);
394312c0ed1SDimitry Andric }
395312c0ed1SDimitry Andric 
396145449b1SDimitry Andric char SelectOptimize::ID = 0;
397145449b1SDimitry Andric 
398145449b1SDimitry Andric INITIALIZE_PASS_BEGIN(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
399145449b1SDimitry Andric                       false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)400145449b1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
401145449b1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
402145449b1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
403145449b1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
404312c0ed1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
405145449b1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
406145449b1SDimitry Andric INITIALIZE_PASS_END(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
407145449b1SDimitry Andric                     false)
408145449b1SDimitry Andric 
409145449b1SDimitry Andric FunctionPass *llvm::createSelectOptimizePass() { return new SelectOptimize(); }
410145449b1SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)411312c0ed1SDimitry Andric PreservedAnalyses SelectOptimizeImpl::run(Function &F,
412312c0ed1SDimitry Andric                                           FunctionAnalysisManager &FAM) {
413145449b1SDimitry Andric   TSI = TM->getSubtargetImpl(F);
414145449b1SDimitry Andric   TLI = TSI->getTargetLowering();
415145449b1SDimitry Andric 
416312c0ed1SDimitry Andric   // If none of the select types are supported then skip this pass.
417312c0ed1SDimitry Andric   // This is an optimization pass. Legality issues will be handled by
418312c0ed1SDimitry Andric   // instruction selection.
419312c0ed1SDimitry Andric   if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) &&
420312c0ed1SDimitry Andric       !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) &&
421312c0ed1SDimitry Andric       !TLI->isSelectSupported(TargetLowering::VectorMaskSelect))
422312c0ed1SDimitry Andric     return PreservedAnalyses::all();
423312c0ed1SDimitry Andric 
424312c0ed1SDimitry Andric   TTI = &FAM.getResult<TargetIRAnalysis>(F);
425312c0ed1SDimitry Andric   if (!TTI->enableSelectOptimize())
426312c0ed1SDimitry Andric     return PreservedAnalyses::all();
427312c0ed1SDimitry Andric 
428312c0ed1SDimitry Andric   PSI = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F)
429312c0ed1SDimitry Andric             .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
430312c0ed1SDimitry Andric   assert(PSI && "This pass requires module analysis pass `profile-summary`!");
431312c0ed1SDimitry Andric   BFI = &FAM.getResult<BlockFrequencyAnalysis>(F);
432312c0ed1SDimitry Andric 
433312c0ed1SDimitry Andric   // When optimizing for size, selects are preferable over branches.
434312c0ed1SDimitry Andric   if (F.hasOptSize() || llvm::shouldOptimizeForSize(&F, PSI, BFI))
435312c0ed1SDimitry Andric     return PreservedAnalyses::all();
436312c0ed1SDimitry Andric 
437312c0ed1SDimitry Andric   LI = &FAM.getResult<LoopAnalysis>(F);
438312c0ed1SDimitry Andric   ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
439312c0ed1SDimitry Andric   TSchedModel.init(TSI);
440312c0ed1SDimitry Andric 
441312c0ed1SDimitry Andric   bool Changed = optimizeSelects(F);
442312c0ed1SDimitry Andric   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
443312c0ed1SDimitry Andric }
444312c0ed1SDimitry Andric 
runOnFunction(Function & F,Pass & P)445312c0ed1SDimitry Andric bool SelectOptimizeImpl::runOnFunction(Function &F, Pass &P) {
446312c0ed1SDimitry Andric   TM = &P.getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
447312c0ed1SDimitry Andric   TSI = TM->getSubtargetImpl(F);
448312c0ed1SDimitry Andric   TLI = TSI->getTargetLowering();
449312c0ed1SDimitry Andric 
450312c0ed1SDimitry Andric   // If none of the select types are supported then skip this pass.
451145449b1SDimitry Andric   // This is an optimization pass. Legality issues will be handled by
452145449b1SDimitry Andric   // instruction selection.
453145449b1SDimitry Andric   if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) &&
454145449b1SDimitry Andric       !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) &&
455145449b1SDimitry Andric       !TLI->isSelectSupported(TargetLowering::VectorMaskSelect))
456145449b1SDimitry Andric     return false;
457145449b1SDimitry Andric 
458312c0ed1SDimitry Andric   TTI = &P.getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
459e3b55780SDimitry Andric 
460e3b55780SDimitry Andric   if (!TTI->enableSelectOptimize())
461e3b55780SDimitry Andric     return false;
462e3b55780SDimitry Andric 
463312c0ed1SDimitry Andric   LI = &P.getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
464312c0ed1SDimitry Andric   BFI = &P.getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
465312c0ed1SDimitry Andric   PSI = &P.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
466312c0ed1SDimitry Andric   ORE = &P.getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
467145449b1SDimitry Andric   TSchedModel.init(TSI);
468145449b1SDimitry Andric 
469145449b1SDimitry Andric   // When optimizing for size, selects are preferable over branches.
470312c0ed1SDimitry Andric   if (F.hasOptSize() || llvm::shouldOptimizeForSize(&F, PSI, BFI))
471145449b1SDimitry Andric     return false;
472145449b1SDimitry Andric 
473145449b1SDimitry Andric   return optimizeSelects(F);
474145449b1SDimitry Andric }
475145449b1SDimitry Andric 
optimizeSelects(Function & F)476312c0ed1SDimitry Andric bool SelectOptimizeImpl::optimizeSelects(Function &F) {
477145449b1SDimitry Andric   // Determine for which select groups it is profitable converting to branches.
478145449b1SDimitry Andric   SelectGroups ProfSIGroups;
479145449b1SDimitry Andric   // Base heuristics apply only to non-loops and outer loops.
480145449b1SDimitry Andric   optimizeSelectsBase(F, ProfSIGroups);
481145449b1SDimitry Andric   // Separate heuristics for inner-most loops.
482145449b1SDimitry Andric   optimizeSelectsInnerLoops(F, ProfSIGroups);
483145449b1SDimitry Andric 
484145449b1SDimitry Andric   // Convert to branches the select groups that were deemed
485145449b1SDimitry Andric   // profitable-to-convert.
486145449b1SDimitry Andric   convertProfitableSIGroups(ProfSIGroups);
487145449b1SDimitry Andric 
488145449b1SDimitry Andric   // Code modified if at least one select group was converted.
489145449b1SDimitry Andric   return !ProfSIGroups.empty();
490145449b1SDimitry Andric }
491145449b1SDimitry Andric 
optimizeSelectsBase(Function & F,SelectGroups & ProfSIGroups)492312c0ed1SDimitry Andric void SelectOptimizeImpl::optimizeSelectsBase(Function &F,
493145449b1SDimitry Andric                                              SelectGroups &ProfSIGroups) {
494145449b1SDimitry Andric   // Collect all the select groups.
495145449b1SDimitry Andric   SelectGroups SIGroups;
496145449b1SDimitry Andric   for (BasicBlock &BB : F) {
497145449b1SDimitry Andric     // Base heuristics apply only to non-loops and outer loops.
498145449b1SDimitry Andric     Loop *L = LI->getLoopFor(&BB);
499145449b1SDimitry Andric     if (L && L->isInnermost())
500145449b1SDimitry Andric       continue;
501145449b1SDimitry Andric     collectSelectGroups(BB, SIGroups);
502145449b1SDimitry Andric   }
503145449b1SDimitry Andric 
504145449b1SDimitry Andric   // Determine for which select groups it is profitable converting to branches.
505145449b1SDimitry Andric   findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
506145449b1SDimitry Andric }
507145449b1SDimitry Andric 
optimizeSelectsInnerLoops(Function & F,SelectGroups & ProfSIGroups)508312c0ed1SDimitry Andric void SelectOptimizeImpl::optimizeSelectsInnerLoops(Function &F,
509145449b1SDimitry Andric                                                    SelectGroups &ProfSIGroups) {
510145449b1SDimitry Andric   SmallVector<Loop *, 4> Loops(LI->begin(), LI->end());
511145449b1SDimitry Andric   // Need to check size on each iteration as we accumulate child loops.
512145449b1SDimitry Andric   for (unsigned long i = 0; i < Loops.size(); ++i)
513145449b1SDimitry Andric     for (Loop *ChildL : Loops[i]->getSubLoops())
514145449b1SDimitry Andric       Loops.push_back(ChildL);
515145449b1SDimitry Andric 
516145449b1SDimitry Andric   for (Loop *L : Loops) {
517145449b1SDimitry Andric     if (!L->isInnermost())
518145449b1SDimitry Andric       continue;
519145449b1SDimitry Andric 
520145449b1SDimitry Andric     SelectGroups SIGroups;
521145449b1SDimitry Andric     for (BasicBlock *BB : L->getBlocks())
522145449b1SDimitry Andric       collectSelectGroups(*BB, SIGroups);
523145449b1SDimitry Andric 
524145449b1SDimitry Andric     findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
525145449b1SDimitry Andric   }
526145449b1SDimitry Andric }
527145449b1SDimitry Andric 
528145449b1SDimitry Andric /// If \p isTrue is true, return the true value of \p SI, otherwise return
529145449b1SDimitry Andric /// false value of \p SI. If the true/false value of \p SI is defined by any
530145449b1SDimitry Andric /// select instructions in \p Selects, look through the defining select
531145449b1SDimitry Andric /// instruction until the true/false value is not defined in \p Selects.
532145449b1SDimitry Andric static Value *
getTrueOrFalseValue(SelectOptimizeImpl::SelectLike SI,bool isTrue,const SmallPtrSet<const Instruction *,2> & Selects,IRBuilder<> & IB)5334df029ccSDimitry Andric getTrueOrFalseValue(SelectOptimizeImpl::SelectLike SI, bool isTrue,
5344df029ccSDimitry Andric                     const SmallPtrSet<const Instruction *, 2> &Selects,
5354df029ccSDimitry Andric                     IRBuilder<> &IB) {
536145449b1SDimitry Andric   Value *V = nullptr;
5374df029ccSDimitry Andric   for (SelectInst *DefSI = dyn_cast<SelectInst>(SI.getI());
5384df029ccSDimitry Andric        DefSI != nullptr && Selects.count(DefSI);
539145449b1SDimitry Andric        DefSI = dyn_cast<SelectInst>(V)) {
540ac9a064cSDimitry Andric     if (DefSI->getCondition() == SI.getCondition())
541145449b1SDimitry Andric       V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
542ac9a064cSDimitry Andric     else // Handle inverted SI
543ac9a064cSDimitry Andric       V = (!isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
544145449b1SDimitry Andric   }
5454df029ccSDimitry Andric 
5464df029ccSDimitry Andric   if (isa<BinaryOperator>(SI.getI())) {
5474df029ccSDimitry Andric     assert(SI.getI()->getOpcode() == Instruction::Or &&
5484df029ccSDimitry Andric            "Only currently handling Or instructions.");
5494df029ccSDimitry Andric     V = SI.getFalseValue();
5504df029ccSDimitry Andric     if (isTrue)
5514df029ccSDimitry Andric       V = IB.CreateOr(V, ConstantInt::get(V->getType(), 1));
5524df029ccSDimitry Andric   }
5534df029ccSDimitry Andric 
554145449b1SDimitry Andric   assert(V && "Failed to get select true/false value");
555145449b1SDimitry Andric   return V;
556145449b1SDimitry Andric }
557145449b1SDimitry Andric 
convertProfitableSIGroups(SelectGroups & ProfSIGroups)558312c0ed1SDimitry Andric void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
559145449b1SDimitry Andric   for (SelectGroup &ASI : ProfSIGroups) {
560145449b1SDimitry Andric     // The code transformation here is a modified version of the sinking
561145449b1SDimitry Andric     // transformation in CodeGenPrepare::optimizeSelectInst with a more
562145449b1SDimitry Andric     // aggressive strategy of which instructions to sink.
563145449b1SDimitry Andric     //
564145449b1SDimitry Andric     // TODO: eliminate the redundancy of logic transforming selects to branches
565145449b1SDimitry Andric     // by removing CodeGenPrepare::optimizeSelectInst and optimizing here
566145449b1SDimitry Andric     // selects for all cases (with and without profile information).
567145449b1SDimitry Andric 
568145449b1SDimitry Andric     // Transform a sequence like this:
569145449b1SDimitry Andric     //    start:
570145449b1SDimitry Andric     //       %cmp = cmp uge i32 %a, %b
571145449b1SDimitry Andric     //       %sel = select i1 %cmp, i32 %c, i32 %d
572145449b1SDimitry Andric     //
573145449b1SDimitry Andric     // Into:
574145449b1SDimitry Andric     //    start:
575145449b1SDimitry Andric     //       %cmp = cmp uge i32 %a, %b
576145449b1SDimitry Andric     //       %cmp.frozen = freeze %cmp
577145449b1SDimitry Andric     //       br i1 %cmp.frozen, label %select.true, label %select.false
578145449b1SDimitry Andric     //    select.true:
579145449b1SDimitry Andric     //       br label %select.end
580145449b1SDimitry Andric     //    select.false:
581145449b1SDimitry Andric     //       br label %select.end
582145449b1SDimitry Andric     //    select.end:
583145449b1SDimitry Andric     //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
584145449b1SDimitry Andric     //
585145449b1SDimitry Andric     // %cmp should be frozen, otherwise it may introduce undefined behavior.
586145449b1SDimitry Andric     // In addition, we may sink instructions that produce %c or %d into the
587145449b1SDimitry Andric     // destination(s) of the new branch.
588145449b1SDimitry Andric     // If the true or false blocks do not contain a sunken instruction, that
589145449b1SDimitry Andric     // block and its branch may be optimized away. In that case, one side of the
590145449b1SDimitry Andric     // first branch will point directly to select.end, and the corresponding PHI
591145449b1SDimitry Andric     // predecessor block will be the start block.
592145449b1SDimitry Andric 
593145449b1SDimitry Andric     // Find all the instructions that can be soundly sunk to the true/false
594145449b1SDimitry Andric     // blocks. These are instructions that are computed solely for producing the
595145449b1SDimitry Andric     // operands of the select instructions in the group and can be sunk without
596145449b1SDimitry Andric     // breaking the semantics of the LLVM IR (e.g., cannot sink instructions
597145449b1SDimitry Andric     // with side effects).
598145449b1SDimitry Andric     SmallVector<std::stack<Instruction *>, 2> TrueSlices, FalseSlices;
599145449b1SDimitry Andric     typedef std::stack<Instruction *>::size_type StackSizeType;
600145449b1SDimitry Andric     StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0;
6014df029ccSDimitry Andric     for (SelectLike SI : ASI) {
602145449b1SDimitry Andric       // For each select, compute the sinkable dependence chains of the true and
603145449b1SDimitry Andric       // false operands.
6044df029ccSDimitry Andric       if (auto *TI = dyn_cast_or_null<Instruction>(SI.getTrueValue())) {
605145449b1SDimitry Andric         std::stack<Instruction *> TrueSlice;
6064df029ccSDimitry Andric         getExclBackwardsSlice(TI, TrueSlice, SI.getI(), true);
607145449b1SDimitry Andric         maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size());
608145449b1SDimitry Andric         TrueSlices.push_back(TrueSlice);
609145449b1SDimitry Andric       }
6104df029ccSDimitry Andric       if (auto *FI = dyn_cast_or_null<Instruction>(SI.getFalseValue())) {
6114df029ccSDimitry Andric         if (isa<SelectInst>(SI.getI()) || !FI->hasOneUse()) {
612145449b1SDimitry Andric           std::stack<Instruction *> FalseSlice;
6134df029ccSDimitry Andric           getExclBackwardsSlice(FI, FalseSlice, SI.getI(), true);
614145449b1SDimitry Andric           maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size());
615145449b1SDimitry Andric           FalseSlices.push_back(FalseSlice);
616145449b1SDimitry Andric         }
617145449b1SDimitry Andric       }
6184df029ccSDimitry Andric     }
619145449b1SDimitry Andric     // In the case of multiple select instructions in the same group, the order
620145449b1SDimitry Andric     // of non-dependent instructions (instructions of different dependence
621145449b1SDimitry Andric     // slices) in the true/false blocks appears to affect performance.
622145449b1SDimitry Andric     // Interleaving the slices seems to experimentally be the optimal approach.
623145449b1SDimitry Andric     // This interleaving scheduling allows for more ILP (with a natural downside
624145449b1SDimitry Andric     // of increasing a bit register pressure) compared to a simple ordering of
625145449b1SDimitry Andric     // one whole chain after another. One would expect that this ordering would
626145449b1SDimitry Andric     // not matter since the scheduling in the backend of the compiler  would
627145449b1SDimitry Andric     // take care of it, but apparently the scheduler fails to deliver optimal
628145449b1SDimitry Andric     // ILP with a naive ordering here.
629145449b1SDimitry Andric     SmallVector<Instruction *, 2> TrueSlicesInterleaved, FalseSlicesInterleaved;
630145449b1SDimitry Andric     for (StackSizeType IS = 0; IS < maxTrueSliceLen; ++IS) {
631145449b1SDimitry Andric       for (auto &S : TrueSlices) {
632145449b1SDimitry Andric         if (!S.empty()) {
633145449b1SDimitry Andric           TrueSlicesInterleaved.push_back(S.top());
634145449b1SDimitry Andric           S.pop();
635145449b1SDimitry Andric         }
636145449b1SDimitry Andric       }
637145449b1SDimitry Andric     }
638145449b1SDimitry Andric     for (StackSizeType IS = 0; IS < maxFalseSliceLen; ++IS) {
639145449b1SDimitry Andric       for (auto &S : FalseSlices) {
640145449b1SDimitry Andric         if (!S.empty()) {
641145449b1SDimitry Andric           FalseSlicesInterleaved.push_back(S.top());
642145449b1SDimitry Andric           S.pop();
643145449b1SDimitry Andric         }
644145449b1SDimitry Andric       }
645145449b1SDimitry Andric     }
646145449b1SDimitry Andric 
647145449b1SDimitry Andric     // We split the block containing the select(s) into two blocks.
6484df029ccSDimitry Andric     SelectLike SI = ASI.front();
6494df029ccSDimitry Andric     SelectLike LastSI = ASI.back();
6504df029ccSDimitry Andric     BasicBlock *StartBlock = SI.getI()->getParent();
6514df029ccSDimitry Andric     BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI.getI()));
652ac9a064cSDimitry Andric     // With RemoveDIs turned off, SplitPt can be a dbg.* intrinsic. With
653ac9a064cSDimitry Andric     // RemoveDIs turned on, SplitPt would instead point to the next
654ac9a064cSDimitry Andric     // instruction. To match existing dbg.* intrinsic behaviour with RemoveDIs,
655ac9a064cSDimitry Andric     // tell splitBasicBlock that we want to include any DbgVariableRecords
656ac9a064cSDimitry Andric     // attached to SplitPt in the splice.
657ac9a064cSDimitry Andric     SplitPt.setHeadBit(true);
658145449b1SDimitry Andric     BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
659b1c73532SDimitry Andric     BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
660145449b1SDimitry Andric     // Delete the unconditional branch that was just created by the split.
661145449b1SDimitry Andric     StartBlock->getTerminator()->eraseFromParent();
662145449b1SDimitry Andric 
663ac9a064cSDimitry Andric     // Move any debug/pseudo instructions and not's that were in-between the
664ac9a064cSDimitry Andric     // select group to the newly-created end block.
665ac9a064cSDimitry Andric     SmallVector<Instruction *, 2> SinkInstrs;
6664df029ccSDimitry Andric     auto DIt = SI.getI()->getIterator();
6674df029ccSDimitry Andric     while (&*DIt != LastSI.getI()) {
668145449b1SDimitry Andric       if (DIt->isDebugOrPseudoInst())
669ac9a064cSDimitry Andric         SinkInstrs.push_back(&*DIt);
670ac9a064cSDimitry Andric       if (match(&*DIt, m_Not(m_Specific(SI.getCondition()))))
671ac9a064cSDimitry Andric         SinkInstrs.push_back(&*DIt);
672145449b1SDimitry Andric       DIt++;
673145449b1SDimitry Andric     }
674ac9a064cSDimitry Andric     for (auto *DI : SinkInstrs)
675b1c73532SDimitry Andric       DI->moveBeforePreserving(&*EndBlock->getFirstInsertionPt());
676145449b1SDimitry Andric 
677ac9a064cSDimitry Andric     // Duplicate implementation for DbgRecords, the non-instruction debug-info
678ac9a064cSDimitry Andric     // format. Helper lambda for moving DbgRecords to the end block.
679ac9a064cSDimitry Andric     auto TransferDbgRecords = [&](Instruction &I) {
680ac9a064cSDimitry Andric       for (auto &DbgRecord :
681ac9a064cSDimitry Andric            llvm::make_early_inc_range(I.getDbgRecordRange())) {
682ac9a064cSDimitry Andric         DbgRecord.removeFromParent();
683ac9a064cSDimitry Andric         EndBlock->insertDbgRecordBefore(&DbgRecord,
6844df029ccSDimitry Andric                                         EndBlock->getFirstInsertionPt());
6854df029ccSDimitry Andric       }
6864df029ccSDimitry Andric     };
6874df029ccSDimitry Andric 
6884df029ccSDimitry Andric     // Iterate over all instructions in between SI and LastSI, not including
6894df029ccSDimitry Andric     // SI itself. These are all the variable assignments that happen "in the
6904df029ccSDimitry Andric     // middle" of the select group.
6914df029ccSDimitry Andric     auto R = make_range(std::next(SI.getI()->getIterator()),
6924df029ccSDimitry Andric                         std::next(LastSI.getI()->getIterator()));
693ac9a064cSDimitry Andric     llvm::for_each(R, TransferDbgRecords);
6944df029ccSDimitry Andric 
695145449b1SDimitry Andric     // These are the new basic blocks for the conditional branch.
696145449b1SDimitry Andric     // At least one will become an actual new basic block.
697145449b1SDimitry Andric     BasicBlock *TrueBlock = nullptr, *FalseBlock = nullptr;
698145449b1SDimitry Andric     BranchInst *TrueBranch = nullptr, *FalseBranch = nullptr;
699145449b1SDimitry Andric     if (!TrueSlicesInterleaved.empty()) {
7004df029ccSDimitry Andric       TrueBlock = BasicBlock::Create(EndBlock->getContext(), "select.true.sink",
701145449b1SDimitry Andric                                      EndBlock->getParent(), EndBlock);
702145449b1SDimitry Andric       TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
7034df029ccSDimitry Andric       TrueBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
704145449b1SDimitry Andric       for (Instruction *TrueInst : TrueSlicesInterleaved)
705145449b1SDimitry Andric         TrueInst->moveBefore(TrueBranch);
706145449b1SDimitry Andric     }
707145449b1SDimitry Andric     if (!FalseSlicesInterleaved.empty()) {
7084df029ccSDimitry Andric       FalseBlock =
7094df029ccSDimitry Andric           BasicBlock::Create(EndBlock->getContext(), "select.false.sink",
710145449b1SDimitry Andric                              EndBlock->getParent(), EndBlock);
711145449b1SDimitry Andric       FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
7124df029ccSDimitry Andric       FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
713145449b1SDimitry Andric       for (Instruction *FalseInst : FalseSlicesInterleaved)
714145449b1SDimitry Andric         FalseInst->moveBefore(FalseBranch);
715145449b1SDimitry Andric     }
716145449b1SDimitry Andric     // If there was nothing to sink, then arbitrarily choose the 'false' side
717145449b1SDimitry Andric     // for a new input value to the PHI.
718145449b1SDimitry Andric     if (TrueBlock == FalseBlock) {
719145449b1SDimitry Andric       assert(TrueBlock == nullptr &&
720145449b1SDimitry Andric              "Unexpected basic block transform while optimizing select");
721145449b1SDimitry Andric 
7224df029ccSDimitry Andric       FalseBlock = BasicBlock::Create(StartBlock->getContext(), "select.false",
723145449b1SDimitry Andric                                       EndBlock->getParent(), EndBlock);
724145449b1SDimitry Andric       auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
7254df029ccSDimitry Andric       FalseBranch->setDebugLoc(SI.getI()->getDebugLoc());
726145449b1SDimitry Andric     }
727145449b1SDimitry Andric 
728145449b1SDimitry Andric     // Insert the real conditional branch based on the original condition.
729145449b1SDimitry Andric     // If we did not create a new block for one of the 'true' or 'false' paths
730145449b1SDimitry Andric     // of the condition, it means that side of the branch goes to the end block
731145449b1SDimitry Andric     // directly and the path originates from the start block from the point of
732145449b1SDimitry Andric     // view of the new PHI.
733145449b1SDimitry Andric     BasicBlock *TT, *FT;
734145449b1SDimitry Andric     if (TrueBlock == nullptr) {
735145449b1SDimitry Andric       TT = EndBlock;
736145449b1SDimitry Andric       FT = FalseBlock;
737145449b1SDimitry Andric       TrueBlock = StartBlock;
738145449b1SDimitry Andric     } else if (FalseBlock == nullptr) {
739145449b1SDimitry Andric       TT = TrueBlock;
740145449b1SDimitry Andric       FT = EndBlock;
741145449b1SDimitry Andric       FalseBlock = StartBlock;
742145449b1SDimitry Andric     } else {
743145449b1SDimitry Andric       TT = TrueBlock;
744145449b1SDimitry Andric       FT = FalseBlock;
745145449b1SDimitry Andric     }
7464df029ccSDimitry Andric     IRBuilder<> IB(SI.getI());
7474df029ccSDimitry Andric     auto *CondFr = IB.CreateFreeze(SI.getCondition(),
7484df029ccSDimitry Andric                                    SI.getCondition()->getName() + ".frozen");
749145449b1SDimitry Andric 
750145449b1SDimitry Andric     SmallPtrSet<const Instruction *, 2> INS;
7514df029ccSDimitry Andric     for (auto SI : ASI)
7524df029ccSDimitry Andric       INS.insert(SI.getI());
7534df029ccSDimitry Andric 
754145449b1SDimitry Andric     // Use reverse iterator because later select may use the value of the
755145449b1SDimitry Andric     // earlier select, and we need to propagate value through earlier select
756145449b1SDimitry Andric     // to get the PHI operand.
757145449b1SDimitry Andric     for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
7584df029ccSDimitry Andric       SelectLike SI = *It;
759145449b1SDimitry Andric       // The select itself is replaced with a PHI Node.
7604df029ccSDimitry Andric       PHINode *PN = PHINode::Create(SI.getType(), 2, "");
761b1c73532SDimitry Andric       PN->insertBefore(EndBlock->begin());
7624df029ccSDimitry Andric       PN->takeName(SI.getI());
7634df029ccSDimitry Andric       PN->addIncoming(getTrueOrFalseValue(SI, true, INS, IB), TrueBlock);
7644df029ccSDimitry Andric       PN->addIncoming(getTrueOrFalseValue(SI, false, INS, IB), FalseBlock);
7654df029ccSDimitry Andric       PN->setDebugLoc(SI.getI()->getDebugLoc());
7664df029ccSDimitry Andric       SI.getI()->replaceAllUsesWith(PN);
7674df029ccSDimitry Andric       INS.erase(SI.getI());
768145449b1SDimitry Andric       ++NumSelectsConverted;
769145449b1SDimitry Andric     }
7704df029ccSDimitry Andric     IB.CreateCondBr(CondFr, TT, FT, SI.getI());
7714df029ccSDimitry Andric 
7724df029ccSDimitry Andric     // Remove the old select instructions, now that they are not longer used.
7734df029ccSDimitry Andric     for (auto SI : ASI)
7744df029ccSDimitry Andric       SI.getI()->eraseFromParent();
775145449b1SDimitry Andric   }
776145449b1SDimitry Andric }
777145449b1SDimitry Andric 
collectSelectGroups(BasicBlock & BB,SelectGroups & SIGroups)778312c0ed1SDimitry Andric void SelectOptimizeImpl::collectSelectGroups(BasicBlock &BB,
779145449b1SDimitry Andric                                              SelectGroups &SIGroups) {
780145449b1SDimitry Andric   BasicBlock::iterator BBIt = BB.begin();
781145449b1SDimitry Andric   while (BBIt != BB.end()) {
782145449b1SDimitry Andric     Instruction *I = &*BBIt++;
7834df029ccSDimitry Andric     if (SelectLike SI = SelectLike::match(I)) {
7844df029ccSDimitry Andric       if (!TTI->shouldTreatInstructionLikeSelect(I))
785e3b55780SDimitry Andric         continue;
786e3b55780SDimitry Andric 
787145449b1SDimitry Andric       SelectGroup SIGroup;
788145449b1SDimitry Andric       SIGroup.push_back(SI);
789145449b1SDimitry Andric       while (BBIt != BB.end()) {
790145449b1SDimitry Andric         Instruction *NI = &*BBIt;
791145449b1SDimitry Andric         // Debug/pseudo instructions should be skipped and not prevent the
792145449b1SDimitry Andric         // formation of a select group.
7934df029ccSDimitry Andric         if (NI->isDebugOrPseudoInst()) {
7944df029ccSDimitry Andric           ++BBIt;
7954df029ccSDimitry Andric           continue;
796145449b1SDimitry Andric         }
797ac9a064cSDimitry Andric 
798ac9a064cSDimitry Andric         // Skip not(select(..)), if the not is part of the same select group
799ac9a064cSDimitry Andric         if (match(NI, m_Not(m_Specific(SI.getCondition())))) {
800ac9a064cSDimitry Andric           ++BBIt;
801ac9a064cSDimitry Andric           continue;
802ac9a064cSDimitry Andric         }
803ac9a064cSDimitry Andric 
8044df029ccSDimitry Andric         // We only allow selects in the same group, not other select-like
8054df029ccSDimitry Andric         // instructions.
8064df029ccSDimitry Andric         if (!isa<SelectInst>(NI))
8074df029ccSDimitry Andric           break;
8084df029ccSDimitry Andric 
8094df029ccSDimitry Andric         SelectLike NSI = SelectLike::match(NI);
8104df029ccSDimitry Andric         if (NSI && SI.getCondition() == NSI.getCondition()) {
8114df029ccSDimitry Andric           SIGroup.push_back(NSI);
812ac9a064cSDimitry Andric         } else if (NSI && match(NSI.getCondition(),
813ac9a064cSDimitry Andric                                 m_Not(m_Specific(SI.getCondition())))) {
814ac9a064cSDimitry Andric           NSI.setInverted();
815ac9a064cSDimitry Andric           SIGroup.push_back(NSI);
8164df029ccSDimitry Andric         } else
8174df029ccSDimitry Andric           break;
818145449b1SDimitry Andric         ++BBIt;
819145449b1SDimitry Andric       }
820145449b1SDimitry Andric 
821145449b1SDimitry Andric       // If the select type is not supported, no point optimizing it.
822145449b1SDimitry Andric       // Instruction selection will take care of it.
823145449b1SDimitry Andric       if (!isSelectKindSupported(SI))
824145449b1SDimitry Andric         continue;
825145449b1SDimitry Andric 
826ac9a064cSDimitry Andric       LLVM_DEBUG({
827ac9a064cSDimitry Andric         dbgs() << "New Select group with\n";
828ac9a064cSDimitry Andric         for (auto SI : SIGroup)
829ac9a064cSDimitry Andric           dbgs() << "  " << *SI.getI() << "\n";
830ac9a064cSDimitry Andric       });
831ac9a064cSDimitry Andric 
832145449b1SDimitry Andric       SIGroups.push_back(SIGroup);
833145449b1SDimitry Andric     }
834145449b1SDimitry Andric   }
835145449b1SDimitry Andric }
836145449b1SDimitry Andric 
findProfitableSIGroupsBase(SelectGroups & SIGroups,SelectGroups & ProfSIGroups)837312c0ed1SDimitry Andric void SelectOptimizeImpl::findProfitableSIGroupsBase(
838312c0ed1SDimitry Andric     SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
839145449b1SDimitry Andric   for (SelectGroup &ASI : SIGroups) {
840145449b1SDimitry Andric     ++NumSelectOptAnalyzed;
841145449b1SDimitry Andric     if (isConvertToBranchProfitableBase(ASI))
842145449b1SDimitry Andric       ProfSIGroups.push_back(ASI);
843145449b1SDimitry Andric   }
844145449b1SDimitry Andric }
845145449b1SDimitry Andric 
EmitAndPrintRemark(OptimizationRemarkEmitter * ORE,DiagnosticInfoOptimizationBase & Rem)846e3b55780SDimitry Andric static void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE,
847e3b55780SDimitry Andric                                DiagnosticInfoOptimizationBase &Rem) {
848e3b55780SDimitry Andric   LLVM_DEBUG(dbgs() << Rem.getMsg() << "\n");
849e3b55780SDimitry Andric   ORE->emit(Rem);
850e3b55780SDimitry Andric }
851e3b55780SDimitry Andric 
findProfitableSIGroupsInnerLoops(const Loop * L,SelectGroups & SIGroups,SelectGroups & ProfSIGroups)852312c0ed1SDimitry Andric void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops(
853145449b1SDimitry Andric     const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
854145449b1SDimitry Andric   NumSelectOptAnalyzed += SIGroups.size();
855145449b1SDimitry Andric   // For each select group in an inner-most loop,
856145449b1SDimitry Andric   // a branch is more preferable than a select/conditional-move if:
857145449b1SDimitry Andric   // i) conversion to branches for all the select groups of the loop satisfies
858145449b1SDimitry Andric   //    loop-level heuristics including reducing the loop's critical path by
859312c0ed1SDimitry Andric   //    some threshold (see SelectOptimizeImpl::checkLoopHeuristics); and
860145449b1SDimitry Andric   // ii) the total cost of the select group is cheaper with a branch compared
861145449b1SDimitry Andric   //     to its predicated version. The cost is in terms of latency and the cost
862145449b1SDimitry Andric   //     of a select group is the cost of its most expensive select instruction
863145449b1SDimitry Andric   //     (assuming infinite resources and thus fully leveraging available ILP).
864145449b1SDimitry Andric 
865145449b1SDimitry Andric   DenseMap<const Instruction *, CostInfo> InstCostMap;
866145449b1SDimitry Andric   CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
867145449b1SDimitry Andric                           {Scaled64::getZero(), Scaled64::getZero()}};
868145449b1SDimitry Andric   if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
869145449b1SDimitry Andric       !checkLoopHeuristics(L, LoopCost)) {
870145449b1SDimitry Andric     return;
871145449b1SDimitry Andric   }
872145449b1SDimitry Andric 
873145449b1SDimitry Andric   for (SelectGroup &ASI : SIGroups) {
874145449b1SDimitry Andric     // Assuming infinite resources, the cost of a group of instructions is the
875145449b1SDimitry Andric     // cost of the most expensive instruction of the group.
876145449b1SDimitry Andric     Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
8774df029ccSDimitry Andric     for (SelectLike SI : ASI) {
8784df029ccSDimitry Andric       SelectCost = std::max(SelectCost, InstCostMap[SI.getI()].PredCost);
8794df029ccSDimitry Andric       BranchCost = std::max(BranchCost, InstCostMap[SI.getI()].NonPredCost);
880145449b1SDimitry Andric     }
881145449b1SDimitry Andric     if (BranchCost < SelectCost) {
8824df029ccSDimitry Andric       OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", ASI.front().getI());
883145449b1SDimitry Andric       OR << "Profitable to convert to branch (loop analysis). BranchCost="
884145449b1SDimitry Andric          << BranchCost.toString() << ", SelectCost=" << SelectCost.toString()
885145449b1SDimitry Andric          << ". ";
886e3b55780SDimitry Andric       EmitAndPrintRemark(ORE, OR);
887145449b1SDimitry Andric       ++NumSelectConvertedLoop;
888145449b1SDimitry Andric       ProfSIGroups.push_back(ASI);
889145449b1SDimitry Andric     } else {
8904df029ccSDimitry Andric       OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
8914df029ccSDimitry Andric                                       ASI.front().getI());
892145449b1SDimitry Andric       ORmiss << "Select is more profitable (loop analysis). BranchCost="
893145449b1SDimitry Andric              << BranchCost.toString()
894145449b1SDimitry Andric              << ", SelectCost=" << SelectCost.toString() << ". ";
895e3b55780SDimitry Andric       EmitAndPrintRemark(ORE, ORmiss);
896145449b1SDimitry Andric     }
897145449b1SDimitry Andric   }
898145449b1SDimitry Andric }
899145449b1SDimitry Andric 
isConvertToBranchProfitableBase(const SelectGroup & ASI)900312c0ed1SDimitry Andric bool SelectOptimizeImpl::isConvertToBranchProfitableBase(
9014df029ccSDimitry Andric     const SelectGroup &ASI) {
9024df029ccSDimitry Andric   SelectLike SI = ASI.front();
903ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "Analyzing select group containing " << *SI.getI()
9044df029ccSDimitry Andric                     << "\n");
9054df029ccSDimitry Andric   OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", SI.getI());
9064df029ccSDimitry Andric   OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", SI.getI());
907145449b1SDimitry Andric 
908145449b1SDimitry Andric   // Skip cold basic blocks. Better to optimize for size for cold blocks.
9094df029ccSDimitry Andric   if (PSI->isColdBlock(SI.getI()->getParent(), BFI)) {
910145449b1SDimitry Andric     ++NumSelectColdBB;
911145449b1SDimitry Andric     ORmiss << "Not converted to branch because of cold basic block. ";
912e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, ORmiss);
913145449b1SDimitry Andric     return false;
914145449b1SDimitry Andric   }
915145449b1SDimitry Andric 
916145449b1SDimitry Andric   // If unpredictable, branch form is less profitable.
9174df029ccSDimitry Andric   if (SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) {
918145449b1SDimitry Andric     ++NumSelectUnPred;
919145449b1SDimitry Andric     ORmiss << "Not converted to branch because of unpredictable branch. ";
920e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, ORmiss);
921145449b1SDimitry Andric     return false;
922145449b1SDimitry Andric   }
923145449b1SDimitry Andric 
924145449b1SDimitry Andric   // If highly predictable, branch form is more profitable, unless a
925145449b1SDimitry Andric   // predictable select is inexpensive in the target architecture.
926145449b1SDimitry Andric   if (isSelectHighlyPredictable(SI) && TLI->isPredictableSelectExpensive()) {
927145449b1SDimitry Andric     ++NumSelectConvertedHighPred;
928145449b1SDimitry Andric     OR << "Converted to branch because of highly predictable branch. ";
929e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, OR);
930145449b1SDimitry Andric     return true;
931145449b1SDimitry Andric   }
932145449b1SDimitry Andric 
933145449b1SDimitry Andric   // Look for expensive instructions in the cold operand's (if any) dependence
934145449b1SDimitry Andric   // slice of any of the selects in the group.
935145449b1SDimitry Andric   if (hasExpensiveColdOperand(ASI)) {
936145449b1SDimitry Andric     ++NumSelectConvertedExpColdOperand;
937145449b1SDimitry Andric     OR << "Converted to branch because of expensive cold operand.";
938e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, OR);
939145449b1SDimitry Andric     return true;
940145449b1SDimitry Andric   }
941145449b1SDimitry Andric 
942145449b1SDimitry Andric   ORmiss << "Not profitable to convert to branch (base heuristic).";
943e3b55780SDimitry Andric   EmitAndPrintRemark(ORE, ORmiss);
944145449b1SDimitry Andric   return false;
945145449b1SDimitry Andric }
946145449b1SDimitry Andric 
divideNearest(InstructionCost Numerator,uint64_t Denominator)947145449b1SDimitry Andric static InstructionCost divideNearest(InstructionCost Numerator,
948145449b1SDimitry Andric                                      uint64_t Denominator) {
949145449b1SDimitry Andric   return (Numerator + (Denominator / 2)) / Denominator;
950145449b1SDimitry Andric }
951145449b1SDimitry Andric 
extractBranchWeights(const SelectOptimizeImpl::SelectLike SI,uint64_t & TrueVal,uint64_t & FalseVal)9524df029ccSDimitry Andric static bool extractBranchWeights(const SelectOptimizeImpl::SelectLike SI,
9534df029ccSDimitry Andric                                  uint64_t &TrueVal, uint64_t &FalseVal) {
9544df029ccSDimitry Andric   if (isa<SelectInst>(SI.getI()))
9554df029ccSDimitry Andric     return extractBranchWeights(*SI.getI(), TrueVal, FalseVal);
9564df029ccSDimitry Andric   return false;
9574df029ccSDimitry Andric }
9584df029ccSDimitry Andric 
hasExpensiveColdOperand(const SelectGroup & ASI)9594df029ccSDimitry Andric bool SelectOptimizeImpl::hasExpensiveColdOperand(const SelectGroup &ASI) {
960145449b1SDimitry Andric   bool ColdOperand = false;
961145449b1SDimitry Andric   uint64_t TrueWeight, FalseWeight, TotalWeight;
9624df029ccSDimitry Andric   if (extractBranchWeights(ASI.front(), TrueWeight, FalseWeight)) {
963145449b1SDimitry Andric     uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
964145449b1SDimitry Andric     TotalWeight = TrueWeight + FalseWeight;
965145449b1SDimitry Andric     // Is there a path with frequency <ColdOperandThreshold% (default:20%) ?
966145449b1SDimitry Andric     ColdOperand = TotalWeight * ColdOperandThreshold > 100 * MinWeight;
967145449b1SDimitry Andric   } else if (PSI->hasProfileSummary()) {
9684df029ccSDimitry Andric     OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
9694df029ccSDimitry Andric                                     ASI.front().getI());
970145449b1SDimitry Andric     ORmiss << "Profile data available but missing branch-weights metadata for "
971145449b1SDimitry Andric               "select instruction. ";
972e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, ORmiss);
973145449b1SDimitry Andric   }
974145449b1SDimitry Andric   if (!ColdOperand)
975145449b1SDimitry Andric     return false;
976145449b1SDimitry Andric   // Check if the cold path's dependence slice is expensive for any of the
977145449b1SDimitry Andric   // selects of the group.
9784df029ccSDimitry Andric   for (SelectLike SI : ASI) {
979145449b1SDimitry Andric     Instruction *ColdI = nullptr;
980145449b1SDimitry Andric     uint64_t HotWeight;
981145449b1SDimitry Andric     if (TrueWeight < FalseWeight) {
9824df029ccSDimitry Andric       ColdI = dyn_cast_or_null<Instruction>(SI.getTrueValue());
983145449b1SDimitry Andric       HotWeight = FalseWeight;
984145449b1SDimitry Andric     } else {
9854df029ccSDimitry Andric       ColdI = dyn_cast_or_null<Instruction>(SI.getFalseValue());
986145449b1SDimitry Andric       HotWeight = TrueWeight;
987145449b1SDimitry Andric     }
988145449b1SDimitry Andric     if (ColdI) {
989145449b1SDimitry Andric       std::stack<Instruction *> ColdSlice;
9904df029ccSDimitry Andric       getExclBackwardsSlice(ColdI, ColdSlice, SI.getI());
991145449b1SDimitry Andric       InstructionCost SliceCost = 0;
992145449b1SDimitry Andric       while (!ColdSlice.empty()) {
993145449b1SDimitry Andric         SliceCost += TTI->getInstructionCost(ColdSlice.top(),
994145449b1SDimitry Andric                                              TargetTransformInfo::TCK_Latency);
995145449b1SDimitry Andric         ColdSlice.pop();
996145449b1SDimitry Andric       }
997145449b1SDimitry Andric       // The colder the cold value operand of the select is the more expensive
998145449b1SDimitry Andric       // the cmov becomes for computing the cold value operand every time. Thus,
999145449b1SDimitry Andric       // the colder the cold operand is the more its cost counts.
1000145449b1SDimitry Andric       // Get nearest integer cost adjusted for coldness.
1001145449b1SDimitry Andric       InstructionCost AdjSliceCost =
1002145449b1SDimitry Andric           divideNearest(SliceCost * HotWeight, TotalWeight);
1003145449b1SDimitry Andric       if (AdjSliceCost >=
1004145449b1SDimitry Andric           ColdOperandMaxCostMultiplier * TargetTransformInfo::TCC_Expensive)
1005145449b1SDimitry Andric         return true;
1006145449b1SDimitry Andric     }
1007145449b1SDimitry Andric   }
1008145449b1SDimitry Andric   return false;
1009145449b1SDimitry Andric }
1010145449b1SDimitry Andric 
1011e3b55780SDimitry Andric // Check if it is safe to move LoadI next to the SI.
1012e3b55780SDimitry Andric // Conservatively assume it is safe only if there is no instruction
1013e3b55780SDimitry Andric // modifying memory in-between the load and the select instruction.
isSafeToSinkLoad(Instruction * LoadI,Instruction * SI)1014e3b55780SDimitry Andric static bool isSafeToSinkLoad(Instruction *LoadI, Instruction *SI) {
1015e3b55780SDimitry Andric   // Assume loads from different basic blocks are unsafe to move.
1016e3b55780SDimitry Andric   if (LoadI->getParent() != SI->getParent())
1017e3b55780SDimitry Andric     return false;
1018e3b55780SDimitry Andric   auto It = LoadI->getIterator();
1019e3b55780SDimitry Andric   while (&*It != SI) {
1020e3b55780SDimitry Andric     if (It->mayWriteToMemory())
1021e3b55780SDimitry Andric       return false;
1022e3b55780SDimitry Andric     It++;
1023e3b55780SDimitry Andric   }
1024e3b55780SDimitry Andric   return true;
1025e3b55780SDimitry Andric }
1026e3b55780SDimitry Andric 
1027145449b1SDimitry Andric // For a given source instruction, collect its backwards dependence slice
1028145449b1SDimitry Andric // consisting of instructions exclusively computed for the purpose of producing
1029145449b1SDimitry Andric // the operands of the source instruction. As an approximation
1030145449b1SDimitry Andric // (sufficiently-accurate in practice), we populate this set with the
1031145449b1SDimitry Andric // instructions of the backwards dependence slice that only have one-use and
1032145449b1SDimitry Andric // form an one-use chain that leads to the source instruction.
getExclBackwardsSlice(Instruction * I,std::stack<Instruction * > & Slice,Instruction * SI,bool ForSinking)1033312c0ed1SDimitry Andric void SelectOptimizeImpl::getExclBackwardsSlice(Instruction *I,
1034145449b1SDimitry Andric                                                std::stack<Instruction *> &Slice,
1035312c0ed1SDimitry Andric                                                Instruction *SI,
1036312c0ed1SDimitry Andric                                                bool ForSinking) {
1037145449b1SDimitry Andric   SmallPtrSet<Instruction *, 2> Visited;
1038145449b1SDimitry Andric   std::queue<Instruction *> Worklist;
1039145449b1SDimitry Andric   Worklist.push(I);
1040145449b1SDimitry Andric   while (!Worklist.empty()) {
1041145449b1SDimitry Andric     Instruction *II = Worklist.front();
1042145449b1SDimitry Andric     Worklist.pop();
1043145449b1SDimitry Andric 
1044145449b1SDimitry Andric     // Avoid cycles.
1045145449b1SDimitry Andric     if (!Visited.insert(II).second)
1046145449b1SDimitry Andric       continue;
1047145449b1SDimitry Andric 
1048145449b1SDimitry Andric     if (!II->hasOneUse())
1049145449b1SDimitry Andric       continue;
1050145449b1SDimitry Andric 
1051145449b1SDimitry Andric     // Cannot soundly sink instructions with side-effects.
1052145449b1SDimitry Andric     // Terminator or phi instructions cannot be sunk.
1053145449b1SDimitry Andric     // Avoid sinking other select instructions (should be handled separetely).
1054145449b1SDimitry Andric     if (ForSinking && (II->isTerminator() || II->mayHaveSideEffects() ||
1055145449b1SDimitry Andric                        isa<SelectInst>(II) || isa<PHINode>(II)))
1056145449b1SDimitry Andric       continue;
1057145449b1SDimitry Andric 
1058e3b55780SDimitry Andric     // Avoid sinking loads in order not to skip state-modifying instructions,
1059e3b55780SDimitry Andric     // that may alias with the loaded address.
1060e3b55780SDimitry Andric     // Only allow sinking of loads within the same basic block that are
1061e3b55780SDimitry Andric     // conservatively proven to be safe.
1062e3b55780SDimitry Andric     if (ForSinking && II->mayReadFromMemory() && !isSafeToSinkLoad(II, SI))
1063e3b55780SDimitry Andric       continue;
1064e3b55780SDimitry Andric 
1065145449b1SDimitry Andric     // Avoid considering instructions with less frequency than the source
1066145449b1SDimitry Andric     // instruction (i.e., avoid colder code regions of the dependence slice).
1067145449b1SDimitry Andric     if (BFI->getBlockFreq(II->getParent()) < BFI->getBlockFreq(I->getParent()))
1068145449b1SDimitry Andric       continue;
1069145449b1SDimitry Andric 
1070145449b1SDimitry Andric     // Eligible one-use instruction added to the dependence slice.
1071145449b1SDimitry Andric     Slice.push(II);
1072145449b1SDimitry Andric 
1073145449b1SDimitry Andric     // Explore all the operands of the current instruction to expand the slice.
1074ac9a064cSDimitry Andric     for (Value *Op : II->operand_values())
1075ac9a064cSDimitry Andric       if (auto *OpI = dyn_cast<Instruction>(Op))
1076145449b1SDimitry Andric         Worklist.push(OpI);
1077145449b1SDimitry Andric   }
1078145449b1SDimitry Andric }
1079145449b1SDimitry Andric 
isSelectHighlyPredictable(const SelectLike SI)10804df029ccSDimitry Andric bool SelectOptimizeImpl::isSelectHighlyPredictable(const SelectLike SI) {
1081145449b1SDimitry Andric   uint64_t TrueWeight, FalseWeight;
10824df029ccSDimitry Andric   if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1083145449b1SDimitry Andric     uint64_t Max = std::max(TrueWeight, FalseWeight);
1084145449b1SDimitry Andric     uint64_t Sum = TrueWeight + FalseWeight;
1085145449b1SDimitry Andric     if (Sum != 0) {
1086145449b1SDimitry Andric       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
1087145449b1SDimitry Andric       if (Probability > TTI->getPredictableBranchThreshold())
1088145449b1SDimitry Andric         return true;
1089145449b1SDimitry Andric     }
1090145449b1SDimitry Andric   }
1091145449b1SDimitry Andric   return false;
1092145449b1SDimitry Andric }
1093145449b1SDimitry Andric 
checkLoopHeuristics(const Loop * L,const CostInfo LoopCost[2])1094312c0ed1SDimitry Andric bool SelectOptimizeImpl::checkLoopHeuristics(const Loop *L,
1095145449b1SDimitry Andric                                              const CostInfo LoopCost[2]) {
1096145449b1SDimitry Andric   // Loop-level checks to determine if a non-predicated version (with branches)
1097145449b1SDimitry Andric   // of the loop is more profitable than its predicated version.
1098145449b1SDimitry Andric 
1099145449b1SDimitry Andric   if (DisableLoopLevelHeuristics)
1100145449b1SDimitry Andric     return true;
1101145449b1SDimitry Andric 
1102145449b1SDimitry Andric   OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti",
1103145449b1SDimitry Andric                                    L->getHeader()->getFirstNonPHI());
1104145449b1SDimitry Andric 
1105145449b1SDimitry Andric   if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
1106145449b1SDimitry Andric       LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
1107145449b1SDimitry Andric     ORmissL << "No select conversion in the loop due to no reduction of loop's "
1108145449b1SDimitry Andric                "critical path. ";
1109e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, ORmissL);
1110145449b1SDimitry Andric     return false;
1111145449b1SDimitry Andric   }
1112145449b1SDimitry Andric 
1113145449b1SDimitry Andric   Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
1114145449b1SDimitry Andric                       LoopCost[1].PredCost - LoopCost[1].NonPredCost};
1115145449b1SDimitry Andric 
1116145449b1SDimitry Andric   // Profitably converting to branches need to reduce the loop's critical path
1117145449b1SDimitry Andric   // by at least some threshold (absolute gain of GainCycleThreshold cycles and
1118145449b1SDimitry Andric   // relative gain of 12.5%).
1119145449b1SDimitry Andric   if (Gain[1] < Scaled64::get(GainCycleThreshold) ||
1120145449b1SDimitry Andric       Gain[1] * Scaled64::get(GainRelativeThreshold) < LoopCost[1].PredCost) {
1121145449b1SDimitry Andric     Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
1122145449b1SDimitry Andric     ORmissL << "No select conversion in the loop due to small reduction of "
1123145449b1SDimitry Andric                "loop's critical path. Gain="
1124145449b1SDimitry Andric             << Gain[1].toString()
1125145449b1SDimitry Andric             << ", RelativeGain=" << RelativeGain.toString() << "%. ";
1126e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, ORmissL);
1127145449b1SDimitry Andric     return false;
1128145449b1SDimitry Andric   }
1129145449b1SDimitry Andric 
1130145449b1SDimitry Andric   // If the loop's critical path involves loop-carried dependences, the gradient
1131145449b1SDimitry Andric   // of the gain needs to be at least GainGradientThreshold% (defaults to 25%).
1132145449b1SDimitry Andric   // This check ensures that the latency reduction for the loop's critical path
1133145449b1SDimitry Andric   // keeps decreasing with sufficient rate beyond the two analyzed loop
1134145449b1SDimitry Andric   // iterations.
1135145449b1SDimitry Andric   if (Gain[1] > Gain[0]) {
1136145449b1SDimitry Andric     Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
1137145449b1SDimitry Andric                             (LoopCost[1].PredCost - LoopCost[0].PredCost);
1138145449b1SDimitry Andric     if (GradientGain < Scaled64::get(GainGradientThreshold)) {
1139145449b1SDimitry Andric       ORmissL << "No select conversion in the loop due to small gradient gain. "
1140145449b1SDimitry Andric                  "GradientGain="
1141145449b1SDimitry Andric               << GradientGain.toString() << "%. ";
1142e3b55780SDimitry Andric       EmitAndPrintRemark(ORE, ORmissL);
1143145449b1SDimitry Andric       return false;
1144145449b1SDimitry Andric     }
1145145449b1SDimitry Andric   }
1146145449b1SDimitry Andric   // If the gain decreases it is not profitable to convert.
1147145449b1SDimitry Andric   else if (Gain[1] < Gain[0]) {
1148145449b1SDimitry Andric     ORmissL
1149145449b1SDimitry Andric         << "No select conversion in the loop due to negative gradient gain. ";
1150e3b55780SDimitry Andric     EmitAndPrintRemark(ORE, ORmissL);
1151145449b1SDimitry Andric     return false;
1152145449b1SDimitry Andric   }
1153145449b1SDimitry Andric 
1154145449b1SDimitry Andric   // Non-predicated version of the loop is more profitable than its
1155145449b1SDimitry Andric   // predicated version.
1156145449b1SDimitry Andric   return true;
1157145449b1SDimitry Andric }
1158145449b1SDimitry Andric 
1159145449b1SDimitry Andric // Computes instruction and loop-critical-path costs for both the predicated
1160145449b1SDimitry Andric // and non-predicated version of the given loop.
1161145449b1SDimitry Andric // Returns false if unable to compute these costs due to invalid cost of loop
1162145449b1SDimitry Andric // instruction(s).
computeLoopCosts(const Loop * L,const SelectGroups & SIGroups,DenseMap<const Instruction *,CostInfo> & InstCostMap,CostInfo * LoopCost)1163312c0ed1SDimitry Andric bool SelectOptimizeImpl::computeLoopCosts(
1164145449b1SDimitry Andric     const Loop *L, const SelectGroups &SIGroups,
1165145449b1SDimitry Andric     DenseMap<const Instruction *, CostInfo> &InstCostMap, CostInfo *LoopCost) {
1166e3b55780SDimitry Andric   LLVM_DEBUG(dbgs() << "Calculating Latency / IPredCost / INonPredCost of loop "
1167e3b55780SDimitry Andric                     << L->getHeader()->getName() << "\n");
11684df029ccSDimitry Andric   const auto &SImap = getSImap(SIGroups);
1169145449b1SDimitry Andric   // Compute instruction and loop-critical-path costs across two iterations for
1170145449b1SDimitry Andric   // both predicated and non-predicated version.
1171145449b1SDimitry Andric   const unsigned Iterations = 2;
1172145449b1SDimitry Andric   for (unsigned Iter = 0; Iter < Iterations; ++Iter) {
1173145449b1SDimitry Andric     // Cost of the loop's critical path.
1174145449b1SDimitry Andric     CostInfo &MaxCost = LoopCost[Iter];
1175145449b1SDimitry Andric     for (BasicBlock *BB : L->getBlocks()) {
1176145449b1SDimitry Andric       for (const Instruction &I : *BB) {
1177145449b1SDimitry Andric         if (I.isDebugOrPseudoInst())
1178145449b1SDimitry Andric           continue;
1179145449b1SDimitry Andric         // Compute the predicated and non-predicated cost of the instruction.
1180145449b1SDimitry Andric         Scaled64 IPredCost = Scaled64::getZero(),
1181145449b1SDimitry Andric                  INonPredCost = Scaled64::getZero();
1182145449b1SDimitry Andric 
1183145449b1SDimitry Andric         // Assume infinite resources that allow to fully exploit the available
1184145449b1SDimitry Andric         // instruction-level parallelism.
1185145449b1SDimitry Andric         // InstCost = InstLatency + max(Op1Cost, Op2Cost, … OpNCost)
1186145449b1SDimitry Andric         for (const Use &U : I.operands()) {
1187145449b1SDimitry Andric           auto UI = dyn_cast<Instruction>(U.get());
1188145449b1SDimitry Andric           if (!UI)
1189145449b1SDimitry Andric             continue;
1190145449b1SDimitry Andric           if (InstCostMap.count(UI)) {
1191145449b1SDimitry Andric             IPredCost = std::max(IPredCost, InstCostMap[UI].PredCost);
1192145449b1SDimitry Andric             INonPredCost = std::max(INonPredCost, InstCostMap[UI].NonPredCost);
1193145449b1SDimitry Andric           }
1194145449b1SDimitry Andric         }
1195145449b1SDimitry Andric         auto ILatency = computeInstCost(&I);
1196145449b1SDimitry Andric         if (!ILatency) {
1197145449b1SDimitry Andric           OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", &I);
1198145449b1SDimitry Andric           ORmissL << "Invalid instruction cost preventing analysis and "
1199145449b1SDimitry Andric                      "optimization of the inner-most loop containing this "
1200145449b1SDimitry Andric                      "instruction. ";
1201e3b55780SDimitry Andric           EmitAndPrintRemark(ORE, ORmissL);
1202145449b1SDimitry Andric           return false;
1203145449b1SDimitry Andric         }
1204e3b55780SDimitry Andric         IPredCost += Scaled64::get(*ILatency);
1205e3b55780SDimitry Andric         INonPredCost += Scaled64::get(*ILatency);
1206145449b1SDimitry Andric 
1207145449b1SDimitry Andric         // For a select that can be converted to branch,
1208145449b1SDimitry Andric         // compute its cost as a branch (non-predicated cost).
1209145449b1SDimitry Andric         //
1210145449b1SDimitry Andric         // BranchCost = PredictedPathCost + MispredictCost
1211145449b1SDimitry Andric         // PredictedPathCost = TrueOpCost * TrueProb + FalseOpCost * FalseProb
1212145449b1SDimitry Andric         // MispredictCost = max(MispredictPenalty, CondCost) * MispredictRate
12134df029ccSDimitry Andric         if (SImap.contains(&I)) {
12144df029ccSDimitry Andric           auto SI = SImap.at(&I);
12154df029ccSDimitry Andric           Scaled64 TrueOpCost = SI.getTrueOpCost(InstCostMap, TTI);
12164df029ccSDimitry Andric           Scaled64 FalseOpCost = SI.getFalseOpCost(InstCostMap, TTI);
1217145449b1SDimitry Andric           Scaled64 PredictedPathCost =
1218145449b1SDimitry Andric               getPredictedPathCost(TrueOpCost, FalseOpCost, SI);
1219145449b1SDimitry Andric 
1220145449b1SDimitry Andric           Scaled64 CondCost = Scaled64::getZero();
12214df029ccSDimitry Andric           if (auto *CI = dyn_cast<Instruction>(SI.getCondition()))
1222145449b1SDimitry Andric             if (InstCostMap.count(CI))
1223145449b1SDimitry Andric               CondCost = InstCostMap[CI].NonPredCost;
1224145449b1SDimitry Andric           Scaled64 MispredictCost = getMispredictionCost(SI, CondCost);
1225145449b1SDimitry Andric 
1226145449b1SDimitry Andric           INonPredCost = PredictedPathCost + MispredictCost;
1227145449b1SDimitry Andric         }
1228e3b55780SDimitry Andric         LLVM_DEBUG(dbgs() << " " << ILatency << "/" << IPredCost << "/"
1229e3b55780SDimitry Andric                           << INonPredCost << " for " << I << "\n");
1230145449b1SDimitry Andric 
1231145449b1SDimitry Andric         InstCostMap[&I] = {IPredCost, INonPredCost};
1232145449b1SDimitry Andric         MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
1233145449b1SDimitry Andric         MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
1234145449b1SDimitry Andric       }
1235145449b1SDimitry Andric     }
1236e3b55780SDimitry Andric     LLVM_DEBUG(dbgs() << "Iteration " << Iter + 1
1237e3b55780SDimitry Andric                       << " MaxCost = " << MaxCost.PredCost << " "
1238e3b55780SDimitry Andric                       << MaxCost.NonPredCost << "\n");
1239145449b1SDimitry Andric   }
1240145449b1SDimitry Andric   return true;
1241145449b1SDimitry Andric }
1242145449b1SDimitry Andric 
12434df029ccSDimitry Andric SmallDenseMap<const Instruction *, SelectOptimizeImpl::SelectLike, 2>
getSImap(const SelectGroups & SIGroups)12444df029ccSDimitry Andric SelectOptimizeImpl::getSImap(const SelectGroups &SIGroups) {
12454df029ccSDimitry Andric   SmallDenseMap<const Instruction *, SelectLike, 2> SImap;
1246145449b1SDimitry Andric   for (const SelectGroup &ASI : SIGroups)
12474df029ccSDimitry Andric     for (SelectLike SI : ASI)
12484df029ccSDimitry Andric       SImap.try_emplace(SI.getI(), SI);
12494df029ccSDimitry Andric   return SImap;
1250145449b1SDimitry Andric }
1251145449b1SDimitry Andric 
1252312c0ed1SDimitry Andric std::optional<uint64_t>
computeInstCost(const Instruction * I)1253312c0ed1SDimitry Andric SelectOptimizeImpl::computeInstCost(const Instruction *I) {
1254145449b1SDimitry Andric   InstructionCost ICost =
1255145449b1SDimitry Andric       TTI->getInstructionCost(I, TargetTransformInfo::TCK_Latency);
1256145449b1SDimitry Andric   if (auto OC = ICost.getValue())
1257e3b55780SDimitry Andric     return std::optional<uint64_t>(*OC);
1258e3b55780SDimitry Andric   return std::nullopt;
1259145449b1SDimitry Andric }
1260145449b1SDimitry Andric 
1261145449b1SDimitry Andric ScaledNumber<uint64_t>
getMispredictionCost(const SelectLike SI,const Scaled64 CondCost)12624df029ccSDimitry Andric SelectOptimizeImpl::getMispredictionCost(const SelectLike SI,
1263145449b1SDimitry Andric                                          const Scaled64 CondCost) {
1264145449b1SDimitry Andric   uint64_t MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
1265145449b1SDimitry Andric 
1266145449b1SDimitry Andric   // Account for the default misprediction rate when using a branch
1267145449b1SDimitry Andric   // (conservatively set to 25% by default).
1268145449b1SDimitry Andric   uint64_t MispredictRate = MispredictDefaultRate;
1269145449b1SDimitry Andric   // If the select condition is obviously predictable, then the misprediction
1270145449b1SDimitry Andric   // rate is zero.
1271145449b1SDimitry Andric   if (isSelectHighlyPredictable(SI))
1272145449b1SDimitry Andric     MispredictRate = 0;
1273145449b1SDimitry Andric 
1274145449b1SDimitry Andric   // CondCost is included to account for cases where the computation of the
1275145449b1SDimitry Andric   // condition is part of a long dependence chain (potentially loop-carried)
1276145449b1SDimitry Andric   // that would delay detection of a misprediction and increase its cost.
1277145449b1SDimitry Andric   Scaled64 MispredictCost =
1278145449b1SDimitry Andric       std::max(Scaled64::get(MispredictPenalty), CondCost) *
1279145449b1SDimitry Andric       Scaled64::get(MispredictRate);
1280145449b1SDimitry Andric   MispredictCost /= Scaled64::get(100);
1281145449b1SDimitry Andric 
1282145449b1SDimitry Andric   return MispredictCost;
1283145449b1SDimitry Andric }
1284145449b1SDimitry Andric 
1285145449b1SDimitry Andric // Returns the cost of a branch when the prediction is correct.
1286145449b1SDimitry Andric // TrueCost * TrueProbability + FalseCost * FalseProbability.
1287145449b1SDimitry Andric ScaledNumber<uint64_t>
getPredictedPathCost(Scaled64 TrueCost,Scaled64 FalseCost,const SelectLike SI)1288312c0ed1SDimitry Andric SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
12894df029ccSDimitry Andric                                          const SelectLike SI) {
1290145449b1SDimitry Andric   Scaled64 PredPathCost;
1291145449b1SDimitry Andric   uint64_t TrueWeight, FalseWeight;
12924df029ccSDimitry Andric   if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1293145449b1SDimitry Andric     uint64_t SumWeight = TrueWeight + FalseWeight;
1294145449b1SDimitry Andric     if (SumWeight != 0) {
1295145449b1SDimitry Andric       PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
1296145449b1SDimitry Andric                      FalseCost * Scaled64::get(FalseWeight);
1297145449b1SDimitry Andric       PredPathCost /= Scaled64::get(SumWeight);
1298145449b1SDimitry Andric       return PredPathCost;
1299145449b1SDimitry Andric     }
1300145449b1SDimitry Andric   }
1301145449b1SDimitry Andric   // Without branch weight metadata, we assume 75% for the one path and 25% for
1302145449b1SDimitry Andric   // the other, and pick the result with the biggest cost.
1303145449b1SDimitry Andric   PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
1304145449b1SDimitry Andric                           FalseCost * Scaled64::get(3) + TrueCost);
1305145449b1SDimitry Andric   PredPathCost /= Scaled64::get(4);
1306145449b1SDimitry Andric   return PredPathCost;
1307145449b1SDimitry Andric }
1308145449b1SDimitry Andric 
isSelectKindSupported(const SelectLike SI)13094df029ccSDimitry Andric bool SelectOptimizeImpl::isSelectKindSupported(const SelectLike SI) {
13104df029ccSDimitry Andric   bool VectorCond = !SI.getCondition()->getType()->isIntegerTy(1);
1311145449b1SDimitry Andric   if (VectorCond)
1312145449b1SDimitry Andric     return false;
1313145449b1SDimitry Andric   TargetLowering::SelectSupportKind SelectKind;
13144df029ccSDimitry Andric   if (SI.getType()->isVectorTy())
1315145449b1SDimitry Andric     SelectKind = TargetLowering::ScalarCondVectorVal;
1316145449b1SDimitry Andric   else
1317145449b1SDimitry Andric     SelectKind = TargetLowering::ScalarValSelect;
1318145449b1SDimitry Andric   return TLI->isSelectSupported(SelectKind);
1319145449b1SDimitry Andric }
1320