LLVM 24.0.0git
VPlanLowering.cpp
Go to the documentation of this file.
1//===- VPlanLowering.cpp - VPlan-to-VPlan lowering transforms -------------===//
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/// \file
10/// This file implements VPlan-to-VPlan lowering transformations, which
11/// prepare an optimized VPlan for execution.
12///
13//===----------------------------------------------------------------------===//
14
16#include "VPlan.h"
17#include "VPlanAnalysis.h"
18#include "VPlanCFG.h"
19#include "VPlanDominatorTree.h"
20#include "VPlanHelpers.h"
21#include "VPlanPatternMatch.h"
22#include "VPlanTransforms.h"
23#include "VPlanUtils.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/STLExtras.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/MDBuilder.h"
31#include "llvm/IR/Metadata.h"
35
36using namespace llvm;
37using namespace VPlanPatternMatch;
38using namespace SCEVPatternMatch;
39
43 unsigned UF) {
44 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
45 if (!LoopRegion)
46 return;
47
48 auto *WideCanIV =
50 if (!WideCanIV)
51 return;
52
53 Type *CanIVTy = LoopRegion->getCanonicalIVType();
54
55 // Replace the wide canonical IV with a scalar-iv-steps over the canonical
56 // IV.
57 if (Plan.hasScalarVFOnly() || vputils::onlyFirstLaneUsed(WideCanIV)) {
58 VPBuilder Builder(WideCanIV);
59 WideCanIV->replaceAllUsesWith(vputils::createScalarIVSteps(
60 Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
61 nullptr, Plan.getZero(CanIVTy), Plan.getConstantInt(CanIVTy, 1),
62 WideCanIV->getDebugLoc(), Builder,
63 {static_cast<bool>(WideCanIV->getNoWrapFlags().HasNUW), false}));
64 WideCanIV->eraseFromParent();
65 return;
66 }
67
68 if (vputils::onlyScalarValuesUsed(WideCanIV))
69 return;
70
71 // If a canonical VPWidenIntOrFpInductionRecipe already produces vector lanes
72 // in the header, reuse it instead of introducing another wide induction phi.
73 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
74 for (VPRecipeBase &Phi : Header->phis()) {
76 if (!match(&Phi, m_CanonicalWidenIV(WidenIV)))
77 continue;
78 // The reused wide IV feeds the header mask, whose lanes may extend past
79 // the trip count; drop flags that only hold inside the scalar loop.
81 WideCanIV->replaceAllUsesWith(WidenIV);
82 WideCanIV->eraseFromParent();
83 return;
84 }
85
86 // Introduce a new VPWidenIntOrFpInductionRecipe if profitable.
87 auto *VecTy = VectorType::get(CanIVTy, VF);
88 InstructionCost BroadcastCost = TTI.getShuffleCost(
90 InstructionCost PHICost = TTI.getCFInstrCost(Instruction::PHI, CostKind);
91 if (PHICost > BroadcastCost)
92 return;
93
94 // Bail out if the additional wide induction phi increase the expected spill
95 // cost.
96 VPRegisterUsage UnrolledBase =
98 for (unsigned &NumUsers : make_second_range(UnrolledBase.MaxLocalUsers))
99 NumUsers *= UF;
100 unsigned RegClass = TTI.getRegisterClassForType(/*Vector=*/true, VecTy);
101 VPRegisterUsage Projected = UnrolledBase;
102 Projected.MaxLocalUsers[RegClass] += TTI.getRegUsageForType(VecTy);
103 if (Projected.spillCost(TTI, CostKind) >
104 UnrolledBase.spillCost(TTI, CostKind))
105 return;
106
109 VPValue *StepV = Plan.getConstantInt(CanIVTy, 1);
110 auto *NewWideIV = new VPWidenIntOrFpInductionRecipe(
111 /*IV=*/nullptr, Plan.getZero(CanIVTy), StepV, &Plan.getVF(), ID,
112 WideCanIV->getNoWrapFlags(), WideCanIV->getDebugLoc());
113 NewWideIV->insertBefore(&*Header->getFirstNonPhi());
114 WideCanIV->replaceAllUsesWith(NewWideIV);
115 WideCanIV->eraseFromParent();
116}
117
118// Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
119// the loop terminator with a branch-on-cond recipe with the negated
120// wide-active-lane-mask as operand. Note that this turns the loop into an
121// uncountable one. Only the existing terminator is replaced, all other existing
122// recipes/users remain unchanged, except for poison-generating flags being
123// dropped from the canonical IV increment. Return the created
124// VPActiveLaneMaskPHIRecipe.
125//
126// The function adds the following recipes:
127//
128// vector.ph:
129// %EntryInc = canonical-iv-increment-for-part CanonicalIVStart
130// %EntryALM = wide-active-lane-mask %EntryInc, TC
131// %EntryALMPart = extract-vector-for-part %EntryALM, ir<0>
132//
133// vector.body:
134// ...
135// %P = active-lane-mask-phi [ %EntryALMPart, %vector.ph ],
136// [ %ALMPart, %vector.body ]
137// ...
138// %InLoopInc = canonical-iv-increment-for-part CanonicalIVIncrement
139// %ALM = wide-active-lane-mask %InLoopInc, TC
140// %ALMPart = extract-vector-for-part %ALM, ir<0>
141// %Negated = Not %ALMPart
142// branch-on-cond %Negated
143//
146 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
147 VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
148 VPValue *StartV = Plan.getZero(TopRegion->getCanonicalIVType());
149 auto *CanonicalIVIncrement = TopRegion->getOrCreateCanonicalIVIncrement();
150 // TODO: Check if dropping the flags is needed.
151 TopRegion->clearCanonicalIVNUW(CanonicalIVIncrement);
152 DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
153 auto *VecPreheader = Plan.getVectorPreheader();
154 VPBuilder Builder(VecPreheader);
155 VPValue *TC = Plan.getTripCount();
156
157 // Create the wide active lane mask instruction in the VPlan preheader.
158 VPValue *ALMMultiplier =
159 Plan.getConstantInt(TopRegion->getCanonicalIVType(), 1);
160 auto *EntryALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
161 {StartV, TC, ALMMultiplier}, DL,
162 "active.lane.mask.entry");
163 EntryALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
164 {EntryALM, Plan.getConstantInt(64, 0)}, DL,
165 "extract.entry.alm.part");
166
167 // Now create the ActiveLaneMaskPhi recipe in the main loop using the
168 // preheader WideActiveLaneMask instruction.
169 auto *LaneMaskPhi =
171 auto *HeaderVPBB = TopRegion->getEntryBasicBlock();
172 LaneMaskPhi->insertBefore(*HeaderVPBB, HeaderVPBB->begin());
173
174 // Create the active lane mask for the next iteration of the loop before the
175 // original terminator.
176 VPRecipeBase *OriginalTerminator = EB->getTerminator();
177 Builder.setInsertPoint(OriginalTerminator);
178 auto *ALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
179 {CanonicalIVIncrement, TC, ALMMultiplier},
180 DL, "active.lane.mask.next");
181 ALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
182 {ALM, Plan.getConstantInt(64, 0)}, DL,
183 "extract.next.alm.part");
184 LaneMaskPhi->addBackedgeValue(ALM);
185
186 // Replace the original terminator with BranchOnCond. We have to invert the
187 // mask here because a true condition means jumping to the exit block.
188 auto *NotMask = Builder.createNot(ALM, DL);
189 Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
190 OriginalTerminator->eraseFromParent();
191 return LaneMaskPhi;
192}
193
195 VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow) {
196 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
197 VPValue *HeaderMask = LoopRegion->getUsedHeaderMask();
198 if (!HeaderMask)
199 return;
200
201 if (UseActiveLaneMaskForControlFlow) {
203 return;
204 }
205
206 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
207 VPBuilder Builder(Header, Header->getFirstNonPhi());
208 auto *WideCanonicalIV = Builder.insert(new VPWidenCanonicalIVRecipe(
209 LoopRegion->getCanonicalIV(),
210 VPIRFlags::WrapFlagsTy(/*HasNUW=*/true, /*HasNSW=*/false)));
211 VPValue *Mask;
212 if (UseActiveLaneMask) {
213 Mask = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
214 {WideCanonicalIV, Plan.getTripCount()}, nullptr,
215 "active.lane.mask");
216 } else {
217 Mask = Builder.createICmp(CmpInst::ICMP_ULE, WideCanonicalIV,
219 }
220 HeaderMask->replaceAllUsesWith(Mask);
221}
222
223/// Expand a VPWidenIntOrFpInduction into executable recipes, for the initial
224/// value, phi and backedge value. In the following example:
225///
226/// vector.ph:
227/// Successor(s): vector loop
228///
229/// <x1> vector loop: {
230/// vector.body:
231/// WIDEN-INDUCTION %i = phi %start, %step, %vf
232/// ...
233/// EMIT branch-on-count ...
234/// No successors
235/// }
236///
237/// WIDEN-INDUCTION will get expanded to:
238///
239/// vector.ph:
240/// ...
241/// vp<%induction.start> = ...
242/// vp<%induction.increment> = ...
243///
244/// Successor(s): vector loop
245///
246/// <x1> vector loop: {
247/// vector.body:
248/// ir<%i> = WIDEN-PHI vp<%induction.start>, vp<%vec.ind.next>
249/// ...
250/// vp<%vec.ind.next> = add ir<%i>, vp<%induction.increment>
251/// EMIT branch-on-count ...
252/// No successors
253/// }
254static void
256 VPlan *Plan = WidenIVR->getParent()->getPlan();
257 VPValue *Start = WidenIVR->getStartValue();
258 VPValue *Step = WidenIVR->getStepValue();
259 VPValue *VF = WidenIVR->getVFValue();
260 DebugLoc DL = WidenIVR->getDebugLoc();
261
262 // The value from the original loop to which we are mapping the new induction
263 // variable.
264 Type *Ty = WidenIVR->getScalarType();
265
266 const InductionDescriptor &ID = WidenIVR->getInductionDescriptor();
269 VPIRFlags Flags = *WidenIVR;
270 if (ID.getKind() == InductionDescriptor::IK_IntInduction) {
271 AddOp = Instruction::Add;
272 MulOp = Instruction::Mul;
273 } else {
274 AddOp = ID.getInductionOpcode();
275 MulOp = Instruction::FMul;
276 }
277
278 // If the phi is truncated, truncate the start and step values.
279 VPBuilder Builder(Plan->getVectorPreheader());
280 Type *StepTy = Step->getScalarType();
281 if (Ty->getScalarSizeInBits() < StepTy->getScalarSizeInBits()) {
282 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
283 Step = Builder.createScalarCast(Instruction::Trunc, Step, Ty, DL);
284 Start = Builder.createScalarCast(Instruction::Trunc, Start, Ty, DL);
285 StepTy = Ty;
286 }
287
288 // Construct the initial value of the vector IV in the vector loop preheader.
289 Type *IVIntTy =
291 VPValue *Init = Builder.createNaryOp(VPInstruction::StepVector, {}, IVIntTy);
292 if (StepTy->isFloatingPointTy())
293 Init = Builder.createWidenCast(Instruction::UIToFP, Init, StepTy);
294
295 VPValue *SplatStart = Builder.createNaryOp(VPInstruction::Broadcast, Start);
296 VPValue *SplatStep = Builder.createNaryOp(VPInstruction::Broadcast, Step);
297
298 Init = Builder.createNaryOp(MulOp, {Init, SplatStep}, Flags);
299 Init = Builder.createNaryOp(AddOp, {SplatStart, Init}, Flags,
300 DebugLoc::getUnknown(), "induction");
301
302 // Create the widened phi of the vector IV.
303 auto *WidePHI = VPBuilder(WidenIVR).createWidenPhi(
304 Init, WidenIVR->getDebugLoc(), "vec.ind");
305
306 // Create the backedge value for the vector IV.
307 VPValue *Inc;
308 VPValue *Prev;
309 // If unrolled, use the increment and prev value from the operands.
310 if (auto *SplatVF = WidenIVR->getSplatVFValue()) {
311 Inc = SplatVF;
312 Prev = WidenIVR->getLastUnrolledPartOperand();
313 } else {
314 // Move the insertion point after the VF definition when the VF is defined
315 // inside a loop, such as for EVL tail-folding.
316 if (VPRecipeBase *R = VF->getDefiningRecipe())
317 if (R->getParent()->getEnclosingLoopRegion())
318 Builder.setInsertPoint(R->getParent(), std::next(R->getIterator()));
319
320 // Multiply the vectorization factor by the step using integer or
321 // floating-point arithmetic as appropriate.
322 if (StepTy->isFloatingPointTy())
323 VF = Builder.createScalarCast(Instruction::CastOps::UIToFP, VF, StepTy,
324 DL);
325 else
326 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
327
328 Inc = Builder.createNaryOp(MulOp, {Step, VF}, Flags);
329 Inc = Builder.createNaryOp(VPInstruction::Broadcast, Inc);
330 Prev = WidePHI;
331 }
332
334 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
335 auto *Next = Builder.createNaryOp(AddOp, {Prev, Inc}, Flags,
336 WidenIVR->getDebugLoc(), "vec.ind.next");
337
338 WidePHI->addIncoming(Next);
339
340 WidenIVR->replaceAllUsesWith(WidePHI);
341}
342
343/// Expand a VPWidenPointerInductionRecipe into executable recipes, for the
344/// initial value, phi and backedge value. In the following example:
345///
346/// <x1> vector loop: {
347/// vector.body:
348/// EMIT ir<%ptr.iv> = WIDEN-POINTER-INDUCTION %start, %step, %vf
349/// ...
350/// EMIT branch-on-count ...
351/// }
352///
353/// WIDEN-POINTER-INDUCTION will get expanded to:
354///
355/// <x1> vector loop: {
356/// vector.body:
357/// EMIT-SCALAR %pointer.phi = phi %start, %ptr.ind
358/// EMIT %mul = mul %stepvector, %step
359/// EMIT %vector.gep = wide-ptradd %pointer.phi, %mul
360/// ...
361/// EMIT %ptr.ind = ptradd %pointer.phi, %vf
362/// EMIT branch-on-count ...
363/// }
365 VPlan *Plan = R->getParent()->getPlan();
366 VPValue *Start = R->getStartValue();
367 VPValue *Step = R->getStepValue();
368 VPValue *VF = R->getVFValue();
369
370 assert(R->getInductionDescriptor().getKind() ==
372 "Not a pointer induction according to InductionDescriptor!");
373 assert(R->getScalarType()->isPointerTy() && "Unexpected type.");
374 assert(!R->onlyScalarsGenerated(Plan->hasScalableVF()) &&
375 "Recipe should have been replaced");
376
377 VPBuilder Builder(R);
378 DebugLoc DL = R->getDebugLoc();
379
380 // Build a scalar pointer phi.
381 VPPhi *ScalarPtrPhi = Builder.createScalarPhi(Start, DL, "pointer.phi");
382
383 // Create actual address geps that use the pointer phi as base and a
384 // vectorized version of the step value (<step*0, ..., step*N>) as offset.
385 Builder.setInsertPoint(R->getParent(), R->getParent()->getFirstNonPhi());
386 Type *StepTy = Step->getScalarType();
387 VPValue *Offset = Builder.createNaryOp(VPInstruction::StepVector, {}, StepTy);
388 Offset = Builder.createOverflowingOp(Instruction::Mul, {Offset, Step});
389 VPValue *PtrAdd =
390 Builder.createWidePtrAdd(ScalarPtrPhi, Offset, DL, "vector.gep");
391 R->replaceAllUsesWith(PtrAdd);
392
393 // Create the backedge value for the scalar pointer phi.
395 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
396 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
397 VPValue *Inc = Builder.createOverflowingOp(Instruction::Mul, {Step, VF});
398
399 VPValue *InductionGEP =
400 Builder.createPtrAdd(ScalarPtrPhi, Inc, DL, "ptr.ind");
401 ScalarPtrPhi->addIncoming(InductionGEP);
402}
403
404/// Expand a VPDerivedIVRecipe into executable recipes.
406 VPBuilder Builder(R);
407 VPValue *Start = R->getStartValue();
408 VPValue *Step = R->getStepValue();
409 VPValue *Index = R->getIndex();
410 Type *StepTy = Step->getScalarType();
411 Index = StepTy->isIntegerTy()
412 ? Builder.createScalarZExtOrTrunc(
413 Index, StepTy, DebugLoc::getCompilerGenerated())
414 : Builder.createScalarCast(Instruction::SIToFP, Index, StepTy,
416 VPIRFlags::WrapFlagsTy Flags = R->getNoWrapFlags();
417 switch (R->getInductionKind()) {
419 assert(Index->getScalarType() == Start->getScalarType() &&
420 "Index type does not match StartValue type");
421 return R->replaceAllUsesWith(Builder.createAdd(
422 Start,
423 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags),
424 DebugLoc::getUnknown(), "", Flags));
425 }
427 return R->replaceAllUsesWith(Builder.createPtrAdd(
428 Start,
429 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags)));
431 assert(StepTy->isFloatingPointTy() && "Expected FP Step value");
432 const FPMathOperator *FPBinOp = R->getFPBinOp();
433 assert(FPBinOp &&
434 (FPBinOp->getOpcode() == Instruction::FAdd ||
435 FPBinOp->getOpcode() == Instruction::FSub) &&
436 "Original BinOp should be defined for FP induction");
437 FastMathFlags FMF = FPBinOp->getFastMathFlags();
438 VPValue *FMul = Builder.createNaryOp(Instruction::FMul, {Step, Index}, FMF);
439 return R->replaceAllUsesWith(
440 Builder.createNaryOp(FPBinOp->getOpcode(), {Start, FMul}, FMF));
441 }
443 return;
444 }
445 llvm_unreachable("Unhandled induction kind");
446}
447
449 // Replace loop regions with explicity CFG.
452 vp_depth_first_deep(Plan.getEntry()))) {
453 if (!R->isReplicator())
454 LoopRegions.push_back(R);
455 }
456 for (VPRegionBlock *R : LoopRegions)
457 R->dissolveToCFGLoop();
458}
459
462 // The transform runs after dissolving loop regions, so all VPBasicBlocks
463 // terminated with BranchOnTwoConds are reached via a shallow traversal.
466 if (!VPBB->empty() && match(&VPBB->back(), m_BranchOnTwoConds()))
467 WorkList.push_back(cast<VPInstruction>(&VPBB->back()));
468 }
469
470 // Expand BranchOnTwoConds instructions into explicit CFG with two new
471 // single-condition branches:
472 // 1. A branch that replaces BranchOnTwoConds, jumps to the first successor if
473 // the first condition is true, and otherwise jumps to a new interim block.
474 // 2. A branch that ends the interim block, jumps to the second successor if
475 // the second condition is true, and otherwise jumps to the third
476 // successor.
477 for (VPInstruction *Br : WorkList) {
478 assert(Br->getNumOperands() == 2 &&
479 "BranchOnTwoConds must have exactly 2 conditions");
480 DebugLoc DL = Br->getDebugLoc();
481 VPBasicBlock *BrOnTwoCondsBB = Br->getParent();
482 const auto Successors = to_vector(BrOnTwoCondsBB->getSuccessors());
483 assert(Successors.size() == 3 &&
484 "BranchOnTwoConds must have exactly 3 successors");
485
486 for (VPBlockBase *Succ : Successors)
487 VPBlockUtils::disconnectBlocks(BrOnTwoCondsBB, Succ);
488
489 VPValue *Cond0 = Br->getOperand(0);
490 VPValue *Cond1 = Br->getOperand(1);
491 VPBlockBase *Succ0 = Successors[0];
492 VPBlockBase *Succ1 = Successors[1];
493 VPBlockBase *Succ2 = Successors[2];
494
495 // If the successor block for both conditions is the same, then combine the
496 // two conditions and plant a single conditional branch.
497 if (Succ0 == Succ1) {
498 VPBuilder Builder(Br);
499 VPValue *Combined = Builder.createOr(Cond0, Cond1, DL);
500 Builder.createNaryOp(VPInstruction::BranchOnCond, {Combined}, DL);
501 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
502 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ2);
503 Br->eraseFromParent();
504 continue;
505 }
506
507 assert(!Succ0->getParent() && !Succ1->getParent() && !Succ2->getParent() &&
508 !BrOnTwoCondsBB->getParent() && "regions must already be dissolved");
509
510 VPBasicBlock *InterimBB =
511 Plan.createVPBasicBlock(BrOnTwoCondsBB->getName() + ".interim");
512
513 VPBuilder(BrOnTwoCondsBB)
515 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
516 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, InterimBB);
517
519 VPBlockUtils::connectBlocks(InterimBB, Succ1);
520 VPBlockUtils::connectBlocks(InterimBB, Succ2);
521 Br->eraseFromParent();
522 }
523}
524
527 vp_depth_first_deep(Plan.getEntry()))) {
528 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
529 VPBuilder Builder(&R);
530 if (auto *WidenIVR = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
532 WidenIVR->eraseFromParent();
533 continue;
534 }
535
536 if (auto *WidenIVR = dyn_cast<VPWidenPointerInductionRecipe>(&R)) {
537 // If the recipe only generates scalars, scalarize it instead of
538 // expanding it.
539 if (WidenIVR->onlyScalarsGenerated(Plan.hasScalableVF())) {
541 WidenIVR, Plan, Builder);
542 WidenIVR->replaceAllUsesWith(PtrAdd);
543 WidenIVR->eraseFromParent();
544 continue;
545 }
547 WidenIVR->eraseFromParent();
548 continue;
549 }
550
551 if (auto *DerivedIVR = dyn_cast<VPDerivedIVRecipe>(&R)) {
552 expandVPDerivedIV(DerivedIVR);
553 DerivedIVR->eraseFromParent();
554 continue;
555 }
556
557 if (auto *WideCanIV = dyn_cast<VPWidenCanonicalIVRecipe>(&R)) {
558 VPValue *CanIV = WideCanIV->getCanonicalIV();
559 Type *CanIVTy = CanIV->getScalarType();
560 VPValue *Step = WideCanIV->getStepValue();
561 if (!Step) {
562 assert(Plan.getConcreteUF() == 1 &&
563 "Expected unroller to have materialized step for UF != 1");
564 Step = Plan.getZero(CanIVTy);
565 }
566 CanIV = Builder.createNaryOp(VPInstruction::Broadcast, CanIV);
567 Step = Builder.createNaryOp(VPInstruction::Broadcast, Step);
568 Step = Builder.createAdd(
569 Step, Builder.createNaryOp(VPInstruction::StepVector, {}, CanIVTy));
570 VPValue *CanVecIV =
571 Builder.createAdd(CanIV, Step, WideCanIV->getDebugLoc(), "vec.iv",
572 WideCanIV->getNoWrapFlags());
573 WideCanIV->replaceAllUsesWith(CanVecIV);
574 WideCanIV->eraseFromParent();
575 continue;
576 }
577
578 // Expand VPBlendRecipe into VPInstruction::Select.
579 if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
580 VPValue *Select = Blend->getIncomingValue(0);
581 for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
582 Select = Builder.createSelect(Blend->getMask(I),
583 Blend->getIncomingValue(I), Select,
584 R.getDebugLoc(), "predphi", *Blend);
585 Blend->replaceAllUsesWith(Select);
586 Blend->eraseFromParent();
587 continue;
588 }
589
590 if (auto *VEPR = dyn_cast<VPVectorEndPointerRecipe>(&R)) {
591 if (!VEPR->getOffset()) {
592 assert(Plan.getConcreteUF() == 1 &&
593 "Expected unroller to have materialized offset for UF != 1");
594 VEPR->materializeOffset();
595 }
596 continue;
597 }
598
599 if (auto *Expr = dyn_cast<VPExpressionRecipe>(&R)) {
600 Expr->decompose();
601 Expr->eraseFromParent();
602 continue;
603 }
604
605 // Expand LastActiveLane into Not + FirstActiveLane + Sub.
606 auto *LastActiveL = dyn_cast<VPInstruction>(&R);
607 if (LastActiveL &&
608 LastActiveL->getOpcode() == VPInstruction::LastActiveLane) {
609 // Create Not(Mask) for all operands.
611 for (VPValue *Op : LastActiveL->operands()) {
612 VPValue *NotMask = Builder.createNot(Op, LastActiveL->getDebugLoc());
613 NotMasks.push_back(NotMask);
614 }
615
616 // Create FirstActiveLane on the inverted masks.
617 VPValue *FirstInactiveLane = Builder.createFirstActiveLane(
618 NotMasks, LastActiveL->getDebugLoc(), "first.inactive.lane");
619
620 // Subtract 1 to get the last active lane.
621 VPValue *One =
622 Plan.getConstantInt(FirstInactiveLane->getScalarType(), 1);
623 VPValue *LastLane =
624 Builder.createSub(FirstInactiveLane, One,
625 LastActiveL->getDebugLoc(), "last.active.lane");
626
627 LastActiveL->replaceAllUsesWith(LastLane);
628 LastActiveL->eraseFromParent();
629 continue;
630 }
631
632 // Lower MaskedCond with block mask to LogicalAnd.
634 auto *VPI = cast<VPInstruction>(&R);
635 assert(VPI->isMasked() &&
636 "Unmasked MaskedCond should be simplified earlier");
637 VPI->replaceAllUsesWith(Builder.createNaryOp(
638 VPInstruction::LogicalAnd, {VPI->getMask(), VPI->getOperand(0)}));
639 VPI->eraseFromParent();
640 continue;
641 }
642
643 // Lower CanonicalIVIncrementForPart to plain Add.
644 if (match(
645 &R,
647 auto *VPI = cast<VPInstruction>(&R);
648 VPValue *Add = Builder.createOverflowingOp(
649 Instruction::Add, VPI->operands(), VPI->getNoWrapFlags(),
650 VPI->getDebugLoc());
651 VPI->replaceAllUsesWith(Add);
652 VPI->eraseFromParent();
653 continue;
654 }
655
656 // Lower BranchOnCount to ICmp + BranchOnCond.
657 VPValue *IV, *TC;
658 if (match(&R, m_BranchOnCount(m_VPValue(IV), m_VPValue(TC)))) {
659 auto *BranchOnCountInst = cast<VPInstruction>(&R);
660 DebugLoc DL = BranchOnCountInst->getDebugLoc();
661 VPValue *Cond = Builder.createICmp(CmpInst::ICMP_EQ, IV, TC, DL);
662 Builder.createNaryOp(VPInstruction::BranchOnCond, Cond, DL);
663 BranchOnCountInst->eraseFromParent();
664 continue;
665 }
666
667 VPValue *VectorStep;
668 VPValue *ScalarStep;
670 m_VPValue(VectorStep), m_VPValue(ScalarStep))))
671 continue;
672
673 // Expand WideIVStep.
674 auto *VPI = cast<VPInstruction>(&R);
675 Type *IVTy = VPI->getScalarType();
676 if (VectorStep->getScalarType() != IVTy) {
678 ? Instruction::UIToFP
679 : Instruction::Trunc;
680 VectorStep = Builder.createWidenCast(CastOp, VectorStep, IVTy);
681 }
682
683 assert(!match(ScalarStep, m_One()) && "Expected non-unit scalar-step");
684 if (ScalarStep->getScalarType() != IVTy) {
685 ScalarStep =
686 Builder.createWidenCast(Instruction::Trunc, ScalarStep, IVTy);
687 }
688
689 VPIRFlags Flags;
690 unsigned MulOpc;
691 if (IVTy->isFloatingPointTy()) {
692 MulOpc = Instruction::FMul;
693 Flags = VPI->getFastMathFlagsOrNone();
694 } else {
695 MulOpc = Instruction::Mul;
696 Flags = VPIRFlags::getDefaultFlags(MulOpc);
697 }
698
699 VPInstruction *Mul = Builder.createNaryOp(
700 MulOpc, {VectorStep, ScalarStep}, Flags, R.getDebugLoc());
701 VectorStep = Mul;
702 VPI->replaceAllUsesWith(VectorStep);
703 VPI->eraseFromParent();
704 }
705 }
706}
707
709 if (Plan.hasScalarVFOnly())
710 return;
711
712#ifndef NDEBUG
713 VPDominatorTree VPDT(Plan);
714#endif
715
716 SmallVector<VPValue *> VPValues;
717 if (VPValue *BTC = Plan.getBackedgeTakenCount())
718 VPValues.push_back(BTC);
719 append_range(VPValues, Plan.getLiveIns());
720 for (VPRecipeBase &R : *Plan.getEntry())
721 append_range(VPValues, R.definedValues());
722
723 auto *VectorPreheader = Plan.getVectorPreheader();
724 for (VPValue *VPV : VPValues) {
726 continue;
727
728 // Add explicit broadcast at the insert point that dominates all users.
729 VPBasicBlock *HoistBlock = VectorPreheader;
730 VPBasicBlock::iterator HoistPoint = VectorPreheader->end();
731 for (VPUser *User : VPV->users()) {
732 if (User->usesScalars(VPV))
733 continue;
734 if (cast<VPRecipeBase>(User)->getParent() == VectorPreheader)
735 HoistPoint = HoistBlock->begin();
736 else
737 assert(VPDT.dominates(VectorPreheader,
738 cast<VPRecipeBase>(User)->getParent()) &&
739 "All users must be in the vector preheader or dominated by it");
740 }
741
742 VPBuilder Builder(cast<VPBasicBlock>(HoistBlock), HoistPoint);
743 auto *Broadcast = Builder.createNaryOp(VPInstruction::Broadcast, {VPV});
744 VPV->replaceUsesWithIf(Broadcast,
745 [VPV, Broadcast](VPUser &U, unsigned Idx) {
746 return Broadcast != &U && !U.usesScalars(VPV);
747 });
748 }
749}
750
752 VPlan &Plan, ElementCount BestVF, unsigned BestUF,
754 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
755 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
756
757 VPValue *TC = Plan.getTripCount();
758 if (TC->user_empty())
759 return;
760
761 // Skip cases for which the trip count may be non-trivial to materialize.
762 // I.e., when a scalar tail is absent - due to tail folding, or when a scalar
763 // tail is required.
764 if (Plan.hasTailFolded() || !Plan.hasScalarTail() ||
766 Plan.getScalarPreheader() ||
767 !isa<VPIRValue>(TC))
768 return;
769
770 // Materialize vector trip counts for constants early if it can simply
771 // be computed as (Original TC / VF * UF) * VF * UF.
772 // TODO: Compute vector trip counts for loops requiring a scalar epilogue and
773 // tail-folded loops.
774 ScalarEvolution &SE = *PSE.getSE();
775 auto *TCScev = SE.getSCEV(TC->getLiveInIRValue());
776 if (!isa<SCEVConstant>(TCScev))
777 return;
778 const SCEV *VFxUF = SE.getElementCount(TCScev->getType(), BestVF * BestUF);
779 auto VecTCScev = SE.getMulExpr(SE.getUDivExpr(TCScev, VFxUF), VFxUF);
780 if (auto *ConstVecTC = dyn_cast<SCEVConstant>(VecTCScev))
781 Plan.getVectorTripCount().setUnderlyingValue(ConstVecTC->getValue());
782}
783
785 VPBasicBlock *VectorPH) {
787 if (BTC->user_empty())
788 return;
789
790 VPBuilder Builder(VectorPH, VectorPH->begin());
791 auto *TCTy = Plan.getTripCount()->getScalarType();
792 auto *TCMO =
793 Builder.createSub(Plan.getTripCount(), Plan.getConstantInt(TCTy, 1),
794 DebugLoc::getCompilerGenerated(), "trip.count.minus.1");
795 BTC->replaceAllUsesWith(TCMO);
796}
797
799 if (Plan.hasScalarVFOnly())
800 return;
801
802 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
803 auto VPBBsOutsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
805 auto VPBBsInsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
806 vp_depth_first_shallow(LoopRegion->getEntry()));
807 // Materialize Build(Struct)Vector for all replicating VPReplicateRecipes,
808 // VPScalarIVStepsRecipe and VPInstructions, excluding ones in replicate
809 // regions. Those are not materialized explicitly yet.
810 // TODO: materialize build vectors for replicating recipes in replicating
811 // regions.
812 for (VPBasicBlock *VPBB :
813 concat<VPBasicBlock *>(VPBBsOutsideLoopRegion, VPBBsInsideLoopRegion)) {
814 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
816 continue;
817 auto *DefR = cast<VPSingleDefRecipe>(&R);
818 auto UsesVectorOrInsideReplicateRegion = [DefR, LoopRegion](VPUser *U) {
819 VPRegionBlock *ParentRegion = cast<VPRecipeBase>(U)->getRegion();
820 return !U->usesScalars(DefR) || ParentRegion != LoopRegion;
821 };
822 if (none_of(DefR->users(), UsesVectorOrInsideReplicateRegion))
823 continue;
824
825 Type *ScalarTy = DefR->getScalarType();
826 unsigned Opcode = ScalarTy->isStructTy()
829 auto *BuildVector = new VPInstruction(Opcode, {DefR});
830 BuildVector->insertAfter(DefR);
831
832 DefR->replaceUsesWithIf(
833 BuildVector, [BuildVector, &UsesVectorOrInsideReplicateRegion](
834 VPUser &U, unsigned) {
835 return &U != BuildVector && UsesVectorOrInsideReplicateRegion(&U);
836 });
837 }
838 }
839
840 // Create explicit VPInstructions to convert vectors to scalars. The current
841 // implementation is conservative - it may miss some cases that may or may not
842 // be vector values. TODO: introduce Unpacks speculatively - remove them later
843 // if they are known to operate on scalar values.
844 for (VPBasicBlock *VPBB : VPBBsInsideLoopRegion) {
845 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
848 continue;
849 for (VPValue *Def : R.definedValues()) {
850 // Skip recipes that are single-scalar.
851 // TODO: The Defs skipped here may or may not be vector values.
852 // Introduce Unpacks, and remove them later, if they are guaranteed to
853 // produce scalar values.
855 continue;
856
857 // Only introduce an Unpack if some, but not all, users use the first
858 // lane only.
859 unsigned NumFirstLaneUsers = count_if(Def->users(), [&Def](VPUser *U) {
860 return U->usesFirstLaneOnly(Def);
861 });
862 if (!NumFirstLaneUsers || NumFirstLaneUsers == Def->getNumUsers())
863 continue;
864
865 auto *Unpack = new VPInstruction(VPInstruction::Unpack, {Def});
866 if (R.isPhi())
867 Unpack->insertBefore(*VPBB, VPBB->getFirstNonPhi());
868 else
869 Unpack->insertAfter(&R);
870 Def->replaceUsesWithIf(Unpack, [&Def](VPUser &U, unsigned) {
871 return U.usesFirstLaneOnly(Def);
872 });
873 }
874 }
875 }
876}
877
879 VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking,
880 bool RequiresScalarEpilogue, VPValue *Step,
881 std::optional<uint64_t> MaxRuntimeStep) {
882 VPSymbolicValue &VectorTC = Plan.getVectorTripCount();
883 // There's nothing to do if there are no users of the vector trip count or its
884 // IR value has already been set.
885 if (VectorTC.user_empty() || VectorTC.getUnderlyingValue())
886 return;
887
888 VPValue *TC = Plan.getTripCount();
889 Type *TCTy = TC->getScalarType();
890 VPBasicBlock::iterator InsertPt = VectorPHVPBB->begin();
891 if (auto *StepR = Step->getDefiningRecipe()) {
892 assert(VPDominatorTree(Plan).dominates(StepR->getParent(), VectorPHVPBB) &&
893 "Step VPBB must dominate VectorPHVPBB");
894 // Insert after Step's definition to maintain valid def-use ordering.
895 InsertPt = std::next(StepR->getIterator());
896 }
897 VPBuilder Builder(VectorPHVPBB, InsertPt);
898
899 // For scalable steps, if TC is a constant and is divisible by the maximum
900 // possible runtime step, then TC % Step == 0 for all valid vscale values
901 // and the vector trip count equals TC directly.
902 const APInt *TCVal;
903 if (!RequiresScalarEpilogue && match(TC, m_APInt(TCVal)) && MaxRuntimeStep &&
904 TCVal->urem(*MaxRuntimeStep) == 0) {
905 VectorTC.replaceAllUsesWith(TC);
906 return;
907 }
908
909 // If the tail is to be folded by masking, round the number of iterations N
910 // up to a multiple of Step instead of rounding down. This is done by first
911 // adding Step-1 and then rounding down. Note that it's ok if this addition
912 // overflows: the vector induction variable will eventually wrap to zero given
913 // that it starts at zero and its Step is a power of two; the loop will then
914 // exit, with the last early-exit vector comparison also producing all-true.
915 if (TailByMasking) {
916 TC = Builder.createAdd(
917 TC, Builder.createSub(Step, Plan.getConstantInt(TCTy, 1)),
918 DebugLoc::getCompilerGenerated(), "n.rnd.up");
919 }
920
921 // Now we need to generate the expression for the part of the loop that the
922 // vectorized body will execute. This is equal to N - (N % Step) if scalar
923 // iterations are not required for correctness, or N - Step, otherwise. Step
924 // is equal to the vectorization factor (number of SIMD elements) times the
925 // unroll factor (number of SIMD instructions).
926 VPValue *R =
927 Builder.createNaryOp(Instruction::URem, {TC, Step},
928 DebugLoc::getCompilerGenerated(), "n.mod.vf");
929
930 // There are cases where we *must* run at least one iteration in the remainder
931 // loop. See the cost model for when this can happen. If the step evenly
932 // divides the trip count, we set the remainder to be equal to the step. If
933 // the step does not evenly divide the trip count, no adjustment is necessary
934 // since there will already be scalar iterations. Note that the minimum
935 // iterations check ensures that N >= Step.
936 if (RequiresScalarEpilogue) {
937 assert(!TailByMasking &&
938 "requiring scalar epilogue is not supported with fail folding");
939 VPValue *IsZero =
940 Builder.createICmp(CmpInst::ICMP_EQ, R, Plan.getZero(TCTy));
941 R = Builder.createSelect(IsZero, Step, R);
942 }
943
944 VPValue *Res =
945 Builder.createSub(TC, R, DebugLoc::getCompilerGenerated(), "n.vec");
946 VectorTC.replaceAllUsesWith(Res);
947}
948
950 ElementCount VFEC) {
951 // If VF and VFxUF have already been materialized (no remaining users),
952 // there's nothing more to do.
953 if (Plan.getVF().isMaterialized()) {
954 assert(Plan.getVFxUF().isMaterialized() &&
955 "VF and VFxUF must be materialized together");
956 return;
957 }
958
959 VPBuilder Builder(VectorPH, VectorPH->begin());
960 Type *TCTy = Plan.getTripCount()->getScalarType();
961 VPValue &VF = Plan.getVF();
962 VPValue &VFxUF = Plan.getVFxUF();
963 // If there are no users of the runtime VF, compute VFxUF by constant folding
964 // the multiplication of VF and UF.
965 if (VF.user_empty()) {
966 VPValue *RuntimeVFxUF =
967 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
968 VFxUF.replaceAllUsesWith(RuntimeVFxUF);
969 return;
970 }
971
972 // For users of the runtime VF, compute it as VF * vscale, and VFxUF as (VF *
973 // vscale) * UF.
974 VPValue *RuntimeVF = Builder.createElementCount(TCTy, VFEC);
976 VPValue *BC = Builder.createNaryOp(VPInstruction::Broadcast, RuntimeVF);
978 BC, [&VF](VPUser &U, unsigned) { return !U.usesScalars(&VF); });
979 }
980 VF.replaceAllUsesWith(RuntimeVF);
981
982 VPValue *MulByUF =
983 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
984 VFxUF.replaceAllUsesWith(MulByUF);
985}
986
987VPValue *
989 ArrayRef<PointerDiffInfo> DiffChecks) {
990 VPBuilder Builder(AliasCheckVPBB);
991 Type *I1Ty = IntegerType::getInt1Ty(Plan.getContext());
992
993 VPValue *IncomingAliasMask = vputils::findIncomingAliasMask(Plan);
994 assert(IncomingAliasMask && "Expected an alias mask!");
995
996 VPValue *AliasMask = nullptr;
997 for (const PointerDiffInfo &Check : DiffChecks) {
999 VPValue *Sink =
1001 Type *AddrType = Src->getScalarType();
1002
1003 // TODO: Only freeze the required pointer (not both src and sink).
1004 if (Check.NeedsFreeze) {
1005 Src = Builder.createScalarFreeze(Src, DebugLoc::getUnknown());
1006 Sink = Builder.createScalarFreeze(Sink, DebugLoc::getUnknown());
1007 }
1008
1009 // TODO: Generate loop_dependence_raw_mask when there's a read-after-write
1010 // dependency between the source and the sink. This is not necessary for
1011 // correctness of the mask, but using the "raw" variant prevents loads
1012 // depending on the completion of stores.
1013 VPWidenIntrinsicRecipe *WARMask = Builder.insert(new VPWidenIntrinsicRecipe(
1014 Intrinsic::loop_dependence_war_mask,
1015 {Src, Sink, Plan.getConstantInt(AddrType, Check.AccessSize)}, I1Ty));
1016
1017 if (AliasMask)
1018 AliasMask = Builder.createAnd(AliasMask, WARMask);
1019 else
1020 AliasMask = WARMask;
1021 }
1022
1024 Type *IndexTy = Plan.getDataLayout().getIndexType(Plan.getContext(), 0);
1025 VPValue *NumActive = Builder.createNaryOp(
1026 VPInstruction::NumActiveLanes, {AliasMask}, nullptr, {}, {},
1027 DebugLoc::getUnknown(), "num.active.lanes", IndexTy);
1028 VPValue *ClampedVF = Builder.createScalarZExtOrTrunc(
1029 NumActive, IVTy, DebugLoc::getCompilerGenerated());
1030
1031 IncomingAliasMask->replaceAllUsesWith(AliasMask);
1032
1033 return ClampedVF;
1034}
1035
1037 VPlan &Plan, ArrayRef<PointerDiffInfo> DiffChecks, bool HasBranchWeights) {
1038 VPBasicBlock *ClampedVFCheck =
1039 Plan.createVPBasicBlock("vector.clamped.vf.check");
1040
1041 VPValue *ClampedVF = materializeAliasMask(Plan, ClampedVFCheck, DiffChecks);
1042 VPBuilder Builder(ClampedVFCheck);
1044 Type *TCTy = Plan.getTripCount()->getScalarType();
1045
1046 // Check the "ClampedVF" from the alias mask is larger than one.
1047 VPValue *IsScalar =
1048 Builder.createICmp(CmpInst::ICMP_ULE, ClampedVF,
1049 Plan.getConstantInt(TCTy, 1), DL, "vf.is.scalar");
1050
1051 VPValue *TripCount = Plan.getTripCount();
1052 VPValue *MaxUIntTripCount =
1054 VPValue *DistanceToMax = Builder.createSub(MaxUIntTripCount, TripCount);
1055
1056 // For tail-folding: Don't execute the vector loop if (UMax - n) < ClampedVF.
1057 // Note: The ClampedVF may not be a power-of-two. This means the loop exit
1058 // condition (index.next == n.vec) may not be correct in the case of an
1059 // overflow. The issue is `n.vec` could be zero due to an overflow, but
1060 // index.next is not guaranteed to overflow to zero as the ClampedVF is not a
1061 // power-of-two).
1062 VPValue *TripCountCheck = Builder.createICmp(
1063 ICmpInst::ICMP_ULT, DistanceToMax, ClampedVF, DL, "vf.step.overflow");
1064
1065 VPValue *Cond = Builder.createOr(IsScalar, TripCountCheck, DL);
1066 attachVPCheckBlock(Plan, Cond, ClampedVFCheck, HasBranchWeights);
1067
1068 // Materialize the trip count early as this will add a use of (VFxUF) that
1069 // needs to be replaced with the ClampedVF.
1071 /*TailByMasking=*/true,
1072 /*RequiresScalarEpilogue=*/false,
1073 &Plan.getVFxUF());
1074
1075 assert(Plan.getConcreteUF() == 1 &&
1076 "Clamped VF not supported with interleaving");
1077 Plan.getVF().replaceAllUsesWith(ClampedVF);
1078 Plan.getVFxUF().replaceAllUsesWith(ClampedVF);
1079}
1080
1082 ScalarEvolution &SE) {
1083 auto *Entry = Plan.getEntry();
1084 VPBuilder Builder(Entry, Entry->begin());
1086 ->getIRBasicBlock()
1087 ->getTerminator()
1088 ->getDebugLoc();
1089 VPSCEVExpander Expander(Builder, SE, DL);
1090
1091 // Expand VPExpandSCEVRecipes to VPInstructions using VPSCEVExpander.
1092 for (VPRecipeBase &R : make_early_inc_range(*Entry)) {
1093 auto *ExpSCEV = dyn_cast<VPExpandSCEVRecipe>(&R);
1094 if (!ExpSCEV || ExpSCEV->user_empty())
1095 continue;
1096 Builder.setInsertPoint(ExpSCEV);
1097 VPValue *Expanded = Expander.expand(ExpSCEV->getSCEV());
1098 ExpSCEV->replaceAllUsesWith(Expanded);
1099 // TripCount should not be used after expansion to VPInstructions. Reset to
1100 // poison to avoid dangling references.
1101 if (Plan.getTripCount() == ExpSCEV)
1102 Plan.resetTripCount(Plan.getPoison(ExpSCEV->getScalarType()));
1103 ExpSCEV->eraseFromParent();
1104 }
1105}
1106
1109 SCEVExpander Expander(SE, "induction", /*PreserveLCSSA=*/false);
1110
1111 auto *Entry = cast<VPIRBasicBlock>(Plan.getEntry());
1112 BasicBlock *EntryBB = Entry->getIRBasicBlock();
1113 DenseMap<const SCEV *, Value *> ExpandedSCEVs;
1114 // Expand remaining VPExpandSCEVRecipes to IR instructions using SCEVExpander.
1115 for (VPRecipeBase &R : make_early_inc_range(*Entry)) {
1116 auto *ExpSCEV = dyn_cast<VPExpandSCEVRecipe>(&R);
1117 if (!ExpSCEV)
1118 continue;
1119 const SCEV *Expr = ExpSCEV->getSCEV();
1120 Value *Res =
1121 Expander.expandCodeFor(Expr, Expr->getType(), EntryBB->getTerminator());
1122 ExpandedSCEVs[Expr] = Res;
1123 VPValue *Exp = Plan.getOrAddLiveIn(Res);
1124 ExpSCEV->replaceAllUsesWith(Exp);
1125 if (Plan.getTripCount() == ExpSCEV)
1126 Plan.resetTripCount(Exp);
1127 ExpSCEV->eraseFromParent();
1128 }
1130 "all VPExpandSCEVRecipes must have been expanded");
1131 // Add IR instructions in the entry basic block but not in the VPIRBasicBlock
1132 // to the VPIRBasicBlock.
1133 auto EI = Entry->begin();
1134 for (Instruction &I : drop_end(*EntryBB)) {
1135 if (EI != Entry->end() && isa<VPIRInstruction>(*EI) &&
1136 &cast<VPIRInstruction>(&*EI)->getInstruction() == &I) {
1137 EI++;
1138 continue;
1139 }
1141 }
1142
1143 return ExpandedSCEVs;
1144}
1145
1146/// Add branch weight metadata, if the \p Plan's middle block is terminated by a
1147/// BranchOnCond recipe.
1149 VPlan &Plan, ElementCount VF, std::optional<unsigned> VScaleForTuning) {
1150 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1151 auto *MiddleTerm =
1153 // Only add branch metadata if there is a (conditional) terminator.
1154 if (!MiddleTerm)
1155 return;
1156
1157 assert(MiddleTerm->getOpcode() == VPInstruction::BranchOnCond &&
1158 "must have a BranchOnCond");
1159 // Assume that `TripCount % VectorStep ` is equally distributed.
1160 unsigned VectorStep = Plan.getConcreteUF() * VF.getKnownMinValue();
1161 if (VF.isScalable() && VScaleForTuning.has_value())
1162 VectorStep *= *VScaleForTuning;
1163 assert(VectorStep > 0 && "trip count should not be zero");
1164 MDBuilder MDB(Plan.getContext());
1165 MDNode *BranchWeights =
1166 MDB.createBranchWeights({1, VectorStep - 1}, /*IsExpected=*/false);
1167 MiddleTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1168}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
This file provides a LoopVectorizationPlanner class.
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
const SmallVectorImpl< MachineOperand > & Cond
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
This file contains some templates that are useful if you are working with the STL at all.
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
static VPActiveLaneMaskPHIRecipe * addVPLaneMaskPhiAndUpdateExitBranch(VPlan &Plan)
static void expandVPDerivedIV(VPDerivedIVRecipe *R)
Expand a VPDerivedIVRecipe into executable recipes.
static void expandVPWidenIntOrFpInduction(VPWidenIntOrFpInductionRecipe *WidenIVR)
Expand a VPWidenIntOrFpInduction into executable recipes, for the initial value, phi and backedge val...
static void expandVPWidenPointerInduction(VPWidenPointerInductionRecipe *R)
Expand a VPWidenPointerInductionRecipe into executable recipes, for the initial value,...
This file provides utility VPlan to VPlan transformations.
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1693
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
static DebugLoc getUnknown()
Definition DebugLoc.h:153
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Definition Operator.h:291
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
A struct for saving information about induction variables.
static LLVM_ABI InductionDescriptor getCanonicalIntInduction(Type *Ty, ScalarEvolution &SE)
Returns the canonical integer induction for type Ty with start = 0 and step = 1.
@ IK_NoInduction
Not an induction variable.
@ IK_FpInduction
Floating point induction variable.
@ IK_PtrInduction
Pointer induction var. Step = C.
@ IK_IntInduction
Integer induction variable. Step = C.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
Metadata node.
Definition Metadata.h:1069
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
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.
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ SK_Broadcast
Broadcast element 0 to all other elements.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition VPlan.h:4061
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4400
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4427
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4435
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:663
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:93
VPRegionBlock * getParent()
Definition VPlan.h:191
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:236
VPlan * getPlan()
Definition VPlan.cpp:211
const std::string & getName() const
Definition VPlan.h:182
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:232
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:216
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:405
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:333
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:351
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:387
VPlan-based builder utility analogous to IRBuilder.
VPWidenPHIRecipe * createWidenPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr)
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4194
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
Class to record and manage LLVM IR flags.
Definition VPlan.h:703
static VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
void dropPoisonGeneratingFlags()
Drop all poison-generating flags.
Definition VPlan.h:901
static LLVM_ABI_FOR_TEST VPIRInstruction * create(Instruction &I)
Create a new VPIRPhi for \I , if it is a PHINode, otherwise create a VPIRInstruction.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1235
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1286
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1281
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1278
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1676
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:410
VPBasicBlock * getParent()
Definition VPlan.h:482
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:560
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:354
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4625
const VPBlockBase * getEntry() const
Definition VPlan.h:4669
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4765
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:898
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4753
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4792
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4745
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3405
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:250
VPValue * expand(const SCEV *S)
Expand S into recipes and live-ins using the builder.
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4255
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:217
bool isMaterialized() const
Returns true if this value has been materialized.
Definition VPlanValue.h:235
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:149
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:143
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:130
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
bool user_empty() const
Definition VPlanValue.h:161
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:209
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1495
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser &U, unsigned Idx)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1501
A Recipe for widening the canonical induction variable of the vector loop.
Definition VPlan.h:4137
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2573
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2576
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2596
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2625
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2673
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2699
A recipe for widening vector intrinsics.
Definition VPlan.h:1941
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4812
bool hasVF(ElementCount VF) const
Definition VPlan.h:5044
const DataLayout & getDataLayout() const
Definition VPlan.h:5026
LLVMContext & getContext() const
Definition VPlan.h:5022
VPBasicBlock * getEntry()
Definition VPlan.h:4908
bool hasScalableVF() const
Definition VPlan.h:5045
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4980
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition VPlan.h:5001
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5020
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5154
bool hasUF(unsigned UF) const
Definition VPlan.h:5069
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5145
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5010
VPValue * getBackedgeTakenCount() const
Definition VPlan.h:5007
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5094
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5120
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1080
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5072
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4994
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4950
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5177
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4913
bool hasScalarVFOnly() const
Definition VPlan.h:5062
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4964
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:4929
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5013
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5247
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5128
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:426
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
VPInstruction_match< VPInstruction::BranchOnTwoConds > m_BranchOnTwoConds()
canonical_widen_iv_match m_CanonicalWidenIV()
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPRecipeBase * findUserOf(VPValue *V, const MatchT &P)
If V is used by a recipe matching pattern P, return it.
match_bind< VPInstruction > m_VPInstruction(VPInstruction *&V)
Match a VPInstruction, capturing if we match.
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
VPValue * findIncomingAliasMask(const VPlan &Plan)
Finds the incoming alias-mask within the vector preheader.
bool doesGeneratePerAllLanes(const VPRecipeBase *R)
Returns true if R produces scalar values for all VF lanes.
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
VPValue * scalarizeVPWidenPointerInduction(VPWidenPointerInductionRecipe *PtrIV, VPlan &Plan, VPBuilder &Builder)
Scalarize a VPWidenPointerInductionRecipe by replacing it with a PtrAdd (IndStart,...
VPScalarIVStepsRecipe * createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind, Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, Instruction *TruncI, VPIRValue *StartV, VPValue *Step, DebugLoc DL, VPBuilder &Builder, const VPIRFlags::WrapFlagsTy &Flags={})
Create a scalar-iv-steps recipe over Plan's canonical IV for an induction of Kind with InductionOpcod...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
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:633
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.
Definition VPlanCFG.h:250
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:285
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1151
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
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...
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
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:322
TargetTransformInfo TTI
@ Mul
Product of integers.
@ FMul
Product of floats.
@ Add
Sum of integers.
DWARFExpression::Operation Op
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1409
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
A struct that represents some properties of the register usage of a loop.
SmallMapVector< unsigned, unsigned, 4 > MaxLocalUsers
Holds the maximum number of concurrent live intervals in the loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
static VPValue * materializeAliasMask(VPlan &Plan, VPBasicBlock *AliasCheckVPBB, ArrayRef< PointerDiffInfo > DiffChecks)
Materializes within the AliasCheckVPBB block.
static void expandSCEVsToVPInstructions(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block to VPInstructions.
static void materializeBroadcasts(VPlan &Plan)
Add explicit broadcasts for live-ins and VPValues defined in Plan's entry block if they are used as v...
static void materializePacksAndUnpacks(VPlan &Plan)
Add explicit Build[Struct]Vector recipes to Pack multiple scalar values into vectors and Unpack recip...
static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize UF, VF and VFxUF to be computed explicitly using VPInstructions.
static void materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static void materializeHeaderMask(VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow)
Materialize the abstract header mask of the loop region into concrete recipes: an active-lane-mask if...
static void addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF, std::optional< unsigned > VScaleForTuning)
Add branch weight metadata, if the Plan's middle block is terminated by a BranchOnCond recipe.
static void materializeAliasMaskCheckBlock(VPlan &Plan, ArrayRef< PointerDiffInfo > DiffChecks, bool HasBranchWeights)
Materializes the alias mask within a check block before the loop.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand remaining VPExpandSCEVRecipes in Plan's entry block using SCEVExpander.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static void expandBranchOnTwoConds(VPlan &Plan)
Expand BranchOnTwoConds instructions into explicit CFG with BranchOnCond instructions.
static void materializeVectorTripCount(VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking, bool RequiresScalarEpilogue, VPValue *Step, std::optional< uint64_t > MaxRuntimeStep=std::nullopt)
Materialize vector trip count computations to a set of VPInstructions.
static void materializeConstantVectorTripCount(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
static void replaceWideCanonicalIVWithWideIV(VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, ElementCount VF, unsigned UF)
Replace a VPWidenCanonicalIVRecipe if it is present in Plan, with a VPWidenIntOrFpInductionRecipe,...
static void attachVPCheckBlock(VPlan &Plan, VPValue *Cond, VPBasicBlock *CheckBlock, bool AddBranchWeights)
Wrap runtime check block CheckBlock in a VPIRBB and Cond in a VPValue and connect the block to Plan,...
static void dissolveLoopRegions(VPlan &Plan)
Replace loop regions with explicit CFG.