LLVM 24.0.0git
SelectOptimize.cpp
Go to the documentation of this file.
1//===--- SelectOptimize.cpp - Convert select to branches if profitable ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass converts selects to conditional jumps when profitable.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/Passes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instruction.h"
36#include "llvm/Pass.h"
40#include <algorithm>
41#include <queue>
42#include <stack>
43
44using namespace llvm;
45using namespace llvm::PatternMatch;
46
47#define DEBUG_TYPE "select-optimize"
48
49STATISTIC(NumSelectOptAnalyzed,
50 "Number of select groups considered for conversion to branch");
51STATISTIC(NumSelectConvertedExpColdOperand,
52 "Number of select groups converted due to expensive cold operand");
53STATISTIC(NumSelectConvertedHighPred,
54 "Number of select groups converted due to high-predictability");
55STATISTIC(NumSelectUnPred,
56 "Number of select groups not converted due to unpredictability");
57STATISTIC(NumSelectColdBB,
58 "Number of select groups not converted due to cold basic block");
59STATISTIC(NumSelectConvertedLoop,
60 "Number of select groups converted due to loop-level analysis");
61STATISTIC(NumSelectsConverted, "Number of selects converted");
62
63namespace llvm {
65}
66
68 "cold-operand-threshold",
69 cl::desc("Maximum frequency of path for an operand to be considered cold."),
70 cl::init(20), cl::Hidden);
71
73 "cold-operand-max-cost-multiplier",
74 cl::desc("Maximum cost multiplier of TCC_expensive for the dependence "
75 "slice of a cold operand to be considered inexpensive."),
77
79 GainGradientThreshold("select-opti-loop-gradient-gain-threshold",
80 cl::desc("Gradient gain threshold (%)."),
81 cl::init(25), cl::Hidden);
82
84 GainCycleThreshold("select-opti-loop-cycle-gain-threshold",
85 cl::desc("Minimum gain per loop (in cycles) threshold."),
87
89 "select-opti-loop-relative-gain-threshold",
91 "Minimum relative gain per loop threshold (1/X). Defaults to 12.5%"),
93
95 "mispredict-default-rate", cl::Hidden, cl::init(25),
96 cl::desc("Default mispredict rate (initialized to 25%)."));
97
98static cl::opt<bool>
99 DisableLoopLevelHeuristics("disable-loop-level-heuristics", cl::Hidden,
100 cl::init(false),
101 cl::desc("Disable loop-level heuristics."));
102
103namespace {
104
105class SelectOptimizeImpl {
106 const TargetMachine *TM = nullptr;
107 const TargetSubtargetInfo *TSI = nullptr;
108 const TargetLowering *TLI = nullptr;
109 const TargetTransformInfo *TTI = nullptr;
110 const LoopInfo *LI = nullptr;
112 ProfileSummaryInfo *PSI = nullptr;
113 OptimizationRemarkEmitter *ORE = nullptr;
114 TargetSchedModel TSchedModel;
115
116public:
117 SelectOptimizeImpl() = default;
118 SelectOptimizeImpl(const TargetMachine *TM) : TM(TM){};
119 PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
120 bool runOnFunction(Function &F, Pass &P);
121
122 using Scaled64 = ScaledNumber<uint64_t>;
123
124 struct CostInfo {
125 /// Predicated cost (with selects as conditional moves).
126 Scaled64 PredCost;
127 /// Non-predicated cost (with selects converted to branches).
128 Scaled64 NonPredCost;
129 };
130
131 /// SelectLike is an abstraction over SelectInst and other operations that can
132 /// act like selects. For example Or(Zext(icmp), X) can be treated like
133 /// select(icmp, X|1, X).
134 class SelectLike {
135 /// The select (/or) instruction.
136 Instruction *I;
137 /// Whether this select is inverted, "not(cond), FalseVal, TrueVal", as
138 /// opposed to the original condition.
139 bool Inverted = false;
140
141 /// The index of the operand that depends on condition. Only for select-like
142 /// instruction such as Or/Add.
143 unsigned CondIdx;
144
145 public:
146 SelectLike(Instruction *I, bool Inverted = false, unsigned CondIdx = 0)
147 : I(I), Inverted(Inverted), CondIdx(CondIdx) {}
148
149 Instruction *getI() { return I; }
150 const Instruction *getI() const { return I; }
151
152 Type *getType() const { return I->getType(); }
153
154 unsigned getConditionOpIndex() { return CondIdx; };
155
156 /// Return the true value for the SelectLike instruction. Note this may not
157 /// exist for all SelectLike instructions. For example, for `or(zext(c), x)`
158 /// the true value would be `or(x,1)`. As this value does not exist, nullptr
159 /// is returned.
160 Value *getTrueValue(bool HonorInverts = true) const {
161 if (Inverted && HonorInverts)
162 return getFalseValue(/*HonorInverts=*/false);
163 if (auto *Sel = dyn_cast<SelectInst>(I))
164 return Sel->getTrueValue();
165 // Or(zext) case - The true value is Or(X), so return nullptr as the value
166 // does not yet exist.
167 if (isa<BinaryOperator>(I))
168 return nullptr;
169
170 llvm_unreachable("Unhandled case in getTrueValue");
171 }
172
173 /// Return the false value for the SelectLike instruction. For example the
174 /// getFalseValue of a select or `x` in `or(zext(c), x)` (which is
175 /// `select(c, x|1, x)`)
176 Value *getFalseValue(bool HonorInverts = true) const {
177 if (Inverted && HonorInverts)
178 return getTrueValue(/*HonorInverts=*/false);
179 if (auto *Sel = dyn_cast<SelectInst>(I))
180 return Sel->getFalseValue();
181 // We are on the branch where the condition is zero, which means BinOp
182 // does not perform any computation, and we can simply return the operand
183 // that is not related to the condition
184 if (auto *BO = dyn_cast<BinaryOperator>(I))
185 return BO->getOperand(1 - CondIdx);
186
187 llvm_unreachable("Unhandled case in getFalseValue");
188 }
189
190 /// Return the NonPredCost cost of the op on \p isTrue branch, given the
191 /// costs in \p InstCostMap. This may need to be generated for select-like
192 /// instructions.
193 Scaled64 getOpCostOnBranch(
194 bool IsTrue, const DenseMap<const Instruction *, CostInfo> &InstCostMap,
195 const TargetTransformInfo *TTI) {
196 auto *V = IsTrue ? getTrueValue() : getFalseValue();
197 if (V) {
198 if (auto *IV = dyn_cast<Instruction>(V)) {
199 auto It = InstCostMap.find(IV);
200 return It != InstCostMap.end() ? It->second.NonPredCost
202 }
203 return Scaled64::getZero();
204 }
205 // If getTrue(False)Value() return nullptr, it means we are dealing with
206 // select-like instructions on the branch where the actual computation is
207 // happening. In that case the cost is equal to the cost of computation +
208 // cost of non-dependant on condition operand
210 getI()->getOpcode(), I->getType(), TargetTransformInfo::TCK_Latency,
211 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
212 {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2});
213 auto TotalCost = Scaled64::get(Cost.getValue());
214 if (auto *OpI = dyn_cast<Instruction>(I->getOperand(1 - CondIdx))) {
215 auto It = InstCostMap.find(OpI);
216 if (It != InstCostMap.end())
217 TotalCost += It->second.NonPredCost;
218 }
219 return TotalCost;
220 }
221 };
222
223private:
224 // Select groups consist of consecutive select-like instructions with the same
225 // condition. Between select-likes could be any number of auxiliary
226 // instructions related to the condition like not, zext, ashr/lshr
227 struct SelectGroup {
228 Value *Condition;
230 };
231 using SelectGroups = SmallVector<SelectGroup, 2>;
232
233 // Converts select instructions of a function to conditional jumps when deemed
234 // profitable. Returns true if at least one select was converted.
235 bool optimizeSelects(Function &F);
236
237 // Heuristics for determining which select instructions can be profitably
238 // conveted to branches. Separate heuristics for selects in inner-most loops
239 // and the rest of code regions (base heuristics for non-inner-most loop
240 // regions).
241 void optimizeSelectsBase(Function &F, SelectGroups &ProfSIGroups);
242 void optimizeSelectsInnerLoops(Function &F, SelectGroups &ProfSIGroups);
243
244 // Converts to branches the select groups that were deemed
245 // profitable-to-convert.
246 void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
247
248 // Splits selects of a given basic block into select groups.
249 void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
250
251 // Determines for which select groups it is profitable converting to branches
252 // (base and inner-most-loop heuristics).
253 void findProfitableSIGroupsBase(SelectGroups &SIGroups,
254 SelectGroups &ProfSIGroups);
255 void findProfitableSIGroupsInnerLoops(const Loop *L, SelectGroups &SIGroups,
256 SelectGroups &ProfSIGroups);
257
258 // Determines if a select group should be converted to a branch (base
259 // heuristics).
260 bool isConvertToBranchProfitableBase(const SelectGroup &ASI);
261
262 // Returns true if there are expensive instructions in the cold value
263 // operand's (if any) dependence slice of any of the selects of the given
264 // group.
265 bool hasExpensiveColdOperand(const SelectGroup &ASI);
266
267 // For a given source instruction, collect its backwards dependence slice
268 // consisting of instructions exclusively computed for producing the operands
269 // of the source instruction. When sinking, the slice stops at members of
270 // \p Group.
271 void getExclBackwardsSlice(Instruction *I, std::stack<Instruction *> &Slice,
272 Instruction *SI, bool ForSinking = false,
273 const SelectGroup *Group = nullptr);
274
275 // Returns true if the condition of the select is highly predictable.
276 bool isSelectHighlyPredictable(const SelectLike SI);
277
278 // Loop-level checks to determine if a non-predicated version (with branches)
279 // of the given loop is more profitable than its predicated version.
280 bool checkLoopHeuristics(const Loop *L, const CostInfo LoopDepth[2]);
281
282 // Computes instruction and loop-critical-path costs for both the predicated
283 // and non-predicated version of the given loop.
284 bool computeLoopCosts(const Loop *L, const SelectGroups &SIGroups,
285 DenseMap<const Instruction *, CostInfo> &InstCostMap,
286 CostInfo *LoopCost);
287
288 // Returns a set of all the select instructions in the given select groups.
289 SmallDenseMap<const Instruction *, SelectLike, 2>
290 getSImap(const SelectGroups &SIGroups);
291
292 // Returns a map from select-like instructions to the corresponding select
293 // group.
294 SmallDenseMap<const Instruction *, const SelectGroup *, 2>
295 getSGmap(const SelectGroups &SIGroups);
296
297 // Returns the latency cost of a given instruction.
298 std::optional<uint64_t> computeInstCost(const Instruction *I);
299
300 // Returns the misprediction cost of a given select when converted to branch.
301 Scaled64 getMispredictionCost(const SelectLike SI, const Scaled64 CondCost);
302
303 // Returns the cost of a branch when the prediction is correct.
304 Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
305 const SelectLike SI);
306
307 // Returns true if the target architecture supports lowering a given select.
308 bool isSelectKindSupported(const SelectLike SI);
309};
310
311class SelectOptimize : public FunctionPass {
312 SelectOptimizeImpl Impl;
313
314public:
315 static char ID;
316
317 SelectOptimize() : FunctionPass(ID) {}
318
319 bool runOnFunction(Function &F) override {
320 if (skipFunction(F))
321 return false;
322
323 return Impl.runOnFunction(F, *this);
324 }
325
326 void getAnalysisUsage(AnalysisUsage &AU) const override {
327 AU.addRequired<ProfileSummaryInfoWrapperPass>();
328 AU.addRequired<TargetPassConfig>();
329 AU.addRequired<TargetTransformInfoWrapperPass>();
330 AU.addRequired<LoopInfoWrapperPass>();
331 AU.addRequired<BlockFrequencyInfoWrapperPass>();
332 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
333 }
334};
335
336} // namespace
337
340 SelectOptimizeImpl Impl(TM);
341 return Impl.run(F, FAM);
342}
343
344char SelectOptimize::ID = 0;
345
346INITIALIZE_PASS_BEGIN(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
347 false)
354INITIALIZE_PASS_END(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
355 false)
356
357FunctionPass *llvm::createSelectOptimizePass() { return new SelectOptimize(); }
358
359PreservedAnalyses SelectOptimizeImpl::run(Function &F,
361 TSI = TM->getSubtargetImpl(F);
362 TLI = TSI->getTargetLowering();
363
364 // If none of the select types are supported then skip this pass.
365 // This is an optimization pass. Legality issues will be handled by
366 // instruction selection.
370 return PreservedAnalyses::all();
371
372 TTI = &FAM.getResult<TargetIRAnalysis>(F);
373 if (!TTI->enableSelectOptimize())
374 return PreservedAnalyses::all();
375
377 .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
378 if (!PSI)
379 reportFatalUsageError("this pass requires the profile-summary module "
380 "analysis to be available");
381 BFI = &FAM.getResult<BlockFrequencyAnalysis>(F);
382
383 // When optimizing for size, selects are preferable over branches.
384 if (llvm::shouldOptimizeForSize(&F, PSI, BFI))
385 return PreservedAnalyses::all();
386
387 LI = &FAM.getResult<LoopAnalysis>(F);
388 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
389 TSchedModel.init(TSI);
390
391 bool Changed = optimizeSelects(F);
393}
394
395bool SelectOptimizeImpl::runOnFunction(Function &F, Pass &P) {
396 TM = &P.getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
397 TSI = TM->getSubtargetImpl(F);
398 TLI = TSI->getTargetLowering();
399
400 // If none of the select types are supported then skip this pass.
401 // This is an optimization pass. Legality issues will be handled by
402 // instruction selection.
406 return false;
407
408 TTI = &P.getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
409
410 if (!TTI->enableSelectOptimize())
411 return false;
412
413 LI = &P.getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
414 BFI = &P.getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
415 PSI = &P.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
416 ORE = &P.getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
417 TSchedModel.init(TSI);
418
419 // When optimizing for size, selects are preferable over branches.
420 if (llvm::shouldOptimizeForSize(&F, PSI, BFI))
421 return false;
422
423 return optimizeSelects(F);
424}
425
426bool SelectOptimizeImpl::optimizeSelects(Function &F) {
427 // Determine for which select groups it is profitable converting to branches.
428 SelectGroups ProfSIGroups;
429 // Base heuristics apply only to non-loops and outer loops.
430 optimizeSelectsBase(F, ProfSIGroups);
431 // Separate heuristics for inner-most loops.
432 optimizeSelectsInnerLoops(F, ProfSIGroups);
433
434 // Convert to branches the select groups that were deemed
435 // profitable-to-convert.
436 convertProfitableSIGroups(ProfSIGroups);
437
438 // Code modified if at least one select group was converted.
439 return !ProfSIGroups.empty();
440}
441
442void SelectOptimizeImpl::optimizeSelectsBase(Function &F,
443 SelectGroups &ProfSIGroups) {
444 // Collect all the select groups.
445 SelectGroups SIGroups;
446 for (BasicBlock &BB : F) {
447 // Base heuristics apply only to non-loops and outer loops.
448 Loop *L = LI->getLoopFor(&BB);
449 if (L && L->isInnermost())
450 continue;
451 collectSelectGroups(BB, SIGroups);
452 }
453
454 // Determine for which select groups it is profitable converting to branches.
455 findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
456}
457
458void SelectOptimizeImpl::optimizeSelectsInnerLoops(Function &F,
459 SelectGroups &ProfSIGroups) {
461 // Need to check size on each iteration as we accumulate child loops.
462 for (unsigned long i = 0; i < Loops.size(); ++i)
463 llvm::append_range(Loops, Loops[i]->getSubLoops());
464
465 for (Loop *L : Loops) {
466 if (!L->isInnermost())
467 continue;
468
469 SelectGroups SIGroups;
470 for (BasicBlock *BB : L->getBlocks())
471 collectSelectGroups(*BB, SIGroups);
472
473 findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
474 }
475}
476
477/// Returns optimised value on \p IsTrue branch. For SelectInst that would be
478/// either True or False value. For (BinaryOperator) instructions, where the
479/// condition may be skipped, the operation will use a non-conditional operand.
480/// For example, for `or(V,zext(cond))` this function would return V.
481/// However, if the conditional operand on \p IsTrue branch matters, we create a
482/// clone of instruction at the end of that branch \p B and replace the
483/// condition operand with a constant.
484///
485/// Also /p OptSelects contains previously optimised select-like instructions.
486/// If the current value uses one of the optimised values, we can optimise it
487/// further by replacing it with the corresponding value on the given branch
489 SelectOptimizeImpl::SelectLike &SI, bool isTrue,
490 SmallDenseMap<Instruction *, std::pair<Value *, Value *>, 2> &OptSelects,
491 BasicBlock *B) {
492 Value *V = isTrue ? SI.getTrueValue() : SI.getFalseValue();
493 if (V) {
494 if (auto *IV = dyn_cast<Instruction>(V))
495 if (auto It = OptSelects.find(IV); It != OptSelects.end())
496 return isTrue ? It->second.first : It->second.second;
497 return V;
498 }
499
500 auto *BO = cast<BinaryOperator>(SI.getI());
501 assert((BO->getOpcode() == Instruction::Add ||
502 BO->getOpcode() == Instruction::Or ||
503 BO->getOpcode() == Instruction::Sub) &&
504 "Only currently handling Add, Or and Sub binary operators.");
505
506 auto *CBO = BO->clone();
507 auto CondIdx = SI.getConditionOpIndex();
508 auto *AuxI = cast<Instruction>(CBO->getOperand(CondIdx));
509 if (isa<ZExtInst>(AuxI) || isa<LShrOperator>(AuxI)) {
510 CBO->setOperand(CondIdx, ConstantInt::get(CBO->getType(), 1));
511 } else {
512 assert((isa<AShrOperator>(AuxI) || isa<SExtInst>(AuxI)) &&
513 "Unexpected opcode");
514 CBO->setOperand(CondIdx, ConstantInt::getAllOnesValue(CBO->getType()));
515 }
516
517 unsigned OtherIdx = 1 - CondIdx;
518 if (auto *IV = dyn_cast<Instruction>(CBO->getOperand(OtherIdx))) {
519 if (auto It = OptSelects.find(IV); It != OptSelects.end())
520 CBO->setOperand(OtherIdx, isTrue ? It->second.first : It->second.second);
521 }
522 CBO->insertBefore(B->getTerminator()->getIterator());
523 return CBO;
524}
525
526void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
527 for (SelectGroup &ASI : ProfSIGroups) {
528 // The code transformation here is a modified version of the sinking
529 // transformation in CodeGenPrepare::optimizeSelectInst with a more
530 // aggressive strategy of which instructions to sink.
531 //
532 // TODO: eliminate the redundancy of logic transforming selects to branches
533 // by removing CodeGenPrepare::optimizeSelectInst and optimizing here
534 // selects for all cases (with and without profile information).
535
536 // Transform a sequence like this:
537 // start:
538 // %cmp = cmp uge i32 %a, %b
539 // %sel = select i1 %cmp, i32 %c, i32 %d
540 //
541 // Into:
542 // start:
543 // %cmp = cmp uge i32 %a, %b
544 // %cmp.frozen = freeze %cmp
545 // br i1 %cmp.frozen, label %select.true, label %select.false
546 // select.true:
547 // br label %select.end
548 // select.false:
549 // br label %select.end
550 // select.end:
551 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
552 //
553 // %cmp should be frozen, otherwise it may introduce undefined behavior.
554 // In addition, we may sink instructions that produce %c or %d into the
555 // destination(s) of the new branch.
556 // If the true or false blocks do not contain a sunken instruction, that
557 // block and its branch may be optimized away. In that case, one side of the
558 // first branch will point directly to select.end, and the corresponding PHI
559 // predecessor block will be the start block.
560
561 // Find all the instructions that can be soundly sunk to the true/false
562 // blocks. These are instructions that are computed solely for producing the
563 // operands of the select instructions in the group and can be sunk without
564 // breaking the semantics of the LLVM IR (e.g., cannot sink instructions
565 // with side effects).
566 SmallVector<std::stack<Instruction *>, 2> TrueSlices, FalseSlices;
567 typedef std::stack<Instruction *>::size_type StackSizeType;
568 StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0;
569 Instruction *SelectWithProfile = nullptr;
570 bool SelectWithProfileIsInverted = false;
571 for (SelectLike &SI : ASI.Selects) {
572 if (!isa<SelectInst>(SI.getI()))
573 continue;
574 // For each select, compute the sinkable dependence chains of the true and
575 // false operands.
576 if (auto *TI = dyn_cast_or_null<Instruction>(SI.getTrueValue())) {
577 std::stack<Instruction *> TrueSlice;
578 getExclBackwardsSlice(TI, TrueSlice, SI.getI(), true, &ASI);
579 maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size());
580 TrueSlices.push_back(TrueSlice);
581 }
582 if (auto *FI = dyn_cast_or_null<Instruction>(SI.getFalseValue())) {
583 if (isa<SelectInst>(SI.getI()) || !FI->hasOneUse()) {
584 std::stack<Instruction *> FalseSlice;
585 getExclBackwardsSlice(FI, FalseSlice, SI.getI(), true, &ASI);
586 maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size());
587 FalseSlices.push_back(FalseSlice);
588 }
589 }
590 // Also see if the select has profile data that we can propagate later
591 // to the conditional branch.
592 Value *SelectCondition = cast<SelectInst>(SI.getI())->getCondition();
593 if (hasProfMD(*SI.getI()) && ASI.Condition == SelectCondition) {
594 SelectWithProfile = SI.getI();
595 } else if (hasProfMD(*SI.getI()) &&
596 match(SelectCondition, m_Not(m_Value(ASI.Condition)))) {
597 SelectWithProfile = SI.getI();
598 SelectWithProfileIsInverted = true;
599 }
600 }
601 // In the case of multiple select instructions in the same group, the order
602 // of non-dependent instructions (instructions of different dependence
603 // slices) in the true/false blocks appears to affect performance.
604 // Interleaving the slices seems to experimentally be the optimal approach.
605 // This interleaving scheduling allows for more ILP (with a natural downside
606 // of increasing a bit register pressure) compared to a simple ordering of
607 // one whole chain after another. One would expect that this ordering would
608 // not matter since the scheduling in the backend of the compiler would
609 // take care of it, but apparently the scheduler fails to deliver optimal
610 // ILP with a naive ordering here.
611 SmallVector<Instruction *, 2> TrueSlicesInterleaved, FalseSlicesInterleaved;
612 for (StackSizeType IS = 0; IS < maxTrueSliceLen; ++IS) {
613 for (auto &S : TrueSlices) {
614 if (!S.empty()) {
615 TrueSlicesInterleaved.push_back(S.top());
616 S.pop();
617 }
618 }
619 }
620 for (StackSizeType IS = 0; IS < maxFalseSliceLen; ++IS) {
621 for (auto &S : FalseSlices) {
622 if (!S.empty()) {
623 FalseSlicesInterleaved.push_back(S.top());
624 S.pop();
625 }
626 }
627 }
628
629 // We split the block containing the select(s) into two blocks.
630 SelectLike &SI = ASI.Selects.front();
631 SelectLike &LastSI = ASI.Selects.back();
632 BasicBlock *StartBlock = SI.getI()->getParent();
633 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI.getI()));
634 // With RemoveDIs turned off, SplitPt can be a dbg.* intrinsic. With
635 // RemoveDIs turned on, SplitPt would instead point to the next
636 // instruction. To match existing dbg.* intrinsic behaviour with RemoveDIs,
637 // tell splitBasicBlock that we want to include any DbgVariableRecords
638 // attached to SplitPt in the splice.
639 SplitPt.setHeadBit(true);
640 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
641 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
642 // Delete the unconditional branch that was just created by the split.
643 StartBlock->getTerminator()->eraseFromParent();
644
645 // Hoist any pseudo and auxiliary instructions that were in-between the
646 // select group before the group, since the true/false values may use them.
648 auto DIt = SI.getI()->getIterator();
649 auto NIt = ASI.Selects.begin();
650 while (&*DIt != LastSI.getI()) {
651 if (NIt != ASI.Selects.end() && &*DIt == NIt->getI())
652 ++NIt;
653 else
654 HoistInstrs.push_back(&*DIt);
655 DIt++;
656 }
657 for (auto *HI : HoistInstrs)
658 HI->moveBefore(SI.getI()->getIterator());
659
660 // Duplicate implementation for DbgRecords, the non-instruction debug-info
661 // format. Helper lambda for moving DbgRecords to the end block.
662 auto TransferDbgRecords = [&](Instruction &I) {
663 for (auto &DbgRecord :
664 llvm::make_early_inc_range(I.getDbgRecordRange())) {
667 EndBlock->getFirstInsertionPt());
668 }
669 };
670
671 // Iterate over all instructions in between SI and LastSI, not including
672 // SI itself. These are all the variable assignments that happen "in the
673 // middle" of the select group.
674 auto R = make_range(std::next(SI.getI()->getIterator()),
675 std::next(LastSI.getI()->getIterator()));
676 llvm::for_each(R, TransferDbgRecords);
677
678 // These are the new basic blocks for the conditional branch.
679 // At least one will become an actual new basic block.
680 BasicBlock *TrueBlock = nullptr, *FalseBlock = nullptr;
681 UncondBrInst *TrueBranch = nullptr, *FalseBranch = nullptr;
682 // Checks if select-like instruction would materialise on the given branch
683 auto HasSelectLike = [](SelectGroup &SG, bool IsTrue) {
684 for (auto &SL : SG.Selects) {
685 if ((IsTrue ? SL.getTrueValue() : SL.getFalseValue()) == nullptr)
686 return true;
687 }
688 return false;
689 };
690 if (!TrueSlicesInterleaved.empty() || HasSelectLike(ASI, true)) {
691 TrueBlock = BasicBlock::Create(EndBlock->getContext(), "select.true.sink",
692 EndBlock->getParent(), EndBlock);
693 TrueBranch = UncondBrInst::Create(EndBlock, TrueBlock);
694 TrueBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
695 for (Instruction *TrueInst : TrueSlicesInterleaved)
696 TrueInst->moveBefore(TrueBranch->getIterator());
697 }
698 if (!FalseSlicesInterleaved.empty() || HasSelectLike(ASI, false)) {
699 FalseBlock =
700 BasicBlock::Create(EndBlock->getContext(), "select.false.sink",
701 EndBlock->getParent(), EndBlock);
702 FalseBranch = UncondBrInst::Create(EndBlock, FalseBlock);
703 FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
704 for (Instruction *FalseInst : FalseSlicesInterleaved)
705 FalseInst->moveBefore(FalseBranch->getIterator());
706 }
707 // If there was nothing to sink, then arbitrarily choose the 'false' side
708 // for a new input value to the PHI.
709 if (TrueBlock == FalseBlock) {
710 assert(TrueBlock == nullptr &&
711 "Unexpected basic block transform while optimizing select");
712
713 FalseBlock = BasicBlock::Create(StartBlock->getContext(), "select.false",
714 EndBlock->getParent(), EndBlock);
715 auto *FalseBranch = UncondBrInst::Create(EndBlock, FalseBlock);
716 FalseBranch->setDebugLoc(SI.getI()->getDebugLoc());
717 }
718
719 // Insert the real conditional branch based on the original condition.
720 // If we did not create a new block for one of the 'true' or 'false' paths
721 // of the condition, it means that side of the branch goes to the end block
722 // directly and the path originates from the start block from the point of
723 // view of the new PHI.
724 BasicBlock *TT, *FT;
725 if (TrueBlock == nullptr) {
726 TT = EndBlock;
727 FT = FalseBlock;
728 TrueBlock = StartBlock;
729 } else if (FalseBlock == nullptr) {
730 TT = TrueBlock;
731 FT = EndBlock;
732 FalseBlock = StartBlock;
733 } else {
734 TT = TrueBlock;
735 FT = FalseBlock;
736 }
737 IRBuilder<> IB(SI.getI());
738 auto *CondFr =
739 IB.CreateFreeze(ASI.Condition, ASI.Condition->getName() + ".frozen");
740
742
743 // Use reverse iterator because later select may use the value of the
744 // earlier select, and we need to propagate value through earlier select
745 // to get the PHI operand.
746 auto InsertionPoint = EndBlock->begin();
747 for (SelectLike &SI : ASI.Selects) {
748 // The select itself is replaced with a PHI Node.
749 PHINode *PN = PHINode::Create(SI.getType(), 2, "");
750 PN->insertBefore(InsertionPoint);
751 PN->takeName(SI.getI());
752 // Current instruction might be a condition of some other group, so we
753 // need to replace it there to avoid dangling pointer
754 if (PN->getType()->isIntegerTy(1)) {
755 for (auto &SG : ProfSIGroups) {
756 if (SG.Condition == SI.getI())
757 SG.Condition = PN;
758 }
759 }
760 SI.getI()->replaceAllUsesWith(PN);
761 auto *TV = getTrueOrFalseValue(SI, true, INS, TrueBlock);
762 auto *FV = getTrueOrFalseValue(SI, false, INS, FalseBlock);
763 INS[PN] = {TV, FV};
764 PN->addIncoming(TV, TrueBlock);
765 PN->addIncoming(FV, FalseBlock);
766 PN->setDebugLoc(SI.getI()->getDebugLoc());
767 ++NumSelectsConverted;
768 }
769 Instruction *CondBr = IB.CreateCondBr(CondFr, TT, FT, SI.getI());
770 if (!ProfcheckDisableMetadataFixes && SelectWithProfile) {
771 CondBr->copyMetadata(*SelectWithProfile, {llvm::LLVMContext::MD_prof});
772 if (SelectWithProfileIsInverted)
773 CondBr->swapProfMetadata();
774 } else {
776 }
777
778 // Remove the old select instructions, now that they are not longer used.
779 for (SelectLike &SI : ASI.Selects)
780 SI.getI()->eraseFromParent();
781 }
782}
783
784void SelectOptimizeImpl::collectSelectGroups(BasicBlock &BB,
785 SelectGroups &SIGroups) {
786 // Represents something that can be considered as select instruction.
787 // Auxiliary instruction are instructions that depends on a condition and have
788 // zero or some constant value on True/False branch, such as:
789 // * ZExt(1bit)
790 // * SExt(1bit)
791 // * Not(1bit)
792 // * A(L)Shr(Val), ValBitSize - 1, where there is a condition like `Val <= 0`
793 // earlier in the BB. For conditions that check the sign of the Val compiler
794 // may generate shifts instead of ZExt/SExt.
795 struct SelectLikeInfo {
796 Value *Cond;
797 bool IsAuxiliary;
798 bool IsInverted;
799 unsigned ConditionIdx;
800 };
801
803 // Keeps visited comparisons to help identify AShr/LShr variants of auxiliary
804 // instructions.
806
807 // Check if the instruction is SelectLike or might be part of SelectLike
808 // expression, put information into SelectInfo and return the iterator to the
809 // inserted position.
810 auto ProcessSelectInfo = [&SelectInfo, &SeenCmp](Instruction *I) {
811 if (auto *Cmp = dyn_cast<CmpInst>(I)) {
812 SeenCmp.insert(Cmp);
813 return SelectInfo.end();
814 }
815
816 Value *Cond;
818 Cond->getType()->isIntegerTy(1)) {
819 bool Inverted = match(Cond, m_Not(m_Value(Cond)));
820 return SelectInfo.insert({I, {Cond, true, Inverted, 0}}).first;
821 }
822
823 if (match(I, m_Not(m_Value(Cond)))) {
824 return SelectInfo.insert({I, {Cond, true, true, 0}}).first;
825 }
826
827 // Select instruction are what we are usually looking for.
828 if (match(I, m_Select(m_Value(Cond), m_Value(), m_Value()))) {
829 bool Inverted = match(Cond, m_Not(m_Value(Cond)));
830 return SelectInfo.insert({I, {Cond, false, Inverted, 0}}).first;
831 }
832 Value *Val;
833 ConstantInt *Shift;
834 if (match(I, m_Shr(m_Value(Val), m_ConstantInt(Shift))) &&
835 I->getType()->getIntegerBitWidth() == Shift->getZExtValue() + 1) {
836 for (auto *CmpI : SeenCmp) {
837 auto Pred = CmpI->getPredicate();
838 if (Val != CmpI->getOperand(0))
839 continue;
840 if ((Pred == CmpInst::ICMP_SGT &&
841 match(CmpI->getOperand(1), m_ConstantInt<-1>())) ||
842 (Pred == CmpInst::ICMP_SGE &&
843 match(CmpI->getOperand(1), m_Zero())) ||
844 (Pred == CmpInst::ICMP_SLT &&
845 match(CmpI->getOperand(1), m_Zero())) ||
846 (Pred == CmpInst::ICMP_SLE &&
847 match(CmpI->getOperand(1), m_ConstantInt<-1>()))) {
848 bool Inverted =
849 Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
850 return SelectInfo.insert({I, {CmpI, true, Inverted, 0}}).first;
851 }
852 }
853 return SelectInfo.end();
854 }
855
856 // An BinOp(Aux(X), Y) can also be treated like a select, with condition X
857 // and values Y|1 and Y.
858 // `Aux` can be either `ZExt(1bit)`, `SExt(1bit)` or `XShr(Val), ValBitSize
859 // - 1` `BinOp` can be Add, Sub, Or
860 Value *X;
861 auto MatchZExtOrSExtPattern =
863 auto MatchShiftPattern =
865
866 // This check is unnecessary, but it prevents costly access to the
867 // SelectInfo map.
868 if ((match(I, MatchZExtOrSExtPattern) && X->getType()->isIntegerTy(1)) ||
869 (match(I, MatchShiftPattern) &&
870 X->getType()->getIntegerBitWidth() == Shift->getZExtValue() + 1)) {
871 if (I->getOpcode() != Instruction::Add &&
872 I->getOpcode() != Instruction::Sub &&
873 I->getOpcode() != Instruction::Or)
874 return SelectInfo.end();
875
876 if (I->getOpcode() == Instruction::Or && I->getType()->isIntegerTy(1))
877 return SelectInfo.end();
878
879 // Iterate through operands and find dependant on recognised sign
880 // extending auxiliary select-like instructions. The operand index does
881 // not matter for Add and Or. However, for Sub, we can only safely
882 // transform when the operand is second.
883 unsigned Idx = I->getOpcode() == Instruction::Sub ? 1 : 0;
884 for (; Idx < 2; Idx++) {
885 auto *Op = I->getOperand(Idx);
886 auto It = SelectInfo.find(Op);
887 if (It != SelectInfo.end() && It->second.IsAuxiliary) {
888 Cond = It->second.Cond;
889 bool Inverted = It->second.IsInverted;
890 return SelectInfo.insert({I, {Cond, false, Inverted, Idx}}).first;
891 }
892 }
893 }
894 return SelectInfo.end();
895 };
896
897 bool AlreadyProcessed = false;
898 BasicBlock::iterator BBIt = BB.begin();
900 while (BBIt != BB.end()) {
901 Instruction *I = &*BBIt++;
903 continue;
904
905 if (!AlreadyProcessed)
906 It = ProcessSelectInfo(I);
907 else
908 AlreadyProcessed = false;
909
910 if (It == SelectInfo.end() || It->second.IsAuxiliary)
911 continue;
912
913 if (!TTI->shouldTreatInstructionLikeSelect(I))
914 continue;
915
916 Value *Cond = It->second.Cond;
917 // Vector conditions are not supported.
918 if (!Cond->getType()->isIntegerTy(1))
919 continue;
920
921 SelectGroup SIGroup = {Cond, {}};
922 SIGroup.Selects.emplace_back(I, It->second.IsInverted,
923 It->second.ConditionIdx);
924
925 // If the select type is not supported, no point optimizing it.
926 // Instruction selection will take care of it.
927 if (!isSelectKindSupported(SIGroup.Selects.front()))
928 continue;
929
930 while (BBIt != BB.end()) {
931 Instruction *NI = &*BBIt;
932 // Pseudo instructions should be skipped and not prevent the
933 // formation of a select group.
934 if (isa<PseudoProbeInst>(NI)) {
935 ++BBIt;
936 continue;
937 }
938
939 It = ProcessSelectInfo(NI);
940 if (It == SelectInfo.end()) {
941 AlreadyProcessed = true;
942 break;
943 }
944
945 // Auxiliary with same condition
946 auto [CurrCond, IsAux, IsRev, CondIdx] = It->second;
947 if (Cond != CurrCond) {
948 AlreadyProcessed = true;
949 break;
950 }
951
952 if (!IsAux)
953 SIGroup.Selects.emplace_back(NI, IsRev, CondIdx);
954 ++BBIt;
955 }
956 LLVM_DEBUG({
957 dbgs() << "New Select group (" << SIGroup.Selects.size() << ") with\n";
958 for (auto &SI : SIGroup.Selects)
959 dbgs() << " " << *SI.getI() << "\n";
960 });
961
962 SIGroups.push_back(SIGroup);
963 }
964}
965
966void SelectOptimizeImpl::findProfitableSIGroupsBase(
967 SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
968 for (SelectGroup &ASI : SIGroups) {
969 ++NumSelectOptAnalyzed;
970 if (isConvertToBranchProfitableBase(ASI))
971 ProfSIGroups.push_back(ASI);
972 }
973}
974
977 LLVM_DEBUG(dbgs() << Rem.getMsg() << "\n");
978 ORE->emit(Rem);
979}
980
981void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops(
982 const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
983 NumSelectOptAnalyzed += SIGroups.size();
984 // For each select group in an inner-most loop,
985 // a branch is more preferable than a select/conditional-move if:
986 // i) conversion to branches for all the select groups of the loop satisfies
987 // loop-level heuristics including reducing the loop's critical path by
988 // some threshold (see SelectOptimizeImpl::checkLoopHeuristics); and
989 // ii) the total cost of the select group is cheaper with a branch compared
990 // to its predicated version. The cost is in terms of latency and the cost
991 // of a select group is the cost of its most expensive select instruction
992 // (assuming infinite resources and thus fully leveraging available ILP).
993
995 CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
996 {Scaled64::getZero(), Scaled64::getZero()}};
997 if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
998 !checkLoopHeuristics(L, LoopCost)) {
999 return;
1000 }
1001
1002 for (SelectGroup &ASI : SIGroups) {
1003 // Assuming infinite resources, the cost of a group of instructions is the
1004 // cost of the most expensive instruction of the group.
1005 Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
1006 for (SelectLike &SI : ASI.Selects) {
1007 const auto &ICM = InstCostMap[SI.getI()];
1008 SelectCost = std::max(SelectCost, ICM.PredCost);
1009 BranchCost = std::max(BranchCost, ICM.NonPredCost);
1010 }
1011 if (BranchCost < SelectCost) {
1012 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti",
1013 ASI.Selects.front().getI());
1014 OR << "Profitable to convert to branch (loop analysis). BranchCost="
1015 << BranchCost.toString() << ", SelectCost=" << SelectCost.toString()
1016 << ". ";
1017 EmitAndPrintRemark(ORE, OR);
1018 ++NumSelectConvertedLoop;
1019 ProfSIGroups.push_back(ASI);
1020 } else {
1021 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
1022 ASI.Selects.front().getI());
1023 ORmiss << "Select is more profitable (loop analysis). BranchCost="
1024 << BranchCost.toString()
1025 << ", SelectCost=" << SelectCost.toString() << ". ";
1026 EmitAndPrintRemark(ORE, ORmiss);
1027 }
1028 }
1029}
1030
1031bool SelectOptimizeImpl::isConvertToBranchProfitableBase(
1032 const SelectGroup &ASI) {
1033 const SelectLike &SI = ASI.Selects.front();
1034 LLVM_DEBUG(dbgs() << "Analyzing select group containing " << *SI.getI()
1035 << "\n");
1036 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", SI.getI());
1037 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", SI.getI());
1038
1039 // Skip cold basic blocks. Better to optimize for size for cold blocks.
1040 if (PSI->isColdBlock(SI.getI()->getParent(), BFI)) {
1041 ++NumSelectColdBB;
1042 ORmiss << "Not converted to branch because of cold basic block. ";
1043 EmitAndPrintRemark(ORE, ORmiss);
1044 return false;
1045 }
1046
1047 // If unpredictable, branch form is less profitable.
1048 if (SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) {
1049 ++NumSelectUnPred;
1050 ORmiss << "Not converted to branch because of unpredictable branch. ";
1051 EmitAndPrintRemark(ORE, ORmiss);
1052 return false;
1053 }
1054
1055 // If highly predictable, branch form is more profitable, unless a
1056 // predictable select is inexpensive in the target architecture.
1057 if (isSelectHighlyPredictable(SI) && TLI->isPredictableSelectExpensive()) {
1058 ++NumSelectConvertedHighPred;
1059 OR << "Converted to branch because of highly predictable branch. ";
1060 EmitAndPrintRemark(ORE, OR);
1061 return true;
1062 }
1063
1064 // Look for expensive instructions in the cold operand's (if any) dependence
1065 // slice of any of the selects in the group.
1066 if (hasExpensiveColdOperand(ASI)) {
1067 ++NumSelectConvertedExpColdOperand;
1068 OR << "Converted to branch because of expensive cold operand.";
1069 EmitAndPrintRemark(ORE, OR);
1070 return true;
1071 }
1072
1073 // If latch has a select group with several elements, it is usually profitable
1074 // to convert it to branches. We let `optimizeSelectsInnerLoops` decide if
1075 // conversion is profitable for innermost loops.
1076 auto *BB = SI.getI()->getParent();
1077 auto *L = LI->getLoopFor(BB);
1078 if (L && !L->isInnermost() && L->getLoopLatch() == BB &&
1079 ASI.Selects.size() >= 3) {
1080 OR << "Converted to branch because select group in the latch block is big.";
1081 EmitAndPrintRemark(ORE, OR);
1082 return true;
1083 }
1084
1085 ORmiss << "Not profitable to convert to branch (base heuristic).";
1086 EmitAndPrintRemark(ORE, ORmiss);
1087 return false;
1088}
1089
1091 uint64_t Denominator) {
1092 return (Numerator + (Denominator / 2)) / Denominator;
1093}
1094
1095static bool extractBranchWeights(const SelectOptimizeImpl::SelectLike SI,
1096 uint64_t &TrueVal, uint64_t &FalseVal) {
1097 if (isa<SelectInst>(SI.getI()))
1098 return extractBranchWeights(*SI.getI(), TrueVal, FalseVal);
1099 return false;
1100}
1101
1102bool SelectOptimizeImpl::hasExpensiveColdOperand(const SelectGroup &ASI) {
1103 bool ColdOperand = false;
1104 uint64_t TrueWeight, FalseWeight, TotalWeight;
1105 if (extractBranchWeights(ASI.Selects.front(), TrueWeight, FalseWeight)) {
1106 uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
1107 TotalWeight = TrueWeight + FalseWeight;
1108 // Is there a path with frequency <ColdOperandThreshold% (default:20%) ?
1109 ColdOperand = TotalWeight * ColdOperandThreshold > 100 * MinWeight;
1110 } else if (PSI->hasProfileSummary()) {
1111 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
1112 ASI.Selects.front().getI());
1113 ORmiss << "Profile data available but missing branch-weights metadata for "
1114 "select instruction. ";
1115 EmitAndPrintRemark(ORE, ORmiss);
1116 }
1117 if (!ColdOperand)
1118 return false;
1119 // Check if the cold path's dependence slice is expensive for any of the
1120 // selects of the group.
1121 for (SelectLike SI : ASI.Selects) {
1122 Instruction *ColdI = nullptr;
1123 uint64_t HotWeight;
1124 if (TrueWeight < FalseWeight) {
1125 ColdI = dyn_cast_or_null<Instruction>(SI.getTrueValue());
1126 HotWeight = FalseWeight;
1127 } else {
1128 ColdI = dyn_cast_or_null<Instruction>(SI.getFalseValue());
1129 HotWeight = TrueWeight;
1130 }
1131 if (ColdI) {
1132 std::stack<Instruction *> ColdSlice;
1133 getExclBackwardsSlice(ColdI, ColdSlice, SI.getI());
1134 InstructionCost SliceCost = 0;
1135 while (!ColdSlice.empty()) {
1136 SliceCost += TTI->getInstructionCost(ColdSlice.top(),
1138 ColdSlice.pop();
1139 }
1140 // The colder the cold value operand of the select is the more expensive
1141 // the cmov becomes for computing the cold value operand every time. Thus,
1142 // the colder the cold operand is the more its cost counts.
1143 // Get nearest integer cost adjusted for coldness.
1144 InstructionCost AdjSliceCost =
1145 divideNearest(SliceCost * HotWeight, TotalWeight);
1146 if (AdjSliceCost >=
1148 return true;
1149 }
1150 }
1151 return false;
1152}
1153
1154// Check if it is safe to move LoadI next to the SI.
1155// Conservatively assume it is safe only if there is no instruction
1156// modifying memory in-between the load and the select instruction.
1158 // Assume loads from different basic blocks are unsafe to move.
1159 if (LoadI->getParent() != SI->getParent())
1160 return false;
1161 auto It = LoadI->getIterator();
1162 while (&*It != SI) {
1163 if (It->mayWriteToMemory())
1164 return false;
1165 It++;
1166 }
1167 return true;
1168}
1169
1170// For a given source instruction, collect its backwards dependence slice
1171// consisting of instructions exclusively computed for the purpose of producing
1172// the operands of the source instruction. As an approximation
1173// (sufficiently-accurate in practice), we populate this set with the
1174// instructions of the backwards dependence slice that only have one-use and
1175// form an one-use chain that leads to the source instruction.
1176void SelectOptimizeImpl::getExclBackwardsSlice(Instruction *I,
1177 std::stack<Instruction *> &Slice,
1178 Instruction *SI, bool ForSinking,
1179 const SelectGroup *Group) {
1181 std::queue<Instruction *> Worklist;
1182 Worklist.push(I);
1183 while (!Worklist.empty()) {
1184 Instruction *II = Worklist.front();
1185 Worklist.pop();
1186
1187 // Avoid cycles.
1188 if (!Visited.insert(II).second)
1189 continue;
1190
1191 if (!II->hasOneUse())
1192 continue;
1193
1194 // Cannot soundly sink instructions with side-effects.
1195 // Terminator or phi instructions cannot be sunk.
1196 // Avoid sinking other select instructions (should be handled separetely).
1197 if (ForSinking && (II->isTerminator() || II->mayHaveSideEffects() ||
1199 continue;
1200
1201 // Select-like members of the group are replaced separately, and their
1202 // operands may still be needed on the other branch.
1203 if (ForSinking && Group &&
1204 llvm::any_of(Group->Selects, [&](auto &S) { return S.getI() == II; }))
1205 continue;
1206
1207 // Avoid sinking loads in order not to skip state-modifying instructions,
1208 // that may alias with the loaded address.
1209 // Only allow sinking of loads within the same basic block that are
1210 // conservatively proven to be safe.
1211 if (ForSinking && II->mayReadFromMemory() && !isSafeToSinkLoad(II, SI))
1212 continue;
1213
1214 // Avoid considering instructions with less frequency than the source
1215 // instruction (i.e., avoid colder code regions of the dependence slice).
1216 if (BFI->getBlockFreq(II->getParent()) < BFI->getBlockFreq(I->getParent()))
1217 continue;
1218
1219 // Eligible one-use instruction added to the dependence slice.
1220 Slice.push(II);
1221
1222 // Explore all the operands of the current instruction to expand the slice.
1223 for (Value *Op : II->operand_values())
1224 if (auto *OpI = dyn_cast<Instruction>(Op))
1225 Worklist.push(OpI);
1226 }
1227}
1228
1229bool SelectOptimizeImpl::isSelectHighlyPredictable(const SelectLike SI) {
1230 uint64_t TrueWeight, FalseWeight;
1231 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1232 uint64_t Max = std::max(TrueWeight, FalseWeight);
1233 uint64_t Sum = TrueWeight + FalseWeight;
1234 if (Sum != 0) {
1235 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
1236 if (Probability > TTI->getPredictableBranchThreshold())
1237 return true;
1238 }
1239 }
1240 return false;
1241}
1242
1243bool SelectOptimizeImpl::checkLoopHeuristics(const Loop *L,
1244 const CostInfo LoopCost[2]) {
1245 // Loop-level checks to determine if a non-predicated version (with branches)
1246 // of the loop is more profitable than its predicated version.
1247
1249 return true;
1250
1251 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti",
1252 &*L->getHeader()->getFirstNonPHIIt());
1253
1254 if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
1255 LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
1256 ORmissL << "No select conversion in the loop due to no reduction of loop's "
1257 "critical path. ";
1258 EmitAndPrintRemark(ORE, ORmissL);
1259 return false;
1260 }
1261
1262 Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
1263 LoopCost[1].PredCost - LoopCost[1].NonPredCost};
1264
1265 // Profitably converting to branches need to reduce the loop's critical path
1266 // by at least some threshold (absolute gain of GainCycleThreshold cycles and
1267 // relative gain of 12.5%).
1268 if (Gain[1] < Scaled64::get(GainCycleThreshold) ||
1269 Gain[1] * Scaled64::get(GainRelativeThreshold) < LoopCost[1].PredCost) {
1270 Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
1271 ORmissL << "No select conversion in the loop due to small reduction of "
1272 "loop's critical path. Gain="
1273 << Gain[1].toString()
1274 << ", RelativeGain=" << RelativeGain.toString() << "%. ";
1275 EmitAndPrintRemark(ORE, ORmissL);
1276 return false;
1277 }
1278
1279 // If the loop's critical path involves loop-carried dependences, the gradient
1280 // of the gain needs to be at least GainGradientThreshold% (defaults to 25%).
1281 // This check ensures that the latency reduction for the loop's critical path
1282 // keeps decreasing with sufficient rate beyond the two analyzed loop
1283 // iterations.
1284 if (Gain[1] > Gain[0]) {
1285 Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
1286 (LoopCost[1].PredCost - LoopCost[0].PredCost);
1287 if (GradientGain < Scaled64::get(GainGradientThreshold)) {
1288 ORmissL << "No select conversion in the loop due to small gradient gain. "
1289 "GradientGain="
1290 << GradientGain.toString() << "%. ";
1291 EmitAndPrintRemark(ORE, ORmissL);
1292 return false;
1293 }
1294 }
1295 // If the gain decreases it is not profitable to convert.
1296 else if (Gain[1] < Gain[0]) {
1297 ORmissL
1298 << "No select conversion in the loop due to negative gradient gain. ";
1299 EmitAndPrintRemark(ORE, ORmissL);
1300 return false;
1301 }
1302
1303 // Non-predicated version of the loop is more profitable than its
1304 // predicated version.
1305 return true;
1306}
1307
1308// Computes instruction and loop-critical-path costs for both the predicated
1309// and non-predicated version of the given loop.
1310// Returns false if unable to compute these costs due to invalid cost of loop
1311// instruction(s).
1312bool SelectOptimizeImpl::computeLoopCosts(
1313 const Loop *L, const SelectGroups &SIGroups,
1314 DenseMap<const Instruction *, CostInfo> &InstCostMap, CostInfo *LoopCost) {
1315 LLVM_DEBUG(dbgs() << "Calculating Latency / IPredCost / INonPredCost of loop "
1316 << L->getHeader()->getName() << "\n");
1317 const auto SImap = getSImap(SIGroups);
1318 const auto SGmap = getSGmap(SIGroups);
1319 // Compute instruction and loop-critical-path costs across two iterations for
1320 // both predicated and non-predicated version.
1321 const unsigned Iterations = 2;
1322 for (unsigned Iter = 0; Iter < Iterations; ++Iter) {
1323 // Cost of the loop's critical path.
1324 CostInfo &MaxCost = LoopCost[Iter];
1325 for (BasicBlock *BB : L->getBlocks()) {
1326 for (const Instruction &I : *BB) {
1328 continue;
1329 // Compute the predicated and non-predicated cost of the instruction.
1330 Scaled64 IPredCost = Scaled64::getZero(),
1331 INonPredCost = Scaled64::getZero();
1332
1333 // Assume infinite resources that allow to fully exploit the available
1334 // instruction-level parallelism.
1335 // InstCost = InstLatency + max(Op1Cost, Op2Cost, … OpNCost)
1336 for (const Use &U : I.operands()) {
1337 auto UI = dyn_cast<Instruction>(U.get());
1338 if (!UI)
1339 continue;
1340 if (auto It = InstCostMap.find(UI); It != InstCostMap.end()) {
1341 IPredCost = std::max(IPredCost, It->second.PredCost);
1342 INonPredCost = std::max(INonPredCost, It->second.NonPredCost);
1343 }
1344 }
1345 auto ILatency = computeInstCost(&I);
1346 if (!ILatency) {
1347 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", &I);
1348 ORmissL << "Invalid instruction cost preventing analysis and "
1349 "optimization of the inner-most loop containing this "
1350 "instruction. ";
1351 EmitAndPrintRemark(ORE, ORmissL);
1352 return false;
1353 }
1354 IPredCost += Scaled64::get(*ILatency);
1355 INonPredCost += Scaled64::get(*ILatency);
1356
1357 // For a select that can be converted to branch,
1358 // compute its cost as a branch (non-predicated cost).
1359 //
1360 // BranchCost = PredictedPathCost + MispredictCost
1361 // PredictedPathCost = TrueOpCost * TrueProb + FalseOpCost * FalseProb
1362 // MispredictCost = max(MispredictPenalty, CondCost) * MispredictRate
1363 if (auto It = SImap.find(&I); It != SImap.end()) {
1364 auto SI = It->second;
1365 const auto *SG = SGmap.at(&I);
1366 Scaled64 TrueOpCost = SI.getOpCostOnBranch(true, InstCostMap, TTI);
1367 Scaled64 FalseOpCost = SI.getOpCostOnBranch(false, InstCostMap, TTI);
1368 Scaled64 PredictedPathCost =
1369 getPredictedPathCost(TrueOpCost, FalseOpCost, SI);
1370
1371 Scaled64 CondCost = Scaled64::getZero();
1372 if (auto *CI = dyn_cast<Instruction>(SG->Condition))
1373 if (auto It = InstCostMap.find(CI); It != InstCostMap.end())
1374 CondCost = It->second.NonPredCost;
1375 Scaled64 MispredictCost = getMispredictionCost(SI, CondCost);
1376
1377 INonPredCost = PredictedPathCost + MispredictCost;
1378 }
1379 LLVM_DEBUG(dbgs() << " " << ILatency << "/" << IPredCost << "/"
1380 << INonPredCost << " for " << I << "\n");
1381
1382 InstCostMap[&I] = {IPredCost, INonPredCost};
1383 MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
1384 MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
1385 }
1386 }
1387 LLVM_DEBUG(dbgs() << "Iteration " << Iter + 1
1388 << " MaxCost = " << MaxCost.PredCost << " "
1389 << MaxCost.NonPredCost << "\n");
1390 }
1391 return true;
1392}
1393
1395SelectOptimizeImpl::getSImap(const SelectGroups &SIGroups) {
1397 for (const SelectGroup &ASI : SIGroups)
1398 for (const SelectLike &SI : ASI.Selects)
1399 SImap.try_emplace(SI.getI(), SI);
1400 return SImap;
1401}
1402
1404SelectOptimizeImpl::getSGmap(const SelectGroups &SIGroups) {
1406 for (const SelectGroup &ASI : SIGroups)
1407 for (const SelectLike &SI : ASI.Selects)
1408 SImap.try_emplace(SI.getI(), &ASI);
1409 return SImap;
1410}
1411
1412std::optional<uint64_t>
1413SelectOptimizeImpl::computeInstCost(const Instruction *I) {
1414 InstructionCost ICost =
1415 TTI->getInstructionCost(I, TargetTransformInfo::TCK_Latency);
1416 if (ICost.isValid())
1417 return std::optional<uint64_t>(ICost.getValue());
1418 return std::nullopt;
1419}
1420
1422SelectOptimizeImpl::getMispredictionCost(const SelectLike SI,
1423 const Scaled64 CondCost) {
1424 uint64_t MispredictPenalty = TSI->getMispredictionPenalty();
1425
1426 // Account for the default misprediction rate when using a branch
1427 // (conservatively set to 25% by default).
1428 uint64_t MispredictRate = MispredictDefaultRate;
1429 // If the select condition is obviously predictable, then the misprediction
1430 // rate is zero.
1431 if (isSelectHighlyPredictable(SI))
1432 MispredictRate = 0;
1433
1434 // CondCost is included to account for cases where the computation of the
1435 // condition is part of a long dependence chain (potentially loop-carried)
1436 // that would delay detection of a misprediction and increase its cost.
1437 Scaled64 MispredictCost =
1438 std::max(Scaled64::get(MispredictPenalty), CondCost) *
1439 Scaled64::get(MispredictRate);
1440 MispredictCost /= Scaled64::get(100);
1441
1442 return MispredictCost;
1443}
1444
1445// Returns the cost of a branch when the prediction is correct.
1446// TrueCost * TrueProbability + FalseCost * FalseProbability.
1448SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
1449 const SelectLike SI) {
1450 Scaled64 PredPathCost;
1451 uint64_t TrueWeight, FalseWeight;
1452 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1453 uint64_t SumWeight = TrueWeight + FalseWeight;
1454 if (SumWeight != 0) {
1455 PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
1456 FalseCost * Scaled64::get(FalseWeight);
1457 PredPathCost /= Scaled64::get(SumWeight);
1458 return PredPathCost;
1459 }
1460 }
1461 // Without branch weight metadata, we assume 75% for the one path and 25% for
1462 // the other, and pick the result with the biggest cost.
1463 PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
1464 FalseCost * Scaled64::get(3) + TrueCost);
1465 PredPathCost /= Scaled64::get(4);
1466 return PredPathCost;
1467}
1468
1469bool SelectOptimizeImpl::isSelectKindSupported(const SelectLike SI) {
1471 if (SI.getType()->isVectorTy())
1473 else
1475 return TLI->isSelectSupported(SelectKind);
1476}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Hardware Loops
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:629
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
static bool isSafeToSinkLoad(Instruction *LoadI, Instruction *SI)
static cl::opt< unsigned > ColdOperandMaxCostMultiplier("cold-operand-max-cost-multiplier", cl::desc("Maximum cost multiplier of TCC_expensive for the dependence " "slice of a cold operand to be considered inexpensive."), cl::init(1), cl::Hidden)
static cl::opt< unsigned > ColdOperandThreshold("cold-operand-threshold", cl::desc("Maximum frequency of path for an operand to be considered cold."), cl::init(20), cl::Hidden)
static cl::opt< bool > DisableLoopLevelHeuristics("disable-loop-level-heuristics", cl::Hidden, cl::init(false), cl::desc("Disable loop-level heuristics."))
static cl::opt< unsigned > GainCycleThreshold("select-opti-loop-cycle-gain-threshold", cl::desc("Minimum gain per loop (in cycles) threshold."), cl::init(4), cl::Hidden)
static cl::opt< unsigned > MispredictDefaultRate("mispredict-default-rate", cl::Hidden, cl::init(25), cl::desc("Default mispredict rate (initialized to 25%)."))
static void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE, DiagnosticInfoOptimizationBase &Rem)
static cl::opt< unsigned > GainGradientThreshold("select-opti-loop-gradient-gain-threshold", cl::desc("Gradient gain threshold (%)."), cl::init(25), cl::Hidden)
static cl::opt< unsigned > GainRelativeThreshold("select-opti-loop-relative-gain-threshold", cl::desc("Minimum relative gain per loop threshold (1/X). Defaults to 12.5%"), cl::init(8), cl::Hidden)
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static const uint32_t IV[8]
Definition blake3_impl.h:83
AnalysisUsage & addRequired()
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
iterator end() const
iterator begin() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
bool isColdBlock(const BBType *BB, BFIT *BFI) const
Returns true if BasicBlock BB is considered cold.
Simple representation of a scaled number.
static ScaledNumber get(uint64_t N)
static ScaledNumber getZero()
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
virtual bool isSelectSupported(SelectSupportKind) const
SelectSupportKind
Enum that describes what type of support for selects the target has.
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Target-Independent Code Generator Pass Configuration Options.
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual unsigned getMispredictionPenalty() const
Return the number of extra cycles the processor takes to recover from a branch misprediction.
virtual const TargetLowering * getTargetLowering() const
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_Latency
The latency of instruction.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
@ TCC_Expensive
The cost of a 'div' instruction on x86.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
InstructionCost Cost
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI FunctionPass * createSelectOptimizePass()
This pass converts conditional moves to conditional jumps when profitable.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition MathExtras.h:453
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
LLVM_ABI bool hasProfMD(const Instruction &I)
Checks if an Instruction has MD_prof Metadata.
DWARFExpression::Operation Op
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177