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 "CodeGenOptions.h"
15#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
24#include "llvm/CodeGen/Passes.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instruction.h"
37#include "llvm/Pass.h"
41#include <algorithm>
42#include <queue>
43#include <stack>
44
45using namespace llvm;
46using namespace llvm::PatternMatch;
47
48#define DEBUG_TYPE "select-optimize"
49
50STATISTIC(NumSelectOptAnalyzed,
51 "Number of select groups considered for conversion to branch");
52STATISTIC(NumSelectConvertedExpColdOperand,
53 "Number of select groups converted due to expensive cold operand");
54STATISTIC(NumSelectConvertedHighPred,
55 "Number of select groups converted due to high-predictability");
56STATISTIC(NumSelectUnPred,
57 "Number of select groups not converted due to unpredictability");
58STATISTIC(NumSelectColdBB,
59 "Number of select groups not converted due to cold basic block");
60STATISTIC(NumSelectConvertedLoop,
61 "Number of select groups converted due to loop-level analysis");
62STATISTIC(NumSelectsConverted, "Number of selects converted");
63
64namespace llvm {
66}
67
68namespace {
69
70class SelectOptimizeImpl {
71 const CodeGenOptions *Opts = nullptr;
72 const TargetMachine *TM = nullptr;
73 const TargetSubtargetInfo *TSI = nullptr;
74 const TargetLowering *TLI = nullptr;
75 const TargetTransformInfo *TTI = nullptr;
76 const LoopInfo *LI = nullptr;
77 BlockFrequencyInfo *BFI;
78 ProfileSummaryInfo *PSI = nullptr;
79 OptimizationRemarkEmitter *ORE = nullptr;
80 TargetSchedModel TSchedModel;
81
82public:
83 SelectOptimizeImpl() = default;
84 SelectOptimizeImpl(const TargetMachine *TM) : TM(TM){};
85 PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
86 bool runOnFunction(Function &F, Pass &P);
87
88 using Scaled64 = ScaledNumber<uint64_t>;
89
90 struct CostInfo {
91 /// Predicated cost (with selects as conditional moves).
92 Scaled64 PredCost;
93 /// Non-predicated cost (with selects converted to branches).
94 Scaled64 NonPredCost;
95 };
96
97 /// SelectLike is an abstraction over SelectInst and other operations that can
98 /// act like selects. For example Or(Zext(icmp), X) can be treated like
99 /// select(icmp, X|1, X).
100 class SelectLike {
101 /// The select (/or) instruction.
102 Instruction *I;
103 /// Whether this select is inverted, "not(cond), FalseVal, TrueVal", as
104 /// opposed to the original condition.
105 bool Inverted = false;
106
107 /// The index of the operand that depends on condition. Only for select-like
108 /// instruction such as Or/Add.
109 unsigned CondIdx;
110
111 public:
112 SelectLike(Instruction *I, bool Inverted = false, unsigned CondIdx = 0)
113 : I(I), Inverted(Inverted), CondIdx(CondIdx) {}
114
115 Instruction *getI() { return I; }
116 const Instruction *getI() const { return I; }
117
118 Type *getType() const { return I->getType(); }
119
120 unsigned getConditionOpIndex() { return CondIdx; };
121
122 /// Return the true value for the SelectLike instruction. Note this may not
123 /// exist for all SelectLike instructions. For example, for `or(zext(c), x)`
124 /// the true value would be `or(x,1)`. As this value does not exist, nullptr
125 /// is returned.
126 Value *getTrueValue(bool HonorInverts = true) const {
127 if (Inverted && HonorInverts)
128 return getFalseValue(/*HonorInverts=*/false);
129 if (auto *Sel = dyn_cast<SelectInst>(I))
130 return Sel->getTrueValue();
131 // Or(zext) case - The true value is Or(X), so return nullptr as the value
132 // does not yet exist.
133 if (isa<BinaryOperator>(I))
134 return nullptr;
135
136 llvm_unreachable("Unhandled case in getTrueValue");
137 }
138
139 /// Return the false value for the SelectLike instruction. For example the
140 /// getFalseValue of a select or `x` in `or(zext(c), x)` (which is
141 /// `select(c, x|1, x)`)
142 Value *getFalseValue(bool HonorInverts = true) const {
143 if (Inverted && HonorInverts)
144 return getTrueValue(/*HonorInverts=*/false);
145 if (auto *Sel = dyn_cast<SelectInst>(I))
146 return Sel->getFalseValue();
147 // We are on the branch where the condition is zero, which means BinOp
148 // does not perform any computation, and we can simply return the operand
149 // that is not related to the condition
150 if (auto *BO = dyn_cast<BinaryOperator>(I))
151 return BO->getOperand(1 - CondIdx);
152
153 llvm_unreachable("Unhandled case in getFalseValue");
154 }
155
156 /// Return the NonPredCost cost of the op on \p isTrue branch, given the
157 /// costs in \p InstCostMap. This may need to be generated for select-like
158 /// instructions.
159 Scaled64 getOpCostOnBranch(
160 bool IsTrue, const DenseMap<const Instruction *, CostInfo> &InstCostMap,
161 const TargetTransformInfo *TTI) {
162 auto *V = IsTrue ? getTrueValue() : getFalseValue();
163 if (V) {
164 if (auto *IV = dyn_cast<Instruction>(V)) {
165 auto It = InstCostMap.find(IV);
166 return It != InstCostMap.end() ? It->second.NonPredCost
168 }
169 return Scaled64::getZero();
170 }
171 // If getTrue(False)Value() return nullptr, it means we are dealing with
172 // select-like instructions on the branch where the actual computation is
173 // happening. In that case the cost is equal to the cost of computation +
174 // cost of non-dependant on condition operand
176 getI()->getOpcode(), I->getType(), TargetTransformInfo::TCK_Latency,
177 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
178 {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2});
179 auto TotalCost = Scaled64::get(Cost.getValue());
180 if (auto *OpI = dyn_cast<Instruction>(I->getOperand(1 - CondIdx))) {
181 auto It = InstCostMap.find(OpI);
182 if (It != InstCostMap.end())
183 TotalCost += It->second.NonPredCost;
184 }
185 return TotalCost;
186 }
187 };
188
189private:
190 // Select groups consist of consecutive select-like instructions with the same
191 // condition. Between select-likes could be any number of auxiliary
192 // instructions related to the condition like not, zext, ashr/lshr
193 struct SelectGroup {
194 Value *Condition;
196
197 bool isUnpredictable() const {
198 return any_of(Selects, [](const SelectLike &SI) {
199 return SI.getI()->getMetadata(LLVMContext::MD_unpredictable);
200 });
201 }
202 };
203 using SelectGroups = SmallVector<SelectGroup, 2>;
204
205 // Converts select instructions of a function to conditional jumps when deemed
206 // profitable. Returns true if at least one select was converted.
207 bool optimizeSelects(Function &F);
208
209 // Heuristics for determining which select instructions can be profitably
210 // conveted to branches. Separate heuristics for selects in inner-most loops
211 // and the rest of code regions (base heuristics for non-inner-most loop
212 // regions).
213 void optimizeSelectsBase(Function &F, SelectGroups &ProfSIGroups);
214 void optimizeSelectsInnerLoops(Function &F, SelectGroups &ProfSIGroups);
215
216 // Converts to branches the select groups that were deemed
217 // profitable-to-convert.
218 void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
219
220 // Splits selects of a given basic block into select groups.
221 void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
222
223 // Determines for which select groups it is profitable converting to branches
224 // (base and inner-most-loop heuristics).
225 void findProfitableSIGroupsBase(SelectGroups &SIGroups,
226 SelectGroups &ProfSIGroups);
227 void findProfitableSIGroupsInnerLoops(const Loop *L, SelectGroups &SIGroups,
228 SelectGroups &ProfSIGroups);
229
230 // Determines if a select group should be converted to a branch (base
231 // heuristics).
232 bool isConvertToBranchProfitableBase(const SelectGroup &ASI);
233
234 // Returns true if there are expensive instructions in the cold value
235 // operand's (if any) dependence slice of any of the selects of the given
236 // group.
237 bool hasExpensiveColdOperand(const SelectGroup &ASI);
238
239 // For a given source instruction, collect its backwards dependence slice
240 // consisting of instructions exclusively computed for producing the operands
241 // of the source instruction. When sinking, the slice stops at members of
242 // \p Group.
243 void getExclBackwardsSlice(Instruction *I, std::stack<Instruction *> &Slice,
244 Instruction *SI, bool ForSinking = false,
245 const SelectGroup *Group = nullptr);
246
247 // Returns true if the condition of the select is highly predictable.
248 bool isSelectHighlyPredictable(const SelectLike SI);
249
250 // Loop-level checks to determine if a non-predicated version (with branches)
251 // of the given loop is more profitable than its predicated version.
252 bool checkLoopHeuristics(const Loop *L, const CostInfo LoopDepth[2]);
253
254 // Computes instruction and loop-critical-path costs for both the predicated
255 // and non-predicated version of the given loop.
256 bool computeLoopCosts(const Loop *L, const SelectGroups &SIGroups,
257 DenseMap<const Instruction *, CostInfo> &InstCostMap,
258 CostInfo *LoopCost);
259
260 // Returns a set of all the select instructions in the given select groups.
261 SmallDenseMap<const Instruction *, SelectLike, 2>
262 getSImap(const SelectGroups &SIGroups);
263
264 // Returns a map from select-like instructions to the corresponding select
265 // group.
266 SmallDenseMap<const Instruction *, const SelectGroup *, 2>
267 getSGmap(const SelectGroups &SIGroups);
268
269 // Returns the latency cost of a given instruction.
270 std::optional<uint64_t> computeInstCost(const Instruction *I);
271
272 // Returns the misprediction cost of a given select when converted to branch.
273 Scaled64 getMispredictionCost(const SelectLike SI, const Scaled64 CondCost);
274
275 // Returns the cost of a branch when the prediction is correct.
276 Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
277 const SelectLike SI);
278
279 // Returns true if the target architecture supports lowering a given select.
280 bool isSelectKindSupported(const SelectLike SI);
281};
282
283class SelectOptimize : public FunctionPass {
284 SelectOptimizeImpl Impl;
285
286public:
287 static char ID;
288
289 SelectOptimize() : FunctionPass(ID) {}
290
291 bool runOnFunction(Function &F) override {
292 if (skipFunction(F))
293 return false;
294
295 return Impl.runOnFunction(F, *this);
296 }
297
298 void getAnalysisUsage(AnalysisUsage &AU) const override {
299 AU.addRequired<ProfileSummaryInfoWrapperPass>();
300 AU.addRequired<TargetPassConfig>();
301 AU.addRequired<TargetTransformInfoWrapperPass>();
302 AU.addRequired<LoopInfoWrapperPass>();
303 AU.addRequired<BlockFrequencyInfoWrapperPass>();
304 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
305 }
306};
307
308} // namespace
309
312 SelectOptimizeImpl Impl(TM);
313 return Impl.run(F, FAM);
314}
315
316char SelectOptimize::ID = 0;
317
318INITIALIZE_PASS_BEGIN(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
319 false)
326INITIALIZE_PASS_END(SelectOptimize, DEBUG_TYPE, "Optimize selects", false,
327 false)
328
329FunctionPass *llvm::createSelectOptimizePass() { return new SelectOptimize(); }
330
331PreservedAnalyses SelectOptimizeImpl::run(Function &F,
333 TSI = TM->getSubtargetImpl(F);
334 TLI = TSI->getTargetLowering();
335
336 // If none of the select types are supported then skip this pass.
337 // This is an optimization pass. Legality issues will be handled by
338 // instruction selection.
339 if (!TLI->isSelectSupported(TargetLowering::ScalarValSelect) &&
340 !TLI->isSelectSupported(TargetLowering::ScalarCondVectorVal) &&
341 !TLI->isSelectSupported(TargetLowering::VectorMaskSelect))
342 return PreservedAnalyses::all();
343
344 TTI = &FAM.getResult<TargetIRAnalysis>(F);
345 if (!TTI->enableSelectOptimize())
346 return PreservedAnalyses::all();
347
349 .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
350 if (!PSI)
351 reportFatalUsageError("this pass requires the profile-summary module "
352 "analysis to be available");
353 BFI = &FAM.getResult<BlockFrequencyAnalysis>(F);
354
355 // When optimizing for size, selects are preferable over branches.
356 if (llvm::shouldOptimizeForSize(&F, PSI, BFI))
357 return PreservedAnalyses::all();
358
359 LI = &FAM.getResult<LoopAnalysis>(F);
360 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
361 TSchedModel.init(TSI);
362
363 bool Changed = optimizeSelects(F);
365}
366
367bool SelectOptimizeImpl::runOnFunction(Function &F, Pass &P) {
368 TM = &P.getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
369 TSI = TM->getSubtargetImpl(F);
370 TLI = TSI->getTargetLowering();
371
372 // If none of the select types are supported then skip this pass.
373 // This is an optimization pass. Legality issues will be handled by
374 // instruction selection.
378 return false;
379
380 TTI = &P.getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
381
382 if (!TTI->enableSelectOptimize())
383 return false;
384
385 LI = &P.getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
386 BFI = &P.getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
387 PSI = &P.getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
388 ORE = &P.getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
389 TSchedModel.init(TSI);
390
391 // When optimizing for size, selects are preferable over branches.
392 if (llvm::shouldOptimizeForSize(&F, PSI, BFI))
393 return false;
394
395 return optimizeSelects(F);
396}
397
398bool SelectOptimizeImpl::optimizeSelects(Function &F) {
399 Opts = &getCodeGenOptions(F);
400 // Determine for which select groups it is profitable converting to branches.
401 SelectGroups ProfSIGroups;
402 // Base heuristics apply only to non-loops and outer loops.
403 optimizeSelectsBase(F, ProfSIGroups);
404 // Separate heuristics for inner-most loops.
405 optimizeSelectsInnerLoops(F, ProfSIGroups);
406
407 // Convert to branches the select groups that were deemed
408 // profitable-to-convert.
409 convertProfitableSIGroups(ProfSIGroups);
410
411 // Code modified if at least one select group was converted.
412 return !ProfSIGroups.empty();
413}
414
415void SelectOptimizeImpl::optimizeSelectsBase(Function &F,
416 SelectGroups &ProfSIGroups) {
417 // Collect all the select groups.
418 SelectGroups SIGroups;
419 for (BasicBlock &BB : F) {
420 // Base heuristics apply only to non-loops and outer loops.
421 Loop *L = LI->getLoopFor(&BB);
422 if (L && L->isInnermost())
423 continue;
424 collectSelectGroups(BB, SIGroups);
425 }
426
427 // Determine for which select groups it is profitable converting to branches.
428 findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
429}
430
431void SelectOptimizeImpl::optimizeSelectsInnerLoops(Function &F,
432 SelectGroups &ProfSIGroups) {
434 // Need to check size on each iteration as we accumulate child loops.
435 for (unsigned long i = 0; i < Loops.size(); ++i)
436 llvm::append_range(Loops, Loops[i]->getSubLoops());
437
438 for (Loop *L : Loops) {
439 if (!L->isInnermost())
440 continue;
441
442 SelectGroups SIGroups;
443 for (BasicBlock *BB : L->getBlocks())
444 collectSelectGroups(*BB, SIGroups);
445
446 findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
447 }
448}
449
450/// Returns optimised value on \p IsTrue branch. For SelectInst that would be
451/// either True or False value. For (BinaryOperator) instructions, where the
452/// condition may be skipped, the operation will use a non-conditional operand.
453/// For example, for `or(V,zext(cond))` this function would return V.
454/// However, if the conditional operand on \p IsTrue branch matters, we create a
455/// clone of instruction at the end of that branch \p B and replace the
456/// condition operand with a constant.
457///
458/// Also /p OptSelects contains previously optimised select-like instructions.
459/// If the current value uses one of the optimised values, we can optimise it
460/// further by replacing it with the corresponding value on the given branch
462 SelectOptimizeImpl::SelectLike &SI, bool isTrue,
463 SmallDenseMap<Instruction *, std::pair<Value *, Value *>, 2> &OptSelects,
464 BasicBlock *B) {
465 Value *V = isTrue ? SI.getTrueValue() : SI.getFalseValue();
466 if (V) {
467 if (auto *IV = dyn_cast<Instruction>(V))
468 if (auto It = OptSelects.find(IV); It != OptSelects.end())
469 return isTrue ? It->second.first : It->second.second;
470 return V;
471 }
472
473 auto *BO = cast<BinaryOperator>(SI.getI());
474 assert((BO->getOpcode() == Instruction::Add ||
475 BO->getOpcode() == Instruction::Or ||
476 BO->getOpcode() == Instruction::Sub) &&
477 "Only currently handling Add, Or and Sub binary operators.");
478
479 auto *CBO = BO->clone();
480 auto CondIdx = SI.getConditionOpIndex();
481 auto *AuxI = cast<Instruction>(CBO->getOperand(CondIdx));
482 if (isa<ZExtInst>(AuxI) || isa<LShrOperator>(AuxI)) {
483 CBO->setOperand(CondIdx, ConstantInt::get(CBO->getType(), 1));
484 } else {
485 assert((isa<AShrOperator>(AuxI) || isa<SExtInst>(AuxI)) &&
486 "Unexpected opcode");
487 CBO->setOperand(CondIdx, ConstantInt::getAllOnesValue(CBO->getType()));
488 }
489
490 unsigned OtherIdx = 1 - CondIdx;
491 if (auto *IV = dyn_cast<Instruction>(CBO->getOperand(OtherIdx))) {
492 if (auto It = OptSelects.find(IV); It != OptSelects.end())
493 CBO->setOperand(OtherIdx, isTrue ? It->second.first : It->second.second);
494 }
495 CBO->insertBefore(B->getTerminator()->getIterator());
496 return CBO;
497}
498
499void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
500 for (SelectGroup &ASI : ProfSIGroups) {
501 // The code transformation here is a modified version of the sinking
502 // transformation in CodeGenPrepare::optimizeSelectInst with a more
503 // aggressive strategy of which instructions to sink.
504 //
505 // TODO: eliminate the redundancy of logic transforming selects to branches
506 // by removing CodeGenPrepare::optimizeSelectInst and optimizing here
507 // selects for all cases (with and without profile information).
508
509 // Transform a sequence like this:
510 // start:
511 // %cmp = cmp uge i32 %a, %b
512 // %sel = select i1 %cmp, i32 %c, i32 %d
513 //
514 // Into:
515 // start:
516 // %cmp = cmp uge i32 %a, %b
517 // %cmp.frozen = freeze %cmp
518 // br i1 %cmp.frozen, label %select.true, label %select.false
519 // select.true:
520 // br label %select.end
521 // select.false:
522 // br label %select.end
523 // select.end:
524 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
525 //
526 // %cmp should be frozen, otherwise it may introduce undefined behavior.
527 // In addition, we may sink instructions that produce %c or %d into the
528 // destination(s) of the new branch.
529 // If the true or false blocks do not contain a sunken instruction, that
530 // block and its branch may be optimized away. In that case, one side of the
531 // first branch will point directly to select.end, and the corresponding PHI
532 // predecessor block will be the start block.
533
534 // Find all the instructions that can be soundly sunk to the true/false
535 // blocks. These are instructions that are computed solely for producing the
536 // operands of the select instructions in the group and can be sunk without
537 // breaking the semantics of the LLVM IR (e.g., cannot sink instructions
538 // with side effects).
539 SmallVector<std::stack<Instruction *>, 2> TrueSlices, FalseSlices;
540 typedef std::stack<Instruction *>::size_type StackSizeType;
541 StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0;
542 Instruction *SelectWithProfile = nullptr;
543 bool SelectWithProfileIsInverted = false;
544 for (SelectLike &SI : ASI.Selects) {
545 if (!isa<SelectInst>(SI.getI()))
546 continue;
547 // For each select, compute the sinkable dependence chains of the true and
548 // false operands.
549 if (auto *TI = dyn_cast_or_null<Instruction>(SI.getTrueValue())) {
550 std::stack<Instruction *> TrueSlice;
551 getExclBackwardsSlice(TI, TrueSlice, SI.getI(), true, &ASI);
552 maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size());
553 TrueSlices.push_back(TrueSlice);
554 }
555 if (auto *FI = dyn_cast_or_null<Instruction>(SI.getFalseValue())) {
556 if (isa<SelectInst>(SI.getI()) || !FI->hasOneUse()) {
557 std::stack<Instruction *> FalseSlice;
558 getExclBackwardsSlice(FI, FalseSlice, SI.getI(), true, &ASI);
559 maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size());
560 FalseSlices.push_back(FalseSlice);
561 }
562 }
563 // Also see if the select has profile data that we can propagate later
564 // to the conditional branch.
565 Value *SelectCondition = cast<SelectInst>(SI.getI())->getCondition();
566 if (hasProfMD(*SI.getI()) && ASI.Condition == SelectCondition) {
567 SelectWithProfile = SI.getI();
568 } else if (hasProfMD(*SI.getI()) &&
569 match(SelectCondition, m_Not(m_Value(ASI.Condition)))) {
570 SelectWithProfile = SI.getI();
571 SelectWithProfileIsInverted = true;
572 }
573 }
574 // In the case of multiple select instructions in the same group, the order
575 // of non-dependent instructions (instructions of different dependence
576 // slices) in the true/false blocks appears to affect performance.
577 // Interleaving the slices seems to experimentally be the optimal approach.
578 // This interleaving scheduling allows for more ILP (with a natural downside
579 // of increasing a bit register pressure) compared to a simple ordering of
580 // one whole chain after another. One would expect that this ordering would
581 // not matter since the scheduling in the backend of the compiler would
582 // take care of it, but apparently the scheduler fails to deliver optimal
583 // ILP with a naive ordering here.
584 SmallVector<Instruction *, 2> TrueSlicesInterleaved, FalseSlicesInterleaved;
585 for (StackSizeType IS = 0; IS < maxTrueSliceLen; ++IS) {
586 for (auto &S : TrueSlices) {
587 if (!S.empty()) {
588 TrueSlicesInterleaved.push_back(S.top());
589 S.pop();
590 }
591 }
592 }
593 for (StackSizeType IS = 0; IS < maxFalseSliceLen; ++IS) {
594 for (auto &S : FalseSlices) {
595 if (!S.empty()) {
596 FalseSlicesInterleaved.push_back(S.top());
597 S.pop();
598 }
599 }
600 }
601
602 // We split the block containing the select(s) into two blocks.
603 SelectLike &SI = ASI.Selects.front();
604 SelectLike &LastSI = ASI.Selects.back();
605 BasicBlock *StartBlock = SI.getI()->getParent();
606 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI.getI()));
607 // With RemoveDIs turned off, SplitPt can be a dbg.* intrinsic. With
608 // RemoveDIs turned on, SplitPt would instead point to the next
609 // instruction. To match existing dbg.* intrinsic behaviour with RemoveDIs,
610 // tell splitBasicBlock that we want to include any DbgVariableRecords
611 // attached to SplitPt in the splice.
612 SplitPt.setHeadBit(true);
613 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
614 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
615 // Delete the unconditional branch that was just created by the split.
616 StartBlock->getTerminator()->eraseFromParent();
617
618 // Hoist any pseudo and auxiliary instructions that were in-between the
619 // select group before the group, since the true/false values may use them.
621 auto DIt = SI.getI()->getIterator();
622 auto NIt = ASI.Selects.begin();
623 while (&*DIt != LastSI.getI()) {
624 if (NIt != ASI.Selects.end() && &*DIt == NIt->getI())
625 ++NIt;
626 else
627 HoistInstrs.push_back(&*DIt);
628 DIt++;
629 }
630 for (auto *HI : HoistInstrs)
631 HI->moveBefore(SI.getI()->getIterator());
632
633 // Duplicate implementation for DbgRecords, the non-instruction debug-info
634 // format. Helper lambda for moving DbgRecords to the end block.
635 auto TransferDbgRecords = [&](Instruction &I) {
636 for (auto &DbgRecord :
637 llvm::make_early_inc_range(I.getDbgRecordRange())) {
640 EndBlock->getFirstInsertionPt());
641 }
642 };
643
644 // Iterate over all instructions in between SI and LastSI, not including
645 // SI itself. These are all the variable assignments that happen "in the
646 // middle" of the select group.
647 auto R = make_range(std::next(SI.getI()->getIterator()),
648 std::next(LastSI.getI()->getIterator()));
649 llvm::for_each(R, TransferDbgRecords);
650
651 // These are the new basic blocks for the conditional branch.
652 // At least one will become an actual new basic block.
653 BasicBlock *TrueBlock = nullptr, *FalseBlock = nullptr;
654 UncondBrInst *TrueBranch = nullptr, *FalseBranch = nullptr;
655 // Checks if select-like instruction would materialise on the given branch
656 auto HasSelectLike = [](SelectGroup &SG, bool IsTrue) {
657 for (auto &SL : SG.Selects) {
658 if ((IsTrue ? SL.getTrueValue() : SL.getFalseValue()) == nullptr)
659 return true;
660 }
661 return false;
662 };
663 if (!TrueSlicesInterleaved.empty() || HasSelectLike(ASI, true)) {
664 TrueBlock = BasicBlock::Create(EndBlock->getContext(), "select.true.sink",
665 EndBlock->getParent(), EndBlock);
666 TrueBranch = UncondBrInst::Create(EndBlock, TrueBlock);
667 TrueBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
668 for (Instruction *TrueInst : TrueSlicesInterleaved)
669 TrueInst->moveBefore(TrueBranch->getIterator());
670 }
671 if (!FalseSlicesInterleaved.empty() || HasSelectLike(ASI, false)) {
672 FalseBlock =
673 BasicBlock::Create(EndBlock->getContext(), "select.false.sink",
674 EndBlock->getParent(), EndBlock);
675 FalseBranch = UncondBrInst::Create(EndBlock, FalseBlock);
676 FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
677 for (Instruction *FalseInst : FalseSlicesInterleaved)
678 FalseInst->moveBefore(FalseBranch->getIterator());
679 }
680 // If there was nothing to sink, then arbitrarily choose the 'false' side
681 // for a new input value to the PHI.
682 if (TrueBlock == FalseBlock) {
683 assert(TrueBlock == nullptr &&
684 "Unexpected basic block transform while optimizing select");
685
686 FalseBlock = BasicBlock::Create(StartBlock->getContext(), "select.false",
687 EndBlock->getParent(), EndBlock);
688 auto *FalseBranch = UncondBrInst::Create(EndBlock, FalseBlock);
689 FalseBranch->setDebugLoc(SI.getI()->getDebugLoc());
690 }
691
692 // Insert the real conditional branch based on the original condition.
693 // If we did not create a new block for one of the 'true' or 'false' paths
694 // of the condition, it means that side of the branch goes to the end block
695 // directly and the path originates from the start block from the point of
696 // view of the new PHI.
697 BasicBlock *TT, *FT;
698 if (TrueBlock == nullptr) {
699 TT = EndBlock;
700 FT = FalseBlock;
701 TrueBlock = StartBlock;
702 } else if (FalseBlock == nullptr) {
703 TT = TrueBlock;
704 FT = EndBlock;
705 FalseBlock = StartBlock;
706 } else {
707 TT = TrueBlock;
708 FT = FalseBlock;
709 }
710 IRBuilder<> IB(SI.getI());
711 auto *CondFr =
712 IB.CreateFreeze(ASI.Condition, ASI.Condition->getName() + ".frozen");
713
715
716 // Use reverse iterator because later select may use the value of the
717 // earlier select, and we need to propagate value through earlier select
718 // to get the PHI operand.
719 auto InsertionPoint = EndBlock->begin();
720 for (SelectLike &SI : ASI.Selects) {
721 // The select itself is replaced with a PHI Node.
722 PHINode *PN = PHINode::Create(SI.getType(), 2, "");
723 PN->insertBefore(InsertionPoint);
724 PN->takeName(SI.getI());
725 // Current instruction might be a condition of some other group, so we
726 // need to replace it there to avoid dangling pointer
727 if (PN->getType()->isIntegerTy(1)) {
728 for (auto &SG : ProfSIGroups) {
729 if (SG.Condition == SI.getI())
730 SG.Condition = PN;
731 }
732 }
733 SI.getI()->replaceAllUsesWith(PN);
734 auto *TV = getTrueOrFalseValue(SI, true, INS, TrueBlock);
735 auto *FV = getTrueOrFalseValue(SI, false, INS, FalseBlock);
736 INS[PN] = {TV, FV};
737 PN->addIncoming(TV, TrueBlock);
738 PN->addIncoming(FV, FalseBlock);
739 PN->setDebugLoc(SI.getI()->getDebugLoc());
740 ++NumSelectsConverted;
741 }
742 Instruction *CondBr = IB.CreateCondBr(CondFr, TT, FT, SI.getI());
743 if (!ProfcheckDisableMetadataFixes && SelectWithProfile) {
744 CondBr->copyMetadata(*SelectWithProfile, {llvm::LLVMContext::MD_prof});
745 if (SelectWithProfileIsInverted)
746 CondBr->swapProfMetadata();
747 } else {
749 }
750
751 // Remove the old select instructions, now that they are not longer used.
752 for (SelectLike &SI : ASI.Selects)
753 SI.getI()->eraseFromParent();
754 }
755}
756
757void SelectOptimizeImpl::collectSelectGroups(BasicBlock &BB,
758 SelectGroups &SIGroups) {
759 // Represents something that can be considered as select instruction.
760 // Auxiliary instruction are instructions that depends on a condition and have
761 // zero or some constant value on True/False branch, such as:
762 // * ZExt(1bit)
763 // * SExt(1bit)
764 // * Not(1bit)
765 // * A(L)Shr(Val), ValBitSize - 1, where there is a condition like `Val <= 0`
766 // earlier in the BB. For conditions that check the sign of the Val compiler
767 // may generate shifts instead of ZExt/SExt.
768 struct SelectLikeInfo {
769 Value *Cond;
770 bool IsAuxiliary;
771 bool IsInverted;
772 unsigned ConditionIdx;
773 };
774
776 // Keeps visited comparisons to help identify AShr/LShr variants of auxiliary
777 // instructions.
779
780 // Check if the instruction is SelectLike or might be part of SelectLike
781 // expression, put information into SelectInfo and return the iterator to the
782 // inserted position.
783 auto ProcessSelectInfo = [&SelectInfo, &SeenCmp](Instruction *I) {
784 if (auto *Cmp = dyn_cast<CmpInst>(I)) {
785 SeenCmp.insert(Cmp);
786 return SelectInfo.end();
787 }
788
789 Value *Cond;
791 Cond->getType()->isIntegerTy(1)) {
792 bool Inverted = match(Cond, m_Not(m_Value(Cond)));
793 return SelectInfo.insert({I, {Cond, true, Inverted, 0}}).first;
794 }
795
796 if (match(I, m_Not(m_Value(Cond)))) {
797 return SelectInfo.insert({I, {Cond, true, true, 0}}).first;
798 }
799
800 // Select instruction are what we are usually looking for.
801 if (match(I, m_Select(m_Value(Cond), m_Value(), m_Value()))) {
802 bool Inverted = match(Cond, m_Not(m_Value(Cond)));
803 return SelectInfo.insert({I, {Cond, false, Inverted, 0}}).first;
804 }
805 Value *Val;
806 ConstantInt *Shift;
807 if (match(I, m_Shr(m_Value(Val), m_ConstantInt(Shift))) &&
808 I->getType()->getIntegerBitWidth() == Shift->getZExtValue() + 1) {
809 for (auto *CmpI : SeenCmp) {
810 auto Pred = CmpI->getPredicate();
811 if (Val != CmpI->getOperand(0))
812 continue;
813 if ((Pred == CmpInst::ICMP_SGT &&
814 match(CmpI->getOperand(1), m_ConstantInt<-1>())) ||
816 match(CmpI->getOperand(1), m_Zero())) ||
818 match(CmpI->getOperand(1), m_Zero())) ||
820 match(CmpI->getOperand(1), m_ConstantInt<-1>()))) {
821 bool Inverted =
823 return SelectInfo.insert({I, {CmpI, true, Inverted, 0}}).first;
824 }
825 }
826 return SelectInfo.end();
827 }
828
829 // An BinOp(Aux(X), Y) can also be treated like a select, with condition X
830 // and values Y|1 and Y.
831 // `Aux` can be either `ZExt(1bit)`, `SExt(1bit)` or `XShr(Val), ValBitSize
832 // - 1` `BinOp` can be Add, Sub, Or
833 Value *X;
834 auto MatchZExtOrSExtPattern =
836 auto MatchShiftPattern =
838
839 // This check is unnecessary, but it prevents costly access to the
840 // SelectInfo map.
841 if ((match(I, MatchZExtOrSExtPattern) && X->getType()->isIntegerTy(1)) ||
842 (match(I, MatchShiftPattern) &&
843 X->getType()->getIntegerBitWidth() == Shift->getZExtValue() + 1)) {
844 if (I->getOpcode() != Instruction::Add &&
845 I->getOpcode() != Instruction::Sub &&
846 I->getOpcode() != Instruction::Or)
847 return SelectInfo.end();
848
849 if (I->getOpcode() == Instruction::Or && I->getType()->isIntegerTy(1))
850 return SelectInfo.end();
851
852 // Iterate through operands and find dependant on recognised sign
853 // extending auxiliary select-like instructions. The operand index does
854 // not matter for Add and Or. However, for Sub, we can only safely
855 // transform when the operand is second.
856 unsigned Idx = I->getOpcode() == Instruction::Sub ? 1 : 0;
857 for (; Idx < 2; Idx++) {
858 auto *Op = I->getOperand(Idx);
859 auto It = SelectInfo.find(Op);
860 if (It != SelectInfo.end() && It->second.IsAuxiliary) {
861 Cond = It->second.Cond;
862 bool Inverted = It->second.IsInverted;
863 return SelectInfo.insert({I, {Cond, false, Inverted, Idx}}).first;
864 }
865 }
866 }
867 return SelectInfo.end();
868 };
869
870 bool AlreadyProcessed = false;
871 BasicBlock::iterator BBIt = BB.begin();
873 while (BBIt != BB.end()) {
874 Instruction *I = &*BBIt++;
876 continue;
877
878 if (!AlreadyProcessed)
879 It = ProcessSelectInfo(I);
880 else
881 AlreadyProcessed = false;
882
883 if (It == SelectInfo.end() || It->second.IsAuxiliary)
884 continue;
885
886 if (!TTI->shouldTreatInstructionLikeSelect(I))
887 continue;
888
889 Value *Cond = It->second.Cond;
890 // Vector conditions are not supported.
891 if (!Cond->getType()->isIntegerTy(1))
892 continue;
893
894 SelectGroup SIGroup = {Cond, {}};
895 SIGroup.Selects.emplace_back(I, It->second.IsInverted,
896 It->second.ConditionIdx);
897
898 // If the select type is not supported, no point optimizing it.
899 // Instruction selection will take care of it.
900 if (!isSelectKindSupported(SIGroup.Selects.front()))
901 continue;
902
903 while (BBIt != BB.end()) {
904 Instruction *NI = &*BBIt;
905 // Pseudo instructions should be skipped and not prevent the
906 // formation of a select group.
907 if (isa<PseudoProbeInst>(NI)) {
908 ++BBIt;
909 continue;
910 }
911
912 It = ProcessSelectInfo(NI);
913 if (It == SelectInfo.end()) {
914 AlreadyProcessed = true;
915 break;
916 }
917
918 // Auxiliary with same condition
919 auto [CurrCond, IsAux, IsRev, CondIdx] = It->second;
920 if (Cond != CurrCond) {
921 AlreadyProcessed = true;
922 break;
923 }
924
925 if (!IsAux)
926 SIGroup.Selects.emplace_back(NI, IsRev, CondIdx);
927 ++BBIt;
928 }
929 LLVM_DEBUG({
930 dbgs() << "New Select group (" << SIGroup.Selects.size() << ") with\n";
931 for (auto &SI : SIGroup.Selects)
932 dbgs() << " " << *SI.getI() << "\n";
933 });
934
935 SIGroups.push_back(SIGroup);
936 }
937}
938
939void SelectOptimizeImpl::findProfitableSIGroupsBase(
940 SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
941 for (SelectGroup &ASI : SIGroups) {
942 ++NumSelectOptAnalyzed;
943 if (isConvertToBranchProfitableBase(ASI))
944 ProfSIGroups.push_back(ASI);
945 }
946}
947
950 LLVM_DEBUG(dbgs() << Rem.getMsg() << "\n");
951 ORE->emit(Rem);
952}
953
954void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops(
955 const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
956 NumSelectOptAnalyzed += SIGroups.size();
957 // For each select group in an inner-most loop,
958 // a branch is more preferable than a select/conditional-move if:
959 // i) conversion to branches for all the select groups of the loop satisfies
960 // loop-level heuristics including reducing the loop's critical path by
961 // some threshold (see SelectOptimizeImpl::checkLoopHeuristics); and
962 // ii) the total cost of the select group is cheaper with a branch compared
963 // to its predicated version. The cost is in terms of latency and the cost
964 // of a select group is the cost of its most expensive select instruction
965 // (assuming infinite resources and thus fully leveraging available ILP).
966
967 // Unpredictable selects should never be converted to branches.
968 erase_if(SIGroups, [&](const SelectGroup &ASI) {
969 if (!ASI.isUnpredictable())
970 return false;
971 ++NumSelectUnPred;
972 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
973 ASI.Selects.front().getI());
974 ORmiss << "Not converted to branch because of unpredictable branch. ";
975 EmitAndPrintRemark(ORE, ORmiss);
976 return true;
977 });
978
980 CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
981 {Scaled64::getZero(), Scaled64::getZero()}};
982 if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
983 !checkLoopHeuristics(L, LoopCost)) {
984 return;
985 }
986
987 for (SelectGroup &ASI : SIGroups) {
988 // Assuming infinite resources, the cost of a group of instructions is the
989 // cost of the most expensive instruction of the group.
990 Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
991 for (SelectLike &SI : ASI.Selects) {
992 const auto &ICM = InstCostMap[SI.getI()];
993 SelectCost = std::max(SelectCost, ICM.PredCost);
994 BranchCost = std::max(BranchCost, ICM.NonPredCost);
995 }
996 if (BranchCost < SelectCost) {
997 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti",
998 ASI.Selects.front().getI());
999 OR << "Profitable to convert to branch (loop analysis). BranchCost="
1000 << BranchCost.toString() << ", SelectCost=" << SelectCost.toString()
1001 << ". ";
1002 EmitAndPrintRemark(ORE, OR);
1003 ++NumSelectConvertedLoop;
1004 ProfSIGroups.push_back(ASI);
1005 } else {
1006 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
1007 ASI.Selects.front().getI());
1008 ORmiss << "Select is more profitable (loop analysis). BranchCost="
1009 << BranchCost.toString()
1010 << ", SelectCost=" << SelectCost.toString() << ". ";
1011 EmitAndPrintRemark(ORE, ORmiss);
1012 }
1013 }
1014}
1015
1016bool SelectOptimizeImpl::isConvertToBranchProfitableBase(
1017 const SelectGroup &ASI) {
1018 const SelectLike &SI = ASI.Selects.front();
1019 LLVM_DEBUG(dbgs() << "Analyzing select group containing " << *SI.getI()
1020 << "\n");
1021 OptimizationRemark OR(DEBUG_TYPE, "SelectOpti", SI.getI());
1022 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti", SI.getI());
1023
1024 // Skip cold basic blocks. Better to optimize for size for cold blocks.
1025 if (PSI->isColdBlock(SI.getI()->getParent(), BFI)) {
1026 ++NumSelectColdBB;
1027 ORmiss << "Not converted to branch because of cold basic block. ";
1028 EmitAndPrintRemark(ORE, ORmiss);
1029 return false;
1030 }
1031
1032 // If unpredictable, branch form is less profitable.
1033 if (SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) {
1034 ++NumSelectUnPred;
1035 ORmiss << "Not converted to branch because of unpredictable branch. ";
1036 EmitAndPrintRemark(ORE, ORmiss);
1037 return false;
1038 }
1039
1040 // If highly predictable, branch form is more profitable, unless a
1041 // predictable select is inexpensive in the target architecture.
1042 if (isSelectHighlyPredictable(SI) && TLI->isPredictableSelectExpensive()) {
1043 ++NumSelectConvertedHighPred;
1044 OR << "Converted to branch because of highly predictable branch. ";
1045 EmitAndPrintRemark(ORE, OR);
1046 return true;
1047 }
1048
1049 // Look for expensive instructions in the cold operand's (if any) dependence
1050 // slice of any of the selects in the group.
1051 if (hasExpensiveColdOperand(ASI)) {
1052 ++NumSelectConvertedExpColdOperand;
1053 OR << "Converted to branch because of expensive cold operand.";
1054 EmitAndPrintRemark(ORE, OR);
1055 return true;
1056 }
1057
1058 // If latch has a select group with several elements, it is usually profitable
1059 // to convert it to branches. We let `optimizeSelectsInnerLoops` decide if
1060 // conversion is profitable for innermost loops.
1061 auto *BB = SI.getI()->getParent();
1062 auto *L = LI->getLoopFor(BB);
1063 if (L && !L->isInnermost() && L->getLoopLatch() == BB &&
1064 ASI.Selects.size() >= 3) {
1065 OR << "Converted to branch because select group in the latch block is big.";
1066 EmitAndPrintRemark(ORE, OR);
1067 return true;
1068 }
1069
1070 ORmiss << "Not profitable to convert to branch (base heuristic).";
1071 EmitAndPrintRemark(ORE, ORmiss);
1072 return false;
1073}
1074
1076 uint64_t Denominator) {
1077 return (Numerator + (Denominator / 2)) / Denominator;
1078}
1079
1080static bool extractBranchWeights(const SelectOptimizeImpl::SelectLike SI,
1081 uint64_t &TrueVal, uint64_t &FalseVal) {
1082 if (isa<SelectInst>(SI.getI()))
1083 return extractBranchWeights(*SI.getI(), TrueVal, FalseVal);
1084 return false;
1085}
1086
1087bool SelectOptimizeImpl::hasExpensiveColdOperand(const SelectGroup &ASI) {
1088 bool ColdOperand = false;
1089 uint64_t TrueWeight, FalseWeight, TotalWeight;
1090 if (extractBranchWeights(ASI.Selects.front(), TrueWeight, FalseWeight)) {
1091 uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
1092 TotalWeight = TrueWeight + FalseWeight;
1093 // Is there a path with frequency <ColdOperandThreshold% (default:20%) ?
1094 ColdOperand = TotalWeight * Opts->cold_operand_threshold > 100 * MinWeight;
1095 } else if (PSI->hasProfileSummary()) {
1096 OptimizationRemarkMissed ORmiss(DEBUG_TYPE, "SelectOpti",
1097 ASI.Selects.front().getI());
1098 ORmiss << "Profile data available but missing branch-weights metadata for "
1099 "select instruction. ";
1100 EmitAndPrintRemark(ORE, ORmiss);
1101 }
1102 if (!ColdOperand)
1103 return false;
1104 // Check if the cold path's dependence slice is expensive for any of the
1105 // selects of the group.
1106 for (SelectLike SI : ASI.Selects) {
1107 Instruction *ColdI = nullptr;
1108 uint64_t HotWeight;
1109 if (TrueWeight < FalseWeight) {
1110 ColdI = dyn_cast_or_null<Instruction>(SI.getTrueValue());
1111 HotWeight = FalseWeight;
1112 } else {
1113 ColdI = dyn_cast_or_null<Instruction>(SI.getFalseValue());
1114 HotWeight = TrueWeight;
1115 }
1116 if (ColdI) {
1117 std::stack<Instruction *> ColdSlice;
1118 getExclBackwardsSlice(ColdI, ColdSlice, SI.getI());
1119 InstructionCost SliceCost = 0;
1120 while (!ColdSlice.empty()) {
1121 SliceCost += TTI->getInstructionCost(ColdSlice.top(),
1123 ColdSlice.pop();
1124 }
1125 // The colder the cold value operand of the select is the more expensive
1126 // the cmov becomes for computing the cold value operand every time. Thus,
1127 // the colder the cold operand is the more its cost counts.
1128 // Get nearest integer cost adjusted for coldness.
1129 InstructionCost AdjSliceCost =
1130 divideNearest(SliceCost * HotWeight, TotalWeight);
1131 if (AdjSliceCost >= Opts->cold_operand_max_cost_multiplier *
1133 return true;
1134 }
1135 }
1136 return false;
1137}
1138
1139// Check if it is safe to move LoadI next to the SI.
1140// Conservatively assume it is safe only if there is no instruction
1141// modifying memory in-between the load and the select instruction.
1143 // Assume loads from different basic blocks are unsafe to move.
1144 if (LoadI->getParent() != SI->getParent())
1145 return false;
1146 auto It = LoadI->getIterator();
1147 while (&*It != SI) {
1148 if (It->mayWriteToMemory())
1149 return false;
1150 It++;
1151 }
1152 return true;
1153}
1154
1155// For a given source instruction, collect its backwards dependence slice
1156// consisting of instructions exclusively computed for the purpose of producing
1157// the operands of the source instruction. As an approximation
1158// (sufficiently-accurate in practice), we populate this set with the
1159// instructions of the backwards dependence slice that only have one-use and
1160// form an one-use chain that leads to the source instruction.
1161void SelectOptimizeImpl::getExclBackwardsSlice(Instruction *I,
1162 std::stack<Instruction *> &Slice,
1163 Instruction *SI, bool ForSinking,
1164 const SelectGroup *Group) {
1166 std::queue<Instruction *> Worklist;
1167 Worklist.push(I);
1168 while (!Worklist.empty()) {
1169 Instruction *II = Worklist.front();
1170 Worklist.pop();
1171
1172 // Avoid cycles.
1173 if (!Visited.insert(II).second)
1174 continue;
1175
1176 if (!II->hasOneUse())
1177 continue;
1178
1179 // Cannot soundly sink instructions with side-effects.
1180 // Terminator or phi instructions cannot be sunk.
1181 // Avoid sinking other select instructions (should be handled separetely).
1182 if (ForSinking && (II->isTerminator() || II->mayHaveSideEffects() ||
1184 continue;
1185
1186 // Select-like members of the group are replaced separately, and their
1187 // operands may still be needed on the other branch.
1188 if (ForSinking && Group &&
1189 llvm::any_of(Group->Selects, [&](auto &S) { return S.getI() == II; }))
1190 continue;
1191
1192 // Avoid sinking loads in order not to skip state-modifying instructions,
1193 // that may alias with the loaded address.
1194 // Only allow sinking of loads within the same basic block that are
1195 // conservatively proven to be safe.
1196 if (ForSinking && II->mayReadFromMemory() && !isSafeToSinkLoad(II, SI))
1197 continue;
1198
1199 // Avoid considering instructions with less frequency than the source
1200 // instruction (i.e., avoid colder code regions of the dependence slice).
1201 if (BFI->getBlockFreq(II->getParent()) < BFI->getBlockFreq(I->getParent()))
1202 continue;
1203
1204 // Eligible one-use instruction added to the dependence slice.
1205 Slice.push(II);
1206
1207 // Explore all the operands of the current instruction to expand the slice.
1208 for (Value *Op : II->operand_values())
1209 if (auto *OpI = dyn_cast<Instruction>(Op))
1210 Worklist.push(OpI);
1211 }
1212}
1213
1214bool SelectOptimizeImpl::isSelectHighlyPredictable(const SelectLike SI) {
1215 uint64_t TrueWeight, FalseWeight;
1216 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1217 uint64_t Max = std::max(TrueWeight, FalseWeight);
1218 uint64_t Sum = TrueWeight + FalseWeight;
1219 if (Sum != 0) {
1220 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
1221 if (Probability > TTI->getPredictableBranchThreshold())
1222 return true;
1223 }
1224 }
1225 return false;
1226}
1227
1228bool SelectOptimizeImpl::checkLoopHeuristics(const Loop *L,
1229 const CostInfo LoopCost[2]) {
1230 // Loop-level checks to determine if a non-predicated version (with branches)
1231 // of the loop is more profitable than its predicated version.
1232
1233 if (!Opts->select_opti_loop_level_heuristics)
1234 return true;
1235
1236 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti",
1237 &*L->getHeader()->getFirstNonPHIIt());
1238
1239 if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
1240 LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
1241 ORmissL << "No select conversion in the loop due to no reduction of loop's "
1242 "critical path. ";
1243 EmitAndPrintRemark(ORE, ORmissL);
1244 return false;
1245 }
1246
1247 Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
1248 LoopCost[1].PredCost - LoopCost[1].NonPredCost};
1249
1250 // Profitably converting to branches need to reduce the loop's critical path
1251 // by at least some threshold (absolute gain of GainCycleThreshold cycles and
1252 // relative gain of 12.5%).
1253 if (Gain[1] < Scaled64::get(Opts->select_opti_loop_cycle_gain_threshold) ||
1254 Gain[1] * Scaled64::get(Opts->select_opti_loop_relative_gain_threshold) <
1255 LoopCost[1].PredCost) {
1256 Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
1257 ORmissL << "No select conversion in the loop due to small reduction of "
1258 "loop's critical path. Gain="
1259 << Gain[1].toString()
1260 << ", RelativeGain=" << RelativeGain.toString() << "%. ";
1261 EmitAndPrintRemark(ORE, ORmissL);
1262 return false;
1263 }
1264
1265 // If the loop's critical path involves loop-carried dependences, the gradient
1266 // of the gain needs to be at least GainGradientThreshold% (defaults to 25%).
1267 // This check ensures that the latency reduction for the loop's critical path
1268 // keeps decreasing with sufficient rate beyond the two analyzed loop
1269 // iterations.
1270 if (Gain[1] > Gain[0]) {
1271 Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
1272 (LoopCost[1].PredCost - LoopCost[0].PredCost);
1273 if (GradientGain <
1274 Scaled64::get(Opts->select_opti_loop_gradient_gain_threshold)) {
1275 ORmissL << "No select conversion in the loop due to small gradient gain. "
1276 "GradientGain="
1277 << GradientGain.toString() << "%. ";
1278 EmitAndPrintRemark(ORE, ORmissL);
1279 return false;
1280 }
1281 }
1282 // If the gain decreases it is not profitable to convert.
1283 else if (Gain[1] < Gain[0]) {
1284 ORmissL
1285 << "No select conversion in the loop due to negative gradient gain. ";
1286 EmitAndPrintRemark(ORE, ORmissL);
1287 return false;
1288 }
1289
1290 // Non-predicated version of the loop is more profitable than its
1291 // predicated version.
1292 return true;
1293}
1294
1295// Computes instruction and loop-critical-path costs for both the predicated
1296// and non-predicated version of the given loop.
1297// Returns false if unable to compute these costs due to invalid cost of loop
1298// instruction(s).
1299bool SelectOptimizeImpl::computeLoopCosts(
1300 const Loop *L, const SelectGroups &SIGroups,
1301 DenseMap<const Instruction *, CostInfo> &InstCostMap, CostInfo *LoopCost) {
1302 LLVM_DEBUG(dbgs() << "Calculating Latency / IPredCost / INonPredCost of loop "
1303 << L->getHeader()->getName() << "\n");
1304 const auto SImap = getSImap(SIGroups);
1305 const auto SGmap = getSGmap(SIGroups);
1306 // Compute instruction and loop-critical-path costs across two iterations for
1307 // both predicated and non-predicated version.
1308 const unsigned Iterations = 2;
1309 for (unsigned Iter = 0; Iter < Iterations; ++Iter) {
1310 // Cost of the loop's critical path.
1311 CostInfo &MaxCost = LoopCost[Iter];
1312 for (BasicBlock *BB : L->getBlocks()) {
1313 for (const Instruction &I : *BB) {
1315 continue;
1316 // Compute the predicated and non-predicated cost of the instruction.
1317 Scaled64 IPredCost = Scaled64::getZero(),
1318 INonPredCost = Scaled64::getZero();
1319
1320 // Assume infinite resources that allow to fully exploit the available
1321 // instruction-level parallelism.
1322 // InstCost = InstLatency + max(Op1Cost, Op2Cost, … OpNCost)
1323 for (const Use &U : I.operands()) {
1324 auto UI = dyn_cast<Instruction>(U.get());
1325 if (!UI)
1326 continue;
1327 if (auto It = InstCostMap.find(UI); It != InstCostMap.end()) {
1328 IPredCost = std::max(IPredCost, It->second.PredCost);
1329 INonPredCost = std::max(INonPredCost, It->second.NonPredCost);
1330 }
1331 }
1332 auto ILatency = computeInstCost(&I);
1333 if (!ILatency) {
1334 OptimizationRemarkMissed ORmissL(DEBUG_TYPE, "SelectOpti", &I);
1335 ORmissL << "Invalid instruction cost preventing analysis and "
1336 "optimization of the inner-most loop containing this "
1337 "instruction. ";
1338 EmitAndPrintRemark(ORE, ORmissL);
1339 return false;
1340 }
1341 IPredCost += Scaled64::get(*ILatency);
1342 INonPredCost += Scaled64::get(*ILatency);
1343
1344 // For a select that can be converted to branch,
1345 // compute its cost as a branch (non-predicated cost).
1346 //
1347 // BranchCost = PredictedPathCost + MispredictCost
1348 // PredictedPathCost = TrueOpCost * TrueProb + FalseOpCost * FalseProb
1349 // MispredictCost = max(MispredictPenalty, CondCost) * MispredictRate
1350 if (auto It = SImap.find(&I); It != SImap.end()) {
1351 auto SI = It->second;
1352 const auto *SG = SGmap.at(&I);
1353 Scaled64 TrueOpCost = SI.getOpCostOnBranch(true, InstCostMap, TTI);
1354 Scaled64 FalseOpCost = SI.getOpCostOnBranch(false, InstCostMap, TTI);
1355 Scaled64 PredictedPathCost =
1356 getPredictedPathCost(TrueOpCost, FalseOpCost, SI);
1357
1358 Scaled64 CondCost = Scaled64::getZero();
1359 if (auto *CI = dyn_cast<Instruction>(SG->Condition))
1360 if (auto It = InstCostMap.find(CI); It != InstCostMap.end())
1361 CondCost = It->second.NonPredCost;
1362 Scaled64 MispredictCost = getMispredictionCost(SI, CondCost);
1363
1364 INonPredCost = PredictedPathCost + MispredictCost;
1365 }
1366 LLVM_DEBUG(dbgs() << " " << ILatency << "/" << IPredCost << "/"
1367 << INonPredCost << " for " << I << "\n");
1368
1369 InstCostMap[&I] = {IPredCost, INonPredCost};
1370 MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
1371 MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
1372 }
1373 }
1374 LLVM_DEBUG(dbgs() << "Iteration " << Iter + 1
1375 << " MaxCost = " << MaxCost.PredCost << " "
1376 << MaxCost.NonPredCost << "\n");
1377 }
1378 return true;
1379}
1380
1382SelectOptimizeImpl::getSImap(const SelectGroups &SIGroups) {
1384 for (const SelectGroup &ASI : SIGroups)
1385 for (const SelectLike &SI : ASI.Selects)
1386 SImap.try_emplace(SI.getI(), SI);
1387 return SImap;
1388}
1389
1391SelectOptimizeImpl::getSGmap(const SelectGroups &SIGroups) {
1393 for (const SelectGroup &ASI : SIGroups)
1394 for (const SelectLike &SI : ASI.Selects)
1395 SImap.try_emplace(SI.getI(), &ASI);
1396 return SImap;
1397}
1398
1399std::optional<uint64_t>
1400SelectOptimizeImpl::computeInstCost(const Instruction *I) {
1401 InstructionCost ICost =
1402 TTI->getInstructionCost(I, TargetTransformInfo::TCK_Latency);
1403 if (ICost.isValid())
1404 return std::optional<uint64_t>(ICost.getValue());
1405 return std::nullopt;
1406}
1407
1409SelectOptimizeImpl::getMispredictionCost(const SelectLike SI,
1410 const Scaled64 CondCost) {
1411 uint64_t MispredictPenalty = TSI->getMispredictionPenalty();
1412
1413 // Account for the default misprediction rate when using a branch
1414 // (conservatively set to 25% by default).
1415 uint64_t MispredictRate = Opts->mispredict_default_rate;
1416 // If the select condition is obviously predictable, then the misprediction
1417 // rate is zero.
1418 if (isSelectHighlyPredictable(SI))
1419 MispredictRate = 0;
1420
1421 // CondCost is included to account for cases where the computation of the
1422 // condition is part of a long dependence chain (potentially loop-carried)
1423 // that would delay detection of a misprediction and increase its cost.
1424 Scaled64 MispredictCost =
1425 std::max(Scaled64::get(MispredictPenalty), CondCost) *
1426 Scaled64::get(MispredictRate);
1427 MispredictCost /= Scaled64::get(100);
1428
1429 return MispredictCost;
1430}
1431
1432// Returns the cost of a branch when the prediction is correct.
1433// TrueCost * TrueProbability + FalseCost * FalseProbability.
1435SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
1436 const SelectLike SI) {
1437 Scaled64 PredPathCost;
1438 uint64_t TrueWeight, FalseWeight;
1439 if (extractBranchWeights(SI, TrueWeight, FalseWeight)) {
1440 uint64_t SumWeight = TrueWeight + FalseWeight;
1441 if (SumWeight != 0) {
1442 PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
1443 FalseCost * Scaled64::get(FalseWeight);
1444 PredPathCost /= Scaled64::get(SumWeight);
1445 return PredPathCost;
1446 }
1447 }
1448 // Without branch weight metadata, we assume 75% for the one path and 25% for
1449 // the other, and pick the result with the biggest cost.
1450 PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
1451 FalseCost * Scaled64::get(3) + TrueCost);
1452 PredPathCost /= Scaled64::get(4);
1453 return PredPathCost;
1454}
1455
1456bool SelectOptimizeImpl::isSelectKindSupported(const SelectLike SI) {
1458 if (SI.getType()->isVectorTy())
1460 else
1462 return TLI->isSelectSupported(SelectKind);
1463}
const TargetLowering & TLI
SDValue Pred
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:656
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 void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE, DiagnosticInfoOptimizationBase &Rem)
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.
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:2990
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:598
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:623
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.
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:346
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...
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.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
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.
@ 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:395
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.
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
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:2229
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
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177