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 CanIVTy, Plan.getZero(CanIVTy), Plan.getConstantInt(CanIVTy, 1),
62 WideCanIV->getDebugLoc(), Builder,
63 WideCanIV->getNoWrapFlags().withoutNoSignedWrap()));
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. Return the created VPActiveLaneMaskPHIRecipe.
123//
124// The function adds the following recipes:
125//
126// vector.ph:
127// %EntryInc = canonical-iv-increment-for-part CanonicalIVStart
128// %EntryALM = wide-active-lane-mask %EntryInc, TC
129// %EntryALMPart = extract-vector-for-part %EntryALM, ir<0>
130//
131// vector.body:
132// ...
133// %P = active-lane-mask-phi [ %EntryALMPart, %vector.ph ],
134// [ %ALMPart, %vector.body ]
135// ...
136// %InLoopInc = canonical-iv-increment-for-part CanonicalIVIncrement
137// %ALM = wide-active-lane-mask %InLoopInc, TC
138// %ALMPart = extract-vector-for-part %ALM, ir<0>
139// %Negated = Not %ALMPart
140// branch-on-cond %Negated
141//
144 VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
145 VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
146 VPValue *StartV = Plan.getZero(TopRegion->getCanonicalIVType());
147 auto *CanonicalIVIncrement = TopRegion->getOrCreateCanonicalIVIncrement();
148 DebugLoc DL = CanonicalIVIncrement->getDebugLoc();
149 auto *VecPreheader = Plan.getVectorPreheader();
150 VPBuilder Builder(VecPreheader);
151 VPValue *TC = Plan.getTripCount();
152
153 // Create the wide active lane mask instruction in the VPlan preheader.
154 VPValue *ALMMultiplier =
155 Plan.getConstantInt(TopRegion->getCanonicalIVType(), 1);
156 auto *EntryALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
157 {StartV, TC, ALMMultiplier}, DL,
158 "active.lane.mask.entry");
159 EntryALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
160 {EntryALM, Plan.getConstantInt(64, 0)}, DL,
161 "extract.entry.alm.part");
162
163 // Now create the ActiveLaneMaskPhi recipe in the main loop using the
164 // preheader WideActiveLaneMask instruction.
165 auto *LaneMaskPhi =
167 auto *HeaderVPBB = TopRegion->getEntryBasicBlock();
168 LaneMaskPhi->insertBefore(*HeaderVPBB, HeaderVPBB->begin());
169
170 // Create the active lane mask for the next iteration of the loop before the
171 // original terminator.
172 VPRecipeBase *OriginalTerminator = EB->getTerminator();
173 Builder.setInsertPoint(OriginalTerminator);
174 auto *ALM = Builder.createNaryOp(VPInstruction::WideActiveLaneMask,
175 {CanonicalIVIncrement, TC, ALMMultiplier},
176 DL, "active.lane.mask.next");
177 ALM = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
178 {ALM, Plan.getConstantInt(64, 0)}, DL,
179 "extract.next.alm.part");
180 LaneMaskPhi->addBackedgeValue(ALM);
181
182 // Replace the original terminator with BranchOnCond. We have to invert the
183 // mask here because a true condition means jumping to the exit block.
184 auto *NotMask = Builder.createNot(ALM, DL);
185 Builder.createNaryOp(VPInstruction::BranchOnCond, {NotMask}, DL);
186 OriginalTerminator->eraseFromParent();
187 return LaneMaskPhi;
188}
189
191 VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow) {
192 VPRegionBlock *LoopRegion = Plan.getVectorLoopRegion();
193 VPValue *HeaderMask = LoopRegion->getUsedHeaderMask();
194 if (!HeaderMask)
195 return;
196
197 if (UseActiveLaneMaskForControlFlow) {
199 return;
200 }
201
202 VPBasicBlock *Header = LoopRegion->getEntryBasicBlock();
203 VPBuilder Builder(Header, Header->getFirstNonPhi());
204 auto *WideCanonicalIV = Builder.insert(new VPWidenCanonicalIVRecipe(
205 LoopRegion->getCanonicalIV(),
206 VPIRFlags::WrapFlagsTy(/*HasNUW=*/true, /*HasNSW=*/false)));
207 VPValue *Mask;
208 if (UseActiveLaneMask) {
209 Mask = Builder.createNaryOp(VPInstruction::ActiveLaneMask,
210 {WideCanonicalIV, Plan.getTripCount()}, nullptr,
211 "active.lane.mask");
212 } else {
213 Mask = Builder.createICmp(CmpInst::ICMP_ULE, WideCanonicalIV,
215 }
216 HeaderMask->replaceAllUsesWith(Mask);
217}
218
219/// Expand a VPWidenIntOrFpInduction into executable recipes, for the initial
220/// value, phi and backedge value. In the following example:
221///
222/// vector.ph:
223/// Successor(s): vector loop
224///
225/// <x1> vector loop: {
226/// vector.body:
227/// WIDEN-INDUCTION %i = phi %start, %step, %vf
228/// ...
229/// EMIT branch-on-count ...
230/// No successors
231/// }
232///
233/// WIDEN-INDUCTION will get expanded to:
234///
235/// vector.ph:
236/// ...
237/// vp<%induction.start> = ...
238/// vp<%induction.increment> = ...
239///
240/// Successor(s): vector loop
241///
242/// <x1> vector loop: {
243/// vector.body:
244/// ir<%i> = WIDEN-PHI vp<%induction.start>, vp<%vec.ind.next>
245/// ...
246/// vp<%vec.ind.next> = add ir<%i>, vp<%induction.increment>
247/// EMIT branch-on-count ...
248/// No successors
249/// }
250static void
252 VPlan *Plan = WidenIVR->getParent()->getPlan();
253 VPValue *Start = WidenIVR->getStartValue();
254 VPValue *Step = WidenIVR->getStepValue();
255 VPValue *VF = WidenIVR->getVFValue();
256 DebugLoc DL = WidenIVR->getDebugLoc();
257
258 // The value from the original loop to which we are mapping the new induction
259 // variable.
260 Type *Ty = WidenIVR->getScalarType();
261
262 const InductionDescriptor &ID = WidenIVR->getInductionDescriptor();
265 VPIRFlags Flags = *WidenIVR;
266 if (ID.getKind() == InductionDescriptor::IK_IntInduction) {
267 AddOp = Instruction::Add;
268 MulOp = Instruction::Mul;
269 } else {
270 AddOp = ID.getInductionOpcode();
271 MulOp = Instruction::FMul;
272 }
273
274 // If the phi is truncated, truncate the start and step values.
275 VPBuilder Builder(Plan->getVectorPreheader());
276 Type *StepTy = Step->getScalarType();
277 if (Ty->getScalarSizeInBits() < StepTy->getScalarSizeInBits()) {
278 assert(StepTy->isIntegerTy() && "Truncation requires an integer type");
279 Step = Builder.createScalarCast(Instruction::Trunc, Step, Ty, DL);
280 Start = Builder.createScalarCast(Instruction::Trunc, Start, Ty, DL);
281 StepTy = Ty;
282 }
283
284 // Construct the initial value of the vector IV in the vector loop preheader.
285 Type *IVIntTy =
287 VPValue *Init = Builder.createNaryOp(VPInstruction::StepVector, {}, IVIntTy);
288 if (StepTy->isFloatingPointTy())
289 Init = Builder.createWidenCast(Instruction::UIToFP, Init, StepTy);
290
291 VPValue *SplatStart = Builder.createNaryOp(VPInstruction::Broadcast, Start);
292 VPValue *SplatStep = Builder.createNaryOp(VPInstruction::Broadcast, Step);
293
294 Init = Builder.createNaryOp(MulOp, {Init, SplatStep}, Flags);
295 Init = Builder.createNaryOp(AddOp, {SplatStart, Init}, Flags,
296 DebugLoc::getUnknown(), "induction");
297
298 // Create the widened phi of the vector IV.
299 auto *WidePHI = VPBuilder(WidenIVR).createWidenPhi(
300 Init, WidenIVR->getDebugLoc(), "vec.ind");
301
302 // Create the backedge value for the vector IV.
303 VPValue *Inc;
304 VPValue *Prev;
305 // If unrolled, use the increment and prev value from the operands.
306 if (auto *SplatVF = WidenIVR->getSplatVFValue()) {
307 Inc = SplatVF;
308 Prev = WidenIVR->getLastUnrolledPartOperand();
309 } else {
310 // Move the insertion point after the VF definition when the VF is defined
311 // inside a loop, such as for EVL tail-folding.
312 if (VPRecipeBase *R = VF->getDefiningRecipe())
313 if (R->getParent()->getEnclosingLoopRegion())
314 Builder.setInsertPoint(R->getParent(), std::next(R->getIterator()));
315
316 // Multiply the vectorization factor by the step using integer or
317 // floating-point arithmetic as appropriate.
318 if (StepTy->isFloatingPointTy())
319 VF = Builder.createScalarCast(Instruction::CastOps::UIToFP, VF, StepTy,
320 DL);
321 else
322 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
323
324 Inc = Builder.createNaryOp(MulOp, {Step, VF}, Flags);
325 Inc = Builder.createNaryOp(VPInstruction::Broadcast, Inc);
326 Prev = WidePHI;
327 }
328
330 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
331 auto *Next = Builder.createNaryOp(AddOp, {Prev, Inc}, Flags,
332 WidenIVR->getDebugLoc(), "vec.ind.next");
333
334 WidePHI->addIncoming(Next);
335
336 WidenIVR->replaceAllUsesWith(WidePHI);
337}
338
339/// Expand a VPWidenPointerInductionRecipe into executable recipes, for the
340/// initial value, phi and backedge value. In the following example:
341///
342/// <x1> vector loop: {
343/// vector.body:
344/// EMIT ir<%ptr.iv> = WIDEN-POINTER-INDUCTION %start, %step, %vf
345/// ...
346/// EMIT branch-on-count ...
347/// }
348///
349/// WIDEN-POINTER-INDUCTION will get expanded to:
350///
351/// <x1> vector loop: {
352/// vector.body:
353/// EMIT-SCALAR %pointer.phi = phi %start, %ptr.ind
354/// EMIT %mul = mul %stepvector, %step
355/// EMIT %vector.gep = wide-ptradd %pointer.phi, %mul
356/// ...
357/// EMIT %ptr.ind = ptradd %pointer.phi, %vf
358/// EMIT branch-on-count ...
359/// }
361 VPlan *Plan = R->getParent()->getPlan();
362 VPValue *Start = R->getStartValue();
363 VPValue *Step = R->getStepValue();
364 VPValue *VF = R->getVFValue();
365
366 assert(R->getInductionDescriptor().getKind() ==
368 "Not a pointer induction according to InductionDescriptor!");
369 assert(R->getScalarType()->isPointerTy() && "Unexpected type.");
370 assert(!R->onlyScalarsGenerated(Plan->hasScalableVF()) &&
371 "Recipe should have been replaced");
372
373 VPBuilder Builder(R);
374 DebugLoc DL = R->getDebugLoc();
375
376 // Build a scalar pointer phi.
377 VPPhi *ScalarPtrPhi = Builder.createScalarPhi(Start, DL, "pointer.phi");
378
379 // Create actual address geps that use the pointer phi as base and a
380 // vectorized version of the step value (<step*0, ..., step*N>) as offset.
381 Builder.setInsertPoint(R->getParent(), R->getParent()->getFirstNonPhi());
382 Type *StepTy = Step->getScalarType();
383 VPValue *Offset = Builder.createNaryOp(VPInstruction::StepVector, {}, StepTy);
384 Offset = Builder.createOverflowingOp(Instruction::Mul, {Offset, Step});
385 VPValue *PtrAdd =
386 Builder.createWidePtrAdd(ScalarPtrPhi, Offset, DL, "vector.gep");
387 R->replaceAllUsesWith(PtrAdd);
388
389 // Create the backedge value for the scalar pointer phi.
391 Builder.setInsertPoint(ExitingBB, ExitingBB->getTerminator()->getIterator());
392 VF = Builder.createScalarZExtOrTrunc(VF, StepTy, DL);
393 VPValue *Inc = Builder.createOverflowingOp(Instruction::Mul, {Step, VF});
394
395 VPValue *InductionGEP =
396 Builder.createPtrAdd(ScalarPtrPhi, Inc, DL, "ptr.ind");
397 ScalarPtrPhi->addIncoming(InductionGEP);
398}
399
400/// Expand a VPDerivedIVRecipe into executable recipes.
402 VPBuilder Builder(R);
403 VPValue *Start = R->getStartValue();
404 VPValue *Step = R->getStepValue();
405 VPValue *Index = R->getIndex();
406 Type *StepTy = Step->getScalarType();
407 Index = StepTy->isIntegerTy()
408 ? Builder.createScalarZExtOrTrunc(
409 Index, StepTy, DebugLoc::getCompilerGenerated())
410 : Builder.createScalarCast(Instruction::SIToFP, Index, StepTy,
412 VPIRFlags::WrapFlagsTy Flags = R->getNoWrapFlags();
413 switch (R->getInductionKind()) {
415 assert(Index->getScalarType() == Start->getScalarType() &&
416 "Index type does not match StartValue type");
417 return R->replaceAllUsesWith(Builder.createAdd(
418 Start,
419 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags),
420 DebugLoc::getUnknown(), "", Flags));
421 }
423 return R->replaceAllUsesWith(Builder.createPtrAdd(
424 Start,
425 Builder.createOverflowingOp(Instruction::Mul, {Index, Step}, Flags)));
427 assert(StepTy->isFloatingPointTy() && "Expected FP Step value");
428 const FPMathOperator *FPBinOp = R->getFPBinOp();
429 assert(FPBinOp &&
430 (FPBinOp->getOpcode() == Instruction::FAdd ||
431 FPBinOp->getOpcode() == Instruction::FSub) &&
432 "Original BinOp should be defined for FP induction");
433 FastMathFlags FMF = FPBinOp->getFastMathFlags();
434 VPValue *FMul = Builder.createNaryOp(Instruction::FMul, {Step, Index}, FMF);
435 return R->replaceAllUsesWith(
436 Builder.createNaryOp(FPBinOp->getOpcode(), {Start, FMul}, FMF));
437 }
439 return;
440 }
441 llvm_unreachable("Unhandled induction kind");
442}
443
445 // Replace loop regions with explicity CFG.
448 vp_depth_first_deep(Plan.getEntry()))) {
449 if (!R->isReplicator())
450 LoopRegions.push_back(R);
451 }
452 for (VPRegionBlock *R : LoopRegions)
453 R->dissolveToCFGLoop();
454}
455
458 // The transform runs after dissolving loop regions, so all VPBasicBlocks
459 // terminated with BranchOnTwoConds are reached via a shallow traversal.
462 if (!VPBB->empty() && match(&VPBB->back(), m_BranchOnTwoConds()))
463 WorkList.push_back(cast<VPInstruction>(&VPBB->back()));
464 }
465
466 // Expand BranchOnTwoConds instructions into explicit CFG with two new
467 // single-condition branches:
468 // 1. A branch that replaces BranchOnTwoConds, jumps to the first successor if
469 // the first condition is true, and otherwise jumps to a new interim block.
470 // 2. A branch that ends the interim block, jumps to the second successor if
471 // the second condition is true, and otherwise jumps to the third
472 // successor.
473 for (VPInstruction *Br : WorkList) {
474 assert(Br->getNumOperands() == 2 &&
475 "BranchOnTwoConds must have exactly 2 conditions");
476 DebugLoc DL = Br->getDebugLoc();
477 VPBasicBlock *BrOnTwoCondsBB = Br->getParent();
478 const auto Successors = to_vector(BrOnTwoCondsBB->getSuccessors());
479 assert(Successors.size() == 3 &&
480 "BranchOnTwoConds must have exactly 3 successors");
481
482 for (VPBlockBase *Succ : Successors)
483 VPBlockUtils::disconnectBlocks(BrOnTwoCondsBB, Succ);
484
485 VPValue *Cond0 = Br->getOperand(0);
486 VPValue *Cond1 = Br->getOperand(1);
487 VPBlockBase *Succ0 = Successors[0];
488 VPBlockBase *Succ1 = Successors[1];
489 VPBlockBase *Succ2 = Successors[2];
490
491 // If the successor block for both conditions is the same, then combine the
492 // two conditions and plant a single conditional branch.
493 if (Succ0 == Succ1) {
494 VPBuilder Builder(Br);
495 VPValue *Combined = Builder.createOr(Cond0, Cond1, DL);
496 Builder.createNaryOp(VPInstruction::BranchOnCond, {Combined}, DL);
497 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
498 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ2);
499 Br->eraseFromParent();
500 continue;
501 }
502
503 assert(!Succ0->getParent() && !Succ1->getParent() && !Succ2->getParent() &&
504 !BrOnTwoCondsBB->getParent() && "regions must already be dissolved");
505
506 VPBasicBlock *InterimBB =
507 Plan.createVPBasicBlock(BrOnTwoCondsBB->getName() + ".interim");
508
509 VPBuilder(BrOnTwoCondsBB)
511 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, Succ0);
512 VPBlockUtils::connectBlocks(BrOnTwoCondsBB, InterimBB);
513
515 VPBlockUtils::connectBlocks(InterimBB, Succ1);
516 VPBlockUtils::connectBlocks(InterimBB, Succ2);
517 Br->eraseFromParent();
518 }
519}
520
523 vp_depth_first_deep(Plan.getEntry()))) {
524 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
525 VPBuilder Builder(&R);
526 // !prof is only supported on scalar selects.
527 if (auto *Widen = dyn_cast<VPWidenRecipe>(&R)) {
528 if (Widen->getOpcode() == Instruction::Select &&
529 !vputils::isSingleScalar(Widen->getOperand(0)))
530 Widen->eraseMetadata(LLVMContext::MD_prof);
531 }
532
533 if (auto *WidenIVR = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) {
535 WidenIVR->eraseFromParent();
536 continue;
537 }
538
539 if (auto *WidenIVR = dyn_cast<VPWidenPointerInductionRecipe>(&R)) {
540 // If the recipe only generates scalars, scalarize it instead of
541 // expanding it.
542 if (WidenIVR->onlyScalarsGenerated(Plan.hasScalableVF())) {
544 WidenIVR, Plan, Builder);
545 WidenIVR->replaceAllUsesWith(PtrAdd);
546 WidenIVR->eraseFromParent();
547 continue;
548 }
550 WidenIVR->eraseFromParent();
551 continue;
552 }
553
554 if (auto *DerivedIVR = dyn_cast<VPDerivedIVRecipe>(&R)) {
555 expandVPDerivedIV(DerivedIVR);
556 DerivedIVR->eraseFromParent();
557 continue;
558 }
559
560 if (auto *WideCanIV = dyn_cast<VPWidenCanonicalIVRecipe>(&R)) {
561 VPValue *CanIV = WideCanIV->getCanonicalIV();
562 Type *CanIVTy = CanIV->getScalarType();
563 VPValue *Step = WideCanIV->getStepValue();
564 if (!Step) {
565 assert(Plan.getConcreteUF() == 1 &&
566 "Expected unroller to have materialized step for UF != 1");
567 Step = Plan.getZero(CanIVTy);
568 }
569 CanIV = Builder.createNaryOp(VPInstruction::Broadcast, CanIV);
570 Step = Builder.createNaryOp(VPInstruction::Broadcast, Step);
571 Step = Builder.createAdd(
572 Step, Builder.createNaryOp(VPInstruction::StepVector, {}, CanIVTy));
573 VPValue *CanVecIV =
574 Builder.createAdd(CanIV, Step, WideCanIV->getDebugLoc(), "vec.iv",
575 WideCanIV->getNoWrapFlags());
576 WideCanIV->replaceAllUsesWith(CanVecIV);
577 WideCanIV->eraseFromParent();
578 continue;
579 }
580
581 // Expand VPBlendRecipe into VPInstruction::Select.
582 if (auto *Blend = dyn_cast<VPBlendRecipe>(&R)) {
583 VPValue *Select = Blend->getIncomingValue(0);
584 for (unsigned I = 1; I != Blend->getNumIncomingValues(); ++I)
585 Select = Builder.createSelect(Blend->getMask(I),
586 Blend->getIncomingValue(I), Select,
587 R.getDebugLoc(), "predphi", *Blend);
588 Blend->replaceAllUsesWith(Select);
589 Blend->eraseFromParent();
590 continue;
591 }
592
593 if (auto *VEPR = dyn_cast<VPVectorEndPointerRecipe>(&R)) {
594 if (!VEPR->getOffset()) {
595 assert(Plan.getConcreteUF() == 1 &&
596 "Expected unroller to have materialized offset for UF != 1");
597 VEPR->materializeOffset();
598 }
599 continue;
600 }
601
602 if (auto *Expr = dyn_cast<VPExpressionRecipe>(&R)) {
603 Expr->decompose();
604 Expr->eraseFromParent();
605 continue;
606 }
607
608 // Expand LastActiveLane into Not + FirstActiveLane + Sub.
609 auto *LastActiveL = dyn_cast<VPInstruction>(&R);
610 if (LastActiveL &&
611 LastActiveL->getOpcode() == VPInstruction::LastActiveLane) {
612 // Create Not(Mask) for all operands.
614 for (VPValue *Op : LastActiveL->operands()) {
615 VPValue *NotMask = Builder.createNot(Op, LastActiveL->getDebugLoc());
616 NotMasks.push_back(NotMask);
617 }
618
619 // Create FirstActiveLane on the inverted masks.
620 VPValue *FirstInactiveLane = Builder.createFirstActiveLane(
621 NotMasks, LastActiveL->getDebugLoc(), "first.inactive.lane");
622
623 // Subtract 1 to get the last active lane.
624 VPValue *One =
625 Plan.getConstantInt(FirstInactiveLane->getScalarType(), 1);
626 VPValue *LastLane =
627 Builder.createSub(FirstInactiveLane, One,
628 LastActiveL->getDebugLoc(), "last.active.lane");
629
630 LastActiveL->replaceAllUsesWith(LastLane);
631 LastActiveL->eraseFromParent();
632 continue;
633 }
634
635 // Lower MaskedCond with block mask to LogicalAnd.
637 auto *VPI = cast<VPInstruction>(&R);
638 assert(VPI->isMasked() &&
639 "Unmasked MaskedCond should be simplified earlier");
640 VPI->replaceAllUsesWith(Builder.createNaryOp(
641 VPInstruction::LogicalAnd, {VPI->getMask(), VPI->getOperand(0)}));
642 VPI->eraseFromParent();
643 continue;
644 }
645
646 // Lower CanonicalIVIncrementForPart to plain Add.
647 if (match(
648 &R,
650 auto *VPI = cast<VPInstruction>(&R);
651 VPValue *Add = Builder.createOverflowingOp(
652 Instruction::Add, VPI->operands(), VPI->getNoWrapFlags(),
653 VPI->getDebugLoc());
654 VPI->replaceAllUsesWith(Add);
655 VPI->eraseFromParent();
656 continue;
657 }
658
659 // Lower BranchOnCount to ICmp + BranchOnCond.
660 VPValue *IV, *TC;
661 if (match(&R, m_BranchOnCount(m_VPValue(IV), m_VPValue(TC)))) {
662 auto *BranchOnCountInst = cast<VPInstruction>(&R);
663 DebugLoc DL = BranchOnCountInst->getDebugLoc();
664 VPValue *Cond = Builder.createICmp(CmpInst::ICMP_EQ, IV, TC, DL);
665 Builder.createNaryOp(VPInstruction::BranchOnCond, Cond, DL);
666 BranchOnCountInst->eraseFromParent();
667 continue;
668 }
669
670 VPValue *VectorStep;
671 VPValue *ScalarStep;
673 m_VPValue(VectorStep), m_VPValue(ScalarStep))))
674 continue;
675
676 // Expand WideIVStep.
677 auto *VPI = cast<VPInstruction>(&R);
678 Type *IVTy = VPI->getScalarType();
679 if (VectorStep->getScalarType() != IVTy) {
681 ? Instruction::UIToFP
682 : Instruction::Trunc;
683 VectorStep = Builder.createWidenCast(CastOp, VectorStep, IVTy);
684 }
685
686 assert(!match(ScalarStep, m_One()) && "Expected non-unit scalar-step");
687 if (ScalarStep->getScalarType() != IVTy) {
688 ScalarStep =
689 Builder.createWidenCast(Instruction::Trunc, ScalarStep, IVTy);
690 }
691
692 VPIRFlags Flags;
693 unsigned MulOpc;
694 if (IVTy->isFloatingPointTy()) {
695 MulOpc = Instruction::FMul;
696 Flags = VPI->getFastMathFlagsOrNone();
697 } else {
698 MulOpc = Instruction::Mul;
699 Flags = VPIRFlags::getDefaultFlags(MulOpc);
700 }
701
702 VPInstruction *Mul = Builder.createNaryOp(
703 MulOpc, {VectorStep, ScalarStep}, Flags, R.getDebugLoc());
704 VectorStep = Mul;
705 VPI->replaceAllUsesWith(VectorStep);
706 VPI->eraseFromParent();
707 }
708 }
709}
710
712 if (Plan.hasScalarVFOnly())
713 return;
714
715#ifndef NDEBUG
716 VPDominatorTree VPDT(Plan);
717#endif
718
719 SmallVector<VPValue *> VPValues;
720 if (VPValue *BTC = Plan.getBackedgeTakenCount())
721 VPValues.push_back(BTC);
722 append_range(VPValues, Plan.getLiveIns());
723 for (VPRecipeBase &R : *Plan.getEntry())
724 append_range(VPValues, R.definedValues());
725
726 auto *VectorPreheader = Plan.getVectorPreheader();
727 for (VPValue *VPV : VPValues) {
729 continue;
730
731 // Add explicit broadcast at the insert point that dominates all users.
732 VPBasicBlock *HoistBlock = VectorPreheader;
733 VPBasicBlock::iterator HoistPoint = VectorPreheader->end();
734 for (VPUser *User : VPV->users()) {
735 if (User->usesScalars(VPV))
736 continue;
737 if (cast<VPRecipeBase>(User)->getParent() == VectorPreheader)
738 HoistPoint = HoistBlock->getFirstNonPhi();
739 else
740 assert(VPDT.dominates(VectorPreheader,
741 cast<VPRecipeBase>(User)->getParent()) &&
742 "All users must be in the vector preheader or dominated by it");
743 }
744
745 VPBuilder Builder(cast<VPBasicBlock>(HoistBlock), HoistPoint);
746 auto *Broadcast = Builder.createNaryOp(VPInstruction::Broadcast, {VPV});
747 VPV->replaceUsesWithIf(Broadcast, [VPV, Broadcast](VPUser *U) {
748 return Broadcast != U && !U->usesScalars(VPV);
749 });
750 }
751}
752
754 VPlan &Plan, ElementCount BestVF, unsigned BestUF,
756 assert(Plan.hasVF(BestVF) && "BestVF is not available in Plan");
757 assert(Plan.hasUF(BestUF) && "BestUF is not available in Plan");
758
759 VPValue *TC = Plan.getTripCount();
760 if (TC->user_empty())
761 return;
762
763 // Skip cases for which the trip count may be non-trivial to materialize.
764 // I.e., when a scalar tail is absent - due to tail folding, or when a scalar
765 // tail is required.
766 if (Plan.hasTailFolded() || !Plan.hasScalarTail() ||
768 Plan.getScalarPreheader() ||
769 !isa<VPIRValue>(TC))
770 return;
771
772 // Materialize vector trip counts for constants early if it can simply
773 // be computed as (Original TC / VF * UF) * VF * UF.
774 // TODO: Compute vector trip counts for loops requiring a scalar epilogue and
775 // tail-folded loops.
776 ScalarEvolution &SE = *PSE.getSE();
777 auto *TCScev = SE.getSCEV(TC->getLiveInIRValue());
778 if (!isa<SCEVConstant>(TCScev))
779 return;
780 const SCEV *VFxUF = SE.getElementCount(TCScev->getType(), BestVF * BestUF);
781 const SCEV *VecTCScev = SE.getMulExpr(SE.getUDivExpr(TCScev, VFxUF), VFxUF);
782 if (auto *ConstVecTC = dyn_cast<SCEVConstant>(VecTCScev))
783 Plan.getVectorTripCount().setUnderlyingValue(ConstVecTC->getValue());
784}
785
787 VPBasicBlock *VectorPH) {
789 if (BTC->user_empty())
790 return;
791
792 VPBuilder Builder(VectorPH, VectorPH->getFirstNonPhi());
793 auto *TCTy = Plan.getTripCount()->getScalarType();
794 auto *TCMO =
795 Builder.createSub(Plan.getTripCount(), Plan.getConstantInt(TCTy, 1),
796 DebugLoc::getCompilerGenerated(), "trip.count.minus.1");
797 BTC->replaceAllUsesWith(TCMO);
798}
799
801 if (Plan.hasScalarVFOnly())
802 return;
803
804 auto VPBBsInsideLoopRegion = VPBlockUtils::blocksOnly<VPBasicBlock>(
806 // Create explicit VPInstructions to convert vectors to scalars. The current
807 // implementation is conservative - it may miss some cases that may or may not
808 // be vector values. TODO: introduce Unpacks speculatively - remove them later
809 // if they are known to operate on scalar values.
810 for (VPBasicBlock *VPBB : VPBBsInsideLoopRegion) {
811 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
814 continue;
815 for (VPValue *Def : R.definedValues()) {
816 // Skip recipes that are single-scalar.
817 // TODO: The Defs skipped here may or may not be vector values.
818 // Introduce Unpacks, and remove them later, if they are guaranteed to
819 // produce scalar values.
821 continue;
822
823 // Only introduce an Unpack if some, but not all, users use the first
824 // lane only.
825 unsigned NumFirstLaneUsers = count_if(Def->users(), [&Def](VPUser *U) {
826 return U->usesFirstLaneOnly(Def);
827 });
828 if (!NumFirstLaneUsers || NumFirstLaneUsers == Def->getNumUsers())
829 continue;
830
831 auto *Unpack = new VPInstruction(VPInstruction::Unpack, {Def});
832 if (R.isPhi())
833 Unpack->insertBefore(*VPBB, VPBB->getFirstNonPhi());
834 else
835 Unpack->insertAfter(&R);
836 Def->replaceUsesWithIf(
837 Unpack, [&Def](VPUser *U) { return U->usesFirstLaneOnly(Def); });
838 }
839 }
840 }
841}
842
844 VPlan &Plan, VPBasicBlock *VectorPHVPBB, bool TailByMasking,
845 bool RequiresScalarEpilogue, VPValue *Step,
846 std::optional<uint64_t> MaxRuntimeStep) {
847 VPSymbolicValue &VectorTC = Plan.getVectorTripCount();
848 // There's nothing to do if there are no users of the vector trip count or its
849 // IR value has already been set.
850 if (VectorTC.user_empty() || VectorTC.getUnderlyingValue())
851 return;
852
853 VPValue *TC = Plan.getTripCount();
854 Type *TCTy = TC->getScalarType();
855 VPBasicBlock::iterator InsertPt = VectorPHVPBB->getFirstNonPhi();
856 if (auto *StepR = Step->getDefiningRecipe()) {
857 assert(VPDominatorTree(Plan).dominates(StepR->getParent(), VectorPHVPBB) &&
858 "Step VPBB must dominate VectorPHVPBB");
859 // Insert after Step's definition to maintain valid def-use ordering.
860 InsertPt = std::next(StepR->getIterator());
861 }
862 VPBuilder Builder(VectorPHVPBB, InsertPt);
863
864 // For scalable steps, if TC is a constant and is divisible by the maximum
865 // possible runtime step, then TC % Step == 0 for all valid vscale values
866 // and the vector trip count equals TC directly.
867 const APInt *TCVal;
868 if (!RequiresScalarEpilogue && match(TC, m_APInt(TCVal)) && MaxRuntimeStep &&
869 TCVal->urem(*MaxRuntimeStep) == 0) {
870 VectorTC.replaceAllUsesWith(TC);
871 return;
872 }
873
874 // If the tail is to be folded by masking, round the number of iterations N
875 // up to a multiple of Step instead of rounding down. This is done by first
876 // adding Step-1 and then rounding down. Note that it's ok if this addition
877 // overflows: the vector induction variable will eventually wrap to zero given
878 // that it starts at zero and its Step is a power of two; the loop will then
879 // exit, with the last early-exit vector comparison also producing all-true.
880 if (TailByMasking) {
881 TC = Builder.createAdd(
882 TC, Builder.createSub(Step, Plan.getConstantInt(TCTy, 1)),
883 DebugLoc::getCompilerGenerated(), "n.rnd.up");
884 }
885
886 // Now we need to generate the expression for the part of the loop that the
887 // vectorized body will execute. This is equal to N - (N % Step) if scalar
888 // iterations are not required for correctness, or N - Step, otherwise. Step
889 // is equal to the vectorization factor (number of SIMD elements) times the
890 // unroll factor (number of SIMD instructions).
891 VPValue *R =
892 Builder.createNaryOp(Instruction::URem, {TC, Step},
893 DebugLoc::getCompilerGenerated(), "n.mod.vf");
894
895 // There are cases where we *must* run at least one iteration in the remainder
896 // loop. See the cost model for when this can happen. If the step evenly
897 // divides the trip count, we set the remainder to be equal to the step. If
898 // the step does not evenly divide the trip count, no adjustment is necessary
899 // since there will already be scalar iterations. Note that the minimum
900 // iterations check ensures that N >= Step.
901 if (RequiresScalarEpilogue) {
902 assert(!TailByMasking &&
903 "requiring scalar epilogue is not supported with fail folding");
904 VPValue *IsZero =
905 Builder.createICmp(CmpInst::ICMP_EQ, R, Plan.getZero(TCTy));
906 R = Builder.createSelect(IsZero, Step, R);
907 }
908
909 VPValue *Res =
910 Builder.createSub(TC, R, DebugLoc::getCompilerGenerated(), "n.vec");
911 VectorTC.replaceAllUsesWith(Res);
912}
913
915 ElementCount VFEC) {
916 // If VF and VFxUF have already been materialized (no remaining users),
917 // there's nothing more to do.
918 if (Plan.getVF().isMaterialized()) {
919 assert(Plan.getVFxUF().isMaterialized() &&
920 "VF and VFxUF must be materialized together");
921 return;
922 }
923
924 VPBuilder Builder(VectorPH, VectorPH->getFirstNonPhi());
925 Type *TCTy = Plan.getTripCount()->getScalarType();
926 VPValue &VF = Plan.getVF();
927 VPValue &VFxUF = Plan.getVFxUF();
928 // If there are no users of the runtime VF, compute VFxUF by constant folding
929 // the multiplication of VF and UF.
930 if (VF.user_empty()) {
931 VPValue *RuntimeVFxUF =
932 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
933 VFxUF.replaceAllUsesWith(RuntimeVFxUF);
934 return;
935 }
936
937 // For users of the runtime VF, compute it as VF * vscale, and VFxUF as (VF *
938 // vscale) * UF.
939 VPValue *RuntimeVF = Builder.createElementCount(TCTy, VFEC);
941 VPValue *BC = Builder.createNaryOp(VPInstruction::Broadcast, RuntimeVF);
942 VF.replaceUsesWithIf(BC, [&VF](VPUser *U) { return !U->usesScalars(&VF); });
943 }
944 VF.replaceAllUsesWith(RuntimeVF);
945
946 VPValue *MulByUF =
947 Builder.createElementCount(TCTy, VFEC * Plan.getConcreteUF());
948 VFxUF.replaceAllUsesWith(MulByUF);
949}
950
951VPValue *
953 ArrayRef<PointerDiffInfo> DiffChecks) {
954 VPBuilder Builder(AliasCheckVPBB);
955 Type *I1Ty = IntegerType::getInt1Ty(Plan.getContext());
956
957 VPValue *IncomingAliasMask = vputils::findIncomingAliasMask(Plan);
958 assert(IncomingAliasMask && "Expected an alias mask!");
959
960 VPValue *AliasMask = nullptr;
961 for (const PointerDiffInfo &Check : DiffChecks) {
963 VPValue *Sink =
965 Type *AddrType = Src->getScalarType();
966
967 // TODO: Only freeze the required pointer (not both src and sink).
968 if (Check.NeedsFreeze) {
969 Src = Builder.createFreeze(Src);
970 Sink = Builder.createFreeze(Sink);
971 }
972
973 // TODO: Generate loop_dependence_raw_mask when there's a read-after-write
974 // dependency between the source and the sink. This is not necessary for
975 // correctness of the mask, but using the "raw" variant prevents loads
976 // depending on the completion of stores.
977 VPWidenIntrinsicRecipe *WARMask = Builder.insert(new VPWidenIntrinsicRecipe(
978 Intrinsic::loop_dependence_war_mask,
979 {Src, Sink, Plan.getConstantInt(AddrType, Check.AccessSize)}, I1Ty));
980
981 if (AliasMask)
982 AliasMask = Builder.createAnd(AliasMask, WARMask);
983 else
984 AliasMask = WARMask;
985 }
986
988 Type *IndexTy = Plan.getDataLayout().getIndexType(Plan.getContext(), 0);
989 VPValue *NumActive = Builder.createNaryOp(
990 VPInstruction::NumActiveLanes, {AliasMask}, nullptr, {}, {},
991 DebugLoc::getUnknown(), "num.active.lanes", IndexTy);
992 VPValue *ClampedVF = Builder.createScalarZExtOrTrunc(
993 NumActive, IVTy, DebugLoc::getCompilerGenerated());
994
995 IncomingAliasMask->replaceAllUsesWith(AliasMask);
996
997 return ClampedVF;
998}
999
1001 VPlan &Plan, ArrayRef<PointerDiffInfo> DiffChecks, bool HasBranchWeights) {
1002 VPBasicBlock *ClampedVFCheck =
1003 Plan.createVPBasicBlock("vector.clamped.vf.check");
1004
1005 VPValue *ClampedVF = materializeAliasMask(Plan, ClampedVFCheck, DiffChecks);
1006 VPBuilder Builder(ClampedVFCheck);
1008 Type *TCTy = Plan.getTripCount()->getScalarType();
1009
1010 // Check the "ClampedVF" from the alias mask is larger than one.
1011 VPValue *IsScalar =
1012 Builder.createICmp(CmpInst::ICMP_ULE, ClampedVF,
1013 Plan.getConstantInt(TCTy, 1), DL, "vf.is.scalar");
1014
1015 VPValue *TripCount = Plan.getTripCount();
1016 VPValue *MaxUIntTripCount =
1018 VPValue *DistanceToMax = Builder.createSub(MaxUIntTripCount, TripCount);
1019
1020 // For tail-folding: Don't execute the vector loop if (UMax - n) < ClampedVF.
1021 // Note: The ClampedVF may not be a power-of-two. This means the loop exit
1022 // condition (index.next == n.vec) may not be correct in the case of an
1023 // overflow. The issue is `n.vec` could be zero due to an overflow, but
1024 // index.next is not guaranteed to overflow to zero as the ClampedVF is not a
1025 // power-of-two).
1026 VPValue *TripCountCheck = Builder.createICmp(
1027 ICmpInst::ICMP_ULT, DistanceToMax, ClampedVF, DL, "vf.step.overflow");
1028
1029 VPValue *Cond = Builder.createOr(IsScalar, TripCountCheck, DL);
1030 attachVPCheckBlock(Plan, Cond, ClampedVFCheck, HasBranchWeights);
1031
1032 // Materialize the trip count early as this will add a use of (VFxUF) that
1033 // needs to be replaced with the ClampedVF.
1035 /*TailByMasking=*/true,
1036 /*RequiresScalarEpilogue=*/false,
1037 &Plan.getVFxUF());
1038
1039 assert(Plan.getConcreteUF() == 1 &&
1040 "Clamped VF not supported with interleaving");
1041 Plan.getVF().replaceAllUsesWith(ClampedVF);
1042 Plan.getVFxUF().replaceAllUsesWith(ClampedVF);
1043}
1044
1046 ScalarEvolution &SE) {
1047 auto *Entry = Plan.getEntry();
1048 VPBuilder Builder(Entry, Entry->begin());
1050 ->getIRBasicBlock()
1051 ->getTerminator()
1052 ->getDebugLoc();
1053 VPSCEVExpander Expander(Builder, SE, DL);
1054
1055 // Expand VPExpandSCEVRecipes to VPInstructions using VPSCEVExpander.
1056 for (VPExpandSCEVRecipe &ExpSCEV :
1058 if (ExpSCEV.user_empty())
1059 continue;
1060 Builder.setInsertPoint(&ExpSCEV);
1061 VPValue *Expanded = Expander.expand(ExpSCEV.getSCEV());
1062 ExpSCEV.replaceAllUsesWith(Expanded);
1063 // TripCount should not be used after expansion to VPInstructions. Reset to
1064 // poison to avoid dangling references.
1065 if (Plan.getTripCount() == &ExpSCEV)
1066 Plan.resetTripCount(Plan.getPoison(ExpSCEV.getScalarType()));
1067 ExpSCEV.eraseFromParent();
1068 }
1069}
1070
1073 SCEVExpander Expander(SE, "induction", /*PreserveLCSSA=*/false);
1074
1075 auto *Entry = cast<VPIRBasicBlock>(Plan.getEntry());
1076 BasicBlock *EntryBB = Entry->getIRBasicBlock();
1077 DenseMap<const SCEV *, Value *> ExpandedSCEVs;
1078 // Expand remaining VPExpandSCEVRecipes to IR instructions using SCEVExpander.
1079 for (VPExpandSCEVRecipe &ExpSCEV :
1081 const SCEV *Expr = ExpSCEV.getSCEV();
1082 Value *Res =
1083 Expander.expandCodeFor(Expr, Expr->getType(), EntryBB->getTerminator());
1084 ExpandedSCEVs[Expr] = Res;
1085 VPValue *Exp = Plan.getOrAddLiveIn(Res);
1086 ExpSCEV.replaceAllUsesWith(Exp);
1087 if (Plan.getTripCount() == &ExpSCEV)
1088 Plan.resetTripCount(Exp);
1089 ExpSCEV.eraseFromParent();
1090 }
1092 "all VPExpandSCEVRecipes must have been expanded");
1093 // Add IR instructions in the entry basic block but not in the VPIRBasicBlock
1094 // to the VPIRBasicBlock.
1095 auto EI = Entry->begin();
1096 for (Instruction &I : drop_end(*EntryBB)) {
1097 if (EI != Entry->end() && isa<VPIRInstruction>(*EI) &&
1098 &cast<VPIRInstruction>(&*EI)->getInstruction() == &I) {
1099 EI++;
1100 continue;
1101 }
1103 }
1104
1105 return ExpandedSCEVs;
1106}
1107
1108/// Add branch weight metadata, if the \p Plan's middle block is terminated by a
1109/// BranchOnCond recipe.
1111 VPlan &Plan, ElementCount VF, std::optional<unsigned> VScaleForTuning) {
1112 VPBasicBlock *MiddleVPBB = Plan.getMiddleBlock();
1113 auto *MiddleTerm =
1115 // Only add branch metadata if there is a (conditional) terminator.
1116 if (!MiddleTerm)
1117 return;
1118
1119 assert(MiddleTerm->getOpcode() == VPInstruction::BranchOnCond &&
1120 "must have a BranchOnCond");
1121 // Assume that `TripCount % VectorStep ` is equally distributed.
1122 unsigned VectorStep = Plan.getConcreteUF() * VF.getKnownMinValue();
1123 if (VF.isScalable() && VScaleForTuning.has_value())
1124 VectorStep *= *VScaleForTuning;
1125 assert(VectorStep > 0 && "trip count should not be zero");
1126 MDBuilder MDB(Plan.getContext());
1127 MDNode *BranchWeights =
1128 MDB.createBranchWeights({1, VectorStep - 1}, /*IsExpected=*/false);
1129 MiddleTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
1130}
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
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:1695
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:338
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:1081
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 * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, 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:363
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
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:252
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition VPlan.h:4077
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4429
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4456
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:228
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:607
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:97
VPRegionBlock * getParent()
Definition VPlan.h:195
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:198
VPlan * getPlan()
Definition VPlan.h:199
const std::string & getName() const
Definition VPlan.h:186
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:183
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:235
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:219
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:421
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:348
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:366
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:414
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.
VPWidenPHIRecipe * createWidenPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4210
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
Recipe to expand a SCEV expression.
Definition VPlan.h:4042
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2491
Class to record and manage LLVM IR flags.
Definition VPlan.h:688
static LLVM_ABI_FOR_TEST 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:889
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:1282
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1338
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1654
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:403
VPBasicBlock * getParent()
Definition VPlan.h:475
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:553
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4654
const VPBlockBase * getEntry() const
Definition VPlan.h:4698
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4794
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:848
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4782
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4774
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3412
Lightweight SCEV-to-VPlan expander.
Definition VPlanUtils.h:268
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:4271
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:212
bool isMaterialized() const
Returns true if this value has been materialized.
Definition VPlanValue.h:230
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
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:142
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:136
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:123
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser *U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1458
bool user_empty() const
Definition VPlanValue.h:161
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1452
A Recipe for widening the canonical induction variable of the vector loop.
Definition VPlan.h:4153
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2569
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2586
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2615
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2657
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2686
A recipe for widening vector intrinsics.
Definition VPlan.h:1921
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4841
bool hasVF(ElementCount VF) const
Definition VPlan.h:5077
const DataLayout & getDataLayout() const
Definition VPlan.h:5055
LLVMContext & getContext() const
Definition VPlan.h:5051
VPBasicBlock * getEntry()
Definition VPlan.h:4937
bool hasScalableVF() const
Definition VPlan.h:5078
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5009
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition VPlan.h:5030
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5049
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5187
bool hasUF(unsigned UF) const
Definition VPlan.h:5102
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5178
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5039
VPValue * getBackedgeTakenCount() const
Definition VPlan.h:5036
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:5127
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5153
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1030
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5105
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5023
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4979
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5210
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4942
bool hasScalarVFOnly() const
Definition VPlan.h:5095
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4993
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:4958
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5042
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5283
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:5161
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
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.
VPScalarIVStepsRecipe * createScalarIVSteps(VPlan &Plan, InductionDescriptor::InductionKind Kind, Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, Type *ResultTy, VPValue *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...
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,...
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
VPBuilderBase<> VPBuilder
Definition VPlan.h:67
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
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
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
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:1769
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:323
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:1425
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:2035
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 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 materializeUnpacks(VPlan &Plan)
Add explicit Unpack recipes to extract scalars from vectors as needed.
static void attachVPCheckBlock(VPlan &Plan, VPValue *Cond, VPBasicBlock *CheckBlock, bool AddBranchWeights)
Connect CheckBlock to Plan, branching on Cond.
static void dissolveLoopRegions(VPlan &Plan)
Replace loop regions with explicit CFG.