LLVM 23.0.0git
VPlanRecipes.cpp
Go to the documentation of this file.
1//===- VPlanRecipes.cpp - Implementations for VPlan recipes ---------------===//
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 contains implementations for different VPlan recipes.
11///
12//===----------------------------------------------------------------------===//
13
15#include "VPlan.h"
16#include "VPlanAnalysis.h"
17#include "VPlanHelpers.h"
18#include "VPlanPatternMatch.h"
19#include "VPlanUtils.h"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Twine.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
36#include "llvm/Support/Debug.h"
40#include <cassert>
41
42using namespace llvm;
43using namespace llvm::VPlanPatternMatch;
44
46
47#define LV_NAME "loop-vectorize"
48#define DEBUG_TYPE LV_NAME
49
51 switch (getVPRecipeID()) {
52 case VPExpressionSC:
53 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
54 case VPInstructionSC: {
55 auto *VPI = cast<VPInstruction>(this);
56 // Loads read from memory but don't write to memory.
57 if (VPI->getOpcode() == Instruction::Load)
58 return false;
59 return VPI->opcodeMayReadOrWriteFromMemory();
60 }
61 case VPInterleaveEVLSC:
62 case VPInterleaveSC:
63 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
64 case VPWidenStoreEVLSC:
65 case VPWidenStoreSC:
66 return true;
67 case VPReplicateSC:
68 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
69 ->mayWriteToMemory();
70 case VPWidenCallSC:
71 return !cast<VPWidenCallRecipe>(this)
72 ->getCalledScalarFunction()
73 ->onlyReadsMemory();
74 case VPWidenIntrinsicSC:
75 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
76 case VPActiveLaneMaskPHISC:
77 case VPCanonicalIVPHISC:
78 case VPCurrentIterationPHISC:
79 case VPBranchOnMaskSC:
80 case VPDerivedIVSC:
81 case VPFirstOrderRecurrencePHISC:
82 case VPReductionPHISC:
83 case VPScalarIVStepsSC:
84 case VPPredInstPHISC:
85 return false;
86 case VPBlendSC:
87 case VPReductionEVLSC:
88 case VPReductionSC:
89 case VPVectorPointerSC:
90 case VPWidenCanonicalIVSC:
91 case VPWidenCastSC:
92 case VPWidenGEPSC:
93 case VPWidenIntOrFpInductionSC:
94 case VPWidenLoadEVLSC:
95 case VPWidenLoadSC:
96 case VPWidenPHISC:
97 case VPWidenPointerInductionSC:
98 case VPWidenSC: {
99 const Instruction *I =
100 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
101 (void)I;
102 assert((!I || !I->mayWriteToMemory()) &&
103 "underlying instruction may write to memory");
104 return false;
105 }
106 default:
107 return true;
108 }
109}
110
112 switch (getVPRecipeID()) {
113 case VPExpressionSC:
114 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
115 case VPInstructionSC:
116 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
117 case VPWidenLoadEVLSC:
118 case VPWidenLoadSC:
119 return true;
120 case VPReplicateSC:
121 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
122 ->mayReadFromMemory();
123 case VPWidenCallSC:
124 return !cast<VPWidenCallRecipe>(this)
125 ->getCalledScalarFunction()
126 ->onlyWritesMemory();
127 case VPWidenIntrinsicSC:
128 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
129 case VPBranchOnMaskSC:
130 case VPDerivedIVSC:
131 case VPFirstOrderRecurrencePHISC:
132 case VPReductionPHISC:
133 case VPPredInstPHISC:
134 case VPScalarIVStepsSC:
135 case VPWidenStoreEVLSC:
136 case VPWidenStoreSC:
137 return false;
138 case VPBlendSC:
139 case VPReductionEVLSC:
140 case VPReductionSC:
141 case VPVectorPointerSC:
142 case VPWidenCanonicalIVSC:
143 case VPWidenCastSC:
144 case VPWidenGEPSC:
145 case VPWidenIntOrFpInductionSC:
146 case VPWidenPHISC:
147 case VPWidenPointerInductionSC:
148 case VPWidenSC: {
149 const Instruction *I =
150 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
151 (void)I;
152 assert((!I || !I->mayReadFromMemory()) &&
153 "underlying instruction may read from memory");
154 return false;
155 }
156 default:
157 // FIXME: Return false if the recipe represents an interleaved store.
158 return true;
159 }
160}
161
163 switch (getVPRecipeID()) {
164 case VPExpressionSC:
165 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
166 case VPActiveLaneMaskPHISC:
167 case VPDerivedIVSC:
168 case VPFirstOrderRecurrencePHISC:
169 case VPReductionPHISC:
170 case VPPredInstPHISC:
171 case VPVectorEndPointerSC:
172 return false;
173 case VPInstructionSC: {
174 auto *VPI = cast<VPInstruction>(this);
175 return mayWriteToMemory() ||
176 VPI->getOpcode() == VPInstruction::BranchOnCount ||
177 VPI->getOpcode() == VPInstruction::BranchOnCond ||
178 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
179 }
180 case VPWidenCallSC: {
181 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
182 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
183 }
184 case VPWidenIntrinsicSC:
185 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
186 case VPBlendSC:
187 case VPReductionEVLSC:
188 case VPReductionSC:
189 case VPScalarIVStepsSC:
190 case VPVectorPointerSC:
191 case VPWidenCanonicalIVSC:
192 case VPWidenCastSC:
193 case VPWidenGEPSC:
194 case VPWidenIntOrFpInductionSC:
195 case VPWidenPHISC:
196 case VPWidenPointerInductionSC:
197 case VPWidenSC: {
198 const Instruction *I =
199 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
200 (void)I;
201 assert((!I || !I->mayHaveSideEffects()) &&
202 "underlying instruction has side-effects");
203 return false;
204 }
205 case VPInterleaveEVLSC:
206 case VPInterleaveSC:
207 return mayWriteToMemory();
208 case VPWidenLoadEVLSC:
209 case VPWidenLoadSC:
210 case VPWidenStoreEVLSC:
211 case VPWidenStoreSC:
212 assert(
213 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
215 "mayHaveSideffects result for ingredient differs from this "
216 "implementation");
217 return mayWriteToMemory();
218 case VPReplicateSC: {
219 auto *R = cast<VPReplicateRecipe>(this);
220 return R->getUnderlyingInstr()->mayHaveSideEffects();
221 }
222 default:
223 return true;
224 }
225}
226
228 assert(!Parent && "Recipe already in some VPBasicBlock");
229 assert(InsertPos->getParent() &&
230 "Insertion position not in any VPBasicBlock");
231 InsertPos->getParent()->insert(this, InsertPos->getIterator());
232}
233
234void VPRecipeBase::insertBefore(VPBasicBlock &BB,
236 assert(!Parent && "Recipe already in some VPBasicBlock");
237 assert(I == BB.end() || I->getParent() == &BB);
238 BB.insert(this, I);
239}
240
242 assert(!Parent && "Recipe already in some VPBasicBlock");
243 assert(InsertPos->getParent() &&
244 "Insertion position not in any VPBasicBlock");
245 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
246}
247
249 assert(getParent() && "Recipe not in any VPBasicBlock");
251 Parent = nullptr;
252}
253
255 assert(getParent() && "Recipe not in any VPBasicBlock");
257}
258
261 insertAfter(InsertPos);
262}
263
269
271 // Get the underlying instruction for the recipe, if there is one. It is used
272 // to
273 // * decide if cost computation should be skipped for this recipe,
274 // * apply forced target instruction cost.
275 Instruction *UI = nullptr;
276 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
277 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
278 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
279 UI = IG->getInsertPos();
280 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
281 UI = &WidenMem->getIngredient();
282
283 InstructionCost RecipeCost;
284 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
285 RecipeCost = 0;
286 } else {
287 RecipeCost = computeCost(VF, Ctx);
288 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
289 RecipeCost.isValid()) {
290 if (UI)
292 else
293 RecipeCost = InstructionCost(0);
294 }
295 }
296
297 LLVM_DEBUG({
298 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
299 dump();
300 });
301 return RecipeCost;
302}
303
305 VPCostContext &Ctx) const {
306 llvm_unreachable("subclasses should implement computeCost");
307}
308
310 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
312}
313
315 auto *VPI = dyn_cast<VPInstruction>(this);
316 return VPI && Instruction::isCast(VPI->getOpcode());
317}
318
320 assert(OpType == Other.OpType && "OpType must match");
321 switch (OpType) {
322 case OperationType::OverflowingBinOp:
323 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
324 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
325 break;
326 case OperationType::Trunc:
327 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
328 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
329 break;
330 case OperationType::DisjointOp:
331 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
332 break;
333 case OperationType::PossiblyExactOp:
334 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
335 break;
336 case OperationType::GEPOp:
337 GEPFlagsStorage &= Other.GEPFlagsStorage;
338 break;
339 case OperationType::FPMathOp:
340 case OperationType::FCmp:
341 assert((OpType != OperationType::FCmp ||
342 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
343 "Cannot drop CmpPredicate");
344 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
345 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
346 break;
347 case OperationType::NonNegOp:
348 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
349 break;
350 case OperationType::Cmp:
351 assert(CmpPredStorage == Other.CmpPredStorage &&
352 "Cannot drop CmpPredicate");
353 break;
354 case OperationType::ReductionOp:
355 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
356 "Cannot change RecurKind");
357 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
358 "Cannot change IsOrdered");
359 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
360 "Cannot change IsInLoop");
361 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
362 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
363 break;
364 case OperationType::Other:
365 break;
366 }
367}
368
370 assert((OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
371 OpType == OperationType::ReductionOp ||
372 OpType == OperationType::Other) &&
373 "recipe doesn't have fast math flags");
374 if (OpType == OperationType::Other)
375 return FastMathFlags();
376 const FastMathFlagsTy &F = getFMFsRef();
377 FastMathFlags Res;
378 Res.setAllowReassoc(F.AllowReassoc);
379 Res.setNoNaNs(F.NoNaNs);
380 Res.setNoInfs(F.NoInfs);
381 Res.setNoSignedZeros(F.NoSignedZeros);
382 Res.setAllowReciprocal(F.AllowReciprocal);
383 Res.setAllowContract(F.AllowContract);
384 Res.setApproxFunc(F.ApproxFunc);
385 return Res;
386}
387
388#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
390
391void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
392 VPSlotTracker &SlotTracker) const {
393 printRecipe(O, Indent, SlotTracker);
394 if (auto DL = getDebugLoc()) {
395 O << ", !dbg ";
396 DL.print(O);
397 }
398
399 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
401}
402#endif
403
404template <unsigned PartOpIdx>
405VPValue *
407 if (U.getNumOperands() == PartOpIdx + 1)
408 return U.getOperand(PartOpIdx);
409 return nullptr;
410}
411
412template <unsigned PartOpIdx>
414 if (auto *UnrollPartOp = getUnrollPartOperand(U))
415 return cast<VPConstantInt>(UnrollPartOp)->getZExtValue();
416 return 0;
417}
418
419namespace llvm {
420template class VPUnrollPartAccessor<1>;
421template class VPUnrollPartAccessor<2>;
422template class VPUnrollPartAccessor<3>;
423}
424
426 const VPIRFlags &Flags, const VPIRMetadata &MD,
427 DebugLoc DL, const Twine &Name)
428 : VPRecipeWithIRFlags(VPRecipeBase::VPInstructionSC, Operands, Flags, DL),
429 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
431 "Set flags not supported for the provided opcode");
433 "Opcode requires specific flags to be set");
437 "number of operands does not match opcode");
438}
439
441 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
442 return 1;
443
444 if (Instruction::isBinaryOp(Opcode))
445 return 2;
446
447 switch (Opcode) {
450 return 0;
451 case Instruction::Alloca:
452 case Instruction::ExtractValue:
453 case Instruction::Freeze:
454 case Instruction::Load:
467 return 1;
468 case Instruction::ICmp:
469 case Instruction::FCmp:
470 case Instruction::ExtractElement:
471 case Instruction::Store:
481 return 2;
482 case Instruction::Select:
485 return 3;
486 case Instruction::Call: {
487 // For unmasked calls, the last argument will the called function. Use that
488 // to compute the number of operands without the mask.
489 VPValue *LastOp = getOperand(getNumOperands() - 1);
490 if (isa<VPIRValue>(LastOp) && isa<Function>(LastOp->getLiveInIRValue()))
491 return getNumOperands();
492 return getNumOperands() - 1;
493 }
494 case Instruction::GetElementPtr:
495 case Instruction::PHI:
496 case Instruction::Switch:
509 // Cannot determine the number of operands from the opcode.
510 return -1u;
511 }
512 llvm_unreachable("all cases should be handled above");
513}
514
518
519bool VPInstruction::canGenerateScalarForFirstLane() const {
521 return true;
523 return true;
524 switch (Opcode) {
525 case Instruction::Freeze:
526 case Instruction::ICmp:
527 case Instruction::PHI:
528 case Instruction::Select:
538 return true;
539 default:
540 return false;
541 }
542}
543
544Value *VPInstruction::generate(VPTransformState &State) {
545 IRBuilderBase &Builder = State.Builder;
546
548 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
549 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
550 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
551 auto *Res =
552 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
553 if (auto *I = dyn_cast<Instruction>(Res))
554 applyFlags(*I);
555 return Res;
556 }
557
558 switch (getOpcode()) {
559 case VPInstruction::Not: {
560 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
561 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
562 return Builder.CreateNot(A, Name);
563 }
564 case Instruction::ExtractElement: {
565 assert(State.VF.isVector() && "Only extract elements from vectors");
566 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
567 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
568 Value *Vec = State.get(getOperand(0));
569 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
570 return Builder.CreateExtractElement(Vec, Idx, Name);
571 }
572 case Instruction::Freeze: {
574 return Builder.CreateFreeze(Op, Name);
575 }
576 case Instruction::FCmp:
577 case Instruction::ICmp: {
578 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
579 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
580 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
581 return Builder.CreateCmp(getPredicate(), A, B, Name);
582 }
583 case Instruction::PHI: {
584 llvm_unreachable("should be handled by VPPhi::execute");
585 }
586 case Instruction::Select: {
587 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
588 Value *Cond =
589 State.get(getOperand(0),
590 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
591 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
592 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
593 return Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlags(), Name);
594 }
596 // Get first lane of vector induction variable.
597 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
598 // Get the original loop tripcount.
599 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
600
601 // If this part of the active lane mask is scalar, generate the CMP directly
602 // to avoid unnecessary extracts.
603 if (State.VF.isScalar())
604 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
605 Name);
606
607 ElementCount EC = State.VF.multiplyCoefficientBy(
608 cast<VPConstantInt>(getOperand(2))->getZExtValue());
609 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
610 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
611 {PredTy, ScalarTC->getType()},
612 {VIVElem0, ScalarTC}, nullptr, Name);
613 }
615 // Generate code to combine the previous and current values in vector v3.
616 //
617 // vector.ph:
618 // v_init = vector(..., ..., ..., a[-1])
619 // br vector.body
620 //
621 // vector.body
622 // i = phi [0, vector.ph], [i+4, vector.body]
623 // v1 = phi [v_init, vector.ph], [v2, vector.body]
624 // v2 = a[i, i+1, i+2, i+3];
625 // v3 = vector(v1(3), v2(0, 1, 2))
626
627 auto *V1 = State.get(getOperand(0));
628 if (!V1->getType()->isVectorTy())
629 return V1;
630 Value *V2 = State.get(getOperand(1));
631 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
632 }
634 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
635 Value *VFxUF = State.get(getOperand(1), VPLane(0));
636 Value *Sub = Builder.CreateSub(ScalarTC, VFxUF);
637 Value *Cmp =
638 Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, VFxUF);
640 return Builder.CreateSelect(Cmp, Sub, Zero);
641 }
643 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
644 // be outside of the main loop.
645 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
646 // Compute EVL
647 assert(AVL->getType()->isIntegerTy() &&
648 "Requested vector length should be an integer.");
649
650 assert(State.VF.isScalable() && "Expected scalable vector factor.");
651 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
652
653 Value *EVL = Builder.CreateIntrinsic(
654 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
655 {AVL, VFArg, Builder.getTrue()});
656 return EVL;
657 }
659 auto *IV = State.get(getOperand(0), VPLane(0));
660 auto *VFxPart = State.get(getOperand(1), VPLane(0));
661 // The canonical IV is incremented by the vectorization factor (num of
662 // SIMD elements) times the unroll part.
663 return Builder.CreateAdd(IV, VFxPart, Name, hasNoUnsignedWrap(),
665 }
667 Value *Cond = State.get(getOperand(0), VPLane(0));
668 // Replace the temporary unreachable terminator with a new conditional
669 // branch, hooking it up to backward destination for latch blocks now, and
670 // to forward destination(s) later when they are created.
671 // Second successor may be backwards - iff it is already in VPBB2IRBB.
672 VPBasicBlock *SecondVPSucc =
673 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
674 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
675 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
676 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
677 // First successor is always forward, reset it to nullptr.
678 Br->setSuccessor(0, nullptr);
680 applyMetadata(*Br);
681 return Br;
682 }
684 return Builder.CreateVectorSplat(
685 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
686 }
688 // For struct types, we need to build a new 'wide' struct type, where each
689 // element is widened, i.e., we create a struct of vectors.
690 auto *StructTy =
692 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
693 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
694 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
695 FieldIndex++) {
696 Value *ScalarValue =
697 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
698 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
699 VectorValue =
700 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
701 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
702 }
703 }
704 return Res;
705 }
707 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
708 auto NumOfElements = ElementCount::getFixed(getNumOperands());
709 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
710 for (const auto &[Idx, Op] : enumerate(operands()))
711 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
712 Builder.getInt32(Idx));
713 return Res;
714 }
716 if (State.VF.isScalar())
717 return State.get(getOperand(0), true);
718 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
720 // If this start vector is scaled then it should produce a vector with fewer
721 // elements than the VF.
722 ElementCount VF = State.VF.divideCoefficientBy(
723 cast<VPConstantInt>(getOperand(2))->getZExtValue());
724 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
725 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
726 Builder.getInt32(0));
727 }
729 Value *Start = State.get(getOperand(0), VPLane(0));
730 Value *NewVal = State.get(getOperand(1), VPLane(0));
731 Value *ReducedResult = State.get(getOperand(2));
732 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
733 ReducedResult =
734 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
735 ReducedResult, "bin.rdx");
736 // If any predicate is true it means that we want to select the new value.
737 if (ReducedResult->getType()->isVectorTy())
738 ReducedResult = Builder.CreateOrReduce(ReducedResult);
739 // The compares in the loop may yield poison, which propagates through the
740 // bitwise ORs. Freeze it here before the condition is used.
741 ReducedResult = Builder.CreateFreeze(ReducedResult);
742 return Builder.CreateSelect(ReducedResult, NewVal, Start, "rdx.select");
743 }
745 RecurKind RK = getRecurKind();
746 bool IsOrdered = isReductionOrdered();
747 bool IsInLoop = isReductionInLoop();
749 "FindIV should use min/max reduction kinds");
750
751 // The recipe may have multiple operands to be reduced together.
752 unsigned NumOperandsToReduce = getNumOperands();
753 VectorParts RdxParts(NumOperandsToReduce);
754 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
755 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
756
757 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
759
760 // Reduce multiple operands into one.
761 Value *ReducedPartRdx = RdxParts[0];
762 if (IsOrdered) {
763 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
764 } else {
765 // Floating-point operations should have some FMF to enable the reduction.
766 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
767 Value *RdxPart = RdxParts[Part];
769 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
770 else {
771 // For sub-recurrences, each part's reduction variable is already
772 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
774 RK == RecurKind::Sub
775 ? Instruction::Add
777 ReducedPartRdx =
778 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
779 }
780 }
781 }
782
783 // Create the reduction after the loop. Note that inloop reductions create
784 // the target reduction in the loop using a Reduction recipe.
785 if (State.VF.isVector() && !IsInLoop) {
786 // TODO: Support in-order reductions based on the recurrence descriptor.
787 // All ops in the reduction inherit fast-math-flags from the recurrence
788 // descriptor.
789 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
790 }
791
792 return ReducedPartRdx;
793 }
796 unsigned Offset =
798 Value *Res;
799 if (State.VF.isVector()) {
800 assert(Offset <= State.VF.getKnownMinValue() &&
801 "invalid offset to extract from");
802 // Extract lane VF - Offset from the operand.
803 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
804 } else {
805 // TODO: Remove ExtractLastLane for scalar VFs.
806 assert(Offset <= 1 && "invalid offset to extract from");
807 Res = State.get(getOperand(0));
808 }
810 Res->setName(Name);
811 return Res;
812 }
814 Value *A = State.get(getOperand(0));
815 Value *B = State.get(getOperand(1));
816 return Builder.CreateLogicalAnd(A, B, Name);
817 }
819 Value *A = State.get(getOperand(0));
820 Value *B = State.get(getOperand(1));
821 return Builder.CreateLogicalOr(A, B, Name);
822 }
824 assert((State.VF.isScalar() || vputils::onlyFirstLaneUsed(this)) &&
825 "can only generate first lane for PtrAdd");
826 Value *Ptr = State.get(getOperand(0), VPLane(0));
827 Value *Addend = State.get(getOperand(1), VPLane(0));
828 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
829 }
831 Value *Ptr =
833 Value *Addend = State.get(getOperand(1));
834 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
835 }
837 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
838 for (VPValue *Op : drop_begin(operands()))
839 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
840 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
841 }
843 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
844 "simplified to ExtractElement.");
845 Value *LaneToExtract = State.get(getOperand(0), true);
846 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
847 Value *Res = nullptr;
848 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
849
850 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
851 Value *VectorStart =
852 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
853 Value *VectorIdx = Idx == 1
854 ? LaneToExtract
855 : Builder.CreateSub(LaneToExtract, VectorStart);
856 Value *Ext = State.VF.isScalar()
857 ? State.get(getOperand(Idx))
858 : Builder.CreateExtractElement(
859 State.get(getOperand(Idx)), VectorIdx);
860 if (Res) {
861 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
862 Res = Builder.CreateSelect(Cmp, Ext, Res);
863 } else {
864 Res = Ext;
865 }
866 }
867 return Res;
868 }
870 if (getNumOperands() == 1) {
871 Value *Mask = State.get(getOperand(0));
872 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
873 /*ZeroIsPoison=*/false, Name);
874 }
875 // If there are multiple operands, create a chain of selects to pick the
876 // first operand with an active lane and add the number of lanes of the
877 // preceding operands.
878 Value *RuntimeVF = getRuntimeVF(Builder, Builder.getInt64Ty(), State.VF);
879 unsigned LastOpIdx = getNumOperands() - 1;
880 Value *Res = nullptr;
881 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
882 Value *TrailingZeros =
883 State.VF.isScalar()
884 ? Builder.CreateZExt(
885 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
886 Builder.getFalse()),
887 Builder.getInt64Ty())
889 Builder.getInt64Ty(), State.get(getOperand(Idx)),
890 /*ZeroIsPoison=*/false, Name);
891 Value *Current = Builder.CreateAdd(
892 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
893 if (Res) {
894 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
895 Res = Builder.CreateSelect(Cmp, Current, Res);
896 } else {
897 Res = Current;
898 }
899 }
900
901 return Res;
902 }
904 return State.get(getOperand(0), true);
906 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
908 Value *Result = State.get(getOperand(0), /*IsScalar=*/true);
909 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
910 Value *Data = State.get(getOperand(Idx));
911 Value *Mask = State.get(getOperand(Idx + 1));
912 Type *VTy = Data->getType();
913
914 if (State.VF.isScalar())
915 Result = Builder.CreateSelect(Mask, Data, Result);
916 else
917 Result = Builder.CreateIntrinsic(
918 Intrinsic::experimental_vector_extract_last_active, {VTy},
919 {Data, Mask, Result});
920 }
921
922 return Result;
923 }
924 default:
925 llvm_unreachable("Unsupported opcode for instruction");
926 }
927}
928
930 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
931 Type *ScalarTy = Ctx.Types.inferScalarType(this);
932 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
933 switch (Opcode) {
934 case Instruction::FNeg:
935 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
936 case Instruction::UDiv:
937 case Instruction::SDiv:
938 case Instruction::SRem:
939 case Instruction::URem:
940 case Instruction::Add:
941 case Instruction::FAdd:
942 case Instruction::Sub:
943 case Instruction::FSub:
944 case Instruction::Mul:
945 case Instruction::FMul:
946 case Instruction::FDiv:
947 case Instruction::FRem:
948 case Instruction::Shl:
949 case Instruction::LShr:
950 case Instruction::AShr:
951 case Instruction::And:
952 case Instruction::Or:
953 case Instruction::Xor: {
956
957 if (VF.isVector()) {
958 // Certain instructions can be cheaper to vectorize if they have a
959 // constant second vector operand. One example of this are shifts on x86.
960 VPValue *RHS = getOperand(1);
961 RHSInfo = Ctx.getOperandInfo(RHS);
962
963 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
966 }
967
970 if (CtxI)
971 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
972 return Ctx.TTI.getArithmeticInstrCost(
973 Opcode, ResultTy, Ctx.CostKind,
974 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
975 RHSInfo, Operands, CtxI, &Ctx.TLI);
976 }
977 case Instruction::Freeze:
978 // This opcode is unknown. Assume that it is the same as 'mul'.
979 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
980 Ctx.CostKind);
981 case Instruction::ExtractValue:
982 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
983 Ctx.CostKind);
984 case Instruction::ICmp:
985 case Instruction::FCmp: {
986 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
987 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
989 return Ctx.TTI.getCmpSelInstrCost(
990 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
991 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
992 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
993 }
994 case Instruction::BitCast: {
995 Type *ScalarTy = Ctx.Types.inferScalarType(this);
996 if (ScalarTy->isPointerTy())
997 return 0;
998 [[fallthrough]];
999 }
1000 case Instruction::SExt:
1001 case Instruction::ZExt:
1002 case Instruction::FPToUI:
1003 case Instruction::FPToSI:
1004 case Instruction::FPExt:
1005 case Instruction::PtrToInt:
1006 case Instruction::PtrToAddr:
1007 case Instruction::IntToPtr:
1008 case Instruction::SIToFP:
1009 case Instruction::UIToFP:
1010 case Instruction::Trunc:
1011 case Instruction::FPTrunc:
1012 case Instruction::AddrSpaceCast: {
1013 // Computes the CastContextHint from a recipe that may access memory.
1014 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1015 if (isa<VPInterleaveBase>(R))
1017 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1018 // Only compute CCH for memory operations, matching the legacy model
1019 // which only considers loads/stores for cast context hints.
1020 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1021 if (!isa<LoadInst, StoreInst>(UI))
1023 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1025 }
1026 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1027 if (WidenMemoryRecipe == nullptr)
1029 if (VF.isScalar())
1031 if (!WidenMemoryRecipe->isConsecutive())
1033 if (WidenMemoryRecipe->isReverse())
1035 if (WidenMemoryRecipe->isMasked())
1038 };
1039
1040 VPValue *Operand = getOperand(0);
1042 // For Trunc/FPTrunc, get the context from the only user.
1043 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1044 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
1045 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
1046 return nullptr;
1047 return dyn_cast<VPRecipeBase>(*R->user_begin());
1048 };
1049 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
1050 if (match(Recipe, m_Reverse(m_VPValue())))
1051 Recipe = GetOnlyUser(cast<VPInstruction>(Recipe));
1052 if (Recipe)
1053 CCH = ComputeCCH(Recipe);
1054 }
1055 }
1056 // For Z/Sext, get the context from the operand.
1057 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1058 Opcode == Instruction::FPExt) {
1059 if (auto *Recipe = Operand->getDefiningRecipe()) {
1060 VPValue *ReverseOp;
1061 if (match(Recipe, m_Reverse(m_VPValue(ReverseOp))))
1062 Recipe = ReverseOp->getDefiningRecipe();
1063 if (Recipe)
1064 CCH = ComputeCCH(Recipe);
1065 }
1066 }
1067
1068 auto *ScalarSrcTy = Ctx.Types.inferScalarType(Operand);
1069 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1070 // Arm TTI will use the underlying instruction to determine the cost.
1071 return Ctx.TTI.getCastInstrCost(
1072 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1074 }
1075 case Instruction::Select: {
1077 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1078 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1079
1080 VPValue *Op0, *Op1;
1081 bool IsLogicalAnd =
1082 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1083 bool IsLogicalOr =
1084 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1085 // Also match the inverted forms:
1086 // select x, false, y --> !x & y (still AND)
1087 // select x, y, true --> !x | y (still OR)
1088 IsLogicalAnd |=
1089 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1090 IsLogicalOr |=
1091 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1092
1093 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1094 (IsLogicalAnd || IsLogicalOr)) {
1095 // select x, y, false --> x & y
1096 // select x, true, y --> x | y
1097 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1098 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1099
1101 if (SI && all_of(operands(),
1102 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1103 append_range(Operands, SI->operands());
1104 return Ctx.TTI.getArithmeticInstrCost(
1105 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1106 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1107 }
1108
1109 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1110 if (!IsScalarCond)
1111 CondTy = VectorType::get(CondTy, VF);
1112
1113 llvm::CmpPredicate Pred;
1114 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1115 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1116 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1117 Pred = Cmp->getPredicate();
1118 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1119 return Ctx.TTI.getCmpSelInstrCost(
1120 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1121 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1122 }
1123 }
1124 llvm_unreachable("called for unsupported opcode");
1125}
1126
1128 VPCostContext &Ctx) const {
1130 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1131 // TODO: Compute cost for VPInstructions without underlying values once
1132 // the legacy cost model has been retired.
1133 return 0;
1134 }
1135
1137 "Should only generate a vector value or single scalar, not scalars "
1138 "for all lanes.");
1140 getOpcode(),
1142 }
1143
1144 switch (getOpcode()) {
1145 case Instruction::Select: {
1147 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1148 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1149 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1150 if (!vputils::onlyFirstLaneUsed(this)) {
1151 CondTy = toVectorTy(CondTy, VF);
1152 VecTy = toVectorTy(VecTy, VF);
1153 }
1154 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1155 Ctx.CostKind);
1156 }
1157 case Instruction::ExtractElement:
1159 if (VF.isScalar()) {
1160 // ExtractLane with VF=1 takes care of handling extracting across multiple
1161 // parts.
1162 return 0;
1163 }
1164
1165 // Add on the cost of extracting the element.
1166 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1167 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1168 Ctx.CostKind);
1169 }
1170 case VPInstruction::AnyOf: {
1171 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1173 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1174 }
1176 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1177 if (VF.isScalar())
1178 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1181 // Calculate the cost of determining the lane index.
1182 auto *PredTy = toVectorTy(ScalarTy, VF);
1183 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1185 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1186 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1187 }
1189 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1190 if (VF.isScalar())
1191 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1194 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1195 auto *PredTy = toVectorTy(ScalarTy, VF);
1196 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1198 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1200 // Add cost of NOT operation on the predicate.
1202 Instruction::Xor, PredTy, Ctx.CostKind,
1203 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1204 {TargetTransformInfo::OK_UniformConstantValue,
1205 TargetTransformInfo::OP_None});
1206 // Add cost of SUB operation on the index.
1208 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1209 return Cost;
1210 }
1212 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1213 Type *VecTy = toVectorTy(ScalarTy, VF);
1214 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1215 IntrinsicCostAttributes ICA(
1216 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1217 {VecTy, MaskTy, ScalarTy});
1218 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1219 }
1221 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1222 SmallVector<int> Mask(VF.getKnownMinValue());
1223 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1224 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1225
1227 cast<VectorType>(VectorTy),
1228 cast<VectorType>(VectorTy), Mask,
1229 Ctx.CostKind, VF.getKnownMinValue() - 1);
1230 }
1232 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1233 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1234 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1235 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1236 {ArgTy, ArgTy});
1237 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1238 }
1240 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1241 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1242 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1243 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1244 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1245 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1246 }
1248 assert(VF.isVector() && "Reverse operation must be vector type");
1249 auto *VectorTy = cast<VectorType>(
1252 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1253 /*Index=*/0);
1254 }
1256 // Add on the cost of extracting the element.
1257 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1258 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1259 VecTy, Ctx.CostKind, 0);
1260 }
1262 if (VF == ElementCount::getScalable(1))
1264 [[fallthrough]];
1265 default:
1266 // TODO: Compute cost other VPInstructions once the legacy cost model has
1267 // been retired.
1269 "unexpected VPInstruction witht underlying value");
1270 return 0;
1271 }
1272}
1273
1286
1288 switch (getOpcode()) {
1289 case Instruction::Load:
1290 case Instruction::PHI:
1294 return true;
1295 default:
1296 return isScalarCast();
1297 }
1298}
1299
1301 assert(!isMasked() && "cannot execute masked VPInstruction");
1302 assert(!State.Lane && "VPInstruction executing an Lane");
1303 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1305 "Set flags not supported for the provided opcode");
1307 "Opcode requires specific flags to be set");
1308 if (hasFastMathFlags())
1309 State.Builder.setFastMathFlags(getFastMathFlags());
1310 Value *GeneratedValue = generate(State);
1311 if (!hasResult())
1312 return;
1313 assert(GeneratedValue && "generate must produce a value");
1314 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1317 assert((((GeneratedValue->getType()->isVectorTy() ||
1318 GeneratedValue->getType()->isStructTy()) ==
1319 !GeneratesPerFirstLaneOnly) ||
1320 State.VF.isScalar()) &&
1321 "scalar value but not only first lane defined");
1322 State.set(this, GeneratedValue,
1323 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1324}
1325
1328 return false;
1329 switch (getOpcode()) {
1330 case Instruction::GetElementPtr:
1331 case Instruction::ExtractElement:
1332 case Instruction::Freeze:
1333 case Instruction::FCmp:
1334 case Instruction::ICmp:
1335 case Instruction::Select:
1336 case Instruction::PHI:
1360 case VPInstruction::Not:
1369 return false;
1370 default:
1371 return true;
1372 }
1373}
1374
1376 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1378 return vputils::onlyFirstLaneUsed(this);
1379
1380 switch (getOpcode()) {
1381 default:
1382 return false;
1383 case Instruction::ExtractElement:
1384 return Op == getOperand(1);
1385 case Instruction::PHI:
1386 return true;
1387 case Instruction::FCmp:
1388 case Instruction::ICmp:
1389 case Instruction::Select:
1390 case Instruction::Or:
1391 case Instruction::Freeze:
1392 case VPInstruction::Not:
1393 // TODO: Cover additional opcodes.
1394 return vputils::onlyFirstLaneUsed(this);
1395 case Instruction::Load:
1404 return true;
1407 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1408 // operand, after replicating its operands only the first lane is used.
1409 // Before replicating, it will have only a single operand.
1410 return getNumOperands() > 1;
1412 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1414 // WidePtrAdd supports scalar and vector base addresses.
1415 return false;
1417 return Op == getOperand(0) || Op == getOperand(1);
1420 return Op == getOperand(0);
1421 };
1422 llvm_unreachable("switch should return");
1423}
1424
1426 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1428 return vputils::onlyFirstPartUsed(this);
1429
1430 switch (getOpcode()) {
1431 default:
1432 return false;
1433 case Instruction::FCmp:
1434 case Instruction::ICmp:
1435 case Instruction::Select:
1436 return vputils::onlyFirstPartUsed(this);
1441 return true;
1442 };
1443 llvm_unreachable("switch should return");
1444}
1445
1446#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1448 VPSlotTracker SlotTracker(getParent()->getPlan());
1450}
1451
1453 VPSlotTracker &SlotTracker) const {
1454 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1455
1456 if (hasResult()) {
1458 O << " = ";
1459 }
1460
1461 switch (getOpcode()) {
1462 case VPInstruction::Not:
1463 O << "not";
1464 break;
1466 O << "combined load";
1467 break;
1469 O << "combined store";
1470 break;
1472 O << "active lane mask";
1473 break;
1475 O << "EXPLICIT-VECTOR-LENGTH";
1476 break;
1478 O << "first-order splice";
1479 break;
1481 O << "branch-on-cond";
1482 break;
1484 O << "branch-on-two-conds";
1485 break;
1487 O << "TC > VF ? TC - VF : 0";
1488 break;
1490 O << "VF * Part +";
1491 break;
1493 O << "branch-on-count";
1494 break;
1496 O << "broadcast";
1497 break;
1499 O << "buildstructvector";
1500 break;
1502 O << "buildvector";
1503 break;
1505 O << "exiting-iv-value";
1506 break;
1508 O << "masked-cond";
1509 break;
1511 O << "extract-lane";
1512 break;
1514 O << "extract-last-lane";
1515 break;
1517 O << "extract-last-part";
1518 break;
1520 O << "extract-penultimate-element";
1521 break;
1523 O << "compute-anyof-result";
1524 break;
1526 O << "compute-reduction-result";
1527 break;
1529 O << "logical-and";
1530 break;
1532 O << "logical-or";
1533 break;
1535 O << "ptradd";
1536 break;
1538 O << "wide-ptradd";
1539 break;
1541 O << "any-of";
1542 break;
1544 O << "first-active-lane";
1545 break;
1547 O << "last-active-lane";
1548 break;
1550 O << "reduction-start-vector";
1551 break;
1553 O << "resume-for-epilogue";
1554 break;
1556 O << "reverse";
1557 break;
1559 O << "unpack";
1560 break;
1562 O << "extract-last-active";
1563 break;
1564 default:
1566 }
1567
1568 printFlags(O);
1570}
1571#endif
1572
1574 State.setDebugLocFrom(getDebugLoc());
1575 if (isScalarCast()) {
1576 Value *Op = State.get(getOperand(0), VPLane(0));
1577 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1578 Op, ResultTy);
1579 State.set(this, Cast, VPLane(0));
1580 return;
1581 }
1582 switch (getOpcode()) {
1584 Value *StepVector =
1585 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1586 State.set(this, StepVector);
1587 break;
1588 }
1589 case VPInstruction::VScale: {
1590 Value *VScale = State.Builder.CreateVScale(ResultTy);
1591 State.set(this, VScale, true);
1592 break;
1593 }
1594
1595 default:
1596 llvm_unreachable("opcode not implemented yet");
1597 }
1598}
1599
1600#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1602 VPSlotTracker &SlotTracker) const {
1603 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1605 O << " = ";
1606
1607 switch (getOpcode()) {
1609 O << "wide-iv-step ";
1611 break;
1613 O << "step-vector " << *ResultTy;
1614 break;
1616 O << "vscale " << *ResultTy;
1617 break;
1618 case Instruction::Load:
1619 O << "load ";
1621 break;
1622 default:
1623 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1626 O << " to " << *ResultTy;
1627 }
1628}
1629#endif
1630
1632 State.setDebugLocFrom(getDebugLoc());
1633 PHINode *NewPhi = State.Builder.CreatePHI(
1634 State.TypeAnalysis.inferScalarType(this), 2, getName());
1635 unsigned NumIncoming = getNumIncoming();
1636 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1637 // TODO: Fixup all incoming values of header phis once recipes defining them
1638 // are introduced.
1639 NumIncoming = 1;
1640 }
1641 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1642 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1643 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1644 NewPhi->addIncoming(IncV, PredBB);
1645 }
1646 State.set(this, NewPhi, VPLane(0));
1647}
1648
1649#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1650void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1651 VPSlotTracker &SlotTracker) const {
1652 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1654 O << " = phi";
1655 printFlags(O);
1657}
1658#endif
1659
1660VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1661 if (auto *Phi = dyn_cast<PHINode>(&I))
1662 return new VPIRPhi(*Phi);
1663 return new VPIRInstruction(I);
1664}
1665
1667 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1668 "PHINodes must be handled by VPIRPhi");
1669 // Advance the insert point after the wrapped IR instruction. This allows
1670 // interleaving VPIRInstructions and other recipes.
1671 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1672}
1673
1675 VPCostContext &Ctx) const {
1676 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1677 // hence it does not contribute to the cost-modeling for the VPlan.
1678 return 0;
1679}
1680
1681#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1683 VPSlotTracker &SlotTracker) const {
1684 O << Indent << "IR " << I;
1685}
1686#endif
1687
1689 PHINode *Phi = &getIRPhi();
1690 for (const auto &[Idx, Op] : enumerate(operands())) {
1691 VPValue *ExitValue = Op;
1692 auto Lane = vputils::isSingleScalar(ExitValue)
1694 : VPLane::getLastLaneForVF(State.VF);
1695 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1696 auto *PredVPBB = Pred->getExitingBasicBlock();
1697 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1698 // Set insertion point in PredBB in case an extract needs to be generated.
1699 // TODO: Model extracts explicitly.
1700 State.Builder.SetInsertPoint(PredBB->getTerminator());
1701 Value *V = State.get(ExitValue, VPLane(Lane));
1702 // If there is no existing block for PredBB in the phi, add a new incoming
1703 // value. Otherwise update the existing incoming value for PredBB.
1704 if (Phi->getBasicBlockIndex(PredBB) == -1)
1705 Phi->addIncoming(V, PredBB);
1706 else
1707 Phi->setIncomingValueForBlock(PredBB, V);
1708 }
1709
1710 // Advance the insert point after the wrapped IR instruction. This allows
1711 // interleaving VPIRInstructions and other recipes.
1712 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1713}
1714
1716 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1717 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1718 "Number of phi operands must match number of predecessors");
1719 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1720 R->removeOperand(Position);
1721}
1722
1723VPValue *
1725 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1726 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
1727}
1728
1730 VPValue *V) const {
1731 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1732 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
1733}
1734
1735#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1737 VPSlotTracker &SlotTracker) const {
1738 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1739 [this, &O, &SlotTracker](auto Op) {
1740 O << "[ ";
1741 Op.value()->printAsOperand(O, SlotTracker);
1742 O << ", ";
1743 getIncomingBlock(Op.index())->printAsOperand(O);
1744 O << " ]";
1745 });
1746}
1747#endif
1748
1749#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1751 VPSlotTracker &SlotTracker) const {
1753
1754 if (getNumOperands() != 0) {
1755 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1757 [&O, &SlotTracker](auto Op) {
1758 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1759 O << " from ";
1760 std::get<1>(Op)->printAsOperand(O);
1761 });
1762 O << ")";
1763 }
1764}
1765#endif
1766
1768 for (const auto &[Kind, Node] : Metadata)
1769 I.setMetadata(Kind, Node);
1770}
1771
1773 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1774 for (const auto &[KindA, MDA] : Metadata) {
1775 for (const auto &[KindB, MDB] : Other.Metadata) {
1776 if (KindA == KindB && MDA == MDB) {
1777 MetadataIntersection.emplace_back(KindA, MDA);
1778 break;
1779 }
1780 }
1781 }
1782 Metadata = std::move(MetadataIntersection);
1783}
1784
1785#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1787 const Module *M = SlotTracker.getModule();
1788 if (Metadata.empty() || !M)
1789 return;
1790
1791 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1792 O << " (";
1793 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1794 auto [Kind, Node] = KindNodePair;
1795 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1796 "Unexpected unnamed metadata kind");
1797 O << "!" << MDNames[Kind] << " ";
1798 Node->printAsOperand(O, M);
1799 });
1800 O << ")";
1801}
1802#endif
1803
1805 assert(State.VF.isVector() && "not widening");
1806 assert(Variant != nullptr && "Can't create vector function.");
1807
1808 FunctionType *VFTy = Variant->getFunctionType();
1809 // Add return type if intrinsic is overloaded on it.
1811 for (const auto &I : enumerate(args())) {
1812 Value *Arg;
1813 // Some vectorized function variants may also take a scalar argument,
1814 // e.g. linear parameters for pointers. This needs to be the scalar value
1815 // from the start of the respective part when interleaving.
1816 if (!VFTy->getParamType(I.index())->isVectorTy())
1817 Arg = State.get(I.value(), VPLane(0));
1818 else
1819 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1820 Args.push_back(Arg);
1821 }
1822
1825 if (CI)
1826 CI->getOperandBundlesAsDefs(OpBundles);
1827
1828 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1829 applyFlags(*V);
1830 applyMetadata(*V);
1831 V->setCallingConv(Variant->getCallingConv());
1832
1833 if (!V->getType()->isVoidTy())
1834 State.set(this, V);
1835}
1836
1838 VPCostContext &Ctx) const {
1839 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1840 Variant->getFunctionType()->params(),
1841 Ctx.CostKind);
1842}
1843
1844#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1846 VPSlotTracker &SlotTracker) const {
1847 O << Indent << "WIDEN-CALL ";
1848
1849 Function *CalledFn = getCalledScalarFunction();
1850 if (CalledFn->getReturnType()->isVoidTy())
1851 O << "void ";
1852 else {
1854 O << " = ";
1855 }
1856
1857 O << "call";
1858 printFlags(O);
1859 O << " @" << CalledFn->getName() << "(";
1860 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1861 Op->printAsOperand(O, SlotTracker);
1862 });
1863 O << ")";
1864
1865 O << " (using library function";
1866 if (Variant->hasName())
1867 O << ": " << Variant->getName();
1868 O << ")";
1869}
1870#endif
1871
1873 assert(State.VF.isVector() && "not widening");
1874
1875 SmallVector<Type *, 2> TysForDecl;
1876 // Add return type if intrinsic is overloaded on it.
1877 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1878 State.TTI)) {
1879 Type *RetTy = toVectorizedTy(getResultType(), State.VF);
1880 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
1881 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
1883 Idx, State.TTI))
1884 TysForDecl.push_back(Ty);
1885 }
1886 }
1888 for (const auto &I : enumerate(operands())) {
1889 // Some intrinsics have a scalar argument - don't replace it with a
1890 // vector.
1891 Value *Arg;
1892 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1893 State.TTI))
1894 Arg = State.get(I.value(), VPLane(0));
1895 else
1896 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1897 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1898 State.TTI))
1899 TysForDecl.push_back(Arg->getType());
1900 Args.push_back(Arg);
1901 }
1902
1903 // Use vector version of the intrinsic.
1904 Module *M = State.Builder.GetInsertBlock()->getModule();
1905 Function *VectorF =
1906 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1907 assert(VectorF &&
1908 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1909
1912 if (CI)
1913 CI->getOperandBundlesAsDefs(OpBundles);
1914
1915 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1916
1917 applyFlags(*V);
1918 applyMetadata(*V);
1919
1920 if (!V->getType()->isVoidTy())
1921 State.set(this, V);
1922}
1923
1924/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1927 const VPRecipeWithIRFlags &R,
1928 ElementCount VF,
1929 VPCostContext &Ctx) {
1930 // Some backends analyze intrinsic arguments to determine cost. Use the
1931 // underlying value for the operand if it has one. Otherwise try to use the
1932 // operand of the underlying call instruction, if there is one. Otherwise
1933 // clear Arguments.
1934 // TODO: Rework TTI interface to be independent of concrete IR values.
1936 for (const auto &[Idx, Op] : enumerate(Operands)) {
1937 auto *V = Op->getUnderlyingValue();
1938 if (!V) {
1939 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1940 Arguments.push_back(UI->getArgOperand(Idx));
1941 continue;
1942 }
1943 Arguments.clear();
1944 break;
1945 }
1946 Arguments.push_back(V);
1947 }
1948
1949 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1950 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1951 SmallVector<Type *> ParamTys;
1952 for (const VPValue *Op : Operands) {
1953 ParamTys.push_back(VF.isVector()
1954 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1955 : Ctx.Types.inferScalarType(Op));
1956 }
1957
1958 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1959 IntrinsicCostAttributes CostAttrs(
1960 ID, RetTy, Arguments, ParamTys, R.getFastMathFlags(),
1961 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1963 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1964}
1965
1967 VPCostContext &Ctx) const {
1969 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1970}
1971
1973 return Intrinsic::getBaseName(VectorIntrinsicID);
1974}
1975
1977 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1978 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1979 auto [Idx, V] = X;
1981 Idx, nullptr);
1982 });
1983}
1984
1985#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1987 VPSlotTracker &SlotTracker) const {
1988 O << Indent << "WIDEN-INTRINSIC ";
1989 if (ResultTy->isVoidTy()) {
1990 O << "void ";
1991 } else {
1993 O << " = ";
1994 }
1995
1996 O << "call";
1997 printFlags(O);
1998 O << getIntrinsicName() << "(";
1999
2001 Op->printAsOperand(O, SlotTracker);
2002 });
2003 O << ")";
2004}
2005#endif
2006
2008 IRBuilderBase &Builder = State.Builder;
2009
2010 Value *Address = State.get(getOperand(0));
2011 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2012 VectorType *VTy = cast<VectorType>(Address->getType());
2013
2014 // The histogram intrinsic requires a mask even if the recipe doesn't;
2015 // if the mask operand was omitted then all lanes should be executed and
2016 // we just need to synthesize an all-true mask.
2017 Value *Mask = nullptr;
2018 if (VPValue *VPMask = getMask())
2019 Mask = State.get(VPMask);
2020 else
2021 Mask =
2022 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2023
2024 // If this is a subtract, we want to invert the increment amount. We may
2025 // add a separate intrinsic in future, but for now we'll try this.
2026 if (Opcode == Instruction::Sub)
2027 IncAmt = Builder.CreateNeg(IncAmt);
2028 else
2029 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2030
2031 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
2032 {VTy, IncAmt->getType()},
2033 {Address, IncAmt, Mask});
2034}
2035
2037 VPCostContext &Ctx) const {
2038 // FIXME: Take the gather and scatter into account as well. For now we're
2039 // generating the same cost as the fallback path, but we'll likely
2040 // need to create a new TTI method for determining the cost, including
2041 // whether we can use base + vec-of-smaller-indices or just
2042 // vec-of-pointers.
2043 assert(VF.isVector() && "Invalid VF for histogram cost");
2044 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2045 VPValue *IncAmt = getOperand(1);
2046 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2047 VectorType *VTy = VectorType::get(IncTy, VF);
2048
2049 // Assume that a non-constant update value (or a constant != 1) requires
2050 // a multiply, and add that into the cost.
2051 InstructionCost MulCost =
2052 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2053 if (auto *CI = dyn_cast<VPConstantInt>(IncAmt))
2054 if (CI->isOne())
2055 MulCost = TTI::TCC_Free;
2056
2057 // Find the cost of the histogram operation itself.
2058 Type *PtrTy = VectorType::get(AddressTy, VF);
2059 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2060 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2061 Type::getVoidTy(Ctx.LLVMCtx),
2062 {PtrTy, IncTy, MaskTy});
2063
2064 // Add the costs together with the add/sub operation.
2065 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2066 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2067}
2068
2069#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2071 VPSlotTracker &SlotTracker) const {
2072 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2074
2075 if (Opcode == Instruction::Sub)
2076 O << ", dec: ";
2077 else {
2078 assert(Opcode == Instruction::Add);
2079 O << ", inc: ";
2080 }
2082
2083 if (VPValue *Mask = getMask()) {
2084 O << ", mask: ";
2085 Mask->printAsOperand(O, SlotTracker);
2086 }
2087}
2088#endif
2089
2090VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2091 AllowReassoc = FMF.allowReassoc();
2092 NoNaNs = FMF.noNaNs();
2093 NoInfs = FMF.noInfs();
2094 NoSignedZeros = FMF.noSignedZeros();
2095 AllowReciprocal = FMF.allowReciprocal();
2096 AllowContract = FMF.allowContract();
2097 ApproxFunc = FMF.approxFunc();
2098}
2099
2101 switch (Opcode) {
2102 case Instruction::Add:
2103 case Instruction::Sub:
2104 case Instruction::Mul:
2105 case Instruction::Shl:
2107 return WrapFlagsTy(false, false);
2108 case Instruction::Trunc:
2109 return TruncFlagsTy(false, false);
2110 case Instruction::Or:
2111 return DisjointFlagsTy(false);
2112 case Instruction::AShr:
2113 case Instruction::LShr:
2114 case Instruction::UDiv:
2115 case Instruction::SDiv:
2116 return ExactFlagsTy(false);
2117 case Instruction::GetElementPtr:
2120 return GEPNoWrapFlags::none();
2121 case Instruction::ZExt:
2122 case Instruction::UIToFP:
2123 return NonNegFlagsTy(false);
2124 case Instruction::FAdd:
2125 case Instruction::FSub:
2126 case Instruction::FMul:
2127 case Instruction::FDiv:
2128 case Instruction::FRem:
2129 case Instruction::FNeg:
2130 case Instruction::FPExt:
2131 case Instruction::FPTrunc:
2132 return FastMathFlags();
2133 case Instruction::ICmp:
2134 case Instruction::FCmp:
2136 llvm_unreachable("opcode requires explicit flags");
2137 default:
2138 return VPIRFlags();
2139 }
2140}
2141
2142#if !defined(NDEBUG)
2143bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2144 switch (OpType) {
2145 case OperationType::OverflowingBinOp:
2146 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2147 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2148 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2149 case OperationType::Trunc:
2150 return Opcode == Instruction::Trunc;
2151 case OperationType::DisjointOp:
2152 return Opcode == Instruction::Or;
2153 case OperationType::PossiblyExactOp:
2154 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2155 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2156 case OperationType::GEPOp:
2157 return Opcode == Instruction::GetElementPtr ||
2158 Opcode == VPInstruction::PtrAdd ||
2159 Opcode == VPInstruction::WidePtrAdd;
2160 case OperationType::FPMathOp:
2161 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2162 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2163 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2164 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2165 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2166 Opcode == Instruction::Select ||
2167 Opcode == VPInstruction::WideIVStep ||
2169 case OperationType::FCmp:
2170 return Opcode == Instruction::FCmp;
2171 case OperationType::NonNegOp:
2172 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2173 case OperationType::Cmp:
2174 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2175 case OperationType::ReductionOp:
2177 case OperationType::Other:
2178 return true;
2179 }
2180 llvm_unreachable("Unknown OperationType enum");
2181}
2182
2183bool VPIRFlags::hasRequiredFlagsForOpcode(unsigned Opcode) const {
2184 // Handle opcodes without default flags.
2185 if (Opcode == Instruction::ICmp)
2186 return OpType == OperationType::Cmp;
2187 if (Opcode == Instruction::FCmp)
2188 return OpType == OperationType::FCmp;
2190 return OpType == OperationType::ReductionOp;
2191
2192 OperationType Required = getDefaultFlags(Opcode).OpType;
2193 return Required == OperationType::Other || Required == OpType;
2194}
2195#endif
2196
2197#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2199 switch (OpType) {
2200 case OperationType::Cmp:
2202 break;
2203 case OperationType::FCmp:
2206 break;
2207 case OperationType::DisjointOp:
2208 if (DisjointFlags.IsDisjoint)
2209 O << " disjoint";
2210 break;
2211 case OperationType::PossiblyExactOp:
2212 if (ExactFlags.IsExact)
2213 O << " exact";
2214 break;
2215 case OperationType::OverflowingBinOp:
2216 if (WrapFlags.HasNUW)
2217 O << " nuw";
2218 if (WrapFlags.HasNSW)
2219 O << " nsw";
2220 break;
2221 case OperationType::Trunc:
2222 if (TruncFlags.HasNUW)
2223 O << " nuw";
2224 if (TruncFlags.HasNSW)
2225 O << " nsw";
2226 break;
2227 case OperationType::FPMathOp:
2229 break;
2230 case OperationType::GEPOp: {
2232 if (Flags.isInBounds())
2233 O << " inbounds";
2234 else if (Flags.hasNoUnsignedSignedWrap())
2235 O << " nusw";
2236 if (Flags.hasNoUnsignedWrap())
2237 O << " nuw";
2238 break;
2239 }
2240 case OperationType::NonNegOp:
2241 if (NonNegFlags.NonNeg)
2242 O << " nneg";
2243 break;
2244 case OperationType::ReductionOp: {
2245 RecurKind RK = getRecurKind();
2246 O << " (";
2247 switch (RK) {
2248 case RecurKind::AnyOf:
2249 O << "any-of";
2250 break;
2251 case RecurKind::SMax:
2252 O << "smax";
2253 break;
2254 case RecurKind::SMin:
2255 O << "smin";
2256 break;
2257 case RecurKind::UMax:
2258 O << "umax";
2259 break;
2260 case RecurKind::UMin:
2261 O << "umin";
2262 break;
2263 case RecurKind::FMinNum:
2264 O << "fminnum";
2265 break;
2266 case RecurKind::FMaxNum:
2267 O << "fmaxnum";
2268 break;
2270 O << "fminimum";
2271 break;
2273 O << "fmaximum";
2274 break;
2276 O << "fminimumnum";
2277 break;
2279 O << "fmaximumnum";
2280 break;
2281 default:
2283 break;
2284 }
2285 if (isReductionInLoop())
2286 O << ", in-loop";
2287 if (isReductionOrdered())
2288 O << ", ordered";
2289 O << ")";
2291 break;
2292 }
2293 case OperationType::Other:
2294 break;
2295 }
2296 O << " ";
2297}
2298#endif
2299
2301 auto &Builder = State.Builder;
2302 switch (Opcode) {
2303 case Instruction::Call:
2304 case Instruction::Br:
2305 case Instruction::PHI:
2306 case Instruction::GetElementPtr:
2307 llvm_unreachable("This instruction is handled by a different recipe.");
2308 case Instruction::UDiv:
2309 case Instruction::SDiv:
2310 case Instruction::SRem:
2311 case Instruction::URem:
2312 case Instruction::Add:
2313 case Instruction::FAdd:
2314 case Instruction::Sub:
2315 case Instruction::FSub:
2316 case Instruction::FNeg:
2317 case Instruction::Mul:
2318 case Instruction::FMul:
2319 case Instruction::FDiv:
2320 case Instruction::FRem:
2321 case Instruction::Shl:
2322 case Instruction::LShr:
2323 case Instruction::AShr:
2324 case Instruction::And:
2325 case Instruction::Or:
2326 case Instruction::Xor: {
2327 // Just widen unops and binops.
2329 for (VPValue *VPOp : operands())
2330 Ops.push_back(State.get(VPOp));
2331
2332 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2333
2334 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2335 applyFlags(*VecOp);
2336 applyMetadata(*VecOp);
2337 }
2338
2339 // Use this vector value for all users of the original instruction.
2340 State.set(this, V);
2341 break;
2342 }
2343 case Instruction::ExtractValue: {
2344 assert(getNumOperands() == 2 && "expected single level extractvalue");
2345 Value *Op = State.get(getOperand(0));
2346 Value *Extract = Builder.CreateExtractValue(
2347 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2348 State.set(this, Extract);
2349 break;
2350 }
2351 case Instruction::Freeze: {
2352 Value *Op = State.get(getOperand(0));
2353 Value *Freeze = Builder.CreateFreeze(Op);
2354 State.set(this, Freeze);
2355 break;
2356 }
2357 case Instruction::ICmp:
2358 case Instruction::FCmp: {
2359 // Widen compares. Generate vector compares.
2360 bool FCmp = Opcode == Instruction::FCmp;
2361 Value *A = State.get(getOperand(0));
2362 Value *B = State.get(getOperand(1));
2363 Value *C = nullptr;
2364 if (FCmp) {
2365 C = Builder.CreateFCmp(getPredicate(), A, B);
2366 } else {
2367 C = Builder.CreateICmp(getPredicate(), A, B);
2368 }
2369 if (auto *I = dyn_cast<Instruction>(C)) {
2370 applyFlags(*I);
2371 applyMetadata(*I);
2372 }
2373 State.set(this, C);
2374 break;
2375 }
2376 case Instruction::Select: {
2377 VPValue *CondOp = getOperand(0);
2378 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2379 Value *Op0 = State.get(getOperand(1));
2380 Value *Op1 = State.get(getOperand(2));
2381 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2382 State.set(this, Sel);
2383 if (auto *I = dyn_cast<Instruction>(Sel)) {
2385 applyFlags(*I);
2386 applyMetadata(*I);
2387 }
2388 break;
2389 }
2390 default:
2391 // This instruction is not vectorized by simple widening.
2392 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2393 << Instruction::getOpcodeName(Opcode));
2394 llvm_unreachable("Unhandled instruction!");
2395 } // end of switch.
2396
2397#if !defined(NDEBUG)
2398 // Verify that VPlan type inference results agree with the type of the
2399 // generated values.
2400 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2401 State.get(this)->getType() &&
2402 "inferred type and type from generated instructions do not match");
2403#endif
2404}
2405
2407 VPCostContext &Ctx) const {
2408 switch (Opcode) {
2409 case Instruction::UDiv:
2410 case Instruction::SDiv:
2411 case Instruction::SRem:
2412 case Instruction::URem:
2413 // If the div/rem operation isn't safe to speculate and requires
2414 // predication, then the only way we can even create a vplan is to insert
2415 // a select on the second input operand to ensure we use the value of 1
2416 // for the inactive lanes. The select will be costed separately.
2417 case Instruction::FNeg:
2418 case Instruction::Add:
2419 case Instruction::FAdd:
2420 case Instruction::Sub:
2421 case Instruction::FSub:
2422 case Instruction::Mul:
2423 case Instruction::FMul:
2424 case Instruction::FDiv:
2425 case Instruction::FRem:
2426 case Instruction::Shl:
2427 case Instruction::LShr:
2428 case Instruction::AShr:
2429 case Instruction::And:
2430 case Instruction::Or:
2431 case Instruction::Xor:
2432 case Instruction::Freeze:
2433 case Instruction::ExtractValue:
2434 case Instruction::ICmp:
2435 case Instruction::FCmp:
2436 case Instruction::Select:
2437 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2438 default:
2439 llvm_unreachable("Unsupported opcode for instruction");
2440 }
2441}
2442
2443#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2445 VPSlotTracker &SlotTracker) const {
2446 O << Indent << "WIDEN ";
2448 O << " = " << Instruction::getOpcodeName(Opcode);
2449 printFlags(O);
2451}
2452#endif
2453
2455 auto &Builder = State.Builder;
2456 /// Vectorize casts.
2457 assert(State.VF.isVector() && "Not vectorizing?");
2458 Type *DestTy = VectorType::get(getResultType(), State.VF);
2459 VPValue *Op = getOperand(0);
2460 Value *A = State.get(Op);
2461 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2462 State.set(this, Cast);
2463 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2464 applyFlags(*CastOp);
2465 applyMetadata(*CastOp);
2466 }
2467}
2468
2470 VPCostContext &Ctx) const {
2471 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2472 // the legacy cost model, including truncates/extends when evaluating a
2473 // reduction in a smaller type.
2474 if (!getUnderlyingValue())
2475 return 0;
2476 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2477}
2478
2479#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2481 VPSlotTracker &SlotTracker) const {
2482 O << Indent << "WIDEN-CAST ";
2484 O << " = " << Instruction::getOpcodeName(Opcode);
2485 printFlags(O);
2487 O << " to " << *getResultType();
2488}
2489#endif
2490
2492 VPCostContext &Ctx) const {
2493 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2494}
2495
2496#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2498 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2499 O << Indent;
2501 O << " = WIDEN-INDUCTION";
2502 printFlags(O);
2504
2505 if (auto *TI = getTruncInst())
2506 O << " (truncated to " << *TI->getType() << ")";
2507}
2508#endif
2509
2511 // The step may be defined by a recipe in the preheader (e.g. if it requires
2512 // SCEV expansion), but for the canonical induction the step is required to be
2513 // 1, which is represented as live-in.
2514 auto *StepC = dyn_cast<VPConstantInt>(getStepValue());
2515 auto *StartC = dyn_cast<VPConstantInt>(getStartValue());
2516 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2517 getScalarType() == getRegion()->getCanonicalIVType();
2518}
2519
2521 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
2522
2523 // Fast-math-flags propagate from the original induction instruction.
2524 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2525 if (FPBinOp)
2526 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
2527
2528 Value *Step = State.get(getStepValue(), VPLane(0));
2529 Value *Index = State.get(getOperand(1), VPLane(0));
2530 Value *DerivedIV = emitTransformedIndex(
2531 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
2533 DerivedIV->setName(Name);
2534 State.set(this, DerivedIV, VPLane(0));
2535}
2536
2537#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2539 VPSlotTracker &SlotTracker) const {
2540 O << Indent;
2542 O << " = DERIVED-IV ";
2543 getStartValue()->printAsOperand(O, SlotTracker);
2544 O << " + ";
2545 getOperand(1)->printAsOperand(O, SlotTracker);
2546 O << " * ";
2547 getStepValue()->printAsOperand(O, SlotTracker);
2548}
2549#endif
2550
2552 // Fast-math-flags propagate from the original induction instruction.
2553 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2554 State.Builder.setFastMathFlags(getFastMathFlags());
2555
2556 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2557 /// variable on which to base the steps, \p Step is the size of the step.
2558
2559 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2560 Value *Step = State.get(getStepValue(), VPLane(0));
2561 IRBuilderBase &Builder = State.Builder;
2562
2563 // Ensure step has the same type as that of scalar IV.
2564 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2565 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2566
2567 // We build scalar steps for both integer and floating-point induction
2568 // variables. Here, we determine the kind of arithmetic we will perform.
2571 if (BaseIVTy->isIntegerTy()) {
2572 AddOp = Instruction::Add;
2573 MulOp = Instruction::Mul;
2574 } else {
2575 AddOp = InductionOpcode;
2576 MulOp = Instruction::FMul;
2577 }
2578
2579 // Determine the number of scalars we need to generate.
2580 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2581 // Compute the scalar steps and save the results in State.
2582
2583 unsigned StartLane = 0;
2584 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2585 if (State.Lane) {
2586 StartLane = State.Lane->getKnownLane();
2587 EndLane = StartLane + 1;
2588 }
2589 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
2590 : Constant::getNullValue(BaseIVTy);
2591
2592 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2593 // It is okay if the induction variable type cannot hold the lane number,
2594 // we expect truncation in this case.
2595 Constant *LaneValue =
2596 BaseIVTy->isIntegerTy()
2597 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2598 /*ImplicitTrunc=*/true)
2599 : ConstantFP::get(BaseIVTy, Lane);
2600 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2601 // The step returned by `createStepForVF` is a runtime-evaluated value
2602 // when VF is scalable. Otherwise, it should be folded into a Constant.
2603 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2604 "Expected StartIdx to be folded to a constant when VF is not "
2605 "scalable");
2606 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2607 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2608 State.set(this, Add, VPLane(Lane));
2609 }
2610}
2611
2612#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2614 VPSlotTracker &SlotTracker) const {
2615 O << Indent;
2617 O << " = SCALAR-STEPS ";
2619}
2620#endif
2621
2623 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2625}
2626
2628 assert(State.VF.isVector() && "not widening");
2629 // Construct a vector GEP by widening the operands of the scalar GEP as
2630 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2631 // results in a vector of pointers when at least one operand of the GEP
2632 // is vector-typed. Thus, to keep the representation compact, we only use
2633 // vector-typed operands for loop-varying values.
2634
2635 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2636 return Op->isDefinedOutsideLoopRegions();
2637 });
2638 if (AllOperandsAreInvariant) {
2639 // If we are vectorizing, but the GEP has only loop-invariant operands,
2640 // the GEP we build (by only using vector-typed operands for
2641 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2642 // produce a vector of pointers, we need to either arbitrarily pick an
2643 // operand to broadcast, or broadcast a clone of the original GEP.
2644 // Here, we broadcast a clone of the original.
2645
2647 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2648 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2649
2650 auto *NewGEP =
2651 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2652 "", getGEPNoWrapFlags());
2653 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2654 State.set(this, Splat);
2655 return;
2656 }
2657
2658 // If the GEP has at least one loop-varying operand, we are sure to
2659 // produce a vector of pointers unless VF is scalar.
2660 // The pointer operand of the new GEP. If it's loop-invariant, we
2661 // won't broadcast it.
2662 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2663
2664 // Collect all the indices for the new GEP. If any index is
2665 // loop-invariant, we won't broadcast it.
2667 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2668 VPValue *Operand = getOperand(I);
2669 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2670 }
2671
2672 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2673 // but it should be a vector, otherwise.
2674 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2675 "", getGEPNoWrapFlags());
2676 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2677 "NewGEP is not a pointer vector");
2678 State.set(this, NewGEP);
2679}
2680
2681#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2683 VPSlotTracker &SlotTracker) const {
2684 O << Indent << "WIDEN-GEP ";
2685 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2686 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2687 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2688
2689 O << " ";
2691 O << " = getelementptr";
2692 printFlags(O);
2694}
2695#endif
2696
2698 assert(!getOffset() && "Unexpected offset operand");
2699 VPBuilder Builder(this);
2700 VPlan &Plan = *getParent()->getPlan();
2701 VPValue *VFVal = getVFValue();
2702 VPTypeAnalysis TypeInfo(Plan);
2703 const DataLayout &DL =
2705 Type *IndexTy = DL.getIndexType(TypeInfo.inferScalarType(getPointer()));
2706 VPValue *Stride =
2707 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
2708 Type *VFTy = TypeInfo.inferScalarType(VFVal);
2709 VPValue *VF = Builder.createScalarZExtOrTrunc(VFVal, IndexTy, VFTy,
2711
2712 // Offset for Part0 = Offset0 = Stride * (VF - 1).
2713 VPInstruction *VFMinusOne =
2714 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
2715 DebugLoc::getUnknown(), "", {true, true});
2716 VPInstruction *Offset0 =
2717 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
2718
2719 // Offset for PartN = Offset0 + Part * Stride * VF.
2720 VPValue *PartxStride =
2721 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
2722 VPValue *Offset = Builder.createAdd(
2723 Offset0,
2724 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
2726}
2727
2729 auto &Builder = State.Builder;
2730 assert(getOffset() && "Expected prior materialization of offset");
2731 Value *Ptr = State.get(getPointer(), true);
2732 Value *Offset = State.get(getOffset(), true);
2733 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2735 State.set(this, ResultPtr, /*IsScalar*/ true);
2736}
2737
2738#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2740 VPSlotTracker &SlotTracker) const {
2741 O << Indent;
2743 O << " = vector-end-pointer";
2744 printFlags(O);
2746}
2747#endif
2748
2750 auto &Builder = State.Builder;
2751 assert(getOffset() &&
2752 "Expected prior simplification of recipe without offset");
2753 Value *Ptr = State.get(getOperand(0), VPLane(0));
2754 Value *Offset = State.get(getOffset(), true);
2755 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2757 State.set(this, ResultPtr, /*IsScalar*/ true);
2758}
2759
2760#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2762 VPSlotTracker &SlotTracker) const {
2763 O << Indent;
2765 O << " = vector-pointer";
2766 printFlags(O);
2768}
2769#endif
2770
2772 VPCostContext &Ctx) const {
2773 // A blend will be expanded to a select VPInstruction, which will generate a
2774 // scalar select if only the first lane is used.
2776 VF = ElementCount::getFixed(1);
2777
2778 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2779 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2780 return (getNumIncomingValues() - 1) *
2781 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2782 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2783}
2784
2785#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2787 VPSlotTracker &SlotTracker) const {
2788 O << Indent << "BLEND ";
2790 O << " =";
2791 printFlags(O);
2792 if (getNumIncomingValues() == 1) {
2793 // Not a User of any mask: not really blending, this is a
2794 // single-predecessor phi.
2795 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2796 } else {
2797 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2798 if (I != 0)
2799 O << " ";
2800 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2801 if (I == 0 && isNormalized())
2802 continue;
2803 O << "/";
2804 getMask(I)->printAsOperand(O, SlotTracker);
2805 }
2806 }
2807}
2808#endif
2809
2811 assert(!State.Lane && "Reduction being replicated.");
2814 "In-loop AnyOf reductions aren't currently supported");
2815 // Propagate the fast-math flags carried by the underlying instruction.
2816 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2817 State.Builder.setFastMathFlags(getFastMathFlags());
2818 Value *NewVecOp = State.get(getVecOp());
2819 if (VPValue *Cond = getCondOp()) {
2820 Value *NewCond = State.get(Cond, State.VF.isScalar());
2821 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2822 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2823
2824 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2825 if (State.VF.isVector())
2826 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2827
2828 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2829 NewVecOp = Select;
2830 }
2831 Value *NewRed;
2832 Value *NextInChain;
2833 if (isOrdered()) {
2834 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2835 if (State.VF.isVector())
2836 NewRed =
2837 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2838 else
2839 NewRed = State.Builder.CreateBinOp(
2841 PrevInChain, NewVecOp);
2842 PrevInChain = NewRed;
2843 NextInChain = NewRed;
2844 } else if (isPartialReduction()) {
2845 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
2846 "Unexpected partial reduction kind");
2847 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2848 NewRed = State.Builder.CreateIntrinsic(
2849 PrevInChain->getType(),
2850 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
2851 : Intrinsic::vector_partial_reduce_fadd,
2852 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
2853 "partial.reduce");
2854 PrevInChain = NewRed;
2855 NextInChain = NewRed;
2856 } else {
2857 assert(isInLoop() &&
2858 "The reduction must either be ordered, partial or in-loop");
2859 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2860 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2862 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2863 else
2864 NextInChain = State.Builder.CreateBinOp(
2866 PrevInChain, NewRed);
2867 }
2868 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2869}
2870
2872 assert(!State.Lane && "Reduction being replicated.");
2873
2874 auto &Builder = State.Builder;
2875 // Propagate the fast-math flags carried by the underlying instruction.
2876 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2877 Builder.setFastMathFlags(getFastMathFlags());
2878
2880 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2881 Value *VecOp = State.get(getVecOp());
2882 Value *EVL = State.get(getEVL(), VPLane(0));
2883
2884 Value *Mask;
2885 if (VPValue *CondOp = getCondOp())
2886 Mask = State.get(CondOp);
2887 else
2888 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2889
2890 Value *NewRed;
2891 if (isOrdered()) {
2892 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2893 } else {
2894 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2896 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2897 else
2898 NewRed = Builder.CreateBinOp(
2900 Prev);
2901 }
2902 State.set(this, NewRed, /*IsScalar*/ true);
2903}
2904
2906 VPCostContext &Ctx) const {
2907 RecurKind RdxKind = getRecurrenceKind();
2908 Type *ElementTy = Ctx.Types.inferScalarType(this);
2909 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2910 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2912 std::optional<FastMathFlags> OptionalFMF =
2913 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2914
2915 if (isPartialReduction()) {
2916 InstructionCost CondCost = 0;
2917 if (isConditional()) {
2919 auto *CondTy = cast<VectorType>(
2920 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2921 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2922 CondTy, Pred, Ctx.CostKind);
2923 }
2924 return CondCost + Ctx.TTI.getPartialReductionCost(
2925 Opcode, ElementTy, ElementTy, ElementTy, VF,
2926 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
2927 OptionalFMF);
2928 }
2929
2930 // TODO: Support any-of reductions.
2931 assert(
2933 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2934 "Any-of reduction not implemented in VPlan-based cost model currently.");
2935
2936 // Note that TTI should model the cost of moving result to the scalar register
2937 // and the BinOp cost in the getMinMaxReductionCost().
2940 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2941 }
2942
2943 // Note that TTI should model the cost of moving result to the scalar register
2944 // and the BinOp cost in the getArithmeticReductionCost().
2945 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2946 Ctx.CostKind);
2947}
2948
2949VPExpressionRecipe::VPExpressionRecipe(
2950 ExpressionTypes ExpressionType,
2951 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2952 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {}, {}),
2953 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2954 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2955 assert(
2956 none_of(ExpressionRecipes,
2957 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2958 "expression cannot contain recipes with side-effects");
2959
2960 // Maintain a copy of the expression recipes as a set of users.
2961 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2962 for (auto *R : ExpressionRecipes)
2963 ExpressionRecipesAsSetOfUsers.insert(R);
2964
2965 // Recipes in the expression, except the last one, must only be used by
2966 // (other) recipes inside the expression. If there are other users, external
2967 // to the expression, use a clone of the recipe for external users.
2968 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2969 if (R != ExpressionRecipes.back() &&
2970 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2971 return !ExpressionRecipesAsSetOfUsers.contains(U);
2972 })) {
2973 // There are users outside of the expression. Clone the recipe and use the
2974 // clone those external users.
2975 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2976 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2977 VPUser &U, unsigned) {
2978 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2979 });
2980 CopyForExtUsers->insertBefore(R);
2981 }
2982 if (R->getParent())
2983 R->removeFromParent();
2984 }
2985
2986 // Internalize all external operands to the expression recipes. To do so,
2987 // create new temporary VPValues for all operands defined by a recipe outside
2988 // the expression. The original operands are added as operands of the
2989 // VPExpressionRecipe itself.
2990 for (auto *R : ExpressionRecipes) {
2991 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2992 auto *Def = Op->getDefiningRecipe();
2993 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2994 continue;
2995 addOperand(Op);
2996 LiveInPlaceholders.push_back(new VPSymbolicValue());
2997 }
2998 }
2999
3000 // Replace each external operand with the first one created for it in
3001 // LiveInPlaceholders.
3002 for (auto *R : ExpressionRecipes)
3003 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3004 R->replaceUsesOfWith(LiveIn, Tmp);
3005}
3006
3008 for (auto *R : ExpressionRecipes)
3009 // Since the list could contain duplicates, make sure the recipe hasn't
3010 // already been inserted.
3011 if (!R->getParent())
3012 R->insertBefore(this);
3013
3014 for (const auto &[Idx, Op] : enumerate(operands()))
3015 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3016
3017 replaceAllUsesWith(ExpressionRecipes.back());
3018 ExpressionRecipes.clear();
3019}
3020
3022 VPCostContext &Ctx) const {
3023 Type *RedTy = Ctx.Types.inferScalarType(this);
3024 auto *SrcVecTy = cast<VectorType>(
3025 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
3026 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3027 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3028 switch (ExpressionType) {
3029 case ExpressionTypes::ExtendedReduction: {
3030 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3031 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
3032 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3033 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3034
3035 if (RedR->isPartialReduction())
3036 return Ctx.TTI.getPartialReductionCost(
3037 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr, RedTy, VF,
3039 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3040 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3041 : std::nullopt);
3042 else if (!RedTy->isFloatingPointTy())
3043 // TTI::getExtendedReductionCost only supports integer types.
3044 return Ctx.TTI.getExtendedReductionCost(
3045 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3046 std::nullopt, Ctx.CostKind);
3047 else
3049 }
3050 case ExpressionTypes::MulAccReduction:
3051 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3052 Ctx.CostKind);
3053
3054 case ExpressionTypes::ExtNegatedMulAccReduction:
3055 assert(Opcode == Instruction::Add && "Unexpected opcode");
3056 Opcode = Instruction::Sub;
3057 [[fallthrough]];
3058 case ExpressionTypes::ExtMulAccReduction: {
3059 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3060 if (RedR->isPartialReduction()) {
3061 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3062 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3063 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3064 return Ctx.TTI.getPartialReductionCost(
3065 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
3066 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
3068 Ext0R->getOpcode()),
3070 Ext1R->getOpcode()),
3071 Mul->getOpcode(), Ctx.CostKind,
3072 RedTy->isFloatingPointTy() ? std::optional{RedR->getFastMathFlags()}
3073 : std::nullopt);
3074 }
3075 return Ctx.TTI.getMulAccReductionCost(
3076 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3077 Instruction::ZExt,
3078 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3079 }
3080 }
3081 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3082}
3083
3085 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3086 return R->mayReadFromMemory() || R->mayWriteToMemory();
3087 });
3088}
3089
3091 assert(
3092 none_of(ExpressionRecipes,
3093 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3094 "expression cannot contain recipes with side-effects");
3095 return false;
3096}
3097
3099 // Cannot use vputils::isSingleScalar(), because all external operands
3100 // of the expression will be live-ins while bundled.
3101 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3102 return RR && !RR->isPartialReduction();
3103}
3104
3105#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3106
3108 VPSlotTracker &SlotTracker) const {
3109 O << Indent << "EXPRESSION ";
3111 O << " = ";
3112 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3113 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3114
3115 switch (ExpressionType) {
3116 case ExpressionTypes::ExtendedReduction: {
3118 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3119 O << Instruction::getOpcodeName(Opcode) << " (";
3121 Red->printFlags(O);
3122
3123 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3124 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3125 << *Ext0->getResultType();
3126 if (Red->isConditional()) {
3127 O << ", ";
3128 Red->getCondOp()->printAsOperand(O, SlotTracker);
3129 }
3130 O << ")";
3131 break;
3132 }
3133 case ExpressionTypes::ExtNegatedMulAccReduction: {
3135 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3137 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3138 << " (sub (0, mul";
3139 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3140 Mul->printFlags(O);
3141 O << "(";
3143 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3144 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3145 << *Ext0->getResultType() << "), (";
3147 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3148 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3149 << *Ext1->getResultType() << ")";
3150 if (Red->isConditional()) {
3151 O << ", ";
3152 Red->getCondOp()->printAsOperand(O, SlotTracker);
3153 }
3154 O << "))";
3155 break;
3156 }
3157 case ExpressionTypes::MulAccReduction:
3158 case ExpressionTypes::ExtMulAccReduction: {
3160 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3162 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3163 << " (";
3164 O << "mul";
3165 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3166 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3167 : ExpressionRecipes[0]);
3168 Mul->printFlags(O);
3169 if (IsExtended)
3170 O << "(";
3172 if (IsExtended) {
3173 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3174 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3175 << *Ext0->getResultType() << "), (";
3176 } else {
3177 O << ", ";
3178 }
3180 if (IsExtended) {
3181 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3182 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3183 << *Ext1->getResultType() << ")";
3184 }
3185 if (Red->isConditional()) {
3186 O << ", ";
3187 Red->getCondOp()->printAsOperand(O, SlotTracker);
3188 }
3189 O << ")";
3190 break;
3191 }
3192 }
3193}
3194
3196 VPSlotTracker &SlotTracker) const {
3197 if (isPartialReduction())
3198 O << Indent << "PARTIAL-REDUCE ";
3199 else
3200 O << Indent << "REDUCE ";
3202 O << " = ";
3204 O << " +";
3205 printFlags(O);
3206 O << " reduce."
3209 << " (";
3211 if (isConditional()) {
3212 O << ", ";
3214 }
3215 O << ")";
3216}
3217
3219 VPSlotTracker &SlotTracker) const {
3220 O << Indent << "REDUCE ";
3222 O << " = ";
3224 O << " +";
3225 printFlags(O);
3226 O << " vp.reduce."
3229 << " (";
3231 O << ", ";
3233 if (isConditional()) {
3234 O << ", ";
3236 }
3237 O << ")";
3238}
3239
3240#endif
3241
3242/// A helper function to scalarize a single Instruction in the innermost loop.
3243/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3244/// operands from \p RepRecipe instead of \p Instr's operands.
3245static void scalarizeInstruction(const Instruction *Instr,
3246 VPReplicateRecipe *RepRecipe,
3247 const VPLane &Lane, VPTransformState &State) {
3248 assert((!Instr->getType()->isAggregateType() ||
3249 canVectorizeTy(Instr->getType())) &&
3250 "Expected vectorizable or non-aggregate type.");
3251
3252 // Does this instruction return a value ?
3253 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3254
3255 Instruction *Cloned = Instr->clone();
3256 if (!IsVoidRetTy) {
3257 Cloned->setName(Instr->getName() + ".cloned");
3258 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3259 // The operands of the replicate recipe may have been narrowed, resulting in
3260 // a narrower result type. Update the type of the cloned instruction to the
3261 // correct type.
3262 if (ResultTy != Cloned->getType())
3263 Cloned->mutateType(ResultTy);
3264 }
3265
3266 RepRecipe->applyFlags(*Cloned);
3267 RepRecipe->applyMetadata(*Cloned);
3268
3269 if (RepRecipe->hasPredicate())
3270 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3271
3272 if (auto DL = RepRecipe->getDebugLoc())
3273 State.setDebugLocFrom(DL);
3274
3275 // Replace the operands of the cloned instructions with their scalar
3276 // equivalents in the new loop.
3277 for (const auto &I : enumerate(RepRecipe->operands())) {
3278 auto InputLane = Lane;
3279 VPValue *Operand = I.value();
3280 if (vputils::isSingleScalar(Operand))
3281 InputLane = VPLane::getFirstLane();
3282 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3283 }
3284
3285 // Place the cloned scalar in the new loop.
3286 State.Builder.Insert(Cloned);
3287
3288 State.set(RepRecipe, Cloned, Lane);
3289
3290 // If we just cloned a new assumption, add it the assumption cache.
3291 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3292 State.AC->registerAssumption(II);
3293
3294 assert(
3295 (RepRecipe->getRegion() ||
3296 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3297 all_of(RepRecipe->operands(),
3298 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3299 "Expected a recipe is either within a region or all of its operands "
3300 "are defined outside the vectorized region.");
3301}
3302
3305
3306 if (!State.Lane) {
3307 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3308 "must have already been unrolled");
3309 scalarizeInstruction(UI, this, VPLane(0), State);
3310 return;
3311 }
3312
3313 assert((State.VF.isScalar() || !isSingleScalar()) &&
3314 "uniform recipe shouldn't be predicated");
3315 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3316 scalarizeInstruction(UI, this, *State.Lane, State);
3317 // Insert scalar instance packing it into a vector.
3318 if (State.VF.isVector() && shouldPack()) {
3319 Value *WideValue =
3320 State.Lane->isFirstLane()
3321 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3322 : State.get(this);
3323 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3324 *State.Lane));
3325 }
3326}
3327
3329 // Find if the recipe is used by a widened recipe via an intervening
3330 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3331 return any_of(users(), [](const VPUser *U) {
3332 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3333 return !vputils::onlyScalarValuesUsed(PredR);
3334 return false;
3335 });
3336}
3337
3338/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3339/// which the legacy cost model computes a SCEV expression when computing the
3340/// address cost. Computing SCEVs for VPValues is incomplete and returns
3341/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3342/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3343static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3345 const Loop *L) {
3346 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3347 if (isa<SCEVCouldNotCompute>(Addr))
3348 return Addr;
3349
3350 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3351}
3352
3353/// Returns true if \p V is used as part of the address of another load or
3354/// store.
3355static bool isUsedByLoadStoreAddress(const VPUser *V) {
3357 SmallVector<const VPUser *> WorkList = {V};
3358
3359 while (!WorkList.empty()) {
3360 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3361 if (!Cur || !Seen.insert(Cur).second)
3362 continue;
3363
3364 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3365 // Skip blends that use V only through a compare by checking if any incoming
3366 // value was already visited.
3367 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3368 [&](unsigned I) {
3369 return Seen.contains(
3370 Blend->getIncomingValue(I)->getDefiningRecipe());
3371 }))
3372 continue;
3373
3374 for (VPUser *U : Cur->users()) {
3375 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3376 if (InterleaveR->getAddr() == Cur)
3377 return true;
3378 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3379 if (RepR->getOpcode() == Instruction::Load &&
3380 RepR->getOperand(0) == Cur)
3381 return true;
3382 if (RepR->getOpcode() == Instruction::Store &&
3383 RepR->getOperand(1) == Cur)
3384 return true;
3385 }
3386 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3387 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3388 return true;
3389 }
3390 }
3391
3392 // The legacy cost model only supports scalarization loads/stores with phi
3393 // addresses, if the phi is directly used as load/store address. Don't
3394 // traverse further for Blends.
3395 if (Blend)
3396 continue;
3397
3398 append_range(WorkList, Cur->users());
3399 }
3400 return false;
3401}
3402
3404 VPCostContext &Ctx) const {
3406 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3407 // transform, avoid computing their cost multiple times for now.
3408 Ctx.SkipCostComputation.insert(UI);
3409
3410 if (VF.isScalable() && !isSingleScalar())
3412
3413 switch (UI->getOpcode()) {
3414 case Instruction::Alloca:
3415 if (VF.isScalable())
3417 return Ctx.TTI.getArithmeticInstrCost(
3418 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3419 case Instruction::GetElementPtr:
3420 // We mark this instruction as zero-cost because the cost of GEPs in
3421 // vectorized code depends on whether the corresponding memory instruction
3422 // is scalarized or not. Therefore, we handle GEPs with the memory
3423 // instruction cost.
3424 return 0;
3425 case Instruction::Call: {
3426 auto *CalledFn =
3428
3431 for (const VPValue *ArgOp : ArgOps)
3432 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3433
3434 if (CalledFn->isIntrinsic())
3435 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3436 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3437 switch (CalledFn->getIntrinsicID()) {
3438 case Intrinsic::assume:
3439 case Intrinsic::lifetime_end:
3440 case Intrinsic::lifetime_start:
3441 case Intrinsic::sideeffect:
3442 case Intrinsic::pseudoprobe:
3443 case Intrinsic::experimental_noalias_scope_decl: {
3444 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3445 ElementCount::getFixed(1), Ctx) == 0 &&
3446 "scalarizing intrinsic should be free");
3447 return InstructionCost(0);
3448 }
3449 default:
3450 break;
3451 }
3452
3453 Type *ResultTy = Ctx.Types.inferScalarType(this);
3454 InstructionCost ScalarCallCost =
3455 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3456 if (isSingleScalar()) {
3457 if (CalledFn->isIntrinsic())
3458 ScalarCallCost = std::min(
3459 ScalarCallCost,
3460 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3461 ElementCount::getFixed(1), Ctx));
3462 return ScalarCallCost;
3463 }
3464
3465 return ScalarCallCost * VF.getFixedValue() +
3466 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3467 }
3468 case Instruction::Add:
3469 case Instruction::Sub:
3470 case Instruction::FAdd:
3471 case Instruction::FSub:
3472 case Instruction::Mul:
3473 case Instruction::FMul:
3474 case Instruction::FDiv:
3475 case Instruction::FRem:
3476 case Instruction::Shl:
3477 case Instruction::LShr:
3478 case Instruction::AShr:
3479 case Instruction::And:
3480 case Instruction::Or:
3481 case Instruction::Xor:
3482 case Instruction::ICmp:
3483 case Instruction::FCmp:
3485 Ctx) *
3486 (isSingleScalar() ? 1 : VF.getFixedValue());
3487 case Instruction::SDiv:
3488 case Instruction::UDiv:
3489 case Instruction::SRem:
3490 case Instruction::URem: {
3491 InstructionCost ScalarCost =
3493 if (isSingleScalar())
3494 return ScalarCost;
3495
3496 // If any of the operands is from a different replicate region and has its
3497 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3498 // model to avoid cost mis-match.
3499 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3500 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3501 if (!PredR)
3502 return false;
3503 return Ctx.skipCostComputation(
3505 PredR->getOperand(0)->getUnderlyingValue()),
3506 VF.isVector());
3507 }))
3508 break;
3509
3510 ScalarCost = ScalarCost * VF.getFixedValue() +
3511 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3512 to_vector(operands()), VF);
3513 // If the recipe is not predicated (i.e. not in a replicate region), return
3514 // the scalar cost. Otherwise handle predicated cost.
3515 if (!getRegion()->isReplicator())
3516 return ScalarCost;
3517
3518 // Account for the phi nodes that we will create.
3519 ScalarCost += VF.getFixedValue() *
3520 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3521 // Scale the cost by the probability of executing the predicated blocks.
3522 // This assumes the predicated block for each vector lane is equally
3523 // likely.
3524 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3525 return ScalarCost;
3526 }
3527 case Instruction::Load:
3528 case Instruction::Store: {
3529 bool IsLoad = UI->getOpcode() == Instruction::Load;
3530 const VPValue *PtrOp = getOperand(!IsLoad);
3531 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3533 break;
3534
3535 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3536 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3537 const Align Alignment = getLoadStoreAlignment(UI);
3538 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3540 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3541 bool UsedByLoadStoreAddress =
3542 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3543 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3544 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3545 UsedByLoadStoreAddress ? UI : nullptr);
3546
3547 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3548 InstructionCost ScalarCost =
3549 ScalarMemOpCost +
3550 Ctx.TTI.getAddressComputationCost(
3551 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3552 Ctx.CostKind);
3553 if (isSingleScalar())
3554 return ScalarCost;
3555
3556 SmallVector<const VPValue *> OpsToScalarize;
3557 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3558 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3559 // don't assign scalarization overhead in general, if the target prefers
3560 // vectorized addressing or the loaded value is used as part of an address
3561 // of another load or store.
3562 if (!UsedByLoadStoreAddress) {
3563 bool EfficientVectorLoadStore =
3564 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3565 if (!(IsLoad && !PreferVectorizedAddressing) &&
3566 !(!IsLoad && EfficientVectorLoadStore))
3567 append_range(OpsToScalarize, operands());
3568
3569 if (!EfficientVectorLoadStore)
3570 ResultTy = Ctx.Types.inferScalarType(this);
3571 }
3572
3576 (ScalarCost * VF.getFixedValue()) +
3577 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3578
3579 const VPRegionBlock *ParentRegion = getRegion();
3580 if (ParentRegion && ParentRegion->isReplicator()) {
3581 // TODO: Handle loop-invariant pointers in predicated blocks. For now,
3582 // fall back to the legacy cost model.
3583 if (!PtrSCEV || Ctx.PSE.getSE()->isLoopInvariant(PtrSCEV, Ctx.L))
3584 break;
3585 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3586 Cost += Ctx.TTI.getCFInstrCost(Instruction::Br, Ctx.CostKind);
3587
3588 auto *VecI1Ty = VectorType::get(
3589 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3590 Cost += Ctx.TTI.getScalarizationOverhead(
3591 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3592 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3593
3594 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3595 // Artificially setting to a high enough value to practically disable
3596 // vectorization with such operations.
3597 return 3000000;
3598 }
3599 }
3600 return Cost;
3601 }
3602 case Instruction::SExt:
3603 case Instruction::ZExt:
3604 case Instruction::FPToUI:
3605 case Instruction::FPToSI:
3606 case Instruction::FPExt:
3607 case Instruction::PtrToInt:
3608 case Instruction::PtrToAddr:
3609 case Instruction::IntToPtr:
3610 case Instruction::SIToFP:
3611 case Instruction::UIToFP:
3612 case Instruction::Trunc:
3613 case Instruction::FPTrunc:
3614 case Instruction::AddrSpaceCast: {
3616 Ctx) *
3617 (isSingleScalar() ? 1 : VF.getFixedValue());
3618 }
3619 case Instruction::ExtractValue:
3620 case Instruction::InsertValue:
3621 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3622 }
3623
3624 return Ctx.getLegacyCost(UI, VF);
3625}
3626
3627#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3629 VPSlotTracker &SlotTracker) const {
3630 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3631
3632 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3634 O << " = ";
3635 }
3636 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3637 O << "call";
3638 printFlags(O);
3639 O << "@" << CB->getCalledFunction()->getName() << "(";
3641 O, [&O, &SlotTracker](VPValue *Op) {
3642 Op->printAsOperand(O, SlotTracker);
3643 });
3644 O << ")";
3645 } else {
3647 printFlags(O);
3649 }
3650
3651 if (shouldPack())
3652 O << " (S->V)";
3653}
3654#endif
3655
3657 assert(State.Lane && "Branch on Mask works only on single instance.");
3658
3659 VPValue *BlockInMask = getOperand(0);
3660 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3661
3662 // Replace the temporary unreachable terminator with a new conditional branch,
3663 // whose two destinations will be set later when they are created.
3664 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3665 assert(isa<UnreachableInst>(CurrentTerminator) &&
3666 "Expected to replace unreachable terminator with conditional branch.");
3667 auto CondBr =
3668 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3669 CondBr->setSuccessor(0, nullptr);
3670 CurrentTerminator->eraseFromParent();
3671}
3672
3674 VPCostContext &Ctx) const {
3675 // The legacy cost model doesn't assign costs to branches for individual
3676 // replicate regions. Match the current behavior in the VPlan cost model for
3677 // now.
3678 return 0;
3679}
3680
3682 assert(State.Lane && "Predicated instruction PHI works per instance.");
3683 Instruction *ScalarPredInst =
3684 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3685 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3686 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3687 assert(PredicatingBB && "Predicated block has no single predecessor.");
3689 "operand must be VPReplicateRecipe");
3690
3691 // By current pack/unpack logic we need to generate only a single phi node: if
3692 // a vector value for the predicated instruction exists at this point it means
3693 // the instruction has vector users only, and a phi for the vector value is
3694 // needed. In this case the recipe of the predicated instruction is marked to
3695 // also do that packing, thereby "hoisting" the insert-element sequence.
3696 // Otherwise, a phi node for the scalar value is needed.
3697 if (State.hasVectorValue(getOperand(0))) {
3698 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3700 "Packed operands must generate an insertelement or insertvalue");
3701
3702 // If VectorI is a struct, it will be a sequence like:
3703 // %1 = insertvalue %unmodified, %x, 0
3704 // %2 = insertvalue %1, %y, 1
3705 // %VectorI = insertvalue %2, %z, 2
3706 // To get the unmodified vector we need to look through the chain.
3707 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3708 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3709 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3710
3711 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3712 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3713 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3714 if (State.hasVectorValue(this))
3715 State.reset(this, VPhi);
3716 else
3717 State.set(this, VPhi);
3718 // NOTE: Currently we need to update the value of the operand, so the next
3719 // predicated iteration inserts its generated value in the correct vector.
3720 State.reset(getOperand(0), VPhi);
3721 } else {
3722 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3723 return;
3724
3725 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3726 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3727 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3728 PredicatingBB);
3729 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3730 if (State.hasScalarValue(this, *State.Lane))
3731 State.reset(this, Phi, *State.Lane);
3732 else
3733 State.set(this, Phi, *State.Lane);
3734 // NOTE: Currently we need to update the value of the operand, so the next
3735 // predicated iteration inserts its generated value in the correct vector.
3736 State.reset(getOperand(0), Phi, *State.Lane);
3737 }
3738}
3739
3740#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3742 VPSlotTracker &SlotTracker) const {
3743 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3745 O << " = ";
3747}
3748#endif
3749
3751 VPCostContext &Ctx) const {
3753 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3754 ->getAddressSpace();
3755 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3756 ? Instruction::Load
3757 : Instruction::Store;
3758
3759 if (!Consecutive) {
3760 // TODO: Using the original IR may not be accurate.
3761 // Currently, ARM will use the underlying IR to calculate gather/scatter
3762 // instruction cost.
3763 assert(!Reverse &&
3764 "Inconsecutive memory access should not have the order.");
3765
3767 Type *PtrTy = Ptr->getType();
3768
3769 // If the address value is uniform across all lanes, then the address can be
3770 // calculated with scalar type and broadcast.
3772 PtrTy = toVectorTy(PtrTy, VF);
3773
3774 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3775 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3776 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3777 : Intrinsic::vp_scatter;
3778 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3779 Ctx.CostKind) +
3780 Ctx.TTI.getMemIntrinsicInstrCost(
3782 &Ingredient),
3783 Ctx.CostKind);
3784 }
3785
3787 if (IsMasked) {
3788 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3789 : Intrinsic::masked_store;
3790 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3791 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3792 } else {
3793 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3795 : getOperand(1));
3796 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3797 OpInfo, &Ingredient);
3798 }
3799 return Cost;
3800}
3801
3803 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3804 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3805 bool CreateGather = !isConsecutive();
3806
3807 auto &Builder = State.Builder;
3808 Value *Mask = nullptr;
3809 if (auto *VPMask = getMask()) {
3810 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3811 // of a null all-one mask is a null mask.
3812 Mask = State.get(VPMask);
3813 if (isReverse())
3814 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3815 }
3816
3817 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3818 Value *NewLI;
3819 if (CreateGather) {
3820 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3821 "wide.masked.gather");
3822 } else if (Mask) {
3823 NewLI =
3824 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3825 PoisonValue::get(DataTy), "wide.masked.load");
3826 } else {
3827 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3828 }
3830 State.set(this, NewLI);
3831}
3832
3833#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3835 VPSlotTracker &SlotTracker) const {
3836 O << Indent << "WIDEN ";
3838 O << " = load ";
3840}
3841#endif
3842
3843/// Use all-true mask for reverse rather than actual mask, as it avoids a
3844/// dependence w/o affecting the result.
3846 Value *EVL, const Twine &Name) {
3847 VectorType *ValTy = cast<VectorType>(Operand->getType());
3848 Value *AllTrueMask =
3849 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3850 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3851 {Operand, AllTrueMask, EVL}, nullptr, Name);
3852}
3853
3855 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3856 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3857 bool CreateGather = !isConsecutive();
3858
3859 auto &Builder = State.Builder;
3860 CallInst *NewLI;
3861 Value *EVL = State.get(getEVL(), VPLane(0));
3862 Value *Addr = State.get(getAddr(), !CreateGather);
3863 Value *Mask = nullptr;
3864 if (VPValue *VPMask = getMask()) {
3865 Mask = State.get(VPMask);
3866 if (isReverse())
3867 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3868 } else {
3869 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3870 }
3871
3872 if (CreateGather) {
3873 NewLI =
3874 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3875 nullptr, "wide.masked.gather");
3876 } else {
3877 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3878 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3879 }
3880 NewLI->addParamAttr(
3882 applyMetadata(*NewLI);
3883 Instruction *Res = NewLI;
3884 State.set(this, Res);
3885}
3886
3888 VPCostContext &Ctx) const {
3889 if (!Consecutive || IsMasked)
3890 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3891
3892 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3893 // here because the EVL recipes using EVL to replace the tail mask. But in the
3894 // legacy model, it will always calculate the cost of mask.
3895 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3896 // don't need to compare to the legacy cost model.
3898 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3899 ->getAddressSpace();
3900 return Ctx.TTI.getMemIntrinsicInstrCost(
3901 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3902 Ctx.CostKind);
3903}
3904
3905#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3907 VPSlotTracker &SlotTracker) const {
3908 O << Indent << "WIDEN ";
3910 O << " = vp.load ";
3912}
3913#endif
3914
3916 VPValue *StoredVPValue = getStoredValue();
3917 bool CreateScatter = !isConsecutive();
3918
3919 auto &Builder = State.Builder;
3920
3921 Value *Mask = nullptr;
3922 if (auto *VPMask = getMask()) {
3923 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3924 // of a null all-one mask is a null mask.
3925 Mask = State.get(VPMask);
3926 if (isReverse())
3927 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3928 }
3929
3930 Value *StoredVal = State.get(StoredVPValue);
3931 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3932 Instruction *NewSI = nullptr;
3933 if (CreateScatter)
3934 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3935 else if (Mask)
3936 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3937 else
3938 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3939 applyMetadata(*NewSI);
3940}
3941
3942#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3944 VPSlotTracker &SlotTracker) const {
3945 O << Indent << "WIDEN store ";
3947}
3948#endif
3949
3951 VPValue *StoredValue = getStoredValue();
3952 bool CreateScatter = !isConsecutive();
3953
3954 auto &Builder = State.Builder;
3955
3956 CallInst *NewSI = nullptr;
3957 Value *StoredVal = State.get(StoredValue);
3958 Value *EVL = State.get(getEVL(), VPLane(0));
3959 Value *Mask = nullptr;
3960 if (VPValue *VPMask = getMask()) {
3961 Mask = State.get(VPMask);
3962 if (isReverse())
3963 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3964 } else {
3965 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3966 }
3967 Value *Addr = State.get(getAddr(), !CreateScatter);
3968 if (CreateScatter) {
3969 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3970 Intrinsic::vp_scatter,
3971 {StoredVal, Addr, Mask, EVL});
3972 } else {
3973 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3974 Intrinsic::vp_store,
3975 {StoredVal, Addr, Mask, EVL});
3976 }
3977 NewSI->addParamAttr(
3979 applyMetadata(*NewSI);
3980}
3981
3983 VPCostContext &Ctx) const {
3984 if (!Consecutive || IsMasked)
3985 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3986
3987 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3988 // here because the EVL recipes using EVL to replace the tail mask. But in the
3989 // legacy model, it will always calculate the cost of mask.
3990 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3991 // don't need to compare to the legacy cost model.
3993 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3994 ->getAddressSpace();
3995 return Ctx.TTI.getMemIntrinsicInstrCost(
3996 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3997 Ctx.CostKind);
3998}
3999
4000#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4002 VPSlotTracker &SlotTracker) const {
4003 O << Indent << "WIDEN vp.store ";
4005}
4006#endif
4007
4009 VectorType *DstVTy, const DataLayout &DL) {
4010 // Verify that V is a vector type with same number of elements as DstVTy.
4011 auto VF = DstVTy->getElementCount();
4012 auto *SrcVecTy = cast<VectorType>(V->getType());
4013 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4014 Type *SrcElemTy = SrcVecTy->getElementType();
4015 Type *DstElemTy = DstVTy->getElementType();
4016 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4017 "Vector elements must have same size");
4018
4019 // Do a direct cast if element types are castable.
4020 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4021 return Builder.CreateBitOrPointerCast(V, DstVTy);
4022 }
4023 // V cannot be directly casted to desired vector type.
4024 // May happen when V is a floating point vector but DstVTy is a vector of
4025 // pointers or vice-versa. Handle this using a two-step bitcast using an
4026 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4027 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4028 "Only one type should be a pointer type");
4029 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4030 "Only one type should be a floating point type");
4031 Type *IntTy =
4032 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4033 auto *VecIntTy = VectorType::get(IntTy, VF);
4034 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4035 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4036}
4037
4038/// Return a vector containing interleaved elements from multiple
4039/// smaller input vectors.
4041 const Twine &Name) {
4042 unsigned Factor = Vals.size();
4043 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4044
4045 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4046#ifndef NDEBUG
4047 for (Value *Val : Vals)
4048 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4049#endif
4050
4051 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4052 // must use intrinsics to interleave.
4053 if (VecTy->isScalableTy()) {
4054 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4055 return Builder.CreateVectorInterleave(Vals, Name);
4056 }
4057
4058 // Fixed length. Start by concatenating all vectors into a wide vector.
4059 Value *WideVec = concatenateVectors(Builder, Vals);
4060
4061 // Interleave the elements into the wide vector.
4062 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4063 return Builder.CreateShuffleVector(
4064 WideVec, createInterleaveMask(NumElts, Factor), Name);
4065}
4066
4067// Try to vectorize the interleave group that \p Instr belongs to.
4068//
4069// E.g. Translate following interleaved load group (factor = 3):
4070// for (i = 0; i < N; i+=3) {
4071// R = Pic[i]; // Member of index 0
4072// G = Pic[i+1]; // Member of index 1
4073// B = Pic[i+2]; // Member of index 2
4074// ... // do something to R, G, B
4075// }
4076// To:
4077// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4078// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4079// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4080// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4081//
4082// Or translate following interleaved store group (factor = 3):
4083// for (i = 0; i < N; i+=3) {
4084// ... do something to R, G, B
4085// Pic[i] = R; // Member of index 0
4086// Pic[i+1] = G; // Member of index 1
4087// Pic[i+2] = B; // Member of index 2
4088// }
4089// To:
4090// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4091// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4092// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4093// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4094// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4096 assert(!State.Lane && "Interleave group being replicated.");
4097 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4098 "Masking gaps for scalable vectors is not yet supported.");
4100 Instruction *Instr = Group->getInsertPos();
4101
4102 // Prepare for the vector type of the interleaved load/store.
4103 Type *ScalarTy = getLoadStoreType(Instr);
4104 unsigned InterleaveFactor = Group->getFactor();
4105 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4106
4107 VPValue *BlockInMask = getMask();
4108 VPValue *Addr = getAddr();
4109 Value *ResAddr = State.get(Addr, VPLane(0));
4110
4111 auto CreateGroupMask = [&BlockInMask, &State,
4112 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4113 if (State.VF.isScalable()) {
4114 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4115 assert(InterleaveFactor <= 8 &&
4116 "Unsupported deinterleave factor for scalable vectors");
4117 auto *ResBlockInMask = State.get(BlockInMask);
4118 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4119 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4120 }
4121
4122 if (!BlockInMask)
4123 return MaskForGaps;
4124
4125 Value *ResBlockInMask = State.get(BlockInMask);
4126 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4127 ResBlockInMask,
4128 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4129 "interleaved.mask");
4130 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4131 ShuffledMask, MaskForGaps)
4132 : ShuffledMask;
4133 };
4134
4135 const DataLayout &DL = Instr->getDataLayout();
4136 // Vectorize the interleaved load group.
4137 if (isa<LoadInst>(Instr)) {
4138 Value *MaskForGaps = nullptr;
4139 if (needsMaskForGaps()) {
4140 MaskForGaps =
4141 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4142 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4143 }
4144
4145 Instruction *NewLoad;
4146 if (BlockInMask || MaskForGaps) {
4147 Value *GroupMask = CreateGroupMask(MaskForGaps);
4148 Value *PoisonVec = PoisonValue::get(VecTy);
4149 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4150 Group->getAlign(), GroupMask,
4151 PoisonVec, "wide.masked.vec");
4152 } else
4153 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4154 Group->getAlign(), "wide.vec");
4155 applyMetadata(*NewLoad);
4156 // TODO: Also manage existing metadata using VPIRMetadata.
4157 Group->addMetadata(NewLoad);
4158
4160 if (VecTy->isScalableTy()) {
4161 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4162 // so must use intrinsics to deinterleave.
4163 assert(InterleaveFactor <= 8 &&
4164 "Unsupported deinterleave factor for scalable vectors");
4165 NewLoad = State.Builder.CreateIntrinsic(
4166 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4167 NewLoad->getType(), NewLoad,
4168 /*FMFSource=*/nullptr, "strided.vec");
4169 }
4170
4171 auto CreateStridedVector = [&InterleaveFactor, &State,
4172 &NewLoad](unsigned Index) -> Value * {
4173 assert(Index < InterleaveFactor && "Illegal group index");
4174 if (State.VF.isScalable())
4175 return State.Builder.CreateExtractValue(NewLoad, Index);
4176
4177 // For fixed length VF, use shuffle to extract the sub-vectors from the
4178 // wide load.
4179 auto StrideMask =
4180 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4181 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4182 "strided.vec");
4183 };
4184
4185 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4186 Instruction *Member = Group->getMember(I);
4187
4188 // Skip the gaps in the group.
4189 if (!Member)
4190 continue;
4191
4192 Value *StridedVec = CreateStridedVector(I);
4193
4194 // If this member has different type, cast the result type.
4195 if (Member->getType() != ScalarTy) {
4196 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4197 StridedVec =
4198 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4199 }
4200
4201 if (Group->isReverse())
4202 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4203
4204 State.set(VPDefs[J], StridedVec);
4205 ++J;
4206 }
4207 return;
4208 }
4209
4210 // The sub vector type for current instruction.
4211 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4212
4213 // Vectorize the interleaved store group.
4214 Value *MaskForGaps =
4215 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4216 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4217 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4218 ArrayRef<VPValue *> StoredValues = getStoredValues();
4219 // Collect the stored vector from each member.
4220 SmallVector<Value *, 4> StoredVecs;
4221 unsigned StoredIdx = 0;
4222 for (unsigned i = 0; i < InterleaveFactor; i++) {
4223 assert((Group->getMember(i) || MaskForGaps) &&
4224 "Fail to get a member from an interleaved store group");
4225 Instruction *Member = Group->getMember(i);
4226
4227 // Skip the gaps in the group.
4228 if (!Member) {
4229 Value *Undef = PoisonValue::get(SubVT);
4230 StoredVecs.push_back(Undef);
4231 continue;
4232 }
4233
4234 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4235 ++StoredIdx;
4236
4237 if (Group->isReverse())
4238 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4239
4240 // If this member has different type, cast it to a unified type.
4241
4242 if (StoredVec->getType() != SubVT)
4243 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4244
4245 StoredVecs.push_back(StoredVec);
4246 }
4247
4248 // Interleave all the smaller vectors into one wider vector.
4249 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4250 Instruction *NewStoreInstr;
4251 if (BlockInMask || MaskForGaps) {
4252 Value *GroupMask = CreateGroupMask(MaskForGaps);
4253 NewStoreInstr = State.Builder.CreateMaskedStore(
4254 IVec, ResAddr, Group->getAlign(), GroupMask);
4255 } else
4256 NewStoreInstr =
4257 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4258
4259 applyMetadata(*NewStoreInstr);
4260 // TODO: Also manage existing metadata using VPIRMetadata.
4261 Group->addMetadata(NewStoreInstr);
4262}
4263
4264#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4266 VPSlotTracker &SlotTracker) const {
4268 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4269 IG->getInsertPos()->printAsOperand(O, false);
4270 O << ", ";
4272 VPValue *Mask = getMask();
4273 if (Mask) {
4274 O << ", ";
4275 Mask->printAsOperand(O, SlotTracker);
4276 }
4277
4278 unsigned OpIdx = 0;
4279 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4280 if (!IG->getMember(i))
4281 continue;
4282 if (getNumStoreOperands() > 0) {
4283 O << "\n" << Indent << " store ";
4285 O << " to index " << i;
4286 } else {
4287 O << "\n" << Indent << " ";
4289 O << " = load from index " << i;
4290 }
4291 ++OpIdx;
4292 }
4293}
4294#endif
4295
4297 assert(!State.Lane && "Interleave group being replicated.");
4298 assert(State.VF.isScalable() &&
4299 "Only support scalable VF for EVL tail-folding.");
4301 "Masking gaps for scalable vectors is not yet supported.");
4303 Instruction *Instr = Group->getInsertPos();
4304
4305 // Prepare for the vector type of the interleaved load/store.
4306 Type *ScalarTy = getLoadStoreType(Instr);
4307 unsigned InterleaveFactor = Group->getFactor();
4308 assert(InterleaveFactor <= 8 &&
4309 "Unsupported deinterleave/interleave factor for scalable vectors");
4310 ElementCount WideVF = State.VF * InterleaveFactor;
4311 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4312
4313 VPValue *Addr = getAddr();
4314 Value *ResAddr = State.get(Addr, VPLane(0));
4315 Value *EVL = State.get(getEVL(), VPLane(0));
4316 Value *InterleaveEVL = State.Builder.CreateMul(
4317 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4318 /* NUW= */ true, /* NSW= */ true);
4319 LLVMContext &Ctx = State.Builder.getContext();
4320
4321 Value *GroupMask = nullptr;
4322 if (VPValue *BlockInMask = getMask()) {
4323 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4324 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4325 } else {
4326 GroupMask =
4327 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4328 }
4329
4330 // Vectorize the interleaved load group.
4331 if (isa<LoadInst>(Instr)) {
4332 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4333 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4334 "wide.vp.load");
4335 NewLoad->addParamAttr(0,
4336 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4337
4338 applyMetadata(*NewLoad);
4339 // TODO: Also manage existing metadata using VPIRMetadata.
4340 Group->addMetadata(NewLoad);
4341
4342 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4343 // so must use intrinsics to deinterleave.
4344 NewLoad = State.Builder.CreateIntrinsic(
4345 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4346 NewLoad->getType(), NewLoad,
4347 /*FMFSource=*/nullptr, "strided.vec");
4348
4349 const DataLayout &DL = Instr->getDataLayout();
4350 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4351 Instruction *Member = Group->getMember(I);
4352 // Skip the gaps in the group.
4353 if (!Member)
4354 continue;
4355
4356 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4357 // If this member has different type, cast the result type.
4358 if (Member->getType() != ScalarTy) {
4359 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4360 StridedVec =
4361 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4362 }
4363
4364 State.set(getVPValue(J), StridedVec);
4365 ++J;
4366 }
4367 return;
4368 } // End for interleaved load.
4369
4370 // The sub vector type for current instruction.
4371 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4372 // Vectorize the interleaved store group.
4373 ArrayRef<VPValue *> StoredValues = getStoredValues();
4374 // Collect the stored vector from each member.
4375 SmallVector<Value *, 4> StoredVecs;
4376 const DataLayout &DL = Instr->getDataLayout();
4377 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4378 Instruction *Member = Group->getMember(I);
4379 // Skip the gaps in the group.
4380 if (!Member) {
4381 StoredVecs.push_back(PoisonValue::get(SubVT));
4382 continue;
4383 }
4384
4385 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4386 // If this member has different type, cast it to a unified type.
4387 if (StoredVec->getType() != SubVT)
4388 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4389
4390 StoredVecs.push_back(StoredVec);
4391 ++StoredIdx;
4392 }
4393
4394 // Interleave all the smaller vectors into one wider vector.
4395 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4396 CallInst *NewStore =
4397 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4398 {IVec, ResAddr, GroupMask, InterleaveEVL});
4399 NewStore->addParamAttr(1,
4400 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4401
4402 applyMetadata(*NewStore);
4403 // TODO: Also manage existing metadata using VPIRMetadata.
4404 Group->addMetadata(NewStore);
4405}
4406
4407#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4409 VPSlotTracker &SlotTracker) const {
4411 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4412 IG->getInsertPos()->printAsOperand(O, false);
4413 O << ", ";
4415 O << ", ";
4417 if (VPValue *Mask = getMask()) {
4418 O << ", ";
4419 Mask->printAsOperand(O, SlotTracker);
4420 }
4421
4422 unsigned OpIdx = 0;
4423 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4424 if (!IG->getMember(i))
4425 continue;
4426 if (getNumStoreOperands() > 0) {
4427 O << "\n" << Indent << " vp.store ";
4429 O << " to index " << i;
4430 } else {
4431 O << "\n" << Indent << " ";
4433 O << " = vp.load from index " << i;
4434 }
4435 ++OpIdx;
4436 }
4437}
4438#endif
4439
4441 VPCostContext &Ctx) const {
4442 Instruction *InsertPos = getInsertPos();
4443 // Find the VPValue index of the interleave group. We need to skip gaps.
4444 unsigned InsertPosIdx = 0;
4445 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4446 if (auto *Member = IG->getMember(Idx)) {
4447 if (Member == InsertPos)
4448 break;
4449 InsertPosIdx++;
4450 }
4451 Type *ValTy = Ctx.Types.inferScalarType(
4452 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4453 : getStoredValues()[InsertPosIdx]);
4454 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4455 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4456 ->getAddressSpace();
4457
4458 unsigned InterleaveFactor = IG->getFactor();
4459 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4460
4461 // Holds the indices of existing members in the interleaved group.
4463 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4464 if (IG->getMember(IF))
4465 Indices.push_back(IF);
4466
4467 // Calculate the cost of the whole interleaved group.
4468 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4469 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4470 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4471
4472 if (!IG->isReverse())
4473 return Cost;
4474
4475 return Cost + IG->getNumMembers() *
4476 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4477 VectorTy, VectorTy, {}, Ctx.CostKind,
4478 0);
4479}
4480
4481#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4483 VPSlotTracker &SlotTracker) const {
4484 O << Indent << "EMIT ";
4486 O << " = CANONICAL-INDUCTION ";
4488}
4489#endif
4490
4492 return vputils::onlyScalarValuesUsed(this) &&
4493 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4494}
4495
4496#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4498 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4499 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4500 "unexpected number of operands");
4501 O << Indent << "EMIT ";
4503 O << " = WIDEN-POINTER-INDUCTION ";
4505 O << ", ";
4507 O << ", ";
4509 if (getNumOperands() == 5) {
4510 O << ", ";
4512 O << ", ";
4514 }
4515}
4516
4518 VPSlotTracker &SlotTracker) const {
4519 O << Indent << "EMIT ";
4521 O << " = EXPAND SCEV " << *Expr;
4522}
4523#endif
4524
4526 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4527 Type *STy = CanonicalIV->getType();
4528 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4529 ElementCount VF = State.VF;
4530 Value *VStart = VF.isScalar()
4531 ? CanonicalIV
4532 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4533 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4534 if (VF.isVector()) {
4535 VStep = Builder.CreateVectorSplat(VF, VStep);
4536 VStep =
4537 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4538 }
4539 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4540 State.set(this, CanonicalVectorIV);
4541}
4542
4543#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4545 VPSlotTracker &SlotTracker) const {
4546 O << Indent << "EMIT ";
4548 O << " = WIDEN-CANONICAL-INDUCTION ";
4550}
4551#endif
4552
4554 auto &Builder = State.Builder;
4555 // Create a vector from the initial value.
4556 auto *VectorInit = getStartValue()->getLiveInIRValue();
4557
4558 Type *VecTy = State.VF.isScalar()
4559 ? VectorInit->getType()
4560 : VectorType::get(VectorInit->getType(), State.VF);
4561
4562 BasicBlock *VectorPH =
4563 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4564 if (State.VF.isVector()) {
4565 auto *IdxTy = Builder.getInt32Ty();
4566 auto *One = ConstantInt::get(IdxTy, 1);
4567 IRBuilder<>::InsertPointGuard Guard(Builder);
4568 Builder.SetInsertPoint(VectorPH->getTerminator());
4569 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4570 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4571 VectorInit = Builder.CreateInsertElement(
4572 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4573 }
4574
4575 // Create a phi node for the new recurrence.
4576 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4577 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4578 Phi->addIncoming(VectorInit, VectorPH);
4579 State.set(this, Phi);
4580}
4581
4584 VPCostContext &Ctx) const {
4585 if (VF.isScalar())
4586 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4587
4588 return 0;
4589}
4590
4591#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4593 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4594 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4596 O << " = phi ";
4598}
4599#endif
4600
4602 // Reductions do not have to start at zero. They can start with
4603 // any loop invariant values.
4604 VPValue *StartVPV = getStartValue();
4605
4606 // In order to support recurrences we need to be able to vectorize Phi nodes.
4607 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4608 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4609 // this value when we vectorize all of the instructions that use the PHI.
4610 BasicBlock *VectorPH =
4611 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4612 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4613 Value *StartV = State.get(StartVPV, ScalarPHI);
4614 Type *VecTy = StartV->getType();
4615
4616 BasicBlock *HeaderBB = State.CFG.PrevBB;
4617 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4618 "recipe must be in the vector loop header");
4619 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4620 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4621 State.set(this, Phi, isInLoop());
4622
4623 Phi->addIncoming(StartV, VectorPH);
4624}
4625
4626#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4628 VPSlotTracker &SlotTracker) const {
4629 O << Indent << "WIDEN-REDUCTION-PHI ";
4630
4632 O << " = phi";
4633 printFlags(O);
4635 if (getVFScaleFactor() > 1)
4636 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4637}
4638#endif
4639
4641 Value *Op0 = State.get(getOperand(0));
4642 Type *VecTy = Op0->getType();
4643 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4644 State.set(this, VecPhi);
4645}
4646
4648 VPCostContext &Ctx) const {
4649 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4650}
4651
4652#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4654 VPSlotTracker &SlotTracker) const {
4655 O << Indent << "WIDEN-PHI ";
4656
4658 O << " = phi ";
4660}
4661#endif
4662
4664 BasicBlock *VectorPH =
4665 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4666 Value *StartMask = State.get(getOperand(0));
4667 PHINode *Phi =
4668 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4669 Phi->addIncoming(StartMask, VectorPH);
4670 State.set(this, Phi);
4671}
4672
4673#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4675 VPSlotTracker &SlotTracker) const {
4676 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4677
4679 O << " = phi ";
4681}
4682#endif
4683
4684#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4686 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4687 O << Indent << "CURRENT-ITERATION-PHI ";
4688
4690 O << " = phi ";
4692}
4693#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * getPointer(Value *Ptr)
iv users
Definition IVUsers.cpp:48
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isOrdered(const Instruction *I)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static InstructionCost getCostForIntrinsics(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost for the intrinsic ID with Operands, produced by R.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
SmallVector< Value *, 2 > VectorParts
static bool isUsedByLoadStoreAddress(const VPUser *V)
Returns true if V is used as part of the address of another load or store.
static void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition InstrTypes.h:982
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:123
static DebugLoc getUnknown()
Definition DebugLoc.h:161
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:324
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:283
void setAllowContract(bool B=true)
Definition FMF.h:93
bool noSignedZeros() const
Definition FMF.h:70
bool noInfs() const
Definition FMF.h:69
void setAllowReciprocal(bool B=true)
Definition FMF.h:90
bool allowReciprocal() const
Definition FMF.h:71
void setNoSignedZeros(bool B=true)
Definition FMF.h:87
bool allowReassoc() const
Flag queries.
Definition FMF.h:67
bool approxFunc() const
Definition FMF.h:73
void setNoNaNs(bool B=true)
Definition FMF.h:81
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:68
void setApproxFunc(bool B=true)
Definition FMF.h:96
void setNoInfs(bool B=true)
Definition FMF.h:84
bool allowContract() const
Definition FMF.h:72
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool willReturn() const
Determine if the function will return.
Definition Function.h:669
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:602
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2561
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:546
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2615
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2549
LLVM_ABI Value * CreateVectorSpliceRight(Value *V1, Value *V2, Value *Offset, const Twine &Name="")
Create a vector.splice.right intrinsic call, or a shufflevector that produces the same result if the ...
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2608
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2627
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:561
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2025
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:345
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:566
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2312
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:527
LLVM_ABI CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1728
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:522
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2442
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1812
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2308
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1137
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1423
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1200
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2054
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1406
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:507
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1711
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2320
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1736
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2418
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1576
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1440
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
static InstructionCost getInvalid(CostType Val=0)
bool isCast() const
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isReverse() const
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Information for memory intrinsic cost model.
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
This class represents the LLVM 'select' instruction.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
VectorInstrContext
Represents a hint about the context in which an insert/extract is used.
@ None
The insert/extract is not used with a load/store.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, ArrayRef< int > Mask={}, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const
LLVM_ABI InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Reverse
Reverse the order of the vector.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
value_op_iterator value_op_end()
Definition User.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4236
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4289
iterator end()
Definition VPlan.h:4273
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4302
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenMemoryRecipe.
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:2792
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2787
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition VPlan.h:2783
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:82
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:205
VPlan * getPlan()
Definition VPlan.cpp:177
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:350
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPBranchOnMaskRecipe.
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
VPlan-based builder utility analogous to IRBuilder.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:427
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:400
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:412
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:422
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPIRValue * getStartValue() const
Definition VPlan.h:4015
VPValue * getStepValue() const
Definition VPlan.h:4016
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
bool isSingleScalar() const
Returns true if the result of this VPExpressionRecipe is a single-scalar.
bool mayHaveSideEffects() const
Returns true if this expression contains recipes that may have side effects.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
bool mayReadOrWriteMemory() const
Returns true if this expression contains recipes that may read from or write to memory.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2304
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
Definition VPlan.h:2044
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4413
Class to record and manage LLVM IR flags.
Definition VPlan.h:672
FastMathFlagsTy FMFs
Definition VPlan.h:760
ReductionFlagsTy ReductionFlags
Definition VPlan.h:762
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode) const
Returns true if Opcode has its required flags set.
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
static VPIRFlags getDefaultFlags(unsigned Opcode)
Returns default flags for Opcode for opcodes that support it, asserts otherwise.
WrapFlagsTy WrapFlags
Definition VPlan.h:754
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:977
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:1027
TruncFlagsTy TruncFlags
Definition VPlan.h:755
CmpInst::Predicate getPredicate() const
Definition VPlan.h:949
ExactFlagsTy ExactFlags
Definition VPlan.h:757
bool hasNoSignedWrap() const
Definition VPlan.h:1004
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:758
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:967
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:972
DisjointFlagsTy DisjointFlags
Definition VPlan.h:756
bool hasNoUnsignedWrap() const
Definition VPlan.h:993
FCmpFlagsTy FCmpFlags
Definition VPlan.h:761
NonNegFlagsTy NonNegFlags
Definition VPlan.h:759
bool isReductionInLoop() const
Definition VPlan.h:1033
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:906
uint8_t CmpPredStorage
Definition VPlan.h:753
RecurKind getRecurKind() const
Definition VPlan.h:1021
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1661
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
VPIRMetadata()=default
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print metadata with node IDs.
void applyMetadata(Instruction &I) const
Add all metadata to I.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the instruction.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1193
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
bool doesGeneratePerAllLanes() const
Returns true if this VPInstruction generates scalar values for all lanes.
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1304
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1295
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1311
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1240
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1285
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1298
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1237
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1289
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1232
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1229
@ VScale
Returns the value for vscale.
Definition VPlan.h:1307
@ CanonicalIVIncrementForPart
Definition VPlan.h:1213
bool hasResult() const
Definition VPlan.h:1389
bool opcodeMayReadOrWriteFromMemory() const
Returns true if the underlying opcode may read from or write to memory.
LLVM_DUMP_METHOD void dump() const
Print the VPInstruction to dbgs() (for debugging).
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1468
unsigned getOpcode() const
Definition VPlan.h:1373
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
bool isSingleScalar() const
Returns true if this VPInstruction's operands are single scalars and the result is also a single scal...
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1413
void execute(VPTransformState &State) override
Generate the instruction.
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:2904
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2908
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2906
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2898
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2927
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2892
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3001
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3014
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:2964
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
VPValue * getIncomingValueForBlock(const VPBasicBlock *VPBB) const
Returns the incoming value for VPBB. VPBB must be an incoming block.
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1575
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
const VPBasicBlock * getIncomingBlock(unsigned Idx) const
Returns the incoming block with index Idx.
Definition VPlan.h:4380
detail::zippy< llvm::detail::zip_first, VPUser::const_operand_range, const_incoming_blocks_range > incoming_values_and_blocks() const
Returns an iterator range over pairs of incoming values and corresponding incoming blocks.
Definition VPlan.h:1600
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1560
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const
Sets the incoming value for VPBB to V.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:388
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
virtual void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPRecipe prints itself, without printing common information, like debug info or metadat...
VPRegionBlock * getRegion()
Definition VPlan.h:4541
LLVM_ABI_FOR_TEST void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:116
bool isPhi() const
Returns true for PHI-like recipes.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
virtual InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
VPBasicBlock * getParent()
Definition VPlan.h:463
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:537
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
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.
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
bool isScalarCast() const
Return true if the recipe is a scalar cast.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const
Print the recipe, delegating to printRecipe().
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
unsigned getVPRecipeID() const
Definition VPlan.h:509
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:453
friend class VPValue
Definition VPlanValue.h:233
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3162
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2707
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2731
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3104
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of VPReductionRecipe.
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition VPlan.h:3115
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3117
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3100
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3106
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3113
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3108
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4424
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4492
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3184
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3225
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPReplicateRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getOpcode() const
Definition VPlan.h:3254
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:4084
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4092
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:589
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:657
LLVM_ABI_FOR_TEST LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:591
This class can be used to assign names to VPValues.
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
Helper to access the operand that contains the unroll part for this recipe after unrolling.
Definition VPlan.h:1126
VPValue * getUnrollPartOperand(const VPUser &U) const
Return the VPValue operand containing the unroll part or null if there is no such operand.
unsigned getUnrollPart(const VPUser &U) const
Return the unroll part.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:258
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1451
operand_range operands()
Definition VPlanValue.h:326
unsigned getNumOperands() const
Definition VPlanValue.h:296
operand_iterator op_begin()
Definition VPlanValue.h:322
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:297
virtual bool usesFirstLaneOnly(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:341
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:46
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:137
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1405
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:127
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1447
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:71
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1408
VPValue * getVFValue() const
Definition VPlan.h:2142
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2139
int64_t getStride() const
Definition VPlan.h:2140
VPValue * getPointer() const
Definition VPlan.h:2141
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2211
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
operand_range args()
Definition VPlan.h:1999
Function * getCalledScalarFunction() const
Definition VPlan.h:1995
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCallRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the call instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Returns the result type of the cast.
Definition VPlan.h:1848
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce widened copies of the cast.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:2096
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2367
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2370
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2468
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2483
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2492
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:1930
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Type * getResultType() const
Return the scalar return type of the intrinsic.
Definition VPlan.h:1933
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3509
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3506
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3549
Instruction & Ingredient
Definition VPlan.h:3497
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3503
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3563
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3500
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3556
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3553
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPHIRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
void execute(VPTransformState &State) override
Produce a widened instruction using the opcode and operands of the recipe, processing State....
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4554
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1038
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4690
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:4840
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:840
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition TypeSize.h:256
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
iterator erase(iterator where)
Definition ilist.h:204
pointer remove(iterator &IT)
Definition ilist.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
specific_intval< 1 > m_False()
specific_intval< 1 > m_True()
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
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...
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:532
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:831
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
InstructionCost Cost
@ Undef
Value of the register doesn't matter.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2313
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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< 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...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
cl::opt< unsigned > ForceTargetInstructionCost
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
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
@ Other
Any other memory.
Definition ModRef.h:68
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ FMaximum
FP max with llvm.maximum semantics.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
DWARFExpression::Operation Op
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Value * emitTransformedIndex(IRBuilderBase &B, Value *Index, Value *StartValue, Value *Step, InductionDescriptor::InductionKind InductionKind, const BinaryOperator *InductionBinOp)
Compute the transformed value of Index at offset StartValue using step StepValue.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI Value * createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence kind RdxKind.
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Struct to hold various analysis needed for cost computations.
LLVMContext & LLVMCtx
TargetTransformInfo::TargetCostKind CostKind
VPTypeAnalysis Types
const TargetTransformInfo & TTI
void execute(VPTransformState &State) override
Generate the phi nodes.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1719
PHINode & getIRPhi()
Definition VPlan.h:1732
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void execute(VPTransformState &State) override
Generate the instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1080
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
VPRecipeWithIRFlags(const unsigned char SC, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1081
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:223
SmallDenseMap< const VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
struct llvm::VPTransformState::CFGState CFG
Value * get(const VPValue *Def, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def if IsScalar is false, otherwise return the gen...
Definition VPlan.cpp:279
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
ElementCount VF
The chosen Vectorization Factor of the loop being vectorized.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide load or gather.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3641
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3725
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide store or scatter.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3728
void execute(VPTransformState &State) override
Generate a wide store or scatter.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3688