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"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Metadata.h"
36
37using namespace llvm;
38using namespace VPlanPatternMatch;
39using namespace SCEVPatternMatch;
40
44 unsigned UF) {
45 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
46 if (!LoopRegion)
47 return;
48
49 auto *WideCanIV =
51 if (!WideCanIV)
52 return;
53
54 Type *CanIVTy = LoopRegion->getCanonicalIVType();
55
56 // Replace the wide canonical IV with a scalar-iv-steps over the canonical
57 // IV.
58 if (Plan.hasScalarVFOnly() || vputils::onlyFirstLaneUsed(WideCanIV)) {
59 VPBuilder Builder(WideCanIV);
60 WideCanIV->replaceAllUsesWith(vputils::createScalarIVSteps(
61 Plan, InductionDescriptor::IK_IntInduction, Instruction::Add, nullptr,
62 nullptr, Plan.getZero(CanIVTy), Plan.getConstantInt(CanIVTy, 1),
63 WideCanIV->getDebugLoc(), Builder,
64 {static_cast<bool>(WideCanIV->getNoWrapFlags().HasNUW), false}));
65 WideCanIV->eraseFromParent();
66 return;
67 }
68
69 if (vputils::onlyScalarValuesUsed(WideCanIV))
70 return;
71
72 // If a canonical VPWidenIntOrFpInductionRecipe already produces vector lanes
73 // in the header, reuse it instead of introducing another wide induction phi.
74 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
75 for (VPRecipeBase &Phi : Header->phis()) {
77 if (!match(&Phi, m_CanonicalWidenIV(WidenIV)))
78 continue;
79 // The reused wide IV feeds the header mask, whose lanes may extend past
80 // the trip count; drop flags that only hold inside the scalar loop.
82 WideCanIV->replaceAllUsesWith(WidenIV);
83 WideCanIV->eraseFromParent();
84 return;
85 }
86
87 // Introduce a new VPWidenIntOrFpInductionRecipe if profitable.
88 auto *VecTy = VectorType::get(CanIVTy, VF);
89 InstructionCost BroadcastCost = TTI.getShuffleCost(
91 InstructionCost PHICost = TTI.getCFInstrCost(Instruction::PHI, CostKind);
92 if (PHICost > BroadcastCost)
93 return;
94
95 // Bail out if the additional wide induction phi increase the expected spill
96 // cost.
97 VPRegisterUsage UnrolledBase =
99 for (unsigned &NumUsers : make_second_range(UnrolledBase.MaxLocalUsers))
100 NumUsers *= UF;
101 unsigned RegClass = TTI.getRegisterClassForType(/*Vector=*/true, VecTy);
102 VPRegisterUsage Projected = UnrolledBase;
103 Projected.MaxLocalUsers[RegClass] += TTI.getRegUsageForType(VecTy);
104 if (Projected.spillCost(TTI, CostKind) >
105 UnrolledBase.spillCost(TTI, CostKind))
106 return;
107
110 VPValue *StepV = Plan.getConstantInt(CanIVTy, 1);
111 auto *NewWideIV = new VPWidenIntOrFpInductionRecipe(
112 /*IV=*/nullptr, Plan.getZero(CanIVTy), StepV, &Plan.getVF(), ID,
113 WideCanIV->getNoWrapFlags(), WideCanIV->getDebugLoc());
114 NewWideIV->insertBefore(&*Header->getFirstNonPhi());
115 WideCanIV->replaceAllUsesWith(NewWideIV);
116 WideCanIV->eraseFromParent();
117}
118
119// Add a VPActiveLaneMaskPHIRecipe and related recipes to \p Plan and replace
120// the loop terminator with a branch-on-cond recipe with the negated
121// wide-active-lane-mask as operand. Note that this turns the loop into an
122// uncountable one. Only the existing terminator is replaced, all other existing
123// recipes/users remain unchanged, except for poison-generating flags being
124// dropped from the canonical IV increment. Return the created
125// VPActiveLaneMaskPHIRecipe.
126//
127// The function adds the following recipes:
128//
129// vector.ph:
130// %EntryInc = canonical-iv-increment-for-part CanonicalIVStart
131// %EntryALM = wide-active-lane-mask %EntryInc, TC
132// %EntryALMPart = extract-vector-for-part %EntryALM, ir<0>
133//
134// vector.body:
135// ...
136// %P = active-lane-mask-phi [ %EntryALMPart, %vector.ph ],
137// [ %ALMPart, %vector.body ]
138// ...
139// %InLoopInc = canonical-iv-increment-for-part CanonicalIVIncrement
140// %ALM = wide-active-lane-mask %InLoopInc, TC
141// %ALMPart = extract-vector-for-part %ALM, ir<0>
142// %Negated = Not %ALMPart
143// branch-on-cond %Negated
144//
147 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
148 VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
149 VPValue *StartV = Plan.getZero(TopRegion->getCanonicalIVType());
150 auto *CanonicalIVIncrement = TopRegion->getOrCreateCanonicalIVIncrement();
151 // TODO: Check if dropping the flags is needed.
152 TopRegion->clearCanonicalIVNUW(CanonicalIVIncrement);
153 DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
154 auto *VecPreheader = Plan.getVectorPreheader();
155 VPBuilder Builder(VecPreheader);
156 VPValue *TC = Plan.getTripCount();
157
158 // Create the wide active lane mask instruction in the VPlan preheader.
159 VPValue *ALMMultiplier =
160 Plan.getConstantInt(TopRegion->getCanonicalIVType(), 1);
161 auto *EntryALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
162 {StartV, TC, ALMMultiplier}, DL,
163 "active.lane.mask.entry");
164 EntryALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
165 {EntryALM, Plan.getConstantInt(64, 0)}, DL,
166 "extract.entry.alm.part");
167
168 // Now create the ActiveLaneMaskPhi recipe in the main loop using the
169 // preheader WideActiveLaneMask instruction.
170 auto *LaneMaskPhi =
172 auto *HeaderVPBB = TopRegion->getEntryBasicBlock();
173 LaneMaskPhi->insertBefore(*HeaderVPBB, HeaderVPBB->begin());
174
175 // Create the active lane mask for the next iteration of the loop before the
176 // original terminator.
177 VPRecipeBase *OriginalTerminator = EB->getTerminator();
178 Builder.setInsertPoint(OriginalTerminator);
179 auto *ALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
180 {CanonicalIVIncrement, TC, ALMMultiplier},
181 DL, "active.lane.mask.next");
182 ALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
183 {ALM, Plan.getConstantInt(64, 0)}, DL,
184 "extract.next.alm.part");
185 LaneMaskPhi->addBackedgeValue(ALM);
186
187 // Replace the original terminator with BranchOnCond. We have to invert the
188 // mask here because a true condition means jumping to the exit block.
189 auto *NotMask = Builder.createNot(ALM, DL);
190 Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
191 OriginalTerminator->eraseFromParent();
192 return LaneMaskPhi;
193}
194
196 VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow) {
197 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
198 VPValue *HeaderMask = LoopRegion->getUsedHeaderMask();
199 if (!HeaderMask)
200 return;
201
202 if (UseActiveLaneMaskForControlFlow) {
204 return;
205 }
206
207 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
208 VPBuilder Builder(Header, Header->getFirstNonPhi());
209 auto *WideCanonicalIV = Builder.insert(new VPWidenCanonicalIVRecipe(
210 LoopRegion->getCanonicalIV(),
211 VPIRFlags::WrapFlagsTy(/*HasNUW=*/true, /*HasNSW=*/false)));
212 VPValue *Mask;
213 if (UseActiveLaneMask) {
214 Mask = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
215 {WideCanonicalIV, Plan.getTripCount()}, nullptr,
216 "active.lane.mask");
217 } else {
218 Mask = Builder.createICmp(CmpInst::ICMP_ULE, WideCanonicalIV,
220 }
221 HeaderMask->replaceAllUsesWith(Mask);
222}
223
224/// Expand a VPWidenIntOrFpInduction into executable recipes, for the initial
225/// value, phi and backedge value. In the following example:
226///
227/// vector.ph:
228/// Successor(s): vector loop
229///
230/// <x1> vector loop: {
231/// vector.body:
232/// WIDEN-INDUCTION %i = phi %start, %step, %vf
233/// ...
234/// EMIT branch-on-count ...
235/// No successors
236/// }
237///
238/// WIDEN-INDUCTION will get expanded to:
239///
240/// vector.ph:
241/// ...
242/// vp<%induction.start> = ...
243/// vp<%induction.increment> = ...
244///
245/// Successor(s): vector loop
246///
247/// <x1> vector loop: {
248/// vector.body:
249/// ir<%i> = WIDEN-PHI vp<%induction.start>, vp<%vec.ind.next>
250/// ...
251/// vp<%vec.ind.next> = add ir<%i>, vp<%induction.increment>
252/// EMIT branch-on-count ...
253/// No successors
254/// }
255static void
257 VPlan *Plan = WidenIVR->getParent()->getPlan();
258 VPValue *Start = WidenIVR->getStartValue();
259 VPValue *Step = WidenIVR->getStepValue();
260 VPValue *VF = WidenIVR->getVFValue();
261 DebugLoc DL = WidenIVR->getDebugLoc();
262
263 // The value from the original loop to which we are mapping the new induction
264 // variable.
265 Type *Ty = WidenIVR->getScalarType();
266
267 const InductionDescriptor &ID = WidenIVR->getInductionDescriptor();
270 VPIRFlags Flags = *WidenIVR;
271 if (ID.getKind() == InductionDescriptor::IK_IntInduction) {
272 AddOp = Instruction::Add;
273 MulOp = Instruction::Mul;
274 } else {
275 AddOp = ID.getInductionOpcode();
276 MulOp = Instruction::FMul;
277 }
278
279 // If the phi is truncated, truncate the start and step values.
280 VPBuilder Builder(Plan->getVectorPreheader());
281 Type *StepTy = Step->getScalarType();
282 if (Ty->getScalarSizeInBits() < StepTy->getScalarSizeInBits()) {
283 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
284 Step = Builder.createScalarCast(Instruction::Trunc, Step, Ty, DL);
285 Start = Builder.createScalarCast(Instruction::Trunc, Start, Ty, DL);
286 StepTy = Ty;
287 }
288
289 // Construct the initial value of the vector IV in the vector loop preheader.
290 Type *IVIntTy =
292 VPValue *Init = Builder.createNaryOp(VPInstruction::StepVector, {}, IVIntTy);
293 if (StepTy->isFloatingPointTy())
294 Init = Builder.createWidenCast(Instruction::UIToFP, Init, StepTy);
295
296 VPValue *SplatStart = Builder.createNaryOp(VPInstruction::Broadcast, Start);
297 VPValue *SplatStep = Builder.createNaryOp(VPInstruction::Broadcast, Step);
298
299 Init = Builder.createNaryOp(MulOp, {Init, SplatStep}, Flags);
300 Init = Builder.createNaryOp(AddOp, {SplatStart, Init}, Flags,
301 DebugLoc::getUnknown(), "induction");
302
303 // Create the widened phi of the vector IV.
304 auto *WidePHI = VPBuilder(WidenIVR).createWidenPhi(
305 Init, WidenIVR->getDebugLoc(), "vec.ind");
306
307 // Create the backedge value for the vector IV.
308 VPValue *Inc;
309 VPValue *Prev;
310 // If unrolled, use the increment and prev value from the operands.
311 if (auto *SplatVF = WidenIVR->getSplatVFValue()) {
312 Inc = SplatVF;
313 Prev = WidenIVR->getLastUnrolledPartOperand();
314 } else {
315 // Move the insertion point after the VF definition when the VF is defined
316 // inside a loop, such as for EVL tail-folding.
317 if (VPRecipeBase *R = VF->getDefiningRecipe())
318 if (R->getParent()->getEnclosingLoopRegion())
319 Builder.setInsertPoint(R->getParent(), std::next(R->getIterator()));
320
321 // Multiply the vectorization factor by the step using integer or
322 // floating-point arithmetic as appropriate.
323 if (StepTy->isFloatingPointTy())
324 VF = Builder.createScalarCast(Instruction::CastOps::UIToFP, VF, StepTy,
325 DL);
326 else
327 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
328
329 Inc = Builder.createNaryOp(MulOp, {Step, VF}, Flags);
330 Inc = Builder.createNaryOp(VPInstruction::Broadcast, Inc);
331 Prev = WidePHI;
332 }
333
335 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
336 auto *Next = Builder.createNaryOp(AddOp, {Prev, Inc}, Flags,
337 WidenIVR->getDebugLoc(), "vec.ind.next");
338
339 WidePHI->addIncoming(Next);
340
341 WidenIVR->replaceAllUsesWith(WidePHI);
342}
343
344/// Expand a VPWidenPointerInductionRecipe into executable recipes, for the
345/// initial value, phi and backedge value. In the following example:
346///
347/// <x1> vector loop: {
348/// vector.body:
349/// EMIT ir<%ptr.iv> = WIDEN-POINTER-INDUCTION %start, %step, %vf
350/// ...
351/// EMIT branch-on-count ...
352/// }
353///
354/// WIDEN-POINTER-INDUCTION will get expanded to:
355///
356/// <x1> vector loop: {
357/// vector.body:
358/// EMIT-SCALAR %pointer.phi = phi %start, %ptr.ind
359/// EMIT %mul = mul %stepvector, %step
360/// EMIT %vector.gep = wide-ptradd %pointer.phi, %mul
361/// ...
362/// EMIT %ptr.ind = ptradd %pointer.phi, %vf
363/// EMIT branch-on-count ...
364/// }
366 VPlan *Plan = R->getParent()->getPlan();
367 VPValue *Start = R->getStartValue();
368 VPValue *Step = R->getStepValue();
369 VPValue *VF = R->getVFValue();
370
371 assert(R->getInductionDescriptor().getKind() ==
373 "Not a pointer induction according to InductionDescriptor!");
374 assert(R->getScalarType()->isPointerTy() && "Unexpected type.");
375 assert(!R->onlyScalarsGenerated(Plan->hasScalableVF()) &&
376 "Recipe should have been replaced");
377
378 VPBuilder Builder(R);
379 DebugLoc DL = R->getDebugLoc();
380
381 // Build a scalar pointer phi.
382 VPPhi *ScalarPtrPhi = Builder.createScalarPhi(Start, DL, "pointer.phi");
383
384 // Create actual address geps that use the pointer phi as base and a
385 // vectorized version of the step value (<step*0, ..., step*N>) as offset.
386 Builder.setInsertPoint(R->getParent(), R->getParent()->getFirstNonPhi());
387 Type *StepTy = Step->getScalarType();
388 VPValue *Offset = Builder.createNaryOp(VPInstruction::StepVector, {}, StepTy);
389 Offset = Builder.createOverflowingOp(Instruction::Mul, {Offset, Step});
390 VPValue *PtrAdd =
391 Builder.createWidePtrAdd(ScalarPtrPhi, Offset, DL, "vector.gep");
392 R->replaceAllUsesWith(PtrAdd);
393
394 // Create the backedge value for the scalar pointer phi.
396 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
397 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
398 VPValue *Inc = Builder.createOverflowingOp(Instruction::Mul, {Step, VF});
399
400 VPValue *InductionGEP =
401 Builder.createPtrAdd(ScalarPtrPhi, Inc, DL, "ptr.ind");
402 ScalarPtrPhi->addIncoming(InductionGEP);
403}
404
405/// Expand a VPDerivedIVRecipe into executable recipes.
407 VPBuilder Builder(R);
408 VPValue *Start = R->getStartValue();
409 VPValue *Step = R->getStepValue();
410 VPValue *Index = R->getIndex();
411 Type *StepTy = Step->getScalarType();
412 Index = StepTy->isIntegerTy()
413 ? Builder.createScalarZExtOrTrunc(
414 Index, StepTy, DebugLoc::getCompilerGenerated())
415 : Builder.createScalarCast(Instruction::SIToFP, Index, StepTy,
417 VPIRFlags::WrapFlagsTy Flags = R->getNoWrapFlags();
418 switch (R->getInductionKind()) {
420 assert(Index->getScalarType() == Start->getScalarType() &&
421 "Index type does not match StartValue type");
422 return R->replaceAllUsesWith(Builder.createAdd(
423 Start,
424 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags),
425 DebugLoc::getUnknown(), "", Flags));
426 }
428 return R->replaceAllUsesWith(Builder.createPtrAdd(
429 Start,
430 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags)));
432 assert(StepTy->isFloatingPointTy() && "Expected FP Step value");
433 const FPMathOperator *FPBinOp = R->getFPBinOp();
434 assert(FPBinOp &&
435 (FPBinOp->getOpcode() == Instruction::FAdd ||
436 FPBinOp->getOpcode() == Instruction::FSub) &&
437 "Original BinOp should be defined for FP induction");
438 FastMathFlags FMF = FPBinOp->getFastMathFlags();
439 VPValue *FMul = Builder.createNaryOp(Instruction::FMul, {Step, Index}, FMF);
440 return R->replaceAllUsesWith(
441 Builder.createNaryOp(FPBinOp->getOpcode(), {Start, FMul}, FMF));
442 }
444 return;
445 }
446 llvm_unreachable("Unhandled induction kind");
447}
448
450 // Replace loop regions with explicity CFG.
453 vp_depth_first_deep(Plan.getEntry()))) {
454 if (!R->isReplicator())
455 LoopRegions.push_back(R);
456 }
457 for (VPRegionBlock *R : LoopRegions)
458 R->dissolveToCFGLoop();
459}
460
463 // The transform runs after dissolving loop regions, so all VPBasicBlocks
464 // terminated with BranchOnTwoConds are reached via a shallow traversal.
467 if (!VPBB->empty() && match(&VPBB->back(), m_BranchOnTwoConds()))
468 WorkList.push_back(cast<VPInstruction>(&VPBB->back()));
469 }
470
471 // Expand BranchOnTwoConds instructions into explicit CFG with two new
472 // single-condition branches:
473 // 1. A branch that replaces BranchOnTwoConds, jumps to the first successor if
474 // the first condition is true, and otherwise jumps to a new interim block.
475 // 2. A branch that ends the interim block, jumps to the second successor if
476 // the second condition is true, and otherwise jumps to the third
477 // successor.
478 for (VPInstruction *Br : WorkList) {
479 assert(Br->getNumOperands() == 2 &&
480 "BranchOnTwoConds must have exactly 2 conditions");
481 DebugLoc DL = Br->getDebugLoc();
482 VPBasicBlock *BrOnTwoCondsBB = Br->getParent();
483 const auto Successors = to_vector(BrOnTwoCondsBB->getSuccessors());
484 assert(Successors.size() == 3 &&
485 "BranchOnTwoConds must have exactly 3 successors");
486
487 for (VPBlockBase *Succ : Successors)
488 VPBlockUtils::disconnectBlocks(BrOnTwoCondsBB, Succ);
489
490 VPValue *Cond0 = Br->getOperand(0);
491 VPValue *Cond1 = Br->getOperand(1);
492 VPBlockBase *Succ0 = Successors[0];
493 VPBlockBase *Succ1 = Successors[1];
494 VPBlockBase *Succ2 = Successors[2];
495
496 // If the successor block for both conditions is the same, then combine the
497 // two conditions and plant a single conditional branch.
498 if (Succ0 == Succ1) {
499 VPBuilder Builder(Br);
500 VPValue *Combined = Builder.createOr(Cond0, Cond1, DL);
501 Builder.createNaryOp(VPInstruction::BranchOnCond, {Combined}, DL);
502 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
503 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ2);
504 Br->eraseFromParent();
505 continue;
506 }
507
508 assert(!Succ0->getParent() && !Succ1->getParent() && !Succ2->getParent() &&
509 !BrOnTwoCondsBB->getParent() && "regions must already be dissolved");
510
511 VPBasicBlock *InterimBB =
512 Plan.createVPBasicBlock(BrOnTwoCondsBB->getName() + ".interim");
513
514 VPBuilder(BrOnTwoCondsBB)
516 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
517 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, InterimBB);
518
520 VPBlockUtils::connectBlocks(InterimBB, Succ1);
521 VPBlockUtils::connectBlocks(InterimBB, Succ2);
522 Br->eraseFromParent();
523 }
524}
525
528 vp_depth_first_deep(Plan.getEntry()))) {
529 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
530 VPBuilder Builder(&R);
531 if (auto *WidenIVR = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
533 WidenIVR->eraseFromParent();
534 continue;
535 }
536
537 if (auto *WidenIVR = dyn_cast<VPWidenPointerInductionRecipe>(&R)) {
538 // If the recipe only generates scalars, scalarize it instead of
539 // expanding it.
540 if (WidenIVR->onlyScalarsGenerated(Plan.hasScalableVF())) {
542 WidenIVR, Plan, Builder);
543 WidenIVR->replaceAllUsesWith(PtrAdd);
544 WidenIVR->eraseFromParent();
545 continue;
546 }
548 WidenIVR->eraseFromParent();
549 continue;
550 }
551
552 if (auto *DerivedIVR = dyn_cast<VPDerivedIVRecipe>(&R)) {
553 expandVPDerivedIV(DerivedIVR);
554 DerivedIVR->eraseFromParent();
555 continue;
556 }
557
558 if (auto *WideCanIV = dyn_cast<VPWidenCanonicalIVRecipe>(&R)) {
559 VPValue *CanIV = WideCanIV->getCanonicalIV();
560 Type *CanIVTy = CanIV->getScalarType();
561 VPValue *Step = WideCanIV->getStepValue();
562 if (!Step) {
563 assert(Plan.getConcreteUF() == 1 &&
564 "Expected unroller to have materialized step for UF != 1");
565 Step = Plan.getZero(CanIVTy);
566 }
567 CanIV = Builder.createNaryOp(VPInstruction::Broadcast, CanIV);
568 Step = Builder.createNaryOp(VPInstruction::Broadcast, Step);
569 Step = Builder.createAdd(
570 Step, Builder.createNaryOp(VPInstruction::StepVector, {}, CanIVTy));
571 VPValue *CanVecIV =
572 Builder.createAdd(CanIV, Step, WideCanIV->getDebugLoc(), "vec.iv",
573 WideCanIV->getNoWrapFlags());
574 WideCanIV->replaceAllUsesWith(CanVecIV);
575 WideCanIV->eraseFromParent();
576 continue;
577 }
578
579 // Expand VPBlendRecipe into VPInstruction::Select.
580 if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
581 VPValue *Select = Blend->getIncomingValue(0);
582 for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
583 Select = Builder.createSelect(Blend->getMask(I),
584 Blend->getIncomingValue(I), Select,
585 R.getDebugLoc(), "predphi", *Blend);
586 Blend->replaceAllUsesWith(Select);
587 Blend->eraseFromParent();
588 continue;
589 }
590
591 if (auto *VEPR = dyn_cast<VPVectorEndPointerRecipe>(&R)) {
592 if (!VEPR->getOffset()) {
593 assert(Plan.getConcreteUF() == 1 &&
594 "Expected unroller to have materialized offset for UF != 1");
595 VEPR->materializeOffset();
596 }
597 continue;
598 }
599
600 if (auto *Expr = dyn_cast<VPExpressionRecipe>(&R)) {
601 Expr->decompose();
602 Expr->eraseFromParent();
603 continue;
604 }
605
606 // Expand LastActiveLane into Not + FirstActiveLane + Sub.
607 auto *LastActiveL = dyn_cast<VPInstruction>(&R);
608 if (LastActiveL &&
609 LastActiveL->getOpcode() == VPInstruction::LastActiveLane) {
610 // Create Not(Mask) for all operands.
612 for (VPValue *Op : LastActiveL->operands()) {
613 VPValue *NotMask = Builder.createNot(Op, LastActiveL->getDebugLoc());
614 NotMasks.push_back(NotMask);
615 }
616
617 // Create FirstActiveLane on the inverted masks.
618 VPValue *FirstInactiveLane = Builder.createFirstActiveLane(
619 NotMasks, LastActiveL->getDebugLoc(), "first.inactive.lane");
620
621 // Subtract 1 to get the last active lane.
622 VPValue *One =
623 Plan.getConstantInt(FirstInactiveLane->getScalarType(), 1);
624 VPValue *LastLane =
625 Builder.createSub(FirstInactiveLane, One,
626 LastActiveL->getDebugLoc(), "last.active.lane");
627
628 LastActiveL->replaceAllUsesWith(LastLane);
629 LastActiveL->eraseFromParent();
630 continue;
631 }
632
633 // Lower MaskedCond with block mask to LogicalAnd.
635 auto *VPI = cast<VPInstruction>(&R);
636 assert(VPI->isMasked() &&
637 "Unmasked MaskedCond should be simplified earlier");
638 VPI->replaceAllUsesWith(Builder.createNaryOp(
639 VPInstruction::LogicalAnd, {VPI->getMask(), VPI->getOperand(0)}));
640 VPI->eraseFromParent();
641 continue;
642 }
643
644 // Lower CanonicalIVIncrementForPart to plain Add.
645 if (match(
646 &R,
648 auto *VPI = cast<VPInstruction>(&R);
649 VPValue *Add = Builder.createOverflowingOp(
650 Instruction::Add, VPI->operands(), VPI->getNoWrapFlags(),
651 VPI->getDebugLoc());
652 VPI->replaceAllUsesWith(Add);
653 VPI->eraseFromParent();
654 continue;
655 }
656
657 // Lower BranchOnCount to ICmp + BranchOnCond.
658 VPValue *IV, *TC;
659 if (match(&R, m_BranchOnCount(m_VPValue(IV), m_VPValue(TC)))) {
660 auto *BranchOnCountInst = cast<VPInstruction>(&R);
661 DebugLoc DL = BranchOnCountInst->getDebugLoc();
662 VPValue *Cond = Builder.createICmp(CmpInst::ICMP_EQ, IV, TC, DL);
663 Builder.createNaryOp(VPInstruction::BranchOnCond, Cond, DL);
664 BranchOnCountInst->eraseFromParent();
665 continue;
666 }
667
668 VPValue *VectorStep;
669 VPValue *ScalarStep;
671 m_VPValue(VectorStep), m_VPValue(ScalarStep))))
672 continue;
673
674 // Expand WideIVStep.
675 auto *VPI = cast<VPInstruction>(&R);
676 Type *IVTy = VPI->getScalarType();
677 if (VectorStep->getScalarType() != IVTy) {
679 ? Instruction::UIToFP
680 : Instruction::Trunc;
681 VectorStep = Builder.createWidenCast(CastOp, VectorStep, IVTy);
682 }
683
684 assert(!match(ScalarStep, m_One()) && "Expected non-unit scalar-step");
685 if (ScalarStep->getScalarType() != IVTy) {
686 ScalarStep =
687 Builder.createWidenCast(Instruction::Trunc, ScalarStep, IVTy);
688 }
689
690 VPIRFlags Flags;
691 unsigned MulOpc;
692 if (IVTy->isFloatingPointTy()) {
693 MulOpc = Instruction::FMul;
694 Flags = VPI->getFastMathFlagsOrNone();
695 } else {
696 MulOpc = Instruction::Mul;
697 Flags = VPIRFlags::getDefaultFlags(MulOpc);
698 }
699
700 VPInstruction *Mul = Builder.createNaryOp(
701 MulOpc, {VectorStep, ScalarStep}, Flags, R.getDebugLoc());
702 VectorStep = Mul;
703 VPI->replaceAllUsesWith(VectorStep);
704 VPI->eraseFromParent();
705 }
706 }
707}
708
710 if (Plan.hasScalarVFOnly())
711 return;
712
713#ifndef NDEBUG
714 VPDominatorTree VPDT(Plan);
715#endif
716
717 SmallVector<VPValue *> VPValues;
718 if (VPValue *BTC = Plan.getBackedgeTakenCount())
719 VPValues.push_back(BTC);
720 append_range(VPValues, Plan.getLiveIns());
721 for (VPRecipeBase &R : *Plan.getEntry())
722 append_range(VPValues, R.definedValues());
723
724 auto *VectorPreheader = Plan.getVectorPreheader();
725 for (VPValue *VPV : VPValues) {
727 continue;
728
729 // Add explicit broadcast at the insert point that dominates all users.
730 VPBasicBlock *HoistBlock = VectorPreheader;
731 VPBasicBlock::iterator HoistPoint = VectorPreheader->end();
732 for (VPUser *User : VPV->users()) {
733 if (User->usesScalars(VPV))
734 continue;
735 if (cast<VPRecipeBase>(User)->getParent() == VectorPreheader)
736 HoistPoint = HoistBlock->begin();
737 else
738 assert(VPDT.dominates(VectorPreheader,
739 cast<VPRecipeBase>(User)->getParent()) &&
740 "All users must be in the vector preheader or dominated by it");
741 }
742
743 VPBuilder Builder(cast<VPBasicBlock>(HoistBlock), HoistPoint);
744 auto *Broadcast = Builder.createNaryOp(VPInstruction::Broadcast, {VPV});
745 VPV->replaceUsesWithIf(Broadcast,
746 [VPV, Broadcast](VPUser &U, unsigned Idx) {
747 return Broadcast != &U && !U.usesScalars(VPV);
748 });
749 }
750}
751
753 VPlan &Plan, ElementCount BestVF, unsigned BestUF,
755 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
756 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
757
758 VPValue *TC = Plan.getTripCount();
759 if (TC->user_empty())
760 return;
761
762 // Skip cases for which the trip count may be non-trivial to materialize.
763 // I.e., when a scalar tail is absent - due to tail folding, or when a scalar
764 // tail is required.
765 if (Plan.hasTailFolded() || !Plan.hasScalarTail() ||
767 Plan.getScalarPreheader() ||
768 !isa<VPIRValue>(TC))
769 return;
770
771 // Materialize vector trip counts for constants early if it can simply
772 // be computed as (Original TC / VF * UF) * VF * UF.
773 // TODO: Compute vector trip counts for loops requiring a scalar epilogue and
774 // tail-folded loops.
775 ScalarEvolution &SE = *PSE.getSE();
776 auto *TCScev = SE.getSCEV(TC->getLiveInIRValue());
777 if (!isa<SCEVConstant>(TCScev))
778 return;
779 const SCEV *VFxUF = SE.getElementCount(TCScev->getType(), BestVF * BestUF);
780 auto VecTCScev = SE.getMulExpr(SE.getUDivExpr(TCScev, VFxUF), VFxUF);
781 if (auto *ConstVecTC = dyn_cast<SCEVConstant>(VecTCScev))
782 Plan.getVectorTripCount().setUnderlyingValue(ConstVecTC->getValue());
783}
784
786 VPBasicBlock *VectorPH) {
788 if (BTC->user_empty())
789 return;
790
791 VPBuilder Builder(VectorPH, VectorPH->begin());
792 auto *TCTy = Plan.getTripCount()->getScalarType();
793 auto *TCMO =
794 Builder.createSub(Plan.getTripCount(), Plan.getConstantInt(TCTy, 1),
795 DebugLoc::getCompilerGenerated(), "trip.count.minus.1");
796 BTC->replaceAllUsesWith(TCMO);
797}
798
800 if (Plan.hasScalarVFOnly())
801 return;
802
803 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
804 auto VPBBsOutsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
806 auto VPBBsInsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
807 vp_depth_first_shallow(LoopRegion->getEntry()));
808 // Materialize Build(Struct)Vector for all replicating VPReplicateRecipes,
809 // VPScalarIVStepsRecipe and VPInstructions, excluding ones in replicate
810 // regions. Those are not materialized explicitly yet.
811 // TODO: materialize build vectors for replicating recipes in replicating
812 // regions.
813 for (VPBasicBlock *VPBB :
814 concat<VPBasicBlock *>(VPBBsOutsideLoopRegion, VPBBsInsideLoopRegion)) {
815 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
817 continue;
818 auto *DefR = cast<VPSingleDefRecipe>(&R);
819 auto UsesVectorOrInsideReplicateRegion = [DefR, LoopRegion](VPUser *U) {
820 VPRegionBlock *ParentRegion = cast<VPRecipeBase>(U)->getRegion();
821 return !U->usesScalars(DefR) || ParentRegion != LoopRegion;
822 };
823 if (none_of(DefR->users(), UsesVectorOrInsideReplicateRegion))
824 continue;
825
826 Type *ScalarTy = DefR->getScalarType();
827 unsigned Opcode = ScalarTy->isStructTy()
830 auto *BuildVector = new VPInstruction(Opcode, {DefR});
831 BuildVector->insertAfter(DefR);
832
833 DefR->replaceUsesWithIf(
834 BuildVector, [BuildVector, &UsesVectorOrInsideReplicateRegion](
835 VPUser &U, unsigned) {
836 return &U != BuildVector && UsesVectorOrInsideReplicateRegion(&U);
837 });
838 }
839 }
840
841 // Create explicit VPInstructions to convert vectors to scalars. The current
842 // implementation is conservative - it may miss some cases that may or may not
843 // be vector values. TODO: introduce Unpacks speculatively - remove them later
844 // if they are known to operate on scalar values.
845 for (VPBasicBlock *VPBB : VPBBsInsideLoopRegion) {
846 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
849 continue;
850 for (VPValue *Def : R.definedValues()) {
851 // Skip recipes that are single-scalar.
852 // TODO: The Defs skipped here may or may not be vector values.
853 // Introduce Unpacks, and remove them later, if they are guaranteed to
854 // produce scalar values.
856 continue;
857
858 // Only introduce an Unpack if some, but not all, users use the first
859 // lane only.
860 unsigned NumFirstLaneUsers = count_if(Def->users(), [&Def](VPUser *U) {
861 return U->usesFirstLaneOnly(Def);
862 });
863 if (!NumFirstLaneUsers || NumFirstLaneUsers == Def->getNumUsers())
864 continue;
865
866 auto *Unpack = new VPInstruction(VPInstruction::Unpack, {Def});
867 if (R.isPhi())
868 Unpack->insertBefore(*VPBB, VPBB->getFirstNonPhi());
869 else
870 Unpack->insertAfter(&R);
871 Def->replaceUsesWithIf(Unpack, [&Def](VPUser &U, unsigned) {
872 return U.usesFirstLaneOnly(Def);
873 });
874 }
875 }
876 }
877}
878
880 VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking,
881 bool RequiresScalarEpilogue, VPValue *Step,
882 std::optional<uint64_t> MaxRuntimeStep) {
883 VPSymbolicValue &VectorTC = Plan.getVectorTripCount();
884 // There's nothing to do if there are no users of the vector trip count or its
885 // IR value has already been set.
886 if (VectorTC.user_empty() || VectorTC.getUnderlyingValue())
887 return;
888
889 VPValue *TC = Plan.getTripCount();
890 Type *TCTy = TC->getScalarType();
891 VPBasicBlock::iterator InsertPt = VectorPHVPBB->begin();
892 if (auto *StepR = Step->getDefiningRecipe()) {
893 assert(VPDominatorTree(Plan).dominates(StepR->getParent(), VectorPHVPBB) &&
894 "Step VPBB must dominate VectorPHVPBB");
895 // Insert after Step's definition to maintain valid def-use ordering.
896 InsertPt = std::next(StepR->getIterator());
897 }
898 VPBuilder Builder(VectorPHVPBB, InsertPt);
899
900 // For scalable steps, if TC is a constant and is divisible by the maximum
901 // possible runtime step, then TC % Step == 0 for all valid vscale values
902 // and the vector trip count equals TC directly.
903 const APInt *TCVal;
904 if (!RequiresScalarEpilogue && match(TC, m_APInt(TCVal)) && MaxRuntimeStep &&
905 TCVal->urem(*MaxRuntimeStep) == 0) {
906 VectorTC.replaceAllUsesWith(TC);
907 return;
908 }
909
910 // If the tail is to be folded by masking, round the number of iterations N
911 // up to a multiple of Step instead of rounding down. This is done by first
912 // adding Step-1 and then rounding down. Note that it's ok if this addition
913 // overflows: the vector induction variable will eventually wrap to zero given
914 // that it starts at zero and its Step is a power of two; the loop will then
915 // exit, with the last early-exit vector comparison also producing all-true.
916 if (TailByMasking) {
917 TC = Builder.createAdd(
918 TC, Builder.createSub(Step, Plan.getConstantInt(TCTy, 1)),
919 DebugLoc::getCompilerGenerated(), "n.rnd.up");
920 }
921
922 // Now we need to generate the expression for the part of the loop that the
923 // vectorized body will execute. This is equal to N - (N % Step) if scalar
924 // iterations are not required for correctness, or N - Step, otherwise. Step
925 // is equal to the vectorization factor (number of SIMD elements) times the
926 // unroll factor (number of SIMD instructions).
927 VPValue *R =
928 Builder.createNaryOp(Instruction::URem, {TC, Step},
929 DebugLoc::getCompilerGenerated(), "n.mod.vf");
930
931 // There are cases where we *must* run at least one iteration in the remainder
932 // loop. See the cost model for when this can happen. If the step evenly
933 // divides the trip count, we set the remainder to be equal to the step. If
934 // the step does not evenly divide the trip count, no adjustment is necessary
935 // since there will already be scalar iterations. Note that the minimum
936 // iterations check ensures that N >= Step.
937 if (RequiresScalarEpilogue) {
938 assert(!TailByMasking &&
939 "requiring scalar epilogue is not supported with fail folding");
940 VPValue *IsZero =
941 Builder.createICmp(CmpInst::ICMP_EQ, R, Plan.getZero(TCTy));
942 R = Builder.createSelect(IsZero, Step, R);
943 }
944
945 VPValue *Res =
946 Builder.createSub(TC, R, DebugLoc::getCompilerGenerated(), "n.vec");
947 VectorTC.replaceAllUsesWith(Res);
948}
949
951 ElementCount VFEC) {
952 // If VF and VFxUF have already been materialized (no remaining users),
953 // there's nothing more to do.
954 if (Plan.getVF().isMaterialized()) {
955 assert(Plan.getVFxUF().isMaterialized() &&
956 "VF and VFxUF must be materialized together");
957 return;
958 }
959
960 VPBuilder Builder(VectorPH, VectorPH->begin());
961 Type *TCTy = Plan.getTripCount()->getScalarType();
962 VPValue &VF = Plan.getVF();
963 VPValue &VFxUF = Plan.getVFxUF();
964 // If there are no users of the runtime VF, compute VFxUF by constant folding
965 // the multiplication of VF and UF.
966 if (VF.user_empty()) {
967 VPValue *RuntimeVFxUF =
968 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
969 VFxUF.replaceAllUsesWith(RuntimeVFxUF);
970 return;
971 }
972
973 // For users of the runtime VF, compute it as VF * vscale, and VFxUF as (VF *
974 // vscale) * UF.
975 VPValue *RuntimeVF = Builder.createElementCount(TCTy, VFEC);
977 VPValue *BC = Builder.createNaryOp(VPInstruction::Broadcast, RuntimeVF);
979 BC, [&VF](VPUser &U, unsigned) { return !U.usesScalars(&VF); });
980 }
981 VF.replaceAllUsesWith(RuntimeVF);
982
983 VPValue *MulByUF = Builder.createOverflowingOp(
984 Instruction::Mul,
985 {RuntimeVF, Plan.getConstantInt(TCTy, Plan.getConcreteUF())},
986 {true, false});
987 VFxUF.replaceAllUsesWith(MulByUF);
988}
989
990VPValue *
992 ArrayRef<PointerDiffInfo> DiffChecks) {
993 VPBuilder Builder(AliasCheckVPBB);
994 Type *I1Ty = IntegerType::getInt1Ty(Plan.getContext());
995
996 VPValue *IncomingAliasMask = vputils::findIncomingAliasMask(Plan);
997 assert(IncomingAliasMask && "Expected an alias mask!");
998
999 VPValue *AliasMask = nullptr;
1000 for (const PointerDiffInfo &Check : DiffChecks) {
1002 VPValue *Sink =
1004 Type *AddrType = Src->getScalarType();
1005
1006 // TODO: Only freeze the required pointer (not both src and sink).
1007 if (Check.NeedsFreeze) {
1008 Src = Builder.createScalarFreeze(Src, AddrType, DebugLoc::getUnknown());
1009 Sink = Builder.createScalarFreeze(Sink, AddrType, DebugLoc::getUnknown());
1010 }
1011
1012 // TODO: Generate loop_dependence_raw_mask when there's a read-after-write
1013 // dependency between the source and the sink. This is not necessary for
1014 // correctness of the mask, but using the "raw" variant prevents loads
1015 // depending on the completion of stores.
1016 VPWidenIntrinsicRecipe *WARMask = Builder.insert(new VPWidenIntrinsicRecipe(
1017 Intrinsic::loop_dependence_war_mask,
1018 {Src, Sink, Plan.getConstantInt(AddrType, Check.AccessSize)}, I1Ty));
1019
1020 if (AliasMask)
1021 AliasMask = Builder.createAnd(AliasMask, WARMask);
1022 else
1023 AliasMask = WARMask;
1024 }
1025
1027 Type *IndexTy = Plan.getDataLayout().getIndexType(Plan.getContext(), 0);
1028 VPValue *NumActive = Builder.createNaryOp(
1029 VPInstruction::NumActiveLanes, {AliasMask}, nullptr, {}, {},
1030 DebugLoc::getUnknown(), "num.active.lanes", IndexTy);
1031 VPValue *ClampedVF = Builder.createScalarZExtOrTrunc(
1032 NumActive, IVTy, DebugLoc::getCompilerGenerated());
1033
1034 IncomingAliasMask->replaceAllUsesWith(AliasMask);
1035
1036 return ClampedVF;
1037}
1038
1040 VPlan &Plan, ArrayRef<PointerDiffInfo> DiffChecks, bool HasBranchWeights) {
1041 VPBasicBlock *ClampedVFCheck =
1042 Plan.createVPBasicBlock("vector.clamped.vf.check");
1043
1044 VPValue *ClampedVF = materializeAliasMask(Plan, ClampedVFCheck, DiffChecks);
1045 VPBuilder Builder(ClampedVFCheck);
1047 Type *TCTy = Plan.getTripCount()->getScalarType();
1048
1049 // Check the "ClampedVF" from the alias mask is larger than one.
1050 VPValue *IsScalar =
1051 Builder.createICmp(CmpInst::ICMP_ULE, ClampedVF,
1052 Plan.getConstantInt(TCTy, 1), DL, "vf.is.scalar");
1053
1054 VPValue *TripCount = Plan.getTripCount();
1055 VPValue *MaxUIntTripCount =
1057 VPValue *DistanceToMax = Builder.createSub(MaxUIntTripCount, TripCount);
1058
1059 // For tail-folding: Don't execute the vector loop if (UMax - n) < ClampedVF.
1060 // Note: The ClampedVF may not be a power-of-two. This means the loop exit
1061 // condition (index.next == n.vec) may not be correct in the case of an
1062 // overflow. The issue is `n.vec` could be zero due to an overflow, but
1063 // index.next is not guaranteed to overflow to zero as the ClampedVF is not a
1064 // power-of-two).
1065 VPValue *TripCountCheck = Builder.createICmp(
1066 ICmpInst::ICMP_ULT, DistanceToMax, ClampedVF, DL, "vf.step.overflow");
1067
1068 VPValue *Cond = Builder.createOr(IsScalar, TripCountCheck, DL);
1069 attachVPCheckBlock(Plan, Cond, ClampedVFCheck, HasBranchWeights);
1070
1071 // Materialize the trip count early as this will add a use of (VFxUF) that
1072 // needs to be replaced with the ClampedVF.
1074 /*TailByMasking=*/true,
1075 /*RequiresScalarEpilogue=*/false,
1076 &Plan.getVFxUF());
1077
1078 assert(Plan.getConcreteUF() == 1 &&
1079 "Clamped VF not supported with interleaving");
1080 Plan.getVF().replaceAllUsesWith(ClampedVF);
1081 Plan.getVFxUF().replaceAllUsesWith(ClampedVF);
1082}
1083
1085 ScalarEvolution &SE) {
1086 auto *Entry = Plan.getEntry();
1087 VPBuilder Builder(Entry, Entry->begin());
1089 ->getIRBasicBlock()
1090 ->getTerminator()
1091 ->getDebugLoc();
1092 VPSCEVExpander Expander(Builder, SE, DL);
1093
1094 // Expand VPExpandSCEVRecipes to VPInstructions using VPSCEVExpander. During
1095 // the transition, unsupported VPExpandSCEVRecipes are skipped and left for
1096 // late expansion.
1097 for (VPRecipeBase &R : make_early_inc_range(*Entry)) {
1098 auto *ExpSCEV = dyn_cast<VPExpandSCEVRecipe>(&R);
1099 if (!ExpSCEV || ExpSCEV->user_empty())
1100 continue;
1101 Builder.setInsertPoint(ExpSCEV);
1102 VPValue *Expanded = Expander.tryToExpand(ExpSCEV->getSCEV());
1103 if (!Expanded)
1104 continue;
1105 ExpSCEV->replaceAllUsesWith(Expanded);
1106 // TripCount should not be used after expansion to VPInstructions. Reset to
1107 // poison to avoid dangling references.
1108 if (Plan.getTripCount() == ExpSCEV)
1109 Plan.resetTripCount(Plan.getPoison(ExpSCEV->getScalarType()));
1110 ExpSCEV->eraseFromParent();
1111 }
1112}
1113
1116 SCEVExpander Expander(SE, "induction", /*PreserveLCSSA=*/false);
1117
1118 auto *Entry = cast<VPIRBasicBlock>(Plan.getEntry());
1119 BasicBlock *EntryBB = Entry->getIRBasicBlock();
1120 DenseMap<const SCEV *, Value *> ExpandedSCEVs;
1121 // Expand remaining VPExpandSCEVRecipes to IR instructions using SCEVExpander.
1122 for (VPRecipeBase &R : make_early_inc_range(*Entry)) {
1123 auto *ExpSCEV = dyn_cast<VPExpandSCEVRecipe>(&R);
1124 if (!ExpSCEV)
1125 continue;
1126 const SCEV *Expr = ExpSCEV->getSCEV();
1127 Value *Res =
1128 Expander.expandCodeFor(Expr, Expr->getType(), EntryBB->getTerminator());
1129 ExpandedSCEVs[Expr] = Res;
1130 VPValue *Exp = Plan.getOrAddLiveIn(Res);
1131 ExpSCEV->replaceAllUsesWith(Exp);
1132 if (Plan.getTripCount() == ExpSCEV)
1133 Plan.resetTripCount(Exp);
1134 ExpSCEV->eraseFromParent();
1135 }
1137 "all VPExpandSCEVRecipes must have been expanded");
1138 // Add IR instructions in the entry basic block but not in the VPIRBasicBlock
1139 // to the VPIRBasicBlock.
1140 auto EI = Entry->begin();
1141 for (Instruction &I : drop_end(*EntryBB)) {
1142 if (EI != Entry->end() && isa<VPIRInstruction>(*EI) &&
1143 &cast<VPIRInstruction>(&*EI)->getInstruction() == &I) {
1144 EI++;
1145 continue;
1146 }
1148 }
1149
1150 return ExpandedSCEVs;
1151}
1152
1153/// Add branch weight metadata, if the \p Plan's middle block is terminated by a
1154/// BranchOnCond recipe.
1156 VPlan &Plan, ElementCount VF, std::optional<unsigned> VScaleForTuning) {
1157 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1158 auto *MiddleTerm =
1160 // Only add branch metadata if there is a (conditional) terminator.
1161 if (!MiddleTerm)
1162 return;
1163
1164 assert(MiddleTerm->getOpcode() == VPInstruction::BranchOnCond &&
1165 "must have a BranchOnCond");
1166 // Assume that `TripCount % VectorStep ` is equally distributed.
1167 unsigned VectorStep = Plan.getConcreteUF() * VF.getKnownMinValue();
1168 if (VF.isScalable() && VScaleForTuning.has_value())
1169 VectorStep *= *VScaleForTuning;
1170 assert(VectorStep > 0 && "trip count should not be zero");
1171 MDBuilder MDB(Plan.getContext());
1172 MDNode *BranchWeights =
1173 MDB.createBranchWeights({1, VectorStep - 1}, /*IsExpected=*/false);
1174 MiddleTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1175}
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 defines the SmallPtrSet class.
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:1692
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:4050
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4389
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4416
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4424
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:94
VPRegionBlock * getParent()
Definition VPlan.h:192
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:236
VPlan * getPlan()
Definition VPlan.cpp:211
const std::string & getName() const
Definition VPlan.h:183
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:216
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:233
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:217
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:402
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:330
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:348
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:384
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:4183
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
Class to record and manage LLVM IR flags.
Definition VPlan.h:704
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:902
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:1234
@ 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:411
VPBasicBlock * getParent()
Definition VPlan.h:483
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:561
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:4614
const VPBlockBase * getEntry() const
Definition VPlan.h:4658
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4754
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:4742
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4781
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4734
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3397
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:250
VPValue * tryToExpand(const SCEV *S)
Try to 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:4244
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:4126
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2568
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2571
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2591
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2620
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2668
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2694
A recipe for widening vector intrinsics.
Definition VPlan.h:1936
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4801
bool hasVF(ElementCount VF) const
Definition VPlan.h:5026
const DataLayout & getDataLayout() const
Definition VPlan.h:5008
LLVMContext & getContext() const
Definition VPlan.h:5004
VPBasicBlock * getEntry()
Definition VPlan.h:4897
bool hasScalableVF() const
Definition VPlan.h:5027
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4962
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition VPlan.h:4983
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5002
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5136
bool hasUF(unsigned UF) const
Definition VPlan.h:5051
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5127
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4992
VPValue * getBackedgeTakenCount() const
Definition VPlan.h:4989
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:5076
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5102
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:5054
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4976
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4932
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5159
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4902
bool hasScalarVFOnly() const
Definition VPlan.h:5044
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4946
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:4918
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4995
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5229
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:5110
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:578
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)
Try to 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.