30#define DEBUG_TYPE "vplan"
37class PlainCFGBuilder {
48 std::unique_ptr<VPlan> Plan;
69 bool isExternalDef(
Value *Val);
76 : TheLoop(Lp), LI(LI), LVer(LVer), Plan(std::make_unique<VPlan>(Lp)) {}
79 std::unique_ptr<VPlan> buildPlainCFG();
89 VPBBPreds.
push_back(getOrCreateVPBB(Pred));
94 return L && BB == L->getHeader();
98void PlainCFGBuilder::fixHeaderPhis() {
99 for (
auto *Phi : PhisToFix) {
100 assert(IRDef2VPValue.count(Phi) &&
"Missing VPInstruction for PHINode.");
101 VPValue *VPVal = IRDef2VPValue[
Phi];
104 assert(PhiR->getNumOperands() == 0 &&
"Expected VPPhi with no operands.");
106 "Expected Phi in header block.");
108 "header phi must have exactly 2 operands");
111 getOrCreateVPOperand(
Phi->getIncomingValueForBlock(Pred)));
117VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
118 if (
auto *VPBB = BB2VPBB.lookup(BB)) {
125 LLVM_DEBUG(
dbgs() <<
"Creating VPBasicBlock for " << Name <<
"\n");
126 VPBasicBlock *VPBB = Plan->createVPBasicBlock(Name);
137bool PlainCFGBuilder::isExternalDef(
Value *Val) {
153VPValue *PlainCFGBuilder::getOrCreateVPOperand(
Value *IRVal) {
154 auto VPValIt = IRDef2VPValue.find(IRVal);
155 if (VPValIt != IRDef2VPValue.end())
158 return VPValIt->second;
167 assert(isExternalDef(IRVal) &&
"Expected external definition as operand.");
171 VPValue *NewVPVal = Plan->getOrAddLiveIn(IRVal);
172 IRDef2VPValue[IRVal] = NewVPVal;
179void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
188 assert(!IRDef2VPValue.count(Inst) &&
189 "Instruction shouldn't have been visited.");
194 if (Br->isConditional()) {
195 VPValue *
Cond = getOrCreateVPOperand(Br->getCondition());
206 if (
SI->getNumCases() == 0)
209 for (
auto Case :
SI->cases())
210 Ops.push_back(getOrCreateVPOperand(Case.getCaseValue()));
216 VPSingleDefRecipe *NewR;
226 PhisToFix.push_back(Phi);
230 DenseMap<const VPBasicBlock *, VPValue *> VPPredToIncomingValue;
231 for (
unsigned I = 0;
I !=
Phi->getNumOperands(); ++
I) {
232 VPPredToIncomingValue[BB2VPBB[
Phi->getIncomingBlock(
I)]] =
233 getOrCreateVPOperand(
Phi->getIncomingValue(
I));
237 VPPredToIncomingValue.
lookup(Pred->getExitingBasicBlock()));
242 VPIRMetadata MD(*Inst);
244 const auto &[AliasScopeMD, NoAliasMD] =
247 MD.setMetadata(LLVMContext::MD_alias_scope, AliasScopeMD);
249 MD.setMetadata(LLVMContext::MD_noalias, NoAliasMD);
260 CI->getType(), CI->getDebugLoc(),
272 IRDef2VPValue[Inst] = NewR;
277std::unique_ptr<VPlan> PlainCFGBuilder::buildPlainCFG() {
280 for (VPIRBasicBlock *ExitVPBB : Plan->getExitBlocks())
281 BB2VPBB[ExitVPBB->getIRBasicBlock()] = ExitVPBB;
294 "Unexpected loop preheader");
295 for (
auto &
I : *ThePreheaderBB) {
296 if (
I.getType()->isVoidTy())
298 IRDef2VPValue[&
I] = Plan->getOrAddLiveIn(&
I);
301 LoopBlocksRPO RPO(TheLoop);
304 for (BasicBlock *BB : RPO) {
306 VPBasicBlock *VPBB = getOrCreateVPBB(BB);
308 setVPBBPredsFromBB(VPBB, BB);
311 createVPInstructionsForVPBB(VPBB, BB);
318 getOrCreateVPBB(
SI->getDefaultDest())};
319 for (
auto Case :
SI->cases())
320 Succs.
push_back(getOrCreateVPBB(Case.getCaseSuccessor()));
330 assert(BI->isConditional() && NumSuccs == 2 && BI->isConditional() &&
331 "block must have conditional branch with 2 successors");
335 VPBasicBlock *Successor0 = getOrCreateVPBB(IRSucc0);
336 VPBasicBlock *Successor1 = getOrCreateVPBB(IRSucc1);
340 for (
auto *EB : Plan->getExitBlocks())
341 setVPBBPredsFromBB(EB, EB->getIRBasicBlock());
348 Plan->getEntry()->setOneSuccessor(getOrCreateVPBB(TheLoop->
getHeader()));
349 Plan->getEntry()->setPlan(&*Plan);
356 for (
auto *EB : Plan->getExitBlocks()) {
357 for (VPRecipeBase &R : EB->phis()) {
359 PHINode &
Phi = PhiR->getIRPhi();
360 assert(PhiR->getNumOperands() == 0 &&
361 "no phi operands should be added yet");
362 for (BasicBlock *Pred :
predecessors(EB->getIRBasicBlock()))
364 getOrCreateVPOperand(
Phi.getIncomingValueForBlock(Pred)));
369 return std::move(Plan);
382 if (Preds.
size() != 2)
385 auto *PreheaderVPBB = Preds[0];
386 auto *LatchVPBB = Preds[1];
387 if (!VPDT.
dominates(PreheaderVPBB, HeaderVPB) ||
391 if (!VPDT.
dominates(PreheaderVPBB, HeaderVPB) ||
408 if (LatchVPBB->getSingleSuccessor() ||
409 LatchVPBB->getSuccessors()[0] != HeaderVPB)
412 assert(LatchVPBB->getNumSuccessors() == 2 &&
"Must have 2 successors");
416 "terminator must be a BranchOnCond");
418 Not->insertBefore(Term);
419 Term->setOperand(0, Not);
420 LatchVPBB->swapSuccessors();
433 assert(LatchExitVPB &&
"Latch expected to be left with a single successor");
443 R->setEntry(HeaderVPB);
444 R->setExiting(LatchVPBB);
456 Value *StartIdx = ConstantInt::get(IdxTy, 0);
461 HeaderVPBB->
insert(CanonicalIVPHI, HeaderVPBB->
begin());
475 auto *CanonicalIVIncrement = Builder.createOverflowingOp(
476 Instruction::Add, {CanonicalIVPHI, &Plan.
getVFxUF()}, {
true,
false},
DL,
478 CanonicalIVPHI->addOperand(CanonicalIVIncrement);
491 if (EB->getSinglePredecessor() != MiddleVPBB)
496 for (
unsigned Idx = 0; Idx != ExitIRI->getNumIncoming(); ++Idx) {
497 VPRecipeBase *Inc = ExitIRI->getIncomingValue(Idx)->getDefiningRecipe();
500 assert(ExitIRI->getNumOperands() == 1 &&
501 ExitIRI->getParent()->getSinglePredecessor() == MiddleVPBB &&
502 "exit values from early exits must be fixed when branch to "
503 "early-exit is added");
504 ExitIRI->extractLastLaneOfLastPartOfFirstOperand(
B);
526 if (LatchVPBB->getNumSuccessors() == 2) {
531 LatchVPBB->swapSuccessors();
541 "Invalid backedge-taken count");
544 InductionTy, TheLoop);
562 for (
const auto &[PhiR, ScalarPhiR] :
zip_equal(
566 {VectorPhiR, VectorPhiR->getOperand(0)}, VectorPhiR->getDebugLoc());
575 auto GetSimplifiedLiveInViaSCEV = [&](
VPValue *VPV) ->
VPValue * {
583 if (
VPValue *SimplifiedLiveIn = GetSimplifiedLiveInViaSCEV(LiveIn))
584 LiveIn->replaceAllUsesWith(SimplifiedLiveIn);
588std::unique_ptr<VPlan>
592 PlainCFGBuilder Builder(TheLoop, &LI, LVer);
593 std::unique_ptr<VPlan> VPlan0 = Builder.buildPlainCFG();
608 "step must be loop invariant");
613 "Start VPValue must match IndDesc's start value");
624 "must have an integer or float induction at this point");
653 "header must dominate its latch");
659 assert(PhiR->getNumOperands() == 2 &&
660 "Must have 2 operands for header phis");
663 VPValue *Start = PhiR->getOperand(0);
664 VPValue *BackedgeValue = PhiR->getOperand(1);
666 if (FixedOrderRecurrences.
contains(Phi)) {
674 auto InductionIt = Inductions.
find(Phi);
675 if (InductionIt != Inductions.
end())
678 PhiR->getDebugLoc());
684 "incoming value must match start value");
686 unsigned ScaleFactor = 1;
687 bool UseOrderedReductions = !AllowReordering && RdxDesc.
isOrdered();
701 PhiR->replaceAllUsesWith(HeaderPhiR);
702 PhiR->eraseFromParent();
716 if (!PhiR || !PhiR->isInLoop() || (MinVF.
isScalar() && !PhiR->isOrdered()))
719 RecurKind Kind = PhiR->getRecurrenceKind();
723 "AnyOf and FindIV reductions are not allowed for in-loop reductions");
725 bool IsFPRecurrence =
733 for (
unsigned I = 0;
I != Worklist.
size(); ++
I) {
737 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
740 "U must be either in the loop region, the middle block or the "
741 "scalar preheader.");
748 Worklist.
insert(UserRecipe);
762 assert(Blend->getNumIncomingValues() == 2 &&
763 "Blend must have 2 incoming values");
764 unsigned PhiRIdx = Blend->getIncomingValue(0) == PhiR ? 0 : 1;
765 assert(Blend->getIncomingValue(PhiRIdx) == PhiR &&
766 "PhiR must be an operand of the blend");
767 Blend->replaceAllUsesWith(Blend->getIncomingValue(1 - PhiRIdx));
771 if (IsFPRecurrence) {
776 ->getFastMathFlags();
780 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
788 "Expected current VPInstruction to be a call to the "
789 "llvm.fmuladd intrinsic");
790 assert(CurrentLink->getOperand(2) == PreviousLink &&
791 "expected a call where the previous link is the added operand");
799 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
801 LinkVPBB->
insert(FMulRecipe, CurrentLink->getIterator());
808 {Zero, CurrentLink->getOperand(1)}, {},
810 Sub->setUnderlyingValue(CurrentLinkI);
811 LinkVPBB->
insert(
Sub, CurrentLink->getIterator());
815 unsigned IndexOfFirstOperand = 0;
821 "must be a select recipe");
822 IndexOfFirstOperand = 1;
827 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
828 ? IndexOfFirstOperand + 1
829 : IndexOfFirstOperand;
830 VecOp = CurrentLink->getOperand(VecOpId);
831 assert(VecOp != PreviousLink &&
832 CurrentLink->
getOperand(CurrentLink->getNumOperands() - 1 -
833 (VecOpId - IndexOfFirstOperand)) ==
835 "PreviousLink must be the operand other than VecOp");
841 CondOp = BlockMaskCache.
lookup(LinkVPBB);
843 assert(PhiR->getVFScaleFactor() == 1 &&
844 "inloop reductions must be unscaled");
846 Kind, FMFs, CurrentLinkI, PreviousLink, VecOp, CondOp,
854 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->
end())));
858 CurrentLink->replaceAllUsesWith(RedRecipe);
860 PreviousLink = RedRecipe;
865 R->eraseFromParent();
869 bool HasUncountableEarlyExit) {
880 [[maybe_unused]]
bool HandledUncountableEarlyExit =
false;
883 if (Pred == MiddleVPBB)
885 if (HasUncountableEarlyExit) {
886 assert(!HandledUncountableEarlyExit &&
887 "can handle exactly one uncountable early exit");
890 HandledUncountableEarlyExit =
true;
900 assert((!HasUncountableEarlyExit || HandledUncountableEarlyExit) &&
901 "missed an uncountable exit that must be handled");
905 bool RequiresScalarEpilogueCheck,
912 if (MiddleVPBB->getNumSuccessors() == 1) {
914 "must have ScalarPH as single successor");
918 assert(MiddleVPBB->getNumSuccessors() == 2 &&
"must have 2 successors");
936 DebugLoc LatchDL = LatchVPBB->getTerminator()->getDebugLoc();
939 if (!RequiresScalarEpilogueCheck)
956 TopRegion->
setName(
"vector loop");
966 bool AddBranchWeights) {
982 "must have incoming values for all operands");
983 R.addOperand(R.getOperand(NumPredecessors - 2));
992 if (AddBranchWeights) {
996 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1002 ElementCount MinProfitableTripCount,
bool RequiresScalarEpilogue,
1003 bool TailFolded,
bool CheckNeededWithTailFolding,
Loop *OrigLoop,
1018 auto GetMinTripCount = [&]() ->
const SCEV * {
1027 const SCEV *MinProfitableTripCountSCEV =
1029 return SE.
getUMaxExpr(MinProfitableTripCountSCEV, VFxUF);
1035 const SCEV *Step = GetMinTripCount();
1037 if (CheckNeededWithTailFolding) {
1045 VPValue *DistanceToMax = Builder.createNaryOp(
1046 Instruction::Sub, {MaxUIntTripCount, TripCountVPV},
1053 Builder.createExpandSCEV(Step),
DL);
1066 TripCountCheck = Plan.
getTrue();
1071 VPValue *MinTripCountVPV = Builder.createExpandSCEV(Step);
1072 TripCountCheck = Builder.createICmp(
1073 CmpPred, TripCountVPV, MinTripCountVPV,
DL,
"min.iters.check");
1082 Term->setMetadata(LLVMContext::MD_prof, BranchWeights);
1088 bool RequiresScalarEpilogue,
ElementCount EpilogueVF,
unsigned EpilogueUF,
1089 unsigned MainLoopStep,
unsigned EpilogueLoopStep,
ScalarEvolution &SE) {
1102 auto *CheckMinIters = Builder.createICmp(
1113 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
1114 const uint32_t Weights[] = {EstimatedSkipCount,
1115 MainLoopStep - EstimatedSkipCount};
1119 Branch->setMetadata(LLVMContext::MD_prof, BranchWeights);
1124template <
typename MatchT>
1150 if (MinMaxR->getOperand(0) == RedPhiR)
1151 return MinMaxR->getOperand(1);
1153 assert(MinMaxR->getOperand(1) == RedPhiR &&
1154 "Reduction phi operand expected");
1155 return MinMaxR->getOperand(0);
1160 MinMaxNumReductionsToHandle;
1161 bool HasUnsupportedPhi =
false;
1168 HasUnsupportedPhi =
true;
1172 Cur->getRecurrenceKind())) {
1173 HasUnsupportedPhi =
true;
1177 VPValue *MinMaxOp = GetMinMaxCompareValue(Cur);
1181 MinMaxNumReductionsToHandle.
emplace_back(Cur, MinMaxOp);
1184 if (MinMaxNumReductionsToHandle.
empty())
1202 for (
auto &R : *VPBB) {
1210 VPValue *AllNaNLanes =
nullptr;
1212 for (
const auto &[
_, MinMaxOp] : MinMaxNumReductionsToHandle) {
1215 AllNaNLanes = AllNaNLanes ? LatchBuilder.
createOr(AllNaNLanes, RedNaNLanes)
1223 for (
const auto &[RedPhiR,
_] : MinMaxNumReductionsToHandle) {
1225 RedPhiR->getRecurrenceKind()) &&
1226 "unsupported reduction");
1233 auto *NewSel = MiddleBuilder.
createSelect(AnyNaNLane, RedPhiR,
1234 RdxResult->getOperand(1));
1236 assert(!RdxResults.
contains(RdxResult) &&
"RdxResult already used");
1237 RdxResults.
insert(RdxResult);
1242 "Unexpected terminator");
1243 auto *IsLatchExitTaken = LatchBuilder.
createICmp(
1245 LatchExitingBranch->getOperand(1));
1247 Instruction::Or, {AnyNaNLane, IsLatchExitTaken});
1256 VPValue *VecV = ResumeR->getOperand(0);
1260 if (DerivedIV->getNumUsers() == 1 &&
1266 DerivedIV->setOperand(1, NewSel);
1273 LLVM_DEBUG(
dbgs() <<
"Found resume phi we cannot update for VPlan with "
1274 "FMaxNum/FMinNum reduction.\n");
1284 VPValue *MiddleCond = MiddleTerm->getOperand(0);
1296 if (!MinMaxPhiR || !MinMaxPhiR->hasUsesOutsideReductionChain())
1305 RecurKind RdxKind = MinMaxPhiR->getRecurrenceKind();
1308 "only min/max recurrences support users outside the reduction chain");
1323 assert(MinMaxOp->getNumUsers() == 2 &&
1324 "MinMaxOp must have exactly 2 users");
1325 VPValue *MinMaxOpValue = MinMaxOp->getOperand(0);
1326 if (MinMaxOpValue == MinMaxPhiR)
1327 MinMaxOpValue = MinMaxOp->getOperand(1);
1334 if (!Cmp || Cmp->getNumUsers() != 1 ||
1335 (CmpOpA != MinMaxOpValue && CmpOpB != MinMaxOpValue))
1338 if (MinMaxOpValue != CmpOpB)
1345 if (MinMaxPhiR->getNumUsers() != 3)
1351 "one user must be MinMaxOp");
1352 assert(MinMaxResult &&
"MinMaxResult must be a user of MinMaxPhiR");
1354 "MinMaxResult must be a user of MinMaxOp (and of MinMaxPhiR");
1371 FindIVPhiR->getRecurrenceKind()))
1396 if (Pred != RdxPredicate)
1399 assert(!FindIVPhiR->isInLoop() && !FindIVPhiR->isOrdered() &&
1400 "cannot handle inloop/ordered reductions yet");
1426 "both results must be computed in the same block");
1432 auto *FinalMinMaxCmp =
1436 auto *FinalIVSelect =
1437 B.createSelect(FinalMinMaxCmp, LastIVExiting,
Sentinel);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static constexpr uint32_t MinItersBypassWeights[]
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
const SmallVectorImpl< MachineOperand > & Cond
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
static void createLoopRegion(VPlan &Plan, VPBlockBase *HeaderVPB)
Create a new VPRegionBlock for the loop starting at HeaderVPB.
static bool isHeaderBB(BasicBlock *BB, Loop *L)
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-in and replace them with constants, if they can be simplified via SCEV.
static VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
static void addInitialSkeleton(VPlan &Plan, Type *InductionTy, DebugLoc IVDL, PredicatedScalarEvolution &PSE, Loop *TheLoop)
static VPHeaderPHIRecipe * createWidenInductionRecipe(PHINode *Phi, VPPhi *PhiR, VPValue *Start, const InductionDescriptor &IndDesc, VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, DebugLoc DL)
Creates a VPWidenIntOrFpInductionRecipe or VPWidenPointerInductionRecipe for Phi based on IndDesc.
static void addCanonicalIVRecipes(VPlan &Plan, VPBasicBlock *HeaderVPBB, VPBasicBlock *LatchVPBB, Type *IdxTy, DebugLoc DL)
static bool canonicalHeaderAndLatch(VPBlockBase *HeaderVPB, const VPDominatorTree &VPDT)
Checks if HeaderVPB is a loop header block in the plain CFG; that is, it has exactly 2 predecessors (...
static constexpr uint32_t CheckBypassWeights[]
static void createExtractsForLiveOuts(VPlan &Plan, VPBasicBlock *MiddleVPBB)
Creates extracts for values in Plan defined in a loop region and used outside a loop region.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
This file contains the declarations of the Vectorization Plan base classes:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
LLVM Basic Block Representation.
LLVM_ABI iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug(bool SkipPseudoOp=true) const
Return a const iterator range over the instructions in the block, skipping any debug instructions.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static DebugLoc getUnknown()
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Implements a dense probed hash-table based set.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
constexpr bool isScalar() const
Exactly one element.
Convenience struct for specifying and reasoning about fast-math flags.
static FastMathFlags getFast()
A struct for saving information about induction variables.
InductionKind getKind() const
const SCEV * getStep() const
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
Value * getStartValue() const
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
Represents a single loop in the control flow graph.
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
static bool isFMulAddIntrinsic(Instruction *I)
Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
static bool isFPMinMaxNumRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating-point minnum/maxnum kind.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
TrackingVH< Value > getRecurrenceStartValue() const
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindLastIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
bool isOrdered() const
Expose an ordered FP reduction to the instance users.
static LLVM_ABI bool isFloatingPointRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is a floating point kind.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isIntMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is an integer min/max kind.
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUMaxExpr(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
A vector that has set insertion semantics.
size_type size() const
Determine the number of elements in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
iterator begin()
Recipe iterator methods.
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
const VPRecipeBase & back() const
void insert(VPRecipeBase *Recipe, iterator InsertPt)
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
VPRegionBlock * getParent()
const VPBasicBlock * getExitingBasicBlock() const
void setName(const Twine &newName)
size_t getNumSuccessors() const
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
size_t getNumPredecessors() const
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
const VPBlocksTy & getPredecessors() const
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
VPBlockBase * getSinglePredecessor() const
void swapPredecessors()
Swap predecessors of the block.
const VPBasicBlock * getEntryBasicBlock() const
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
void setParent(VPRegionBlock *P)
VPBlockBase * getSingleSuccessor() const
const VPBlocksTy & getSuccessors() const
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={})
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< FastMathFlags > FMFs=std::nullopt)
VPBasicBlock::iterator getInsertPoint() const
VPInstruction * createFCmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new FCmp VPInstruction with predicate Pred and operands A and B.
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL, const Twine &Name="")
VPInstruction * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
VPInstruction * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
void setInsertPoint(VPBasicBlock *TheBB)
This specifies that created VPInstructions should be appended to the end of the specified block.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
Canonical scalar induction phi of the vector loop.
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
A special type of VPBasicBlock that wraps an existing IR basic block.
Class to record and manage LLVM IR flags.
This is a concrete Recipe that models a single VPlan-level instruction.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
VPBasicBlock * getParent()
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
A recipe for handling reduction phis.
A recipe to represent inloop, ordered or partial reduction operations.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the region.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
void setOperand(unsigned I, VPValue *New)
VPValue * getOperand(unsigned N) const
void addOperand(VPValue *Operand)
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
void setUnderlyingValue(Value *Val)
unsigned getNumUsers() const
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
LLVMContext & getContext() const
VPBasicBlock * getEntry()
VPValue & getVectorTripCount()
The vector trip count.
VPValue & getVFxUF()
Returns VF * UF of the vector loop region.
VPValue & getVF()
Returns the VF of the vector loop region.
VPValue * getTripCount() const
The trip count of the original loop.
VPValue * getTrue()
Return a VPValue wrapping i1 true.
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
VPValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPValue wrapping a ConstantInt with the given type and value.
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
VPValue * getFalse()
Return a VPValue wrapping i1 false.
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
VPRegionBlock * createLoopRegion(const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with Name and entry and exiting blocks set to Entry and Exiting respectively...
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
VPValue * getLiveIn(Value *V) const
Return the live-in VPValue for V, if there is one or nullptr otherwise.
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
MatchFunctor< Val, Pattern > match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
bind_ty< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
VPIRFlags getFlagsFromIndDesc(const InductionDescriptor &ID)
Extracts and returns NoWrap and FastMath flags from the induction binop in ID.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
FunctionAddr VTableAddr Value
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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...
auto cast_or_null(const Y &Val)
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionAddr VTableAddr Count
auto succ_size(const MachineBasicBlock *BB)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
iterator_range< po_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_post_order_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in post order.
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...
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A recipe for handling first-order recurrence phis.