181ad6265SDimitry Andric //===--- SelectOptimize.cpp - Convert select to branches if profitable ---===//
281ad6265SDimitry Andric //
381ad6265SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
481ad6265SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
581ad6265SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
681ad6265SDimitry Andric //
781ad6265SDimitry Andric //===----------------------------------------------------------------------===//
881ad6265SDimitry Andric //
981ad6265SDimitry Andric // This pass converts selects to conditional jumps when profitable.
1081ad6265SDimitry Andric //
1181ad6265SDimitry Andric //===----------------------------------------------------------------------===//
1281ad6265SDimitry Andric
13c9157d92SDimitry Andric #include "llvm/CodeGen/SelectOptimize.h"
1481ad6265SDimitry Andric #include "llvm/ADT/SmallVector.h"
1581ad6265SDimitry Andric #include "llvm/ADT/Statistic.h"
1681ad6265SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
1781ad6265SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
1881ad6265SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
1981ad6265SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
2081ad6265SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
2181ad6265SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
2281ad6265SDimitry Andric #include "llvm/CodeGen/Passes.h"
2381ad6265SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
2481ad6265SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
2581ad6265SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
2681ad6265SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
2781ad6265SDimitry Andric #include "llvm/IR/BasicBlock.h"
2881ad6265SDimitry Andric #include "llvm/IR/Dominators.h"
2981ad6265SDimitry Andric #include "llvm/IR/Function.h"
3081ad6265SDimitry Andric #include "llvm/IR/IRBuilder.h"
3181ad6265SDimitry Andric #include "llvm/IR/Instruction.h"
32fe013be4SDimitry Andric #include "llvm/IR/PatternMatch.h"
33bdd1243dSDimitry Andric #include "llvm/IR/ProfDataUtils.h"
3481ad6265SDimitry Andric #include "llvm/InitializePasses.h"
3581ad6265SDimitry Andric #include "llvm/Pass.h"
3681ad6265SDimitry Andric #include "llvm/Support/ScaledNumber.h"
3781ad6265SDimitry Andric #include "llvm/Target/TargetMachine.h"
3881ad6265SDimitry Andric #include "llvm/Transforms/Utils/SizeOpts.h"
3981ad6265SDimitry Andric #include <algorithm>
4081ad6265SDimitry Andric #include <memory>
4181ad6265SDimitry Andric #include <queue>
4281ad6265SDimitry Andric #include <stack>
4381ad6265SDimitry Andric
4481ad6265SDimitry Andric using namespace llvm;
45*a58f00eaSDimitry Andric using namespace llvm::PatternMatch;
4681ad6265SDimitry Andric
4781ad6265SDimitry Andric #define DEBUG_TYPE "select-optimize"
4881ad6265SDimitry Andric
4981ad6265SDimitry Andric STATISTIC(NumSelectOptAnalyzed,
5081ad6265SDimitry Andric "Number of select groups considered for conversion to branch");
5181ad6265SDimitry Andric STATISTIC(NumSelectConvertedExpColdOperand,
5281ad6265SDimitry Andric "Number of select groups converted due to expensive cold operand");
5381ad6265SDimitry Andric STATISTIC(NumSelectConvertedHighPred,
5481ad6265SDimitry Andric "Number of select groups converted due to high-predictability");
5581ad6265SDimitry Andric STATISTIC(NumSelectUnPred,
5681ad6265SDimitry Andric "Number of select groups not converted due to unpredictability");
5781ad6265SDimitry Andric STATISTIC(NumSelectColdBB,
5881ad6265SDimitry Andric "Number of select groups not converted due to cold basic block");
5981ad6265SDimitry Andric STATISTIC(NumSelectConvertedLoop,
6081ad6265SDimitry Andric "Number of select groups converted due to loop-level analysis");
6181ad6265SDimitry Andric STATISTIC(NumSelectsConverted, "Number of selects converted");
6281ad6265SDimitry Andric
6381ad6265SDimitry Andric static cl::opt<unsigned> ColdOperandThreshold(
6481ad6265SDimitry Andric "cold-operand-threshold",
6581ad6265SDimitry Andric cl::desc("Maximum frequency of path for an operand to be considered cold."),
6681ad6265SDimitry Andric cl::init(20), cl::Hidden);
6781ad6265SDimitry Andric
6881ad6265SDimitry Andric static cl::opt<unsigned> ColdOperandMaxCostMultiplier(
6981ad6265SDimitry Andric "cold-operand-max-cost-multiplier",
7081ad6265SDimitry Andric cl::desc("Maximum cost multiplier of TCC_expensive for the dependence "
7181ad6265SDimitry Andric "slice of a cold operand to be considered inexpensive."),
7281ad6265SDimitry Andric cl::init(1), cl::Hidden);
7381ad6265SDimitry Andric
7481ad6265SDimitry Andric static cl::opt<unsigned>
7581ad6265SDimitry Andric GainGradientThreshold("select-opti-loop-gradient-gain-threshold",
7681ad6265SDimitry Andric cl::desc("Gradient gain threshold (%)."),
7781ad6265SDimitry Andric cl::init(25), cl::Hidden);
7881ad6265SDimitry Andric
7981ad6265SDimitry Andric static cl::opt<unsigned>
8081ad6265SDimitry Andric GainCycleThreshold("select-opti-loop-cycle-gain-threshold",
8181ad6265SDimitry Andric cl::desc("Minimum gain per loop (in cycles) threshold."),
8281ad6265SDimitry Andric cl::init(4), cl::Hidden);
8381ad6265SDimitry Andric
8481ad6265SDimitry Andric static cl::opt<unsigned> GainRelativeThreshold(
8581ad6265SDimitry Andric "select-opti-loop-relative-gain-threshold",
8681ad6265SDimitry Andric cl::desc(
8781ad6265SDimitry Andric "Minimum relative gain per loop threshold (1/X). Defaults to 12.5%"),
8881ad6265SDimitry Andric cl::init(8), cl::Hidden);
8981ad6265SDimitry Andric
9081ad6265SDimitry Andric static cl::opt<unsigned> MispredictDefaultRate(
9181ad6265SDimitry Andric "mispredict-default-rate", cl::Hidden, cl::init(25),
9281ad6265SDimitry Andric cl::desc("Default mispredict rate (initialized to 25%)."));
9381ad6265SDimitry Andric
9481ad6265SDimitry Andric static cl::opt<bool>
9581ad6265SDimitry Andric DisableLoopLevelHeuristics("disable-loop-level-heuristics", cl::Hidden,
9681ad6265SDimitry Andric cl::init(false),
9781ad6265SDimitry Andric cl::desc("Disable loop-level heuristics."));
9881ad6265SDimitry Andric
9981ad6265SDimitry Andric namespace {
10081ad6265SDimitry Andric
101c9157d92SDimitry Andric class SelectOptimizeImpl {
10281ad6265SDimitry Andric const TargetMachine *TM = nullptr;
103fe013be4SDimitry Andric const TargetSubtargetInfo *TSI = nullptr;
10481ad6265SDimitry Andric const TargetLowering *TLI = nullptr;
10581ad6265SDimitry Andric const TargetTransformInfo *TTI = nullptr;
106fe013be4SDimitry Andric const LoopInfo *LI = nullptr;
107c9157d92SDimitry Andric BlockFrequencyInfo *BFI;
108fe013be4SDimitry Andric ProfileSummaryInfo *PSI = nullptr;
109fe013be4SDimitry Andric OptimizationRemarkEmitter *ORE = nullptr;
11081ad6265SDimitry Andric TargetSchedModel TSchedModel;
11181ad6265SDimitry Andric
11281ad6265SDimitry Andric public:
113c9157d92SDimitry Andric SelectOptimizeImpl() = default;
SelectOptimizeImpl(const TargetMachine * TM)114c9157d92SDimitry Andric SelectOptimizeImpl(const TargetMachine *TM) : TM(TM){};
115c9157d92SDimitry Andric PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
116c9157d92SDimitry Andric bool runOnFunction(Function &F, Pass &P);
11781ad6265SDimitry Andric
11881ad6265SDimitry Andric using Scaled64 = ScaledNumber<uint64_t>;
11981ad6265SDimitry Andric
12081ad6265SDimitry Andric struct CostInfo {
12181ad6265SDimitry Andric /// Predicated cost (with selects as conditional moves).
12281ad6265SDimitry Andric Scaled64 PredCost;
12381ad6265SDimitry Andric /// Non-predicated cost (with selects converted to branches).
12481ad6265SDimitry Andric Scaled64 NonPredCost;
12581ad6265SDimitry Andric };
12681ad6265SDimitry Andric
127*a58f00eaSDimitry Andric /// SelectLike is an abstraction over SelectInst and other operations that can
128*a58f00eaSDimitry Andric /// act like selects. For example Or(Zext(icmp), X) can be treated like
129*a58f00eaSDimitry Andric /// select(icmp, X|1, X).
130*a58f00eaSDimitry Andric class SelectLike {
SelectLike(Instruction * I)131*a58f00eaSDimitry Andric SelectLike(Instruction *I) : I(I) {}
132*a58f00eaSDimitry Andric
133*a58f00eaSDimitry Andric Instruction *I;
134*a58f00eaSDimitry Andric
135*a58f00eaSDimitry Andric public:
136*a58f00eaSDimitry Andric /// Match a select or select-like instruction, returning a SelectLike.
match(Instruction * I)137*a58f00eaSDimitry Andric static SelectLike match(Instruction *I) {
138*a58f00eaSDimitry Andric // Select instruction are what we are usually looking for.
139*a58f00eaSDimitry Andric if (isa<SelectInst>(I))
140*a58f00eaSDimitry Andric return SelectLike(I);
141*a58f00eaSDimitry Andric
142*a58f00eaSDimitry Andric // An Or(zext(i1 X), Y) can also be treated like a select, with condition
143*a58f00eaSDimitry Andric // C and values Y|1 and Y.
144*a58f00eaSDimitry Andric Value *X;
145*a58f00eaSDimitry Andric if (PatternMatch::match(
146*a58f00eaSDimitry Andric I, m_c_Or(m_OneUse(m_ZExt(m_Value(X))), m_Value())) &&
147*a58f00eaSDimitry Andric X->getType()->isIntegerTy(1))
148*a58f00eaSDimitry Andric return SelectLike(I);
149*a58f00eaSDimitry Andric
150*a58f00eaSDimitry Andric return SelectLike(nullptr);
151*a58f00eaSDimitry Andric }
152*a58f00eaSDimitry Andric
isValid()153*a58f00eaSDimitry Andric bool isValid() { return I; }
operator bool()154*a58f00eaSDimitry Andric operator bool() { return isValid(); }
155*a58f00eaSDimitry Andric
getI()156*a58f00eaSDimitry Andric Instruction *getI() { return I; }
getI() const157*a58f00eaSDimitry Andric const Instruction *getI() const { return I; }
158*a58f00eaSDimitry Andric
getType() const159*a58f00eaSDimitry Andric Type *getType() const { return I->getType(); }
160*a58f00eaSDimitry Andric
161*a58f00eaSDimitry Andric /// Return the condition for the SelectLike instruction. For example the
162*a58f00eaSDimitry Andric /// condition of a select or c in `or(zext(c), x)`
getCondition() const163*a58f00eaSDimitry Andric Value *getCondition() const {
164*a58f00eaSDimitry Andric if (auto *Sel = dyn_cast<SelectInst>(I))
165*a58f00eaSDimitry Andric return Sel->getCondition();
166*a58f00eaSDimitry Andric // Or(zext) case
167*a58f00eaSDimitry Andric if (auto *BO = dyn_cast<BinaryOperator>(I)) {
168*a58f00eaSDimitry Andric Value *X;
169*a58f00eaSDimitry Andric if (PatternMatch::match(BO->getOperand(0),
170*a58f00eaSDimitry Andric m_OneUse(m_ZExt(m_Value(X)))))
171*a58f00eaSDimitry Andric return X;
172*a58f00eaSDimitry Andric if (PatternMatch::match(BO->getOperand(1),
173*a58f00eaSDimitry Andric m_OneUse(m_ZExt(m_Value(X)))))
174*a58f00eaSDimitry Andric return X;
175*a58f00eaSDimitry Andric }
176*a58f00eaSDimitry Andric
177*a58f00eaSDimitry Andric llvm_unreachable("Unhandled case in getCondition");
178*a58f00eaSDimitry Andric }
179*a58f00eaSDimitry Andric
180*a58f00eaSDimitry Andric /// Return the true value for the SelectLike instruction. Note this may not
181*a58f00eaSDimitry Andric /// exist for all SelectLike instructions. For example, for `or(zext(c), x)`
182*a58f00eaSDimitry Andric /// the true value would be `or(x,1)`. As this value does not exist, nullptr
183*a58f00eaSDimitry Andric /// is returned.
getTrueValue() const184*a58f00eaSDimitry Andric Value *getTrueValue() const {
185*a58f00eaSDimitry Andric if (auto *Sel = dyn_cast<SelectInst>(I))
186*a58f00eaSDimitry Andric return Sel->getTrueValue();
187*a58f00eaSDimitry Andric // Or(zext) case - The true value is Or(X), so return nullptr as the value
188*a58f00eaSDimitry Andric // does not yet exist.
189*a58f00eaSDimitry Andric if (isa<BinaryOperator>(I))
190*a58f00eaSDimitry Andric return nullptr;
191*a58f00eaSDimitry Andric
192*a58f00eaSDimitry Andric llvm_unreachable("Unhandled case in getTrueValue");
193*a58f00eaSDimitry Andric }
194*a58f00eaSDimitry Andric
195*a58f00eaSDimitry Andric /// Return the false value for the SelectLike instruction. For example the
196*a58f00eaSDimitry Andric /// getFalseValue of a select or `x` in `or(zext(c), x)` (which is
197*a58f00eaSDimitry Andric /// `select(c, x|1, x)`)
getFalseValue() const198*a58f00eaSDimitry Andric Value *getFalseValue() const {
199*a58f00eaSDimitry Andric if (auto *Sel = dyn_cast<SelectInst>(I))
200*a58f00eaSDimitry Andric return Sel->getFalseValue();
201*a58f00eaSDimitry Andric // Or(zext) case - return the operand which is not the zext.
202*a58f00eaSDimitry Andric if (auto *BO = dyn_cast<BinaryOperator>(I)) {
203*a58f00eaSDimitry Andric Value *X;
204*a58f00eaSDimitry Andric if (PatternMatch::match(BO->getOperand(0),
205*a58f00eaSDimitry Andric m_OneUse(m_ZExt(m_Value(X)))))
206*a58f00eaSDimitry Andric return BO->getOperand(1);
207*a58f00eaSDimitry Andric if (PatternMatch::match(BO->getOperand(1),
208*a58f00eaSDimitry Andric m_OneUse(m_ZExt(m_Value(X)))))
209*a58f00eaSDimitry Andric return BO->getOperand(0);
210*a58f00eaSDimitry Andric }
211*a58f00eaSDimitry Andric
212*a58f00eaSDimitry Andric llvm_unreachable("Unhandled case in getFalseValue");
213*a58f00eaSDimitry Andric }
214*a58f00eaSDimitry Andric
215*a58f00eaSDimitry Andric /// Return the NonPredCost cost of the true op, given the costs in
216*a58f00eaSDimitry Andric /// InstCostMap. This may need to be generated for select-like instructions.
getTrueOpCost(DenseMap<const Instruction *,CostInfo> & InstCostMap,const TargetTransformInfo * TTI)217*a58f00eaSDimitry Andric Scaled64 getTrueOpCost(DenseMap<const Instruction *, CostInfo> &InstCostMap,
218*a58f00eaSDimitry Andric const TargetTransformInfo *TTI) {
219*a58f00eaSDimitry Andric if (auto *Sel = dyn_cast<SelectInst>(I))
220*a58f00eaSDimitry Andric if (auto *I = dyn_cast<Instruction>(Sel->getTrueValue()))
221*a58f00eaSDimitry Andric return InstCostMap.contains(I) ? InstCostMap[I].NonPredCost
222*a58f00eaSDimitry Andric : Scaled64::getZero();
223*a58f00eaSDimitry Andric
224*a58f00eaSDimitry Andric // Or case - add the cost of an extra Or to the cost of the False case.
225*a58f00eaSDimitry Andric if (isa<BinaryOperator>(I))
226*a58f00eaSDimitry Andric if (auto I = dyn_cast<Instruction>(getFalseValue()))
227*a58f00eaSDimitry Andric if (InstCostMap.contains(I)) {
228*a58f00eaSDimitry Andric InstructionCost OrCost = TTI->getArithmeticInstrCost(
229*a58f00eaSDimitry Andric Instruction::Or, I->getType(), TargetTransformInfo::TCK_Latency,
230*a58f00eaSDimitry Andric {TargetTransformInfo::OK_AnyValue,
231*a58f00eaSDimitry Andric TargetTransformInfo::OP_None},
232*a58f00eaSDimitry Andric {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2});
233*a58f00eaSDimitry Andric return InstCostMap[I].NonPredCost +
234*a58f00eaSDimitry Andric Scaled64::get(*OrCost.getValue());
235*a58f00eaSDimitry Andric }
236*a58f00eaSDimitry Andric
237*a58f00eaSDimitry Andric return Scaled64::getZero();
238*a58f00eaSDimitry Andric }
239*a58f00eaSDimitry Andric
240*a58f00eaSDimitry Andric /// Return the NonPredCost cost of the false op, given the costs in
241*a58f00eaSDimitry Andric /// InstCostMap. This may need to be generated for select-like instructions.
242*a58f00eaSDimitry Andric Scaled64
getFalseOpCost(DenseMap<const Instruction *,CostInfo> & InstCostMap,const TargetTransformInfo * TTI)243*a58f00eaSDimitry Andric getFalseOpCost(DenseMap<const Instruction *, CostInfo> &InstCostMap,
244*a58f00eaSDimitry Andric const TargetTransformInfo *TTI) {
245*a58f00eaSDimitry Andric if (auto *Sel = dyn_cast<SelectInst>(I))
246*a58f00eaSDimitry Andric if (auto *I = dyn_cast<Instruction>(Sel->getFalseValue()))
247*a58f00eaSDimitry Andric return InstCostMap.contains(I) ? InstCostMap[I].NonPredCost
248*a58f00eaSDimitry Andric : Scaled64::getZero();
249*a58f00eaSDimitry Andric
250*a58f00eaSDimitry Andric // Or case - return the cost of the false case
251*a58f00eaSDimitry Andric if (isa<BinaryOperator>(I))
252*a58f00eaSDimitry Andric if (auto I = dyn_cast<Instruction>(getFalseValue()))
253*a58f00eaSDimitry Andric if (InstCostMap.contains(I))
254*a58f00eaSDimitry Andric return InstCostMap[I].NonPredCost;
255*a58f00eaSDimitry Andric
256*a58f00eaSDimitry Andric return Scaled64::getZero();
257*a58f00eaSDimitry Andric }
258*a58f00eaSDimitry Andric };
259*a58f00eaSDimitry Andric
260*a58f00eaSDimitry Andric private:
261*a58f00eaSDimitry Andric // Select groups consist of consecutive select instructions with the same
262*a58f00eaSDimitry Andric // condition.
263*a58f00eaSDimitry Andric using SelectGroup = SmallVector<SelectLike, 2>;
264*a58f00eaSDimitry Andric using SelectGroups = SmallVector<SelectGroup, 2>;
265*a58f00eaSDimitry Andric
26681ad6265SDimitry Andric // Converts select instructions of a function to conditional jumps when deemed
26781ad6265SDimitry Andric // profitable. Returns true if at least one select was converted.
26881ad6265SDimitry Andric bool optimizeSelects(Function &F);
26981ad6265SDimitry Andric
27081ad6265SDimitry Andric // Heuristics for determining which select instructions can be profitably
27181ad6265SDimitry Andric // conveted to branches. Separate heuristics for selects in inner-most loops
27281ad6265SDimitry Andric // and the rest of code regions (base heuristics for non-inner-most loop
27381ad6265SDimitry Andric // regions).
27481ad6265SDimitry Andric void optimizeSelectsBase(Function &F, SelectGroups &ProfSIGroups);
27581ad6265SDimitry Andric void optimizeSelectsInnerLoops(Function &F, SelectGroups &ProfSIGroups);
27681ad6265SDimitry Andric
27781ad6265SDimitry Andric // Converts to branches the select groups that were deemed
27881ad6265SDimitry Andric // profitable-to-convert.
27981ad6265SDimitry Andric void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
28081ad6265SDimitry Andric
28181ad6265SDimitry Andric // Splits selects of a given basic block into select groups.
28281ad6265SDimitry Andric void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
28381ad6265SDimitry Andric
28481ad6265SDimitry Andric // Determines for which select groups it is profitable converting to branches
28581ad6265SDimitry Andric // (base and inner-most-loop heuristics).
28681ad6265SDimitry Andric void findProfitableSIGroupsBase(SelectGroups &SIGroups,
28781ad6265SDimitry Andric SelectGroups &ProfSIGroups);
28881ad6265SDimitry Andric void findProfitableSIGroupsInnerLoops(const Loop *L, SelectGroups &SIGroups,
28981ad6265SDimitry Andric SelectGroups &ProfSIGroups);
29081ad6265SDimitry Andric
29181ad6265SDimitry Andric // Determines if a select group should be converted to a branch (base
29281ad6265SDimitry Andric // heuristics).
293*a58f00eaSDimitry Andric bool isConvertToBranchProfitableBase(const SelectGroup &ASI);
29481ad6265SDimitry Andric
29581ad6265SDimitry Andric // Returns true if there are expensive instructions in the cold value
29681ad6265SDimitry Andric // operand's (if any) dependence slice of any of the selects of the given
29781ad6265SDimitry Andric // group.
298*a58f00eaSDimitry Andric bool hasExpensiveColdOperand(const SelectGroup &ASI);
29981ad6265SDimitry Andric
30081ad6265SDimitry Andric // For a given source instruction, collect its backwards dependence slice
30181ad6265SDimitry Andric // consisting of instructions exclusively computed for producing the operands
30281ad6265SDimitry Andric // of the source instruction.
30381ad6265SDimitry Andric void getExclBackwardsSlice(Instruction *I, std::stack<Instruction *> &Slice,
304bdd1243dSDimitry Andric Instruction *SI, bool ForSinking = false);
30581ad6265SDimitry Andric
30681ad6265SDimitry Andric // Returns true if the condition of the select is highly predictable.
307*a58f00eaSDimitry Andric bool isSelectHighlyPredictable(const SelectLike SI);
30881ad6265SDimitry Andric
30981ad6265SDimitry Andric // Loop-level checks to determine if a non-predicated version (with branches)
31081ad6265SDimitry Andric // of the given loop is more profitable than its predicated version.
31181ad6265SDimitry Andric bool checkLoopHeuristics(const Loop *L, const CostInfo LoopDepth[2]);
31281ad6265SDimitry Andric
31381ad6265SDimitry Andric // Computes instruction and loop-critical-path costs for both the predicated
31481ad6265SDimitry Andric // and non-predicated version of the given loop.
31581ad6265SDimitry Andric bool computeLoopCosts(const Loop *L, const SelectGroups &SIGroups,
31681ad6265SDimitry Andric DenseMap<const Instruction *, CostInfo> &InstCostMap,
31781ad6265SDimitry Andric CostInfo *LoopCost);
31881ad6265SDimitry Andric
31981ad6265SDimitry Andric // Returns a set of all the select instructions in the given select groups.
320*a58f00eaSDimitry Andric SmallDenseMap<const Instruction *, SelectLike, 2>
321*a58f00eaSDimitry Andric getSImap(const SelectGroups &SIGroups);
32281ad6265SDimitry Andric
32381ad6265SDimitry Andric // Returns the latency cost of a given instruction.
324bdd1243dSDimitry Andric std::optional<uint64_t> computeInstCost(const Instruction *I);
32581ad6265SDimitry Andric
32681ad6265SDimitry Andric // Returns the misprediction cost of a given select when converted to branch.
327*a58f00eaSDimitry Andric Scaled64 getMispredictionCost(const SelectLike SI, const Scaled64 CondCost);
32881ad6265SDimitry Andric
32981ad6265SDimitry Andric // Returns the cost of a branch when the prediction is correct.
33081ad6265SDimitry Andric Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
331*a58f00eaSDimitry Andric const SelectLike SI);
33281ad6265SDimitry Andric
33381ad6265SDimitry Andric // Returns true if the target architecture supports lowering a given select.
334*a58f00eaSDimitry Andric bool isSelectKindSupported(const SelectLike SI);
33581ad6265SDimitry Andric };
336c9157d92SDimitry Andric
337c9157d92SDimitry Andric class SelectOptimize : public FunctionPass {
338c9157d92SDimitry Andric SelectOptimizeImpl Impl;
339c9157d92SDimitry Andric
340c9157d92SDimitry Andric public:
341c9157d92SDimitry Andric static char ID;
342c9157d92SDimitry Andric
SelectOptimize()343c9157d92SDimitry Andric SelectOptimize() : FunctionPass(ID) {
344c9157d92SDimitry Andric initializeSelectOptimizePass(*PassRegistry::getPassRegistry());
345c9157d92SDimitry Andric }
346c9157d92SDimitry Andric
runOnFunction(Function & F)347c9157d92SDimitry Andric bool runOnFunction(Function &F) override {
348c9157d92SDimitry Andric return Impl.runOnFunction(F, *this);
349c9157d92SDimitry Andric }
350c9157d92SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const351c9157d92SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
352c9157d92SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>();
353c9157d92SDimitry Andric AU.addRequired<TargetPassConfig>();
354c9157d92SDimitry Andric AU.addRequired<TargetTransformInfoWrapperPass>();
355c9157d92SDimitry Andric AU.addRequired<LoopInfoWrapperPass>();
356c9157d92SDimitry Andric AU.addRequired<BlockFrequencyInfoWrapperPass>();
357c9157d92SDimitry Andric AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
358c9157d92SDimitry Andric }
359c9157d92SDimitry Andric };
360c9157d92SDimitry Andric
36181ad6265SDimitry Andric } // namespace
36281ad6265SDimitry Andric
run(Function & F,FunctionAnalysisManager & FAM)363c9157d92SDimitry Andric PreservedAnalyses SelectOptimizePass::run(Function &F,
364c9157d92SDimitry Andric FunctionAnalysisManager &FAM) {
365c9157d92SDimitry Andric SelectOptimizeImpl Impl(TM);
366c9157d92SDimitry Andric return Impl.run(F, FAM);
367c9157d92SDimitry Andric }
368c9157d92SDimitry Andric
36981ad6265SDimitry Andric char SelectOptimize::ID = 0;
37081ad6265SDimitry Andric
37181ad6265SDimitry Andric INITIALIZE_PASS_BEGIN(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
37281ad6265SDimitry Andric false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)37381ad6265SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
37481ad6265SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
37581ad6265SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
37681ad6265SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
377c9157d92SDimitry Andric INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
37881ad6265SDimitry Andric INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
37981ad6265SDimitry Andric INITIALIZE_PASS_END(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
38081ad6265SDimitry Andric false)
38181ad6265SDimitry Andric
38281ad6265SDimitry Andric FunctionPass *llvm::createSelectOptimizePass() { return new SelectOptimize(); }
38381ad6265SDimitry Andric
run(Function & F,FunctionAnalysisManager & FAM)384c9157d92SDimitry Andric PreservedAnalyses SelectOptimizeImpl::run(Function &F,
385c9157d92SDimitry Andric FunctionAnalysisManager &FAM) {
38681ad6265SDimitry Andric TSI = TM->getSubtargetImpl(F);
38781ad6265SDimitry Andric TLI = TSI->getTargetLowering();
38881ad6265SDimitry Andric
389c9157d92SDimitry Andric // If none of the select types are supported then skip this pass.
390c9157d92SDimitry Andric // This is an optimization pass. Legality issues will be handled by
391c9157d92SDimitry Andric // instruction selection.
392c9157d92SDimitry Andric if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) &&
393c9157d92SDimitry Andric !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) &&
394c9157d92SDimitry Andric !TLI->isSelectSupported(TargetLowering::VectorMaskSelect))
395c9157d92SDimitry Andric return PreservedAnalyses::all();
396c9157d92SDimitry Andric
397c9157d92SDimitry Andric TTI = &FAM.getResult<TargetIRAnalysis>(F);
398c9157d92SDimitry Andric if (!TTI->enableSelectOptimize())
399c9157d92SDimitry Andric return PreservedAnalyses::all();
400c9157d92SDimitry Andric
401c9157d92SDimitry Andric PSI = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F)
402c9157d92SDimitry Andric .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
403c9157d92SDimitry Andric assert(PSI && "This pass requires module analysis pass `profile-summary`!");
404c9157d92SDimitry Andric BFI = &FAM.getResult<BlockFrequencyAnalysis>(F);
405c9157d92SDimitry Andric
406c9157d92SDimitry Andric // When optimizing for size, selects are preferable over branches.
407c9157d92SDimitry Andric if (F.hasOptSize() || llvm::shouldOptimizeForSize(&F, PSI, BFI))
408c9157d92SDimitry Andric return PreservedAnalyses::all();
409c9157d92SDimitry Andric
410c9157d92SDimitry Andric LI = &FAM.getResult<LoopAnalysis>(F);
411c9157d92SDimitry Andric ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
412c9157d92SDimitry Andric TSchedModel.init(TSI);
413c9157d92SDimitry Andric
414c9157d92SDimitry Andric bool Changed = optimizeSelects(F);
415c9157d92SDimitry Andric return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
416c9157d92SDimitry Andric }
417c9157d92SDimitry Andric
runOnFunction(Function & F,Pass & P)418c9157d92SDimitry Andric bool SelectOptimizeImpl::runOnFunction(Function &F, Pass &P) {
419c9157d92SDimitry Andric TM = &P.getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
420c9157d92SDimitry Andric TSI = TM->getSubtargetImpl(F);
421c9157d92SDimitry Andric TLI = TSI->getTargetLowering();
422c9157d92SDimitry Andric
423c9157d92SDimitry Andric // If none of the select types are supported then skip this pass.
42481ad6265SDimitry Andric // This is an optimization pass. Legality issues will be handled by
42581ad6265SDimitry Andric // instruction selection.
42681ad6265SDimitry Andric if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) &&
42781ad6265SDimitry Andric !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) &&
42881ad6265SDimitry Andric !TLI->isSelectSupported(TargetLowering::VectorMaskSelect))
42981ad6265SDimitry Andric return false;
43081ad6265SDimitry Andric
431c9157d92SDimitry Andric TTI = &P.getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
432bdd1243dSDimitry Andric
433bdd1243dSDimitry Andric if (!TTI->enableSelectOptimize())
434bdd1243dSDimitry Andric return false;
435bdd1243dSDimitry Andric
436c9157d92SDimitry Andric LI = &P.getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
437c9157d92SDimitry Andric BFI = &P.getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
438c9157d92SDimitry Andric PSI = &P.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
439c9157d92SDimitry Andric ORE = &P.getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
44081ad6265SDimitry Andric TSchedModel.init(TSI);
44181ad6265SDimitry Andric
44281ad6265SDimitry Andric // When optimizing for size, selects are preferable over branches.
443c9157d92SDimitry Andric if (F.hasOptSize() || llvm::shouldOptimizeForSize(&F, PSI, BFI))
44481ad6265SDimitry Andric return false;
44581ad6265SDimitry Andric
44681ad6265SDimitry Andric return optimizeSelects(F);
44781ad6265SDimitry Andric }
44881ad6265SDimitry Andric
optimizeSelects(Function & F)449c9157d92SDimitry Andric bool SelectOptimizeImpl::optimizeSelects(Function &F) {
45081ad6265SDimitry Andric // Determine for which select groups it is profitable converting to branches.
45181ad6265SDimitry Andric SelectGroups ProfSIGroups;
45281ad6265SDimitry Andric // Base heuristics apply only to non-loops and outer loops.
45381ad6265SDimitry Andric optimizeSelectsBase(F, ProfSIGroups);
45481ad6265SDimitry Andric // Separate heuristics for inner-most loops.
45581ad6265SDimitry Andric optimizeSelectsInnerLoops(F, ProfSIGroups);
45681ad6265SDimitry Andric
45781ad6265SDimitry Andric // Convert to branches the select groups that were deemed
45881ad6265SDimitry Andric // profitable-to-convert.
45981ad6265SDimitry Andric convertProfitableSIGroups(ProfSIGroups);
46081ad6265SDimitry Andric
46181ad6265SDimitry Andric // Code modified if at least one select group was converted.
46281ad6265SDimitry Andric return !ProfSIGroups.empty();
46381ad6265SDimitry Andric }
46481ad6265SDimitry Andric
optimizeSelectsBase(Function & F,SelectGroups & ProfSIGroups)465c9157d92SDimitry Andric void SelectOptimizeImpl::optimizeSelectsBase(Function &F,
46681ad6265SDimitry Andric SelectGroups &ProfSIGroups) {
46781ad6265SDimitry Andric // Collect all the select groups.
46881ad6265SDimitry Andric SelectGroups SIGroups;
46981ad6265SDimitry Andric for (BasicBlock &BB : F) {
47081ad6265SDimitry Andric // Base heuristics apply only to non-loops and outer loops.
47181ad6265SDimitry Andric Loop *L = LI->getLoopFor(&BB);
47281ad6265SDimitry Andric if (L && L->isInnermost())
47381ad6265SDimitry Andric continue;
47481ad6265SDimitry Andric collectSelectGroups(BB, SIGroups);
47581ad6265SDimitry Andric }
47681ad6265SDimitry Andric
47781ad6265SDimitry Andric // Determine for which select groups it is profitable converting to branches.
47881ad6265SDimitry Andric findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
47981ad6265SDimitry Andric }
48081ad6265SDimitry Andric
optimizeSelectsInnerLoops(Function & F,SelectGroups & ProfSIGroups)481c9157d92SDimitry Andric void SelectOptimizeImpl::optimizeSelectsInnerLoops(Function &F,
48281ad6265SDimitry Andric SelectGroups &ProfSIGroups) {
48381ad6265SDimitry Andric SmallVector<Loop *, 4> Loops(LI->begin(), LI->end());
48481ad6265SDimitry Andric // Need to check size on each iteration as we accumulate child loops.
48581ad6265SDimitry Andric for (unsigned long i = 0; i < Loops.size(); ++i)
48681ad6265SDimitry Andric for (Loop *ChildL : Loops[i]->getSubLoops())
48781ad6265SDimitry Andric Loops.push_back(ChildL);
48881ad6265SDimitry Andric
48981ad6265SDimitry Andric for (Loop *L : Loops) {
49081ad6265SDimitry Andric if (!L->isInnermost())
49181ad6265SDimitry Andric continue;
49281ad6265SDimitry Andric
49381ad6265SDimitry Andric SelectGroups SIGroups;
49481ad6265SDimitry Andric for (BasicBlock *BB : L->getBlocks())
49581ad6265SDimitry Andric collectSelectGroups(*BB, SIGroups);
49681ad6265SDimitry Andric
49781ad6265SDimitry Andric findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
49881ad6265SDimitry Andric }
49981ad6265SDimitry Andric }
50081ad6265SDimitry Andric
50181ad6265SDimitry Andric /// If \p isTrue is true, return the true value of \p SI, otherwise return
50281ad6265SDimitry Andric /// false value of \p SI. If the true/false value of \p SI is defined by any
50381ad6265SDimitry Andric /// select instructions in \p Selects, look through the defining select
50481ad6265SDimitry Andric /// instruction until the true/false value is not defined in \p Selects.
50581ad6265SDimitry Andric static Value *
getTrueOrFalseValue(SelectOptimizeImpl::SelectLike SI,bool isTrue,const SmallPtrSet<const Instruction *,2> & Selects,IRBuilder<> & IB)506*a58f00eaSDimitry Andric getTrueOrFalseValue(SelectOptimizeImpl::SelectLike SI, bool isTrue,
507*a58f00eaSDimitry Andric const SmallPtrSet<const Instruction *, 2> &Selects,
508*a58f00eaSDimitry Andric IRBuilder<> &IB) {
50981ad6265SDimitry Andric Value *V = nullptr;
510*a58f00eaSDimitry Andric for (SelectInst *DefSI = dyn_cast<SelectInst>(SI.getI());
511*a58f00eaSDimitry Andric DefSI != nullptr && Selects.count(DefSI);
51281ad6265SDimitry Andric DefSI = dyn_cast<SelectInst>(V)) {
513*a58f00eaSDimitry Andric assert(DefSI->getCondition() == SI.getCondition() &&
51481ad6265SDimitry Andric "The condition of DefSI does not match with SI");
51581ad6265SDimitry Andric V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
51681ad6265SDimitry Andric }
517*a58f00eaSDimitry Andric
518*a58f00eaSDimitry Andric if (isa<BinaryOperator>(SI.getI())) {
519*a58f00eaSDimitry Andric assert(SI.getI()->getOpcode() == Instruction::Or &&
520*a58f00eaSDimitry Andric "Only currently handling Or instructions.");
521*a58f00eaSDimitry Andric V = SI.getFalseValue();
522*a58f00eaSDimitry Andric if (isTrue)
523*a58f00eaSDimitry Andric V = IB.CreateOr(V, ConstantInt::get(V->getType(), 1));
524*a58f00eaSDimitry Andric }
525*a58f00eaSDimitry Andric
52681ad6265SDimitry Andric assert(V && "Failed to get select true/false value");
52781ad6265SDimitry Andric return V;
52881ad6265SDimitry Andric }
52981ad6265SDimitry Andric
convertProfitableSIGroups(SelectGroups & ProfSIGroups)530c9157d92SDimitry Andric void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
53181ad6265SDimitry Andric for (SelectGroup &ASI : ProfSIGroups) {
53281ad6265SDimitry Andric // The code transformation here is a modified version of the sinking
53381ad6265SDimitry Andric // transformation in CodeGenPrepare::optimizeSelectInst with a more
53481ad6265SDimitry Andric // aggressive strategy of which instructions to sink.
53581ad6265SDimitry Andric //
53681ad6265SDimitry Andric // TODO: eliminate the redundancy of logic transforming selects to branches
53781ad6265SDimitry Andric // by removing CodeGenPrepare::optimizeSelectInst and optimizing here
53881ad6265SDimitry Andric // selects for all cases (with and without profile information).
53981ad6265SDimitry Andric
54081ad6265SDimitry Andric // Transform a sequence like this:
54181ad6265SDimitry Andric // start:
54281ad6265SDimitry Andric // %cmp = cmp uge i32 %a, %b
54381ad6265SDimitry Andric // %sel = select i1 %cmp, i32 %c, i32 %d
54481ad6265SDimitry Andric //
54581ad6265SDimitry Andric // Into:
54681ad6265SDimitry Andric // start:
54781ad6265SDimitry Andric // %cmp = cmp uge i32 %a, %b
54881ad6265SDimitry Andric // %cmp.frozen = freeze %cmp
54981ad6265SDimitry Andric // br i1 %cmp.frozen, label %select.true, label %select.false
55081ad6265SDimitry Andric // select.true:
55181ad6265SDimitry Andric // br label %select.end
55281ad6265SDimitry Andric // select.false:
55381ad6265SDimitry Andric // br label %select.end
55481ad6265SDimitry Andric // select.end:
55581ad6265SDimitry Andric // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
55681ad6265SDimitry Andric //
55781ad6265SDimitry Andric // %cmp should be frozen, otherwise it may introduce undefined behavior.
55881ad6265SDimitry Andric // In addition, we may sink instructions that produce %c or %d into the
55981ad6265SDimitry Andric // destination(s) of the new branch.
56081ad6265SDimitry Andric // If the true or false blocks do not contain a sunken instruction, that
56181ad6265SDimitry Andric // block and its branch may be optimized away. In that case, one side of the
56281ad6265SDimitry Andric // first branch will point directly to select.end, and the corresponding PHI
56381ad6265SDimitry Andric // predecessor block will be the start block.
56481ad6265SDimitry Andric
56581ad6265SDimitry Andric // Find all the instructions that can be soundly sunk to the true/false
56681ad6265SDimitry Andric // blocks. These are instructions that are computed solely for producing the
56781ad6265SDimitry Andric // operands of the select instructions in the group and can be sunk without
56881ad6265SDimitry Andric // breaking the semantics of the LLVM IR (e.g., cannot sink instructions
56981ad6265SDimitry Andric // with side effects).
57081ad6265SDimitry Andric SmallVector<std::stack<Instruction *>, 2> TrueSlices, FalseSlices;
57181ad6265SDimitry Andric typedef std::stack<Instruction *>::size_type StackSizeType;
57281ad6265SDimitry Andric StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0;
573*a58f00eaSDimitry Andric for (SelectLike SI : ASI) {
57481ad6265SDimitry Andric // For each select, compute the sinkable dependence chains of the true and
57581ad6265SDimitry Andric // false operands.
576*a58f00eaSDimitry Andric if (auto *TI = dyn_cast_or_null<Instruction>(SI.getTrueValue())) {
57781ad6265SDimitry Andric std::stack<Instruction *> TrueSlice;
578*a58f00eaSDimitry Andric getExclBackwardsSlice(TI, TrueSlice, SI.getI(), true);
57981ad6265SDimitry Andric maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size());
58081ad6265SDimitry Andric TrueSlices.push_back(TrueSlice);
58181ad6265SDimitry Andric }
582*a58f00eaSDimitry Andric if (auto *FI = dyn_cast_or_null<Instruction>(SI.getFalseValue())) {
583*a58f00eaSDimitry Andric if (isa<SelectInst>(SI.getI()) || !FI->hasOneUse()) {
58481ad6265SDimitry Andric std::stack<Instruction *> FalseSlice;
585*a58f00eaSDimitry Andric getExclBackwardsSlice(FI, FalseSlice, SI.getI(), true);
58681ad6265SDimitry Andric maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size());
58781ad6265SDimitry Andric FalseSlices.push_back(FalseSlice);
58881ad6265SDimitry Andric }
58981ad6265SDimitry Andric }
590*a58f00eaSDimitry Andric }
59181ad6265SDimitry Andric // In the case of multiple select instructions in the same group, the order
59281ad6265SDimitry Andric // of non-dependent instructions (instructions of different dependence
59381ad6265SDimitry Andric // slices) in the true/false blocks appears to affect performance.
59481ad6265SDimitry Andric // Interleaving the slices seems to experimentally be the optimal approach.
59581ad6265SDimitry Andric // This interleaving scheduling allows for more ILP (with a natural downside
59681ad6265SDimitry Andric // of increasing a bit register pressure) compared to a simple ordering of
59781ad6265SDimitry Andric // one whole chain after another. One would expect that this ordering would
59881ad6265SDimitry Andric // not matter since the scheduling in the backend of the compiler would
59981ad6265SDimitry Andric // take care of it, but apparently the scheduler fails to deliver optimal
60081ad6265SDimitry Andric // ILP with a naive ordering here.
60181ad6265SDimitry Andric SmallVector<Instruction *, 2> TrueSlicesInterleaved, FalseSlicesInterleaved;
60281ad6265SDimitry Andric for (StackSizeType IS = 0; IS < maxTrueSliceLen; ++IS) {
60381ad6265SDimitry Andric for (auto &S : TrueSlices) {
60481ad6265SDimitry Andric if (!S.empty()) {
60581ad6265SDimitry Andric TrueSlicesInterleaved.push_back(S.top());
60681ad6265SDimitry Andric S.pop();
60781ad6265SDimitry Andric }
60881ad6265SDimitry Andric }
60981ad6265SDimitry Andric }
61081ad6265SDimitry Andric for (StackSizeType IS = 0; IS < maxFalseSliceLen; ++IS) {
61181ad6265SDimitry Andric for (auto &S : FalseSlices) {
61281ad6265SDimitry Andric if (!S.empty()) {
61381ad6265SDimitry Andric FalseSlicesInterleaved.push_back(S.top());
61481ad6265SDimitry Andric S.pop();
61581ad6265SDimitry Andric }
61681ad6265SDimitry Andric }
61781ad6265SDimitry Andric }
61881ad6265SDimitry Andric
61981ad6265SDimitry Andric // We split the block containing the select(s) into two blocks.
620*a58f00eaSDimitry Andric SelectLike SI = ASI.front();
621*a58f00eaSDimitry Andric SelectLike LastSI = ASI.back();
622*a58f00eaSDimitry Andric BasicBlock *StartBlock = SI.getI()->getParent();
623*a58f00eaSDimitry Andric BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI.getI()));
62481ad6265SDimitry Andric BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
625c9157d92SDimitry Andric BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
62681ad6265SDimitry Andric // Delete the unconditional branch that was just created by the split.
62781ad6265SDimitry Andric StartBlock->getTerminator()->eraseFromParent();
62881ad6265SDimitry Andric
62981ad6265SDimitry Andric // Move any debug/pseudo instructions that were in-between the select
63081ad6265SDimitry Andric // group to the newly-created end block.
63181ad6265SDimitry Andric SmallVector<Instruction *, 2> DebugPseudoINS;
632*a58f00eaSDimitry Andric auto DIt = SI.getI()->getIterator();
633*a58f00eaSDimitry Andric while (&*DIt != LastSI.getI()) {
63481ad6265SDimitry Andric if (DIt->isDebugOrPseudoInst())
63581ad6265SDimitry Andric DebugPseudoINS.push_back(&*DIt);
63681ad6265SDimitry Andric DIt++;
63781ad6265SDimitry Andric }
638fcaf7f86SDimitry Andric for (auto *DI : DebugPseudoINS) {
639c9157d92SDimitry Andric DI->moveBeforePreserving(&*EndBlock->getFirstInsertionPt());
64081ad6265SDimitry Andric }
64181ad6265SDimitry Andric
642*a58f00eaSDimitry Andric // Duplicate implementation for DPValues, the non-instruction debug-info
643*a58f00eaSDimitry Andric // record. Helper lambda for moving DPValues to the end block.
644*a58f00eaSDimitry Andric auto TransferDPValues = [&](Instruction &I) {
645*a58f00eaSDimitry Andric for (auto &DPValue : llvm::make_early_inc_range(I.getDbgValueRange())) {
646*a58f00eaSDimitry Andric DPValue.removeFromParent();
647*a58f00eaSDimitry Andric EndBlock->insertDPValueBefore(&DPValue,
648*a58f00eaSDimitry Andric EndBlock->getFirstInsertionPt());
649*a58f00eaSDimitry Andric }
650*a58f00eaSDimitry Andric };
651*a58f00eaSDimitry Andric
652*a58f00eaSDimitry Andric // Iterate over all instructions in between SI and LastSI, not including
653*a58f00eaSDimitry Andric // SI itself. These are all the variable assignments that happen "in the
654*a58f00eaSDimitry Andric // middle" of the select group.
655*a58f00eaSDimitry Andric auto R = make_range(std::next(SI.getI()->getIterator()),
656*a58f00eaSDimitry Andric std::next(LastSI.getI()->getIterator()));
657*a58f00eaSDimitry Andric llvm::for_each(R, TransferDPValues);
658*a58f00eaSDimitry Andric
65981ad6265SDimitry Andric // These are the new basic blocks for the conditional branch.
66081ad6265SDimitry Andric // At least one will become an actual new basic block.
66181ad6265SDimitry Andric BasicBlock *TrueBlock = nullptr, *FalseBlock = nullptr;
66281ad6265SDimitry Andric BranchInst *TrueBranch = nullptr, *FalseBranch = nullptr;
66381ad6265SDimitry Andric if (!TrueSlicesInterleaved.empty()) {
664*a58f00eaSDimitry Andric TrueBlock = BasicBlock::Create(EndBlock->getContext(), "select.true.sink",
66581ad6265SDimitry Andric EndBlock->getParent(), EndBlock);
66681ad6265SDimitry Andric TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
667*a58f00eaSDimitry Andric TrueBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
66881ad6265SDimitry Andric for (Instruction *TrueInst : TrueSlicesInterleaved)
66981ad6265SDimitry Andric TrueInst->moveBefore(TrueBranch);
67081ad6265SDimitry Andric }
67181ad6265SDimitry Andric if (!FalseSlicesInterleaved.empty()) {
672*a58f00eaSDimitry Andric FalseBlock =
673*a58f00eaSDimitry Andric BasicBlock::Create(EndBlock->getContext(), "select.false.sink",
67481ad6265SDimitry Andric EndBlock->getParent(), EndBlock);
67581ad6265SDimitry Andric FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
676*a58f00eaSDimitry Andric FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
67781ad6265SDimitry Andric for (Instruction *FalseInst : FalseSlicesInterleaved)
67881ad6265SDimitry Andric FalseInst->moveBefore(FalseBranch);
67981ad6265SDimitry Andric }
68081ad6265SDimitry Andric // If there was nothing to sink, then arbitrarily choose the 'false' side
68181ad6265SDimitry Andric // for a new input value to the PHI.
68281ad6265SDimitry Andric if (TrueBlock == FalseBlock) {
68381ad6265SDimitry Andric assert(TrueBlock == nullptr &&
68481ad6265SDimitry Andric "Unexpected basic block transform while optimizing select");
68581ad6265SDimitry Andric
686*a58f00eaSDimitry Andric FalseBlock = BasicBlock::Create(StartBlock->getContext(), "select.false",
68781ad6265SDimitry Andric EndBlock->getParent(), EndBlock);
68881ad6265SDimitry Andric auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
689*a58f00eaSDimitry Andric FalseBranch->setDebugLoc(SI.getI()->getDebugLoc());
69081ad6265SDimitry Andric }
69181ad6265SDimitry Andric
69281ad6265SDimitry Andric // Insert the real conditional branch based on the original condition.
69381ad6265SDimitry Andric // If we did not create a new block for one of the 'true' or 'false' paths
69481ad6265SDimitry Andric // of the condition, it means that side of the branch goes to the end block
69581ad6265SDimitry Andric // directly and the path originates from the start block from the point of
69681ad6265SDimitry Andric // view of the new PHI.
69781ad6265SDimitry Andric BasicBlock *TT, *FT;
69881ad6265SDimitry Andric if (TrueBlock == nullptr) {
69981ad6265SDimitry Andric TT = EndBlock;
70081ad6265SDimitry Andric FT = FalseBlock;
70181ad6265SDimitry Andric TrueBlock = StartBlock;
70281ad6265SDimitry Andric } else if (FalseBlock == nullptr) {
70381ad6265SDimitry Andric TT = TrueBlock;
70481ad6265SDimitry Andric FT = EndBlock;
70581ad6265SDimitry Andric FalseBlock = StartBlock;
70681ad6265SDimitry Andric } else {
70781ad6265SDimitry Andric TT = TrueBlock;
70881ad6265SDimitry Andric FT = FalseBlock;
70981ad6265SDimitry Andric }
710*a58f00eaSDimitry Andric IRBuilder<> IB(SI.getI());
711*a58f00eaSDimitry Andric auto *CondFr = IB.CreateFreeze(SI.getCondition(),
712*a58f00eaSDimitry Andric SI.getCondition()->getName() + ".frozen");
71381ad6265SDimitry Andric
71481ad6265SDimitry Andric SmallPtrSet<const Instruction *, 2> INS;
715*a58f00eaSDimitry Andric for (auto SI : ASI)
716*a58f00eaSDimitry Andric INS.insert(SI.getI());
717*a58f00eaSDimitry Andric
71881ad6265SDimitry Andric // Use reverse iterator because later select may use the value of the
71981ad6265SDimitry Andric // earlier select, and we need to propagate value through earlier select
72081ad6265SDimitry Andric // to get the PHI operand.
72181ad6265SDimitry Andric for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
722*a58f00eaSDimitry Andric SelectLike SI = *It;
72381ad6265SDimitry Andric // The select itself is replaced with a PHI Node.
724*a58f00eaSDimitry Andric PHINode *PN = PHINode::Create(SI.getType(), 2, "");
725c9157d92SDimitry Andric PN->insertBefore(EndBlock->begin());
726*a58f00eaSDimitry Andric PN->takeName(SI.getI());
727*a58f00eaSDimitry Andric PN->addIncoming(getTrueOrFalseValue(SI, true, INS, IB), TrueBlock);
728*a58f00eaSDimitry Andric PN->addIncoming(getTrueOrFalseValue(SI, false, INS, IB), FalseBlock);
729*a58f00eaSDimitry Andric PN->setDebugLoc(SI.getI()->getDebugLoc());
730*a58f00eaSDimitry Andric SI.getI()->replaceAllUsesWith(PN);
731*a58f00eaSDimitry Andric INS.erase(SI.getI());
73281ad6265SDimitry Andric ++NumSelectsConverted;
73381ad6265SDimitry Andric }
734*a58f00eaSDimitry Andric IB.CreateCondBr(CondFr, TT, FT, SI.getI());
735*a58f00eaSDimitry Andric
736*a58f00eaSDimitry Andric // Remove the old select instructions, now that they are not longer used.
737*a58f00eaSDimitry Andric for (auto SI : ASI)
738*a58f00eaSDimitry Andric SI.getI()->eraseFromParent();
73981ad6265SDimitry Andric }
74081ad6265SDimitry Andric }
74181ad6265SDimitry Andric
collectSelectGroups(BasicBlock & BB,SelectGroups & SIGroups)742c9157d92SDimitry Andric void SelectOptimizeImpl::collectSelectGroups(BasicBlock &BB,
74381ad6265SDimitry Andric SelectGroups &SIGroups) {
74481ad6265SDimitry Andric BasicBlock::iterator BBIt = BB.begin();
74581ad6265SDimitry Andric while (BBIt != BB.end()) {
74681ad6265SDimitry Andric Instruction *I = &*BBIt++;
747*a58f00eaSDimitry Andric if (SelectLike SI = SelectLike::match(I)) {
748*a58f00eaSDimitry Andric if (!TTI->shouldTreatInstructionLikeSelect(I))
749bdd1243dSDimitry Andric continue;
750bdd1243dSDimitry Andric
75181ad6265SDimitry Andric SelectGroup SIGroup;
75281ad6265SDimitry Andric SIGroup.push_back(SI);
75381ad6265SDimitry Andric while (BBIt != BB.end()) {
75481ad6265SDimitry Andric Instruction *NI = &*BBIt;
75581ad6265SDimitry Andric // Debug/pseudo instructions should be skipped and not prevent the
75681ad6265SDimitry Andric // formation of a select group.
757*a58f00eaSDimitry Andric if (NI->isDebugOrPseudoInst()) {
758*a58f00eaSDimitry Andric ++BBIt;
759*a58f00eaSDimitry Andric continue;
76081ad6265SDimitry Andric }
761*a58f00eaSDimitry Andric // We only allow selects in the same group, not other select-like
762*a58f00eaSDimitry Andric // instructions.
763*a58f00eaSDimitry Andric if (!isa<SelectInst>(NI))
764*a58f00eaSDimitry Andric break;
765*a58f00eaSDimitry Andric
766*a58f00eaSDimitry Andric SelectLike NSI = SelectLike::match(NI);
767*a58f00eaSDimitry Andric if (NSI && SI.getCondition() == NSI.getCondition()) {
768*a58f00eaSDimitry Andric SIGroup.push_back(NSI);
769*a58f00eaSDimitry Andric } else
770*a58f00eaSDimitry Andric break;
77181ad6265SDimitry Andric ++BBIt;
77281ad6265SDimitry Andric }
77381ad6265SDimitry Andric
77481ad6265SDimitry Andric // If the select type is not supported, no point optimizing it.
77581ad6265SDimitry Andric // Instruction selection will take care of it.
77681ad6265SDimitry Andric if (!isSelectKindSupported(SI))
77781ad6265SDimitry Andric continue;
77881ad6265SDimitry Andric
77981ad6265SDimitry Andric SIGroups.push_back(SIGroup);
78081ad6265SDimitry Andric }
78181ad6265SDimitry Andric }
78281ad6265SDimitry Andric }
78381ad6265SDimitry Andric
findProfitableSIGroupsBase(SelectGroups & SIGroups,SelectGroups & ProfSIGroups)784c9157d92SDimitry Andric void SelectOptimizeImpl::findProfitableSIGroupsBase(
785c9157d92SDimitry Andric SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
78681ad6265SDimitry Andric for (SelectGroup &ASI : SIGroups) {
78781ad6265SDimitry Andric ++NumSelectOptAnalyzed;
78881ad6265SDimitry Andric if (isConvertToBranchProfitableBase(ASI))
78981ad6265SDimitry Andric ProfSIGroups.push_back(ASI);
79081ad6265SDimitry Andric }
79181ad6265SDimitry Andric }
79281ad6265SDimitry Andric
EmitAndPrintRemark(OptimizationRemarkEmitter * ORE,DiagnosticInfoOptimizationBase & Rem)793bdd1243dSDimitry Andric static void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE,
794bdd1243dSDimitry Andric DiagnosticInfoOptimizationBase &Rem) {
795bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << Rem.getMsg() << "\n");
796bdd1243dSDimitry Andric ORE->emit(Rem);
797bdd1243dSDimitry Andric }
798bdd1243dSDimitry Andric
findProfitableSIGroupsInnerLoops(const Loop * L,SelectGroups & SIGroups,SelectGroups & ProfSIGroups)799c9157d92SDimitry Andric void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops(
80081ad6265SDimitry Andric const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
80181ad6265SDimitry Andric NumSelectOptAnalyzed += SIGroups.size();
80281ad6265SDimitry Andric // For each select group in an inner-most loop,
80381ad6265SDimitry Andric // a branch is more preferable than a select/conditional-move if:
80481ad6265SDimitry Andric // i) conversion to branches for all the select groups of the loop satisfies
80581ad6265SDimitry Andric // loop-level heuristics including reducing the loop's critical path by
806c9157d92SDimitry Andric // some threshold (see SelectOptimizeImpl::checkLoopHeuristics); and
80781ad6265SDimitry Andric // ii) the total cost of the select group is cheaper with a branch compared
80881ad6265SDimitry Andric // to its predicated version. The cost is in terms of latency and the cost
80981ad6265SDimitry Andric // of a select group is the cost of its most expensive select instruction
81081ad6265SDimitry Andric // (assuming infinite resources and thus fully leveraging available ILP).
81181ad6265SDimitry Andric
81281ad6265SDimitry Andric DenseMap<const Instruction *, CostInfo> InstCostMap;
81381ad6265SDimitry Andric CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
81481ad6265SDimitry Andric {Scaled64::getZero(), Scaled64::getZero()}};
81581ad6265SDimitry Andric if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
81681ad6265SDimitry Andric !checkLoopHeuristics(L, LoopCost)) {
81781ad6265SDimitry Andric return;
81881ad6265SDimitry Andric }
81981ad6265SDimitry Andric
82081ad6265SDimitry Andric for (SelectGroup &ASI : SIGroups) {
82181ad6265SDimitry Andric // Assuming infinite resources, the cost of a group of instructions is the
82281ad6265SDimitry Andric // cost of the most expensive instruction of the group.
82381ad6265SDimitry Andric Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
824*a58f00eaSDimitry Andric for (SelectLike SI : ASI) {
825*a58f00eaSDimitry Andric SelectCost = std::max(SelectCost, InstCostMap[SI.getI()].PredCost);
826*a58f00eaSDimitry Andric BranchCost = std::max(BranchCost, InstCostMap[SI.getI()].NonPredCost);
82781ad6265SDimitry Andric }
82881ad6265SDimitry Andric if (BranchCost < SelectCost) {
829*a58f00eaSDimitry Andric OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", ASI.front().getI());
83081ad6265SDimitry Andric OR << "Profitable to convert to branch (loop analysis). BranchCost="
83181ad6265SDimitry Andric << BranchCost.toString() << ", SelectCost=" << SelectCost.toString()
83281ad6265SDimitry Andric << ". ";
833bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, OR);
83481ad6265SDimitry Andric ++NumSelectConvertedLoop;
83581ad6265SDimitry Andric ProfSIGroups.push_back(ASI);
83681ad6265SDimitry Andric } else {
837*a58f00eaSDimitry Andric OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
838*a58f00eaSDimitry Andric ASI.front().getI());
83981ad6265SDimitry Andric ORmiss << "Select is more profitable (loop analysis). BranchCost="
84081ad6265SDimitry Andric << BranchCost.toString()
84181ad6265SDimitry Andric << ", SelectCost=" << SelectCost.toString() << ". ";
842bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmiss);
84381ad6265SDimitry Andric }
84481ad6265SDimitry Andric }
84581ad6265SDimitry Andric }
84681ad6265SDimitry Andric
isConvertToBranchProfitableBase(const SelectGroup & ASI)847c9157d92SDimitry Andric bool SelectOptimizeImpl::isConvertToBranchProfitableBase(
848*a58f00eaSDimitry Andric const SelectGroup &ASI) {
849*a58f00eaSDimitry Andric SelectLike SI = ASI.front();
850*a58f00eaSDimitry Andric LLVM_DEBUG(dbgs() << "Analyzing select group containing " << SI.getI()
851*a58f00eaSDimitry Andric << "\n");
852*a58f00eaSDimitry Andric OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", SI.getI());
853*a58f00eaSDimitry Andric OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", SI.getI());
85481ad6265SDimitry Andric
85581ad6265SDimitry Andric // Skip cold basic blocks. Better to optimize for size for cold blocks.
856*a58f00eaSDimitry Andric if (PSI->isColdBlock(SI.getI()->getParent(), BFI)) {
85781ad6265SDimitry Andric ++NumSelectColdBB;
85881ad6265SDimitry Andric ORmiss << "Not converted to branch because of cold basic block. ";
859bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmiss);
86081ad6265SDimitry Andric return false;
86181ad6265SDimitry Andric }
86281ad6265SDimitry Andric
86381ad6265SDimitry Andric // If unpredictable, branch form is less profitable.
864*a58f00eaSDimitry Andric if (SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) {
86581ad6265SDimitry Andric ++NumSelectUnPred;
86681ad6265SDimitry Andric ORmiss << "Not converted to branch because of unpredictable branch. ";
867bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmiss);
86881ad6265SDimitry Andric return false;
86981ad6265SDimitry Andric }
87081ad6265SDimitry Andric
87181ad6265SDimitry Andric // If highly predictable, branch form is more profitable, unless a
87281ad6265SDimitry Andric // predictable select is inexpensive in the target architecture.
87381ad6265SDimitry Andric if (isSelectHighlyPredictable(SI) && TLI->isPredictableSelectExpensive()) {
87481ad6265SDimitry Andric ++NumSelectConvertedHighPred;
87581ad6265SDimitry Andric OR << "Converted to branch because of highly predictable branch. ";
876bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, OR);
87781ad6265SDimitry Andric return true;
87881ad6265SDimitry Andric }
87981ad6265SDimitry Andric
88081ad6265SDimitry Andric // Look for expensive instructions in the cold operand's (if any) dependence
88181ad6265SDimitry Andric // slice of any of the selects in the group.
88281ad6265SDimitry Andric if (hasExpensiveColdOperand(ASI)) {
88381ad6265SDimitry Andric ++NumSelectConvertedExpColdOperand;
88481ad6265SDimitry Andric OR << "Converted to branch because of expensive cold operand.";
885bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, OR);
88681ad6265SDimitry Andric return true;
88781ad6265SDimitry Andric }
88881ad6265SDimitry Andric
88981ad6265SDimitry Andric ORmiss << "Not profitable to convert to branch (base heuristic).";
890bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmiss);
89181ad6265SDimitry Andric return false;
89281ad6265SDimitry Andric }
89381ad6265SDimitry Andric
divideNearest(InstructionCost Numerator,uint64_t Denominator)89481ad6265SDimitry Andric static InstructionCost divideNearest(InstructionCost Numerator,
89581ad6265SDimitry Andric uint64_t Denominator) {
89681ad6265SDimitry Andric return (Numerator + (Denominator / 2)) / Denominator;
89781ad6265SDimitry Andric }
89881ad6265SDimitry Andric
extractBranchWeights(const SelectOptimizeImpl::SelectLike SI,uint64_t & TrueVal,uint64_t & FalseVal)899*a58f00eaSDimitry Andric static bool extractBranchWeights(const SelectOptimizeImpl::SelectLike SI,
900*a58f00eaSDimitry Andric uint64_t &TrueVal, uint64_t &FalseVal) {
901*a58f00eaSDimitry Andric if (isa<SelectInst>(SI.getI()))
902*a58f00eaSDimitry Andric return extractBranchWeights(*SI.getI(), TrueVal, FalseVal);
903*a58f00eaSDimitry Andric return false;
904*a58f00eaSDimitry Andric }
905*a58f00eaSDimitry Andric
hasExpensiveColdOperand(const SelectGroup & ASI)906*a58f00eaSDimitry Andric bool SelectOptimizeImpl::hasExpensiveColdOperand(const SelectGroup &ASI) {
90781ad6265SDimitry Andric bool ColdOperand = false;
90881ad6265SDimitry Andric uint64_t TrueWeight, FalseWeight, TotalWeight;
909*a58f00eaSDimitry Andric if (extractBranchWeights(ASI.front(), TrueWeight, FalseWeight)) {
91081ad6265SDimitry Andric uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
91181ad6265SDimitry Andric TotalWeight = TrueWeight + FalseWeight;
91281ad6265SDimitry Andric // Is there a path with frequency <ColdOperandThreshold% (default:20%) ?
91381ad6265SDimitry Andric ColdOperand = TotalWeight * ColdOperandThreshold > 100 * MinWeight;
91481ad6265SDimitry Andric } else if (PSI->hasProfileSummary()) {
915*a58f00eaSDimitry Andric OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
916*a58f00eaSDimitry Andric ASI.front().getI());
91781ad6265SDimitry Andric ORmiss << "Profile data available but missing branch-weights metadata for "
91881ad6265SDimitry Andric "select instruction. ";
919bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmiss);
92081ad6265SDimitry Andric }
92181ad6265SDimitry Andric if (!ColdOperand)
92281ad6265SDimitry Andric return false;
92381ad6265SDimitry Andric // Check if the cold path's dependence slice is expensive for any of the
92481ad6265SDimitry Andric // selects of the group.
925*a58f00eaSDimitry Andric for (SelectLike SI : ASI) {
92681ad6265SDimitry Andric Instruction *ColdI = nullptr;
92781ad6265SDimitry Andric uint64_t HotWeight;
92881ad6265SDimitry Andric if (TrueWeight < FalseWeight) {
929*a58f00eaSDimitry Andric ColdI = dyn_cast_or_null<Instruction>(SI.getTrueValue());
93081ad6265SDimitry Andric HotWeight = FalseWeight;
93181ad6265SDimitry Andric } else {
932*a58f00eaSDimitry Andric ColdI = dyn_cast_or_null<Instruction>(SI.getFalseValue());
93381ad6265SDimitry Andric HotWeight = TrueWeight;
93481ad6265SDimitry Andric }
93581ad6265SDimitry Andric if (ColdI) {
93681ad6265SDimitry Andric std::stack<Instruction *> ColdSlice;
937*a58f00eaSDimitry Andric getExclBackwardsSlice(ColdI, ColdSlice, SI.getI());
93881ad6265SDimitry Andric InstructionCost SliceCost = 0;
93981ad6265SDimitry Andric while (!ColdSlice.empty()) {
94081ad6265SDimitry Andric SliceCost += TTI->getInstructionCost(ColdSlice.top(),
94181ad6265SDimitry Andric TargetTransformInfo::TCK_Latency);
94281ad6265SDimitry Andric ColdSlice.pop();
94381ad6265SDimitry Andric }
94481ad6265SDimitry Andric // The colder the cold value operand of the select is the more expensive
94581ad6265SDimitry Andric // the cmov becomes for computing the cold value operand every time. Thus,
94681ad6265SDimitry Andric // the colder the cold operand is the more its cost counts.
94781ad6265SDimitry Andric // Get nearest integer cost adjusted for coldness.
94881ad6265SDimitry Andric InstructionCost AdjSliceCost =
94981ad6265SDimitry Andric divideNearest(SliceCost * HotWeight, TotalWeight);
95081ad6265SDimitry Andric if (AdjSliceCost >=
95181ad6265SDimitry Andric ColdOperandMaxCostMultiplier * TargetTransformInfo::TCC_Expensive)
95281ad6265SDimitry Andric return true;
95381ad6265SDimitry Andric }
95481ad6265SDimitry Andric }
95581ad6265SDimitry Andric return false;
95681ad6265SDimitry Andric }
95781ad6265SDimitry Andric
958bdd1243dSDimitry Andric // Check if it is safe to move LoadI next to the SI.
959bdd1243dSDimitry Andric // Conservatively assume it is safe only if there is no instruction
960bdd1243dSDimitry Andric // modifying memory in-between the load and the select instruction.
isSafeToSinkLoad(Instruction * LoadI,Instruction * SI)961bdd1243dSDimitry Andric static bool isSafeToSinkLoad(Instruction *LoadI, Instruction *SI) {
962bdd1243dSDimitry Andric // Assume loads from different basic blocks are unsafe to move.
963bdd1243dSDimitry Andric if (LoadI->getParent() != SI->getParent())
964bdd1243dSDimitry Andric return false;
965bdd1243dSDimitry Andric auto It = LoadI->getIterator();
966bdd1243dSDimitry Andric while (&*It != SI) {
967bdd1243dSDimitry Andric if (It->mayWriteToMemory())
968bdd1243dSDimitry Andric return false;
969bdd1243dSDimitry Andric It++;
970bdd1243dSDimitry Andric }
971bdd1243dSDimitry Andric return true;
972bdd1243dSDimitry Andric }
973bdd1243dSDimitry Andric
97481ad6265SDimitry Andric // For a given source instruction, collect its backwards dependence slice
97581ad6265SDimitry Andric // consisting of instructions exclusively computed for the purpose of producing
97681ad6265SDimitry Andric // the operands of the source instruction. As an approximation
97781ad6265SDimitry Andric // (sufficiently-accurate in practice), we populate this set with the
97881ad6265SDimitry Andric // instructions of the backwards dependence slice that only have one-use and
97981ad6265SDimitry Andric // form an one-use chain that leads to the source instruction.
getExclBackwardsSlice(Instruction * I,std::stack<Instruction * > & Slice,Instruction * SI,bool ForSinking)980c9157d92SDimitry Andric void SelectOptimizeImpl::getExclBackwardsSlice(Instruction *I,
98181ad6265SDimitry Andric std::stack<Instruction *> &Slice,
982c9157d92SDimitry Andric Instruction *SI,
983c9157d92SDimitry Andric bool ForSinking) {
98481ad6265SDimitry Andric SmallPtrSet<Instruction *, 2> Visited;
98581ad6265SDimitry Andric std::queue<Instruction *> Worklist;
98681ad6265SDimitry Andric Worklist.push(I);
98781ad6265SDimitry Andric while (!Worklist.empty()) {
98881ad6265SDimitry Andric Instruction *II = Worklist.front();
98981ad6265SDimitry Andric Worklist.pop();
99081ad6265SDimitry Andric
99181ad6265SDimitry Andric // Avoid cycles.
99281ad6265SDimitry Andric if (!Visited.insert(II).second)
99381ad6265SDimitry Andric continue;
99481ad6265SDimitry Andric
99581ad6265SDimitry Andric if (!II->hasOneUse())
99681ad6265SDimitry Andric continue;
99781ad6265SDimitry Andric
99881ad6265SDimitry Andric // Cannot soundly sink instructions with side-effects.
99981ad6265SDimitry Andric // Terminator or phi instructions cannot be sunk.
100081ad6265SDimitry Andric // Avoid sinking other select instructions (should be handled separetely).
100181ad6265SDimitry Andric if (ForSinking && (II->isTerminator() || II->mayHaveSideEffects() ||
100281ad6265SDimitry Andric isa<SelectInst>(II) || isa<PHINode>(II)))
100381ad6265SDimitry Andric continue;
100481ad6265SDimitry Andric
1005bdd1243dSDimitry Andric // Avoid sinking loads in order not to skip state-modifying instructions,
1006bdd1243dSDimitry Andric // that may alias with the loaded address.
1007bdd1243dSDimitry Andric // Only allow sinking of loads within the same basic block that are
1008bdd1243dSDimitry Andric // conservatively proven to be safe.
1009bdd1243dSDimitry Andric if (ForSinking && II->mayReadFromMemory() && !isSafeToSinkLoad(II, SI))
1010bdd1243dSDimitry Andric continue;
1011bdd1243dSDimitry Andric
101281ad6265SDimitry Andric // Avoid considering instructions with less frequency than the source
101381ad6265SDimitry Andric // instruction (i.e., avoid colder code regions of the dependence slice).
101481ad6265SDimitry Andric if (BFI->getBlockFreq(II->getParent()) < BFI->getBlockFreq(I->getParent()))
101581ad6265SDimitry Andric continue;
101681ad6265SDimitry Andric
101781ad6265SDimitry Andric // Eligible one-use instruction added to the dependence slice.
101881ad6265SDimitry Andric Slice.push(II);
101981ad6265SDimitry Andric
102081ad6265SDimitry Andric // Explore all the operands of the current instruction to expand the slice.
102181ad6265SDimitry Andric for (unsigned k = 0; k < II->getNumOperands(); ++k)
102281ad6265SDimitry Andric if (auto *OpI = dyn_cast<Instruction>(II->getOperand(k)))
102381ad6265SDimitry Andric Worklist.push(OpI);
102481ad6265SDimitry Andric }
102581ad6265SDimitry Andric }
102681ad6265SDimitry Andric
isSelectHighlyPredictable(const SelectLike SI)1027*a58f00eaSDimitry Andric bool SelectOptimizeImpl::isSelectHighlyPredictable(const SelectLike SI) {
102881ad6265SDimitry Andric uint64_t TrueWeight, FalseWeight;
1029*a58f00eaSDimitry Andric if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
103081ad6265SDimitry Andric uint64_t Max = std::max(TrueWeight, FalseWeight);
103181ad6265SDimitry Andric uint64_t Sum = TrueWeight + FalseWeight;
103281ad6265SDimitry Andric if (Sum != 0) {
103381ad6265SDimitry Andric auto Probability = BranchProbability::getBranchProbability(Max, Sum);
103481ad6265SDimitry Andric if (Probability > TTI->getPredictableBranchThreshold())
103581ad6265SDimitry Andric return true;
103681ad6265SDimitry Andric }
103781ad6265SDimitry Andric }
103881ad6265SDimitry Andric return false;
103981ad6265SDimitry Andric }
104081ad6265SDimitry Andric
checkLoopHeuristics(const Loop * L,const CostInfo LoopCost[2])1041c9157d92SDimitry Andric bool SelectOptimizeImpl::checkLoopHeuristics(const Loop *L,
104281ad6265SDimitry Andric const CostInfo LoopCost[2]) {
104381ad6265SDimitry Andric // Loop-level checks to determine if a non-predicated version (with branches)
104481ad6265SDimitry Andric // of the loop is more profitable than its predicated version.
104581ad6265SDimitry Andric
104681ad6265SDimitry Andric if (DisableLoopLevelHeuristics)
104781ad6265SDimitry Andric return true;
104881ad6265SDimitry Andric
104981ad6265SDimitry Andric OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti",
105081ad6265SDimitry Andric L->getHeader()->getFirstNonPHI());
105181ad6265SDimitry Andric
105281ad6265SDimitry Andric if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
105381ad6265SDimitry Andric LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
105481ad6265SDimitry Andric ORmissL << "No select conversion in the loop due to no reduction of loop's "
105581ad6265SDimitry Andric "critical path. ";
1056bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmissL);
105781ad6265SDimitry Andric return false;
105881ad6265SDimitry Andric }
105981ad6265SDimitry Andric
106081ad6265SDimitry Andric Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
106181ad6265SDimitry Andric LoopCost[1].PredCost - LoopCost[1].NonPredCost};
106281ad6265SDimitry Andric
106381ad6265SDimitry Andric // Profitably converting to branches need to reduce the loop's critical path
106481ad6265SDimitry Andric // by at least some threshold (absolute gain of GainCycleThreshold cycles and
106581ad6265SDimitry Andric // relative gain of 12.5%).
106681ad6265SDimitry Andric if (Gain[1] < Scaled64::get(GainCycleThreshold) ||
106781ad6265SDimitry Andric Gain[1] * Scaled64::get(GainRelativeThreshold) < LoopCost[1].PredCost) {
106881ad6265SDimitry Andric Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
106981ad6265SDimitry Andric ORmissL << "No select conversion in the loop due to small reduction of "
107081ad6265SDimitry Andric "loop's critical path. Gain="
107181ad6265SDimitry Andric << Gain[1].toString()
107281ad6265SDimitry Andric << ", RelativeGain=" << RelativeGain.toString() << "%. ";
1073bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmissL);
107481ad6265SDimitry Andric return false;
107581ad6265SDimitry Andric }
107681ad6265SDimitry Andric
107781ad6265SDimitry Andric // If the loop's critical path involves loop-carried dependences, the gradient
107881ad6265SDimitry Andric // of the gain needs to be at least GainGradientThreshold% (defaults to 25%).
107981ad6265SDimitry Andric // This check ensures that the latency reduction for the loop's critical path
108081ad6265SDimitry Andric // keeps decreasing with sufficient rate beyond the two analyzed loop
108181ad6265SDimitry Andric // iterations.
108281ad6265SDimitry Andric if (Gain[1] > Gain[0]) {
108381ad6265SDimitry Andric Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
108481ad6265SDimitry Andric (LoopCost[1].PredCost - LoopCost[0].PredCost);
108581ad6265SDimitry Andric if (GradientGain < Scaled64::get(GainGradientThreshold)) {
108681ad6265SDimitry Andric ORmissL << "No select conversion in the loop due to small gradient gain. "
108781ad6265SDimitry Andric "GradientGain="
108881ad6265SDimitry Andric << GradientGain.toString() << "%. ";
1089bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmissL);
109081ad6265SDimitry Andric return false;
109181ad6265SDimitry Andric }
109281ad6265SDimitry Andric }
109381ad6265SDimitry Andric // If the gain decreases it is not profitable to convert.
109481ad6265SDimitry Andric else if (Gain[1] < Gain[0]) {
109581ad6265SDimitry Andric ORmissL
109681ad6265SDimitry Andric << "No select conversion in the loop due to negative gradient gain. ";
1097bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmissL);
109881ad6265SDimitry Andric return false;
109981ad6265SDimitry Andric }
110081ad6265SDimitry Andric
110181ad6265SDimitry Andric // Non-predicated version of the loop is more profitable than its
110281ad6265SDimitry Andric // predicated version.
110381ad6265SDimitry Andric return true;
110481ad6265SDimitry Andric }
110581ad6265SDimitry Andric
110681ad6265SDimitry Andric // Computes instruction and loop-critical-path costs for both the predicated
110781ad6265SDimitry Andric // and non-predicated version of the given loop.
110881ad6265SDimitry Andric // Returns false if unable to compute these costs due to invalid cost of loop
110981ad6265SDimitry Andric // instruction(s).
computeLoopCosts(const Loop * L,const SelectGroups & SIGroups,DenseMap<const Instruction *,CostInfo> & InstCostMap,CostInfo * LoopCost)1110c9157d92SDimitry Andric bool SelectOptimizeImpl::computeLoopCosts(
111181ad6265SDimitry Andric const Loop *L, const SelectGroups &SIGroups,
111281ad6265SDimitry Andric DenseMap<const Instruction *, CostInfo> &InstCostMap, CostInfo *LoopCost) {
1113bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Calculating Latency / IPredCost / INonPredCost of loop "
1114bdd1243dSDimitry Andric << L->getHeader()->getName() << "\n");
1115*a58f00eaSDimitry Andric const auto &SImap = getSImap(SIGroups);
111681ad6265SDimitry Andric // Compute instruction and loop-critical-path costs across two iterations for
111781ad6265SDimitry Andric // both predicated and non-predicated version.
111881ad6265SDimitry Andric const unsigned Iterations = 2;
111981ad6265SDimitry Andric for (unsigned Iter = 0; Iter < Iterations; ++Iter) {
112081ad6265SDimitry Andric // Cost of the loop's critical path.
112181ad6265SDimitry Andric CostInfo &MaxCost = LoopCost[Iter];
112281ad6265SDimitry Andric for (BasicBlock *BB : L->getBlocks()) {
112381ad6265SDimitry Andric for (const Instruction &I : *BB) {
112481ad6265SDimitry Andric if (I.isDebugOrPseudoInst())
112581ad6265SDimitry Andric continue;
112681ad6265SDimitry Andric // Compute the predicated and non-predicated cost of the instruction.
112781ad6265SDimitry Andric Scaled64 IPredCost = Scaled64::getZero(),
112881ad6265SDimitry Andric INonPredCost = Scaled64::getZero();
112981ad6265SDimitry Andric
113081ad6265SDimitry Andric // Assume infinite resources that allow to fully exploit the available
113181ad6265SDimitry Andric // instruction-level parallelism.
113281ad6265SDimitry Andric // InstCost = InstLatency + max(Op1Cost, Op2Cost, … OpNCost)
113381ad6265SDimitry Andric for (const Use &U : I.operands()) {
113481ad6265SDimitry Andric auto UI = dyn_cast<Instruction>(U.get());
113581ad6265SDimitry Andric if (!UI)
113681ad6265SDimitry Andric continue;
113781ad6265SDimitry Andric if (InstCostMap.count(UI)) {
113881ad6265SDimitry Andric IPredCost = std::max(IPredCost, InstCostMap[UI].PredCost);
113981ad6265SDimitry Andric INonPredCost = std::max(INonPredCost, InstCostMap[UI].NonPredCost);
114081ad6265SDimitry Andric }
114181ad6265SDimitry Andric }
114281ad6265SDimitry Andric auto ILatency = computeInstCost(&I);
114381ad6265SDimitry Andric if (!ILatency) {
114481ad6265SDimitry Andric OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", &I);
114581ad6265SDimitry Andric ORmissL << "Invalid instruction cost preventing analysis and "
114681ad6265SDimitry Andric "optimization of the inner-most loop containing this "
114781ad6265SDimitry Andric "instruction. ";
1148bdd1243dSDimitry Andric EmitAndPrintRemark(ORE, ORmissL);
114981ad6265SDimitry Andric return false;
115081ad6265SDimitry Andric }
1151bdd1243dSDimitry Andric IPredCost += Scaled64::get(*ILatency);
1152bdd1243dSDimitry Andric INonPredCost += Scaled64::get(*ILatency);
115381ad6265SDimitry Andric
115481ad6265SDimitry Andric // For a select that can be converted to branch,
115581ad6265SDimitry Andric // compute its cost as a branch (non-predicated cost).
115681ad6265SDimitry Andric //
115781ad6265SDimitry Andric // BranchCost = PredictedPathCost + MispredictCost
115881ad6265SDimitry Andric // PredictedPathCost = TrueOpCost * TrueProb + FalseOpCost * FalseProb
115981ad6265SDimitry Andric // MispredictCost = max(MispredictPenalty, CondCost) * MispredictRate
1160*a58f00eaSDimitry Andric if (SImap.contains(&I)) {
1161*a58f00eaSDimitry Andric auto SI = SImap.at(&I);
1162*a58f00eaSDimitry Andric Scaled64 TrueOpCost = SI.getTrueOpCost(InstCostMap, TTI);
1163*a58f00eaSDimitry Andric Scaled64 FalseOpCost = SI.getFalseOpCost(InstCostMap, TTI);
116481ad6265SDimitry Andric Scaled64 PredictedPathCost =
116581ad6265SDimitry Andric getPredictedPathCost(TrueOpCost, FalseOpCost, SI);
116681ad6265SDimitry Andric
116781ad6265SDimitry Andric Scaled64 CondCost = Scaled64::getZero();
1168*a58f00eaSDimitry Andric if (auto *CI = dyn_cast<Instruction>(SI.getCondition()))
116981ad6265SDimitry Andric if (InstCostMap.count(CI))
117081ad6265SDimitry Andric CondCost = InstCostMap[CI].NonPredCost;
117181ad6265SDimitry Andric Scaled64 MispredictCost = getMispredictionCost(SI, CondCost);
117281ad6265SDimitry Andric
117381ad6265SDimitry Andric INonPredCost = PredictedPathCost + MispredictCost;
117481ad6265SDimitry Andric }
1175bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << " " << ILatency << "/" << IPredCost << "/"
1176bdd1243dSDimitry Andric << INonPredCost << " for " << I << "\n");
117781ad6265SDimitry Andric
117881ad6265SDimitry Andric InstCostMap[&I] = {IPredCost, INonPredCost};
117981ad6265SDimitry Andric MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
118081ad6265SDimitry Andric MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
118181ad6265SDimitry Andric }
118281ad6265SDimitry Andric }
1183bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Iteration " << Iter + 1
1184bdd1243dSDimitry Andric << " MaxCost = " << MaxCost.PredCost << " "
1185bdd1243dSDimitry Andric << MaxCost.NonPredCost << "\n");
118681ad6265SDimitry Andric }
118781ad6265SDimitry Andric return true;
118881ad6265SDimitry Andric }
118981ad6265SDimitry Andric
1190*a58f00eaSDimitry Andric SmallDenseMap<const Instruction *, SelectOptimizeImpl::SelectLike, 2>
getSImap(const SelectGroups & SIGroups)1191*a58f00eaSDimitry Andric SelectOptimizeImpl::getSImap(const SelectGroups &SIGroups) {
1192*a58f00eaSDimitry Andric SmallDenseMap<const Instruction *, SelectLike, 2> SImap;
119381ad6265SDimitry Andric for (const SelectGroup &ASI : SIGroups)
1194*a58f00eaSDimitry Andric for (SelectLike SI : ASI)
1195*a58f00eaSDimitry Andric SImap.try_emplace(SI.getI(), SI);
1196*a58f00eaSDimitry Andric return SImap;
119781ad6265SDimitry Andric }
119881ad6265SDimitry Andric
1199c9157d92SDimitry Andric std::optional<uint64_t>
computeInstCost(const Instruction * I)1200c9157d92SDimitry Andric SelectOptimizeImpl::computeInstCost(const Instruction *I) {
120181ad6265SDimitry Andric InstructionCost ICost =
120281ad6265SDimitry Andric TTI->getInstructionCost(I, TargetTransformInfo::TCK_Latency);
120381ad6265SDimitry Andric if (auto OC = ICost.getValue())
1204bdd1243dSDimitry Andric return std::optional<uint64_t>(*OC);
1205bdd1243dSDimitry Andric return std::nullopt;
120681ad6265SDimitry Andric }
120781ad6265SDimitry Andric
120881ad6265SDimitry Andric ScaledNumber<uint64_t>
getMispredictionCost(const SelectLike SI,const Scaled64 CondCost)1209*a58f00eaSDimitry Andric SelectOptimizeImpl::getMispredictionCost(const SelectLike SI,
121081ad6265SDimitry Andric const Scaled64 CondCost) {
121181ad6265SDimitry Andric uint64_t MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
121281ad6265SDimitry Andric
121381ad6265SDimitry Andric // Account for the default misprediction rate when using a branch
121481ad6265SDimitry Andric // (conservatively set to 25% by default).
121581ad6265SDimitry Andric uint64_t MispredictRate = MispredictDefaultRate;
121681ad6265SDimitry Andric // If the select condition is obviously predictable, then the misprediction
121781ad6265SDimitry Andric // rate is zero.
121881ad6265SDimitry Andric if (isSelectHighlyPredictable(SI))
121981ad6265SDimitry Andric MispredictRate = 0;
122081ad6265SDimitry Andric
122181ad6265SDimitry Andric // CondCost is included to account for cases where the computation of the
122281ad6265SDimitry Andric // condition is part of a long dependence chain (potentially loop-carried)
122381ad6265SDimitry Andric // that would delay detection of a misprediction and increase its cost.
122481ad6265SDimitry Andric Scaled64 MispredictCost =
122581ad6265SDimitry Andric std::max(Scaled64::get(MispredictPenalty), CondCost) *
122681ad6265SDimitry Andric Scaled64::get(MispredictRate);
122781ad6265SDimitry Andric MispredictCost /= Scaled64::get(100);
122881ad6265SDimitry Andric
122981ad6265SDimitry Andric return MispredictCost;
123081ad6265SDimitry Andric }
123181ad6265SDimitry Andric
123281ad6265SDimitry Andric // Returns the cost of a branch when the prediction is correct.
123381ad6265SDimitry Andric // TrueCost * TrueProbability + FalseCost * FalseProbability.
123481ad6265SDimitry Andric ScaledNumber<uint64_t>
getPredictedPathCost(Scaled64 TrueCost,Scaled64 FalseCost,const SelectLike SI)1235c9157d92SDimitry Andric SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
1236*a58f00eaSDimitry Andric const SelectLike SI) {
123781ad6265SDimitry Andric Scaled64 PredPathCost;
123881ad6265SDimitry Andric uint64_t TrueWeight, FalseWeight;
1239*a58f00eaSDimitry Andric if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
124081ad6265SDimitry Andric uint64_t SumWeight = TrueWeight + FalseWeight;
124181ad6265SDimitry Andric if (SumWeight != 0) {
124281ad6265SDimitry Andric PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
124381ad6265SDimitry Andric FalseCost * Scaled64::get(FalseWeight);
124481ad6265SDimitry Andric PredPathCost /= Scaled64::get(SumWeight);
124581ad6265SDimitry Andric return PredPathCost;
124681ad6265SDimitry Andric }
124781ad6265SDimitry Andric }
124881ad6265SDimitry Andric // Without branch weight metadata, we assume 75% for the one path and 25% for
124981ad6265SDimitry Andric // the other, and pick the result with the biggest cost.
125081ad6265SDimitry Andric PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
125181ad6265SDimitry Andric FalseCost * Scaled64::get(3) + TrueCost);
125281ad6265SDimitry Andric PredPathCost /= Scaled64::get(4);
125381ad6265SDimitry Andric return PredPathCost;
125481ad6265SDimitry Andric }
125581ad6265SDimitry Andric
isSelectKindSupported(const SelectLike SI)1256*a58f00eaSDimitry Andric bool SelectOptimizeImpl::isSelectKindSupported(const SelectLike SI) {
1257*a58f00eaSDimitry Andric bool VectorCond = !SI.getCondition()->getType()->isIntegerTy(1);
125881ad6265SDimitry Andric if (VectorCond)
125981ad6265SDimitry Andric return false;
126081ad6265SDimitry Andric TargetLowering::SelectSupportKind SelectKind;
1261*a58f00eaSDimitry Andric if (SI.getType()->isVectorTy())
126281ad6265SDimitry Andric SelectKind = TargetLowering::ScalarCondVectorVal;
126381ad6265SDimitry Andric else
126481ad6265SDimitry Andric SelectKind = TargetLowering::ScalarValSelect;
126581ad6265SDimitry Andric return TLI->isSelectSupported(SelectKind);
126681ad6265SDimitry Andric }
1267