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 (getVPDefID()) {
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 VPCanonicalIVPHISC:
77 case VPBranchOnMaskSC:
78 case VPDerivedIVSC:
79 case VPFirstOrderRecurrencePHISC:
80 case VPReductionPHISC:
81 case VPScalarIVStepsSC:
82 case VPPredInstPHISC:
83 return false;
84 case VPBlendSC:
85 case VPReductionEVLSC:
86 case VPReductionSC:
87 case VPVectorPointerSC:
88 case VPWidenCanonicalIVSC:
89 case VPWidenCastSC:
90 case VPWidenGEPSC:
91 case VPWidenIntOrFpInductionSC:
92 case VPWidenLoadEVLSC:
93 case VPWidenLoadSC:
94 case VPWidenPHISC:
95 case VPWidenPointerInductionSC:
96 case VPWidenSC: {
97 const Instruction *I =
98 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
99 (void)I;
100 assert((!I || !I->mayWriteToMemory()) &&
101 "underlying instruction may write to memory");
102 return false;
103 }
104 default:
105 return true;
106 }
107}
108
110 switch (getVPDefID()) {
111 case VPExpressionSC:
112 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
113 case VPInstructionSC:
114 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
115 case VPWidenLoadEVLSC:
116 case VPWidenLoadSC:
117 return true;
118 case VPReplicateSC:
119 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
120 ->mayReadFromMemory();
121 case VPWidenCallSC:
122 return !cast<VPWidenCallRecipe>(this)
123 ->getCalledScalarFunction()
124 ->onlyWritesMemory();
125 case VPWidenIntrinsicSC:
126 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
127 case VPBranchOnMaskSC:
128 case VPDerivedIVSC:
129 case VPFirstOrderRecurrencePHISC:
130 case VPPredInstPHISC:
131 case VPScalarIVStepsSC:
132 case VPWidenStoreEVLSC:
133 case VPWidenStoreSC:
134 return false;
135 case VPBlendSC:
136 case VPReductionEVLSC:
137 case VPReductionSC:
138 case VPVectorPointerSC:
139 case VPWidenCanonicalIVSC:
140 case VPWidenCastSC:
141 case VPWidenGEPSC:
142 case VPWidenIntOrFpInductionSC:
143 case VPWidenPHISC:
144 case VPWidenPointerInductionSC:
145 case VPWidenSC: {
146 const Instruction *I =
147 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
148 (void)I;
149 assert((!I || !I->mayReadFromMemory()) &&
150 "underlying instruction may read from memory");
151 return false;
152 }
153 default:
154 // FIXME: Return false if the recipe represents an interleaved store.
155 return true;
156 }
157}
158
160 switch (getVPDefID()) {
161 case VPExpressionSC:
162 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
163 case VPDerivedIVSC:
164 case VPFirstOrderRecurrencePHISC:
165 case VPPredInstPHISC:
166 case VPVectorEndPointerSC:
167 return false;
168 case VPInstructionSC: {
169 auto *VPI = cast<VPInstruction>(this);
170 return mayWriteToMemory() ||
171 VPI->getOpcode() == VPInstruction::BranchOnCount ||
172 VPI->getOpcode() == VPInstruction::BranchOnCond ||
173 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
174 }
175 case VPWidenCallSC: {
176 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
177 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
178 }
179 case VPWidenIntrinsicSC:
180 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
181 case VPBlendSC:
182 case VPReductionEVLSC:
183 case VPReductionSC:
184 case VPScalarIVStepsSC:
185 case VPVectorPointerSC:
186 case VPWidenCanonicalIVSC:
187 case VPWidenCastSC:
188 case VPWidenGEPSC:
189 case VPWidenIntOrFpInductionSC:
190 case VPWidenPHISC:
191 case VPWidenPointerInductionSC:
192 case VPWidenSC: {
193 const Instruction *I =
194 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
195 (void)I;
196 assert((!I || !I->mayHaveSideEffects()) &&
197 "underlying instruction has side-effects");
198 return false;
199 }
200 case VPInterleaveEVLSC:
201 case VPInterleaveSC:
202 return mayWriteToMemory();
203 case VPWidenLoadEVLSC:
204 case VPWidenLoadSC:
205 case VPWidenStoreEVLSC:
206 case VPWidenStoreSC:
207 assert(
208 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
210 "mayHaveSideffects result for ingredient differs from this "
211 "implementation");
212 return mayWriteToMemory();
213 case VPReplicateSC: {
214 auto *R = cast<VPReplicateRecipe>(this);
215 return R->getUnderlyingInstr()->mayHaveSideEffects();
216 }
217 default:
218 return true;
219 }
220}
221
223 assert(!Parent && "Recipe already in some VPBasicBlock");
224 assert(InsertPos->getParent() &&
225 "Insertion position not in any VPBasicBlock");
226 InsertPos->getParent()->insert(this, InsertPos->getIterator());
227}
228
229void VPRecipeBase::insertBefore(VPBasicBlock &BB,
231 assert(!Parent && "Recipe already in some VPBasicBlock");
232 assert(I == BB.end() || I->getParent() == &BB);
233 BB.insert(this, I);
234}
235
237 assert(!Parent && "Recipe already in some VPBasicBlock");
238 assert(InsertPos->getParent() &&
239 "Insertion position not in any VPBasicBlock");
240 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
241}
242
244 assert(getParent() && "Recipe not in any VPBasicBlock");
246 Parent = nullptr;
247}
248
250 assert(getParent() && "Recipe not in any VPBasicBlock");
252}
253
256 insertAfter(InsertPos);
257}
258
264
266 // Get the underlying instruction for the recipe, if there is one. It is used
267 // to
268 // * decide if cost computation should be skipped for this recipe,
269 // * apply forced target instruction cost.
270 Instruction *UI = nullptr;
271 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
272 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
273 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
274 UI = IG->getInsertPos();
275 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
276 UI = &WidenMem->getIngredient();
277
278 InstructionCost RecipeCost;
279 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
280 RecipeCost = 0;
281 } else {
282 RecipeCost = computeCost(VF, Ctx);
283 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
284 RecipeCost.isValid()) {
285 if (UI)
287 else
288 RecipeCost = InstructionCost(0);
289 }
290 }
291
292 LLVM_DEBUG({
293 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
294 dump();
295 });
296 return RecipeCost;
297}
298
300 VPCostContext &Ctx) const {
301 llvm_unreachable("subclasses should implement computeCost");
302}
303
305 return (getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC) ||
307}
308
310 auto *VPI = dyn_cast<VPInstruction>(this);
311 return VPI && Instruction::isCast(VPI->getOpcode());
312}
313
315 assert(OpType == Other.OpType && "OpType must match");
316 switch (OpType) {
317 case OperationType::OverflowingBinOp:
318 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
319 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
320 break;
321 case OperationType::Trunc:
322 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
323 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
324 break;
325 case OperationType::DisjointOp:
326 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
327 break;
328 case OperationType::PossiblyExactOp:
329 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
330 break;
331 case OperationType::GEPOp:
332 GEPFlags &= Other.GEPFlags;
333 break;
334 case OperationType::FPMathOp:
335 case OperationType::FCmp:
336 assert((OpType != OperationType::FCmp ||
337 FCmpFlags.Pred == Other.FCmpFlags.Pred) &&
338 "Cannot drop CmpPredicate");
339 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
340 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
341 break;
342 case OperationType::NonNegOp:
343 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
344 break;
345 case OperationType::Cmp:
346 assert(CmpPredicate == Other.CmpPredicate && "Cannot drop CmpPredicate");
347 break;
348 case OperationType::ReductionOp:
349 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
350 "Cannot change RecurKind");
351 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
352 "Cannot change IsOrdered");
353 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
354 "Cannot change IsInLoop");
355 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
356 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
357 break;
358 case OperationType::Other:
359 assert(AllFlags == Other.AllFlags && "Cannot drop other flags");
360 break;
361 }
362}
363
365 assert((OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
366 OpType == OperationType::ReductionOp) &&
367 "recipe doesn't have fast math flags");
368 const FastMathFlagsTy &F = getFMFsRef();
369 FastMathFlags Res;
370 Res.setAllowReassoc(F.AllowReassoc);
371 Res.setNoNaNs(F.NoNaNs);
372 Res.setNoInfs(F.NoInfs);
373 Res.setNoSignedZeros(F.NoSignedZeros);
374 Res.setAllowReciprocal(F.AllowReciprocal);
375 Res.setAllowContract(F.AllowContract);
376 Res.setApproxFunc(F.ApproxFunc);
377 return Res;
378}
379
380#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
382
383void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
384 VPSlotTracker &SlotTracker) const {
385 printRecipe(O, Indent, SlotTracker);
386 if (auto DL = getDebugLoc()) {
387 O << ", !dbg ";
388 DL.print(O);
389 }
390
391 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
393}
394#endif
395
396template <unsigned PartOpIdx>
397VPValue *
399 if (U.getNumOperands() == PartOpIdx + 1)
400 return U.getOperand(PartOpIdx);
401 return nullptr;
402}
403
404template <unsigned PartOpIdx>
406 if (auto *UnrollPartOp = getUnrollPartOperand(U))
407 return cast<ConstantInt>(UnrollPartOp->getLiveInIRValue())->getZExtValue();
408 return 0;
409}
410
411namespace llvm {
412template class VPUnrollPartAccessor<1>;
413template class VPUnrollPartAccessor<2>;
414template class VPUnrollPartAccessor<3>;
415}
416
418 const VPIRFlags &Flags, const VPIRMetadata &MD,
419 DebugLoc DL, const Twine &Name)
420 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, Flags, DL),
421 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
423 "Set flags not supported for the provided opcode");
424 assert((getNumOperandsForOpcode(Opcode) == -1u ||
426 "number of operands does not match opcode");
427}
428
429#ifndef NDEBUG
430unsigned VPInstruction::getNumOperandsForOpcode(unsigned Opcode) {
431 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
432 return 1;
433
434 if (Instruction::isBinaryOp(Opcode))
435 return 2;
436
437 switch (Opcode) {
440 return 0;
441 case Instruction::Alloca:
442 case Instruction::ExtractValue:
443 case Instruction::Freeze:
444 case Instruction::Load:
460 return 1;
461 case Instruction::ICmp:
462 case Instruction::FCmp:
463 case Instruction::ExtractElement:
464 case Instruction::Store:
472 return 2;
473 case Instruction::Select:
478 return 3;
480 return 4;
481 case Instruction::Call:
482 case Instruction::GetElementPtr:
483 case Instruction::PHI:
484 case Instruction::Switch:
491 // Cannot determine the number of operands from the opcode.
492 return -1u;
493 }
494 llvm_unreachable("all cases should be handled above");
495}
496#endif
497
501
502bool VPInstruction::canGenerateScalarForFirstLane() const {
504 return true;
506 return true;
507 switch (Opcode) {
508 case Instruction::Freeze:
509 case Instruction::ICmp:
510 case Instruction::PHI:
511 case Instruction::Select:
521 return true;
522 default:
523 return false;
524 }
525}
526
527Value *VPInstruction::generate(VPTransformState &State) {
528 IRBuilderBase &Builder = State.Builder;
529
531 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
532 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
533 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
534 auto *Res =
535 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
536 if (auto *I = dyn_cast<Instruction>(Res))
537 applyFlags(*I);
538 return Res;
539 }
540
541 switch (getOpcode()) {
542 case VPInstruction::Not: {
543 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
544 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
545 return Builder.CreateNot(A, Name);
546 }
547 case Instruction::ExtractElement: {
548 assert(State.VF.isVector() && "Only extract elements from vectors");
549 if (auto *IdxIRV = dyn_cast<VPIRValue>(getOperand(1))) {
550 unsigned IdxToExtract =
551 cast<ConstantInt>(IdxIRV->getValue())->getZExtValue();
552 return State.get(getOperand(0), VPLane(IdxToExtract));
553 }
554 Value *Vec = State.get(getOperand(0));
555 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
556 return Builder.CreateExtractElement(Vec, Idx, Name);
557 }
558 case Instruction::Freeze: {
560 return Builder.CreateFreeze(Op, Name);
561 }
562 case Instruction::FCmp:
563 case Instruction::ICmp: {
564 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
565 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
566 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
567 return Builder.CreateCmp(getPredicate(), A, B, Name);
568 }
569 case Instruction::PHI: {
570 llvm_unreachable("should be handled by VPPhi::execute");
571 }
572 case Instruction::Select: {
573 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
574 Value *Cond =
575 State.get(getOperand(0),
576 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
577 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
578 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
579 return Builder.CreateSelect(Cond, Op1, Op2, Name);
580 }
582 // Get first lane of vector induction variable.
583 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
584 // Get the original loop tripcount.
585 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
586
587 // If this part of the active lane mask is scalar, generate the CMP directly
588 // to avoid unnecessary extracts.
589 if (State.VF.isScalar())
590 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
591 Name);
592
593 ElementCount EC = State.VF.multiplyCoefficientBy(
594 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue());
595 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
596 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
597 {PredTy, ScalarTC->getType()},
598 {VIVElem0, ScalarTC}, nullptr, Name);
599 }
601 // Generate code to combine the previous and current values in vector v3.
602 //
603 // vector.ph:
604 // v_init = vector(..., ..., ..., a[-1])
605 // br vector.body
606 //
607 // vector.body
608 // i = phi [0, vector.ph], [i+4, vector.body]
609 // v1 = phi [v_init, vector.ph], [v2, vector.body]
610 // v2 = a[i, i+1, i+2, i+3];
611 // v3 = vector(v1(3), v2(0, 1, 2))
612
613 auto *V1 = State.get(getOperand(0));
614 if (!V1->getType()->isVectorTy())
615 return V1;
616 Value *V2 = State.get(getOperand(1));
617 return Builder.CreateVectorSplice(V1, V2, -1, Name);
618 }
620 unsigned UF = getParent()->getPlan()->getUF();
621 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
622 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
623 Value *Sub = Builder.CreateSub(ScalarTC, Step);
624 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
626 return Builder.CreateSelect(Cmp, Sub, Zero);
627 }
629 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
630 // be outside of the main loop.
631 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
632 // Compute EVL
633 assert(AVL->getType()->isIntegerTy() &&
634 "Requested vector length should be an integer.");
635
636 assert(State.VF.isScalable() && "Expected scalable vector factor.");
637 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
638
639 Value *EVL = Builder.CreateIntrinsic(
640 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
641 {AVL, VFArg, Builder.getTrue()});
642 return EVL;
643 }
645 unsigned Part = getUnrollPart(*this);
646 auto *IV = State.get(getOperand(0), VPLane(0));
647 assert(Part != 0 && "Must have a positive part");
648 // The canonical IV is incremented by the vectorization factor (num of
649 // SIMD elements) times the unroll part.
650 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
651 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
653 }
655 Value *Cond = State.get(getOperand(0), VPLane(0));
656 // Replace the temporary unreachable terminator with a new conditional
657 // branch, hooking it up to backward destination for latch blocks now, and
658 // to forward destination(s) later when they are created.
659 // Second successor may be backwards - iff it is already in VPBB2IRBB.
660 VPBasicBlock *SecondVPSucc =
661 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
662 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
663 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
664 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
665 // First successor is always forward, reset it to nullptr.
666 Br->setSuccessor(0, nullptr);
668 applyMetadata(*Br);
669 return Br;
670 }
672 return Builder.CreateVectorSplat(
673 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
674 }
676 // For struct types, we need to build a new 'wide' struct type, where each
677 // element is widened, i.e., we create a struct of vectors.
678 auto *StructTy =
680 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
681 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
682 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
683 FieldIndex++) {
684 Value *ScalarValue =
685 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
686 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
687 VectorValue =
688 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
689 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
690 }
691 }
692 return Res;
693 }
695 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
696 auto NumOfElements = ElementCount::getFixed(getNumOperands());
697 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
698 for (const auto &[Idx, Op] : enumerate(operands()))
699 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
700 Builder.getInt32(Idx));
701 return Res;
702 }
704 if (State.VF.isScalar())
705 return State.get(getOperand(0), true);
706 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
708 // If this start vector is scaled then it should produce a vector with fewer
709 // elements than the VF.
710 ElementCount VF = State.VF.divideCoefficientBy(
711 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue());
712 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
713 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
714 Builder.getInt32(0));
715 }
717 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
718 // and will be removed by breaking up the recipe further.
719 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
720 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
721 Value *ReducedPartRdx = State.get(getOperand(2));
722 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
723 ReducedPartRdx =
724 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
725 ReducedPartRdx, "bin.rdx");
726 return createAnyOfReduction(Builder, ReducedPartRdx,
727 State.get(getOperand(1), VPLane(0)), OrigPhi);
728 }
730 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
731 // and will be removed by breaking up the recipe further.
732 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
733 // Get its reduction variable descriptor.
734 RecurKind RK = PhiR->getRecurrenceKind();
736 "Unexpected reduction kind");
737 assert(!PhiR->isInLoop() &&
738 "In-loop FindLastIV reduction is not supported yet");
739
740 // The recipe's operands are the reduction phi, the start value, the
741 // sentinel value, followed by one operand for each part of the reduction.
742 unsigned UF = getNumOperands() - 3;
743 Value *ReducedPartRdx = State.get(getOperand(3));
744 RecurKind MinMaxKind;
747 MinMaxKind = IsSigned ? RecurKind::SMax : RecurKind::UMax;
748 else
749 MinMaxKind = IsSigned ? RecurKind::SMin : RecurKind::UMin;
750 for (unsigned Part = 1; Part < UF; ++Part)
751 ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
752 State.get(getOperand(3 + Part)));
753
754 Value *Start = State.get(getOperand(1), true);
756
757 // Reduce the vector to a scalar.
759 Value *ReducedIV =
760 ReducedPartRdx->getType()->isVectorTy()
761 ? (IsFindLast
762 ? Builder.CreateIntMaxReduce(ReducedPartRdx, IsSigned)
763 : Builder.CreateIntMinReduce(ReducedPartRdx, IsSigned))
764 : ReducedPartRdx;
765 // Correct the final reduction result back to the start value if the
766 // reduction result is the sentinel value.
767 Value *Cmp = Builder.CreateICmpNE(ReducedIV, Sentinel, "rdx.select.cmp");
768 return Builder.CreateSelect(Cmp, ReducedIV, Start, "rdx.select");
769 }
771 RecurKind RK = getRecurKind();
772 bool IsOrdered = isReductionOrdered();
773 bool IsInLoop = isReductionInLoop();
775 "should be handled by ComputeFindIVResult");
776
777 // The recipe may have multiple operands to be reduced together.
778 unsigned NumOperandsToReduce = getNumOperands();
779 VectorParts RdxParts(NumOperandsToReduce);
780 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
781 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
782
783 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
784 if (hasFastMathFlags())
786
787 // Reduce multiple operands into one.
788 Value *ReducedPartRdx = RdxParts[0];
789 if (IsOrdered) {
790 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
791 } else {
792 // Floating-point operations should have some FMF to enable the reduction.
793 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
794 Value *RdxPart = RdxParts[Part];
796 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
797 else {
798 // For sub-recurrences, each part's reduction variable is already
799 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
801 RK == RecurKind::Sub
802 ? Instruction::Add
804 ReducedPartRdx =
805 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
806 }
807 }
808 }
809
810 // Create the reduction after the loop. Note that inloop reductions create
811 // the target reduction in the loop using a Reduction recipe.
812 if (State.VF.isVector() && !IsInLoop) {
813 // TODO: Support in-order reductions based on the recurrence descriptor.
814 // All ops in the reduction inherit fast-math-flags from the recurrence
815 // descriptor.
816 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
817 }
818
819 return ReducedPartRdx;
820 }
823 unsigned Offset =
825 Value *Res;
826 if (State.VF.isVector()) {
827 assert(Offset <= State.VF.getKnownMinValue() &&
828 "invalid offset to extract from");
829 // Extract lane VF - Offset from the operand.
830 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
831 } else {
832 // TODO: Remove ExtractLastLane for scalar VFs.
833 assert(Offset <= 1 && "invalid offset to extract from");
834 Res = State.get(getOperand(0));
835 }
837 Res->setName(Name);
838 return Res;
839 }
841 Value *A = State.get(getOperand(0));
842 Value *B = State.get(getOperand(1));
843 return Builder.CreateLogicalAnd(A, B, Name);
844 }
847 "can only generate first lane for PtrAdd");
848 Value *Ptr = State.get(getOperand(0), VPLane(0));
849 Value *Addend = State.get(getOperand(1), VPLane(0));
850 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
851 }
853 Value *Ptr =
855 Value *Addend = State.get(getOperand(1));
856 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
857 }
859 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
860 for (VPValue *Op : drop_begin(operands()))
861 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
862 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
863 }
865 Value *LaneToExtract = State.get(getOperand(0), true);
866 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
867 Value *Res = nullptr;
868 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
869
870 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
871 Value *VectorStart =
872 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
873 Value *VectorIdx = Idx == 1
874 ? LaneToExtract
875 : Builder.CreateSub(LaneToExtract, VectorStart);
876 Value *Ext = State.VF.isScalar()
877 ? State.get(getOperand(Idx))
878 : Builder.CreateExtractElement(
879 State.get(getOperand(Idx)), VectorIdx);
880 if (Res) {
881 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
882 Res = Builder.CreateSelect(Cmp, Ext, Res);
883 } else {
884 Res = Ext;
885 }
886 }
887 return Res;
888 }
890 if (getNumOperands() == 1) {
891 Value *Mask = State.get(getOperand(0));
892 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
893 /*ZeroIsPoison=*/false, Name);
894 }
895 // If there are multiple operands, create a chain of selects to pick the
896 // first operand with an active lane and add the number of lanes of the
897 // preceding operands.
898 Value *RuntimeVF = getRuntimeVF(Builder, Builder.getInt64Ty(), State.VF);
899 unsigned LastOpIdx = getNumOperands() - 1;
900 Value *Res = nullptr;
901 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
902 Value *TrailingZeros =
903 State.VF.isScalar()
904 ? Builder.CreateZExt(
905 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
906 Builder.getFalse()),
907 Builder.getInt64Ty())
909 Builder.getInt64Ty(), State.get(getOperand(Idx)),
910 /*ZeroIsPoison=*/false, Name);
911 Value *Current = Builder.CreateAdd(
912 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
913 if (Res) {
914 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
915 Res = Builder.CreateSelect(Cmp, Current, Res);
916 } else {
917 Res = Current;
918 }
919 }
920
921 return Res;
922 }
924 return State.get(getOperand(0), true);
926 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
928 Value *Data = State.get(getOperand(0));
929 Value *Mask = State.get(getOperand(1));
930 Value *Default = State.get(getOperand(2), /*IsScalar=*/true);
931 Type *VTy = Data->getType();
932 return Builder.CreateIntrinsic(
933 Intrinsic::experimental_vector_extract_last_active, {VTy},
934 {Data, Mask, Default});
935 }
936 default:
937 llvm_unreachable("Unsupported opcode for instruction");
938 }
939}
940
942 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
943 Type *ScalarTy = Ctx.Types.inferScalarType(this);
944 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
945 switch (Opcode) {
946 case Instruction::FNeg:
947 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
948 case Instruction::UDiv:
949 case Instruction::SDiv:
950 case Instruction::SRem:
951 case Instruction::URem:
952 case Instruction::Add:
953 case Instruction::FAdd:
954 case Instruction::Sub:
955 case Instruction::FSub:
956 case Instruction::Mul:
957 case Instruction::FMul:
958 case Instruction::FDiv:
959 case Instruction::FRem:
960 case Instruction::Shl:
961 case Instruction::LShr:
962 case Instruction::AShr:
963 case Instruction::And:
964 case Instruction::Or:
965 case Instruction::Xor: {
968
969 if (VF.isVector()) {
970 // Certain instructions can be cheaper to vectorize if they have a
971 // constant second vector operand. One example of this are shifts on x86.
972 VPValue *RHS = getOperand(1);
973 RHSInfo = Ctx.getOperandInfo(RHS);
974
975 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
978 }
979
982 if (CtxI)
983 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
984 return Ctx.TTI.getArithmeticInstrCost(
985 Opcode, ResultTy, Ctx.CostKind,
986 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
987 RHSInfo, Operands, CtxI, &Ctx.TLI);
988 }
989 case Instruction::Freeze:
990 // This opcode is unknown. Assume that it is the same as 'mul'.
991 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
992 Ctx.CostKind);
993 case Instruction::ExtractValue:
994 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
995 Ctx.CostKind);
996 case Instruction::ICmp:
997 case Instruction::FCmp: {
998 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
999 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1001 return Ctx.TTI.getCmpSelInstrCost(
1002 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
1003 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1004 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1005 }
1006 case Instruction::BitCast: {
1007 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1008 if (ScalarTy->isPointerTy())
1009 return 0;
1010 [[fallthrough]];
1011 }
1012 case Instruction::SExt:
1013 case Instruction::ZExt:
1014 case Instruction::FPToUI:
1015 case Instruction::FPToSI:
1016 case Instruction::FPExt:
1017 case Instruction::PtrToInt:
1018 case Instruction::PtrToAddr:
1019 case Instruction::IntToPtr:
1020 case Instruction::SIToFP:
1021 case Instruction::UIToFP:
1022 case Instruction::Trunc:
1023 case Instruction::FPTrunc:
1024 case Instruction::AddrSpaceCast: {
1025 // Computes the CastContextHint from a recipe that may access memory.
1026 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1029 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1030 // Only compute CCH for memory operations, matching the legacy model
1031 // which only considers loads/stores for cast context hints.
1032 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1033 if (!isa<LoadInst, StoreInst>(UI))
1035 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1037 }
1038 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1039 if (WidenMemoryRecipe == nullptr)
1041 if (VF.isScalar())
1043 if (!WidenMemoryRecipe->isConsecutive())
1045 if (WidenMemoryRecipe->isReverse())
1047 if (WidenMemoryRecipe->isMasked())
1050 };
1051
1052 VPValue *Operand = getOperand(0);
1054 // For Trunc/FPTrunc, get the context from the only user.
1055 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1056 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
1057 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
1058 return nullptr;
1059 return dyn_cast<VPRecipeBase>(*R->user_begin());
1060 };
1061 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
1062 if (match(Recipe, m_Reverse(m_VPValue())))
1063 Recipe = GetOnlyUser(cast<VPInstruction>(Recipe));
1064 if (Recipe)
1065 CCH = ComputeCCH(Recipe);
1066 }
1067 }
1068 // For Z/Sext, get the context from the operand.
1069 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1070 Opcode == Instruction::FPExt) {
1071 if (auto *Recipe = Operand->getDefiningRecipe()) {
1072 VPValue *ReverseOp;
1073 if (match(Recipe, m_Reverse(m_VPValue(ReverseOp))))
1074 Recipe = ReverseOp->getDefiningRecipe();
1075 if (Recipe)
1076 CCH = ComputeCCH(Recipe);
1077 }
1078 }
1079
1080 auto *ScalarSrcTy = Ctx.Types.inferScalarType(Operand);
1081 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1082 // Arm TTI will use the underlying instruction to determine the cost.
1083 return Ctx.TTI.getCastInstrCost(
1084 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1086 }
1087 case Instruction::Select: {
1089 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1090 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1091
1092 VPValue *Op0, *Op1;
1093 bool IsLogicalAnd =
1094 match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1095 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1096
1097 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1098 (IsLogicalAnd || IsLogicalOr)) {
1099 // select x, y, false --> x & y
1100 // select x, true, y --> x | y
1101 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1102 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1103
1104 SmallVector<const Value *, 2> Operands;
1105 if (SI && all_of(operands(),
1106 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1107 append_range(Operands, SI->operands());
1108 return Ctx.TTI.getArithmeticInstrCost(
1109 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1110 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1111 }
1112
1113 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1114 if (!IsScalarCond)
1115 CondTy = VectorType::get(CondTy, VF);
1116
1117 llvm::CmpPredicate Pred;
1118 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1119 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1120 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1121 Pred = Cmp->getPredicate();
1122 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1123 return Ctx.TTI.getCmpSelInstrCost(
1124 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1125 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1126 }
1127 }
1128 llvm_unreachable("called for unsupported opcode");
1129}
1130
1132 VPCostContext &Ctx) const {
1134 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1135 // TODO: Compute cost for VPInstructions without underlying values once
1136 // the legacy cost model has been retired.
1137 return 0;
1138 }
1139
1141 "Should only generate a vector value or single scalar, not scalars "
1142 "for all lanes.");
1144 getOpcode(),
1146 }
1147
1148 switch (getOpcode()) {
1149 case Instruction::Select: {
1151 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1152 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1153 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1154 if (!vputils::onlyFirstLaneUsed(this)) {
1155 CondTy = toVectorTy(CondTy, VF);
1156 VecTy = toVectorTy(VecTy, VF);
1157 }
1158 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1159 Ctx.CostKind);
1160 }
1161 case Instruction::ExtractElement:
1163 if (VF.isScalar()) {
1164 // ExtractLane with VF=1 takes care of handling extracting across multiple
1165 // parts.
1166 return 0;
1167 }
1168
1169 // Add on the cost of extracting the element.
1170 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1171 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1172 Ctx.CostKind);
1173 }
1174 case VPInstruction::AnyOf: {
1175 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1176 return Ctx.TTI.getArithmeticReductionCost(
1177 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1178 }
1180 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1181 if (VF.isScalar())
1182 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1184 CmpInst::ICMP_EQ, Ctx.CostKind);
1185 // Calculate the cost of determining the lane index.
1186 auto *PredTy = toVectorTy(ScalarTy, VF);
1187 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1188 Type::getInt64Ty(Ctx.LLVMCtx),
1189 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1190 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1191 }
1193 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1194 if (VF.isScalar())
1195 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1197 CmpInst::ICMP_EQ, Ctx.CostKind);
1198 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1199 auto *PredTy = toVectorTy(ScalarTy, VF);
1200 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1201 Type::getInt64Ty(Ctx.LLVMCtx),
1202 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1203 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1204 // Add cost of NOT operation on the predicate.
1205 Cost += Ctx.TTI.getArithmeticInstrCost(
1206 Instruction::Xor, PredTy, Ctx.CostKind,
1207 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1208 {TargetTransformInfo::OK_UniformConstantValue,
1209 TargetTransformInfo::OP_None});
1210 // Add cost of SUB operation on the index.
1211 Cost += Ctx.TTI.getArithmeticInstrCost(
1212 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1213 return Cost;
1214 }
1216 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1217 Type *VecTy = toVectorTy(ScalarTy, VF);
1218 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1220 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1221 {VecTy, MaskTy, ScalarTy});
1222 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1223 }
1225 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1227 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1228 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1229
1230 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1231 cast<VectorType>(VectorTy),
1232 cast<VectorType>(VectorTy), Mask,
1233 Ctx.CostKind, VF.getKnownMinValue() - 1);
1234 }
1236 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1237 unsigned Multiplier =
1238 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue();
1239 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1240 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1241 {ArgTy, ArgTy});
1242 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1243 }
1245 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1246 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1247 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1248 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1249 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1250 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1251 }
1253 assert(VF.isVector() && "Reverse operation must be vector type");
1254 auto *VectorTy = cast<VectorType>(
1255 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
1256 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1257 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1258 /*Index=*/0);
1259 }
1261 // Add on the cost of extracting the element.
1262 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1263 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1264 VecTy, Ctx.CostKind, 0);
1265 }
1267 if (VF == ElementCount::getScalable(1))
1269 [[fallthrough]];
1270 default:
1271 // TODO: Compute cost other VPInstructions once the legacy cost model has
1272 // been retired.
1274 "unexpected VPInstruction witht underlying value");
1275 return 0;
1276 }
1277}
1278
1292
1294 switch (getOpcode()) {
1295 case Instruction::PHI:
1299 return true;
1300 default:
1301 return isScalarCast();
1302 }
1303}
1304
1306 assert(!State.Lane && "VPInstruction executing an Lane");
1307 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1309 "Set flags not supported for the provided opcode");
1310 if (hasFastMathFlags())
1311 State.Builder.setFastMathFlags(getFastMathFlags());
1312 Value *GeneratedValue = generate(State);
1313 if (!hasResult())
1314 return;
1315 assert(GeneratedValue && "generate must produce a value");
1316 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1319 assert((((GeneratedValue->getType()->isVectorTy() ||
1320 GeneratedValue->getType()->isStructTy()) ==
1321 !GeneratesPerFirstLaneOnly) ||
1322 State.VF.isScalar()) &&
1323 "scalar value but not only first lane defined");
1324 State.set(this, GeneratedValue,
1325 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1326}
1327
1330 return false;
1331 switch (getOpcode()) {
1332 case Instruction::GetElementPtr:
1333 case Instruction::ExtractElement:
1334 case Instruction::Freeze:
1335 case Instruction::FCmp:
1336 case Instruction::ICmp:
1337 case Instruction::Select:
1338 case Instruction::PHI:
1359 case VPInstruction::Not:
1368 return false;
1369 default:
1370 return true;
1371 }
1372}
1373
1375 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1377 return vputils::onlyFirstLaneUsed(this);
1378
1379 switch (getOpcode()) {
1380 default:
1381 return false;
1382 case Instruction::ExtractElement:
1383 return Op == getOperand(1);
1384 case Instruction::PHI:
1385 return true;
1386 case Instruction::FCmp:
1387 case Instruction::ICmp:
1388 case Instruction::Select:
1389 case Instruction::Or:
1390 case Instruction::Freeze:
1391 case VPInstruction::Not:
1392 // TODO: Cover additional opcodes.
1393 return vputils::onlyFirstLaneUsed(this);
1402 return true;
1405 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1406 // operand, after replicating its operands only the first lane is used.
1407 // Before replicating, it will have only a single operand.
1408 return getNumOperands() > 1;
1410 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1412 // WidePtrAdd supports scalar and vector base addresses.
1413 return false;
1416 return Op == getOperand(1);
1418 return Op == getOperand(0);
1419 };
1420 llvm_unreachable("switch should return");
1421}
1422
1424 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1426 return vputils::onlyFirstPartUsed(this);
1427
1428 switch (getOpcode()) {
1429 default:
1430 return false;
1431 case Instruction::FCmp:
1432 case Instruction::ICmp:
1433 case Instruction::Select:
1434 return vputils::onlyFirstPartUsed(this);
1439 return true;
1440 };
1441 llvm_unreachable("switch should return");
1442}
1443
1444#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1446 VPSlotTracker SlotTracker(getParent()->getPlan());
1448}
1449
1451 VPSlotTracker &SlotTracker) const {
1452 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1453
1454 if (hasResult()) {
1456 O << " = ";
1457 }
1458
1459 switch (getOpcode()) {
1460 case VPInstruction::Not:
1461 O << "not";
1462 break;
1464 O << "combined load";
1465 break;
1467 O << "combined store";
1468 break;
1470 O << "active lane mask";
1471 break;
1473 O << "EXPLICIT-VECTOR-LENGTH";
1474 break;
1476 O << "first-order splice";
1477 break;
1479 O << "branch-on-cond";
1480 break;
1482 O << "branch-on-two-conds";
1483 break;
1485 O << "TC > VF ? TC - VF : 0";
1486 break;
1488 O << "VF * Part +";
1489 break;
1491 O << "branch-on-count";
1492 break;
1494 O << "broadcast";
1495 break;
1497 O << "buildstructvector";
1498 break;
1500 O << "buildvector";
1501 break;
1503 O << "extract-lane";
1504 break;
1506 O << "extract-last-lane";
1507 break;
1509 O << "extract-last-part";
1510 break;
1512 O << "extract-penultimate-element";
1513 break;
1515 O << "compute-anyof-result";
1516 break;
1518 O << "compute-find-iv-result";
1519 break;
1521 O << "compute-reduction-result";
1522 break;
1524 O << "logical-and";
1525 break;
1527 O << "ptradd";
1528 break;
1530 O << "wide-ptradd";
1531 break;
1533 O << "any-of";
1534 break;
1536 O << "first-active-lane";
1537 break;
1539 O << "last-active-lane";
1540 break;
1542 O << "reduction-start-vector";
1543 break;
1545 O << "resume-for-epilogue";
1546 break;
1548 O << "reverse";
1549 break;
1551 O << "unpack";
1552 break;
1554 O << "extract-last-active";
1555 break;
1556 default:
1558 }
1559
1560 printFlags(O);
1562}
1563#endif
1564
1566 State.setDebugLocFrom(getDebugLoc());
1567 if (isScalarCast()) {
1568 Value *Op = State.get(getOperand(0), VPLane(0));
1569 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1570 Op, ResultTy);
1571 State.set(this, Cast, VPLane(0));
1572 return;
1573 }
1574 switch (getOpcode()) {
1576 Value *StepVector =
1577 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1578 State.set(this, StepVector);
1579 break;
1580 }
1581 case VPInstruction::VScale: {
1582 Value *VScale = State.Builder.CreateVScale(ResultTy);
1583 State.set(this, VScale, true);
1584 break;
1585 }
1586
1587 default:
1588 llvm_unreachable("opcode not implemented yet");
1589 }
1590}
1591
1592#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1594 VPSlotTracker &SlotTracker) const {
1595 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1597 O << " = ";
1598
1599 switch (getOpcode()) {
1601 O << "wide-iv-step ";
1603 break;
1605 O << "step-vector " << *ResultTy;
1606 break;
1608 O << "vscale " << *ResultTy;
1609 break;
1610 default:
1611 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1614 O << " to " << *ResultTy;
1615 }
1616}
1617#endif
1618
1620 State.setDebugLocFrom(getDebugLoc());
1621 PHINode *NewPhi = State.Builder.CreatePHI(
1622 State.TypeAnalysis.inferScalarType(this), 2, getName());
1623 unsigned NumIncoming = getNumIncoming();
1624 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1625 // TODO: Fixup all incoming values of header phis once recipes defining them
1626 // are introduced.
1627 NumIncoming = 1;
1628 }
1629 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1630 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1631 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1632 NewPhi->addIncoming(IncV, PredBB);
1633 }
1634 State.set(this, NewPhi, VPLane(0));
1635}
1636
1637#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1638void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1639 VPSlotTracker &SlotTracker) const {
1640 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1642 O << " = phi ";
1644}
1645#endif
1646
1647VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1648 if (auto *Phi = dyn_cast<PHINode>(&I))
1649 return new VPIRPhi(*Phi);
1650 return new VPIRInstruction(I);
1651}
1652
1654 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1655 "PHINodes must be handled by VPIRPhi");
1656 // Advance the insert point after the wrapped IR instruction. This allows
1657 // interleaving VPIRInstructions and other recipes.
1658 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1659}
1660
1662 VPCostContext &Ctx) const {
1663 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1664 // hence it does not contribute to the cost-modeling for the VPlan.
1665 return 0;
1666}
1667
1669 VPBuilder &Builder) {
1671 "can only update exiting operands to phi nodes");
1672 assert(getNumOperands() > 0 && "must have at least one operand");
1673 VPValue *Exiting = getOperand(0);
1674 if (isa<VPIRValue>(Exiting))
1675 return;
1676
1677 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
1678 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
1679 setOperand(0, Exiting);
1680}
1681
1682#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1684 VPSlotTracker &SlotTracker) const {
1685 O << Indent << "IR " << I;
1686}
1687#endif
1688
1690 PHINode *Phi = &getIRPhi();
1691 for (const auto &[Idx, Op] : enumerate(operands())) {
1692 VPValue *ExitValue = Op;
1693 auto Lane = vputils::isSingleScalar(ExitValue)
1695 : VPLane::getLastLaneForVF(State.VF);
1696 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1697 auto *PredVPBB = Pred->getExitingBasicBlock();
1698 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1699 // Set insertion point in PredBB in case an extract needs to be generated.
1700 // TODO: Model extracts explicitly.
1701 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
1702 Value *V = State.get(ExitValue, VPLane(Lane));
1703 // If there is no existing block for PredBB in the phi, add a new incoming
1704 // value. Otherwise update the existing incoming value for PredBB.
1705 if (Phi->getBasicBlockIndex(PredBB) == -1)
1706 Phi->addIncoming(V, PredBB);
1707 else
1708 Phi->setIncomingValueForBlock(PredBB, V);
1709 }
1710
1711 // Advance the insert point after the wrapped IR instruction. This allows
1712 // interleaving VPIRInstructions and other recipes.
1713 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1714}
1715
1717 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1718 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1719 "Number of phi operands must match number of predecessors");
1720 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1721 R->removeOperand(Position);
1722}
1723
1724#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1726 VPSlotTracker &SlotTracker) const {
1727 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1728 [this, &O, &SlotTracker](auto Op) {
1729 O << "[ ";
1730 Op.value()->printAsOperand(O, SlotTracker);
1731 O << ", ";
1732 getIncomingBlock(Op.index())->printAsOperand(O);
1733 O << " ]";
1734 });
1735}
1736#endif
1737
1738#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1740 VPSlotTracker &SlotTracker) const {
1742
1743 if (getNumOperands() != 0) {
1744 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1746 [&O, &SlotTracker](auto Op) {
1747 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1748 O << " from ";
1749 std::get<1>(Op)->printAsOperand(O);
1750 });
1751 O << ")";
1752 }
1753}
1754#endif
1755
1757 for (const auto &[Kind, Node] : Metadata)
1758 I.setMetadata(Kind, Node);
1759}
1760
1762 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1763 for (const auto &[KindA, MDA] : Metadata) {
1764 for (const auto &[KindB, MDB] : Other.Metadata) {
1765 if (KindA == KindB && MDA == MDB) {
1766 MetadataIntersection.emplace_back(KindA, MDA);
1767 break;
1768 }
1769 }
1770 }
1771 Metadata = std::move(MetadataIntersection);
1772}
1773
1774#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1776 const Module *M = SlotTracker.getModule();
1777 if (Metadata.empty() || !M)
1778 return;
1779
1780 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1781 O << " (";
1782 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1783 auto [Kind, Node] = KindNodePair;
1784 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1785 "Unexpected unnamed metadata kind");
1786 O << "!" << MDNames[Kind] << " ";
1787 Node->printAsOperand(O, M);
1788 });
1789 O << ")";
1790}
1791#endif
1792
1794 assert(State.VF.isVector() && "not widening");
1795 assert(Variant != nullptr && "Can't create vector function.");
1796
1797 FunctionType *VFTy = Variant->getFunctionType();
1798 // Add return type if intrinsic is overloaded on it.
1800 for (const auto &I : enumerate(args())) {
1801 Value *Arg;
1802 // Some vectorized function variants may also take a scalar argument,
1803 // e.g. linear parameters for pointers. This needs to be the scalar value
1804 // from the start of the respective part when interleaving.
1805 if (!VFTy->getParamType(I.index())->isVectorTy())
1806 Arg = State.get(I.value(), VPLane(0));
1807 else
1808 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1809 Args.push_back(Arg);
1810 }
1811
1814 if (CI)
1815 CI->getOperandBundlesAsDefs(OpBundles);
1816
1817 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1818 applyFlags(*V);
1819 applyMetadata(*V);
1820 V->setCallingConv(Variant->getCallingConv());
1821
1822 if (!V->getType()->isVoidTy())
1823 State.set(this, V);
1824}
1825
1827 VPCostContext &Ctx) const {
1828 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1829 Variant->getFunctionType()->params(),
1830 Ctx.CostKind);
1831}
1832
1833#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1835 VPSlotTracker &SlotTracker) const {
1836 O << Indent << "WIDEN-CALL ";
1837
1838 Function *CalledFn = getCalledScalarFunction();
1839 if (CalledFn->getReturnType()->isVoidTy())
1840 O << "void ";
1841 else {
1843 O << " = ";
1844 }
1845
1846 O << "call";
1847 printFlags(O);
1848 O << " @" << CalledFn->getName() << "(";
1849 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1850 Op->printAsOperand(O, SlotTracker);
1851 });
1852 O << ")";
1853
1854 O << " (using library function";
1855 if (Variant->hasName())
1856 O << ": " << Variant->getName();
1857 O << ")";
1858}
1859#endif
1860
1862 assert(State.VF.isVector() && "not widening");
1863
1864 SmallVector<Type *, 2> TysForDecl;
1865 // Add return type if intrinsic is overloaded on it.
1866 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1867 State.TTI)) {
1868 Type *RetTy = toVectorizedTy(getResultType(), State.VF);
1869 append_range(TysForDecl, getContainedTypes(RetTy));
1870 }
1872 for (const auto &I : enumerate(operands())) {
1873 // Some intrinsics have a scalar argument - don't replace it with a
1874 // vector.
1875 Value *Arg;
1876 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1877 State.TTI))
1878 Arg = State.get(I.value(), VPLane(0));
1879 else
1880 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1881 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1882 State.TTI))
1883 TysForDecl.push_back(Arg->getType());
1884 Args.push_back(Arg);
1885 }
1886
1887 // Use vector version of the intrinsic.
1888 Module *M = State.Builder.GetInsertBlock()->getModule();
1889 Function *VectorF =
1890 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1891 assert(VectorF &&
1892 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1893
1896 if (CI)
1897 CI->getOperandBundlesAsDefs(OpBundles);
1898
1899 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1900
1901 applyFlags(*V);
1902 applyMetadata(*V);
1903
1904 if (!V->getType()->isVoidTy())
1905 State.set(this, V);
1906}
1907
1908/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1911 const VPRecipeWithIRFlags &R,
1912 ElementCount VF,
1913 VPCostContext &Ctx) {
1914 // Some backends analyze intrinsic arguments to determine cost. Use the
1915 // underlying value for the operand if it has one. Otherwise try to use the
1916 // operand of the underlying call instruction, if there is one. Otherwise
1917 // clear Arguments.
1918 // TODO: Rework TTI interface to be independent of concrete IR values.
1920 for (const auto &[Idx, Op] : enumerate(Operands)) {
1921 auto *V = Op->getUnderlyingValue();
1922 if (!V) {
1923 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1924 Arguments.push_back(UI->getArgOperand(Idx));
1925 continue;
1926 }
1927 Arguments.clear();
1928 break;
1929 }
1930 Arguments.push_back(V);
1931 }
1932
1933 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1934 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1935 SmallVector<Type *> ParamTys;
1936 for (const VPValue *Op : Operands) {
1937 ParamTys.push_back(VF.isVector()
1938 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1939 : Ctx.Types.inferScalarType(Op));
1940 }
1941
1942 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1943 FastMathFlags FMF =
1944 R.hasFastMathFlags() ? R.getFastMathFlags() : FastMathFlags();
1945 IntrinsicCostAttributes CostAttrs(
1946 ID, RetTy, Arguments, ParamTys, FMF,
1947 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1948 InstructionCost::getInvalid(), &Ctx.TLI);
1949 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1950}
1951
1953 VPCostContext &Ctx) const {
1955 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1956}
1957
1959 return Intrinsic::getBaseName(VectorIntrinsicID);
1960}
1961
1963 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1964 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1965 auto [Idx, V] = X;
1967 Idx, nullptr);
1968 });
1969}
1970
1971#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1973 VPSlotTracker &SlotTracker) const {
1974 O << Indent << "WIDEN-INTRINSIC ";
1975 if (ResultTy->isVoidTy()) {
1976 O << "void ";
1977 } else {
1979 O << " = ";
1980 }
1981
1982 O << "call";
1983 printFlags(O);
1984 O << getIntrinsicName() << "(";
1985
1987 Op->printAsOperand(O, SlotTracker);
1988 });
1989 O << ")";
1990}
1991#endif
1992
1994 IRBuilderBase &Builder = State.Builder;
1995
1996 Value *Address = State.get(getOperand(0));
1997 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
1998 VectorType *VTy = cast<VectorType>(Address->getType());
1999
2000 // The histogram intrinsic requires a mask even if the recipe doesn't;
2001 // if the mask operand was omitted then all lanes should be executed and
2002 // we just need to synthesize an all-true mask.
2003 Value *Mask = nullptr;
2004 if (VPValue *VPMask = getMask())
2005 Mask = State.get(VPMask);
2006 else
2007 Mask =
2008 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2009
2010 // If this is a subtract, we want to invert the increment amount. We may
2011 // add a separate intrinsic in future, but for now we'll try this.
2012 if (Opcode == Instruction::Sub)
2013 IncAmt = Builder.CreateNeg(IncAmt);
2014 else
2015 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2016
2017 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
2018 {VTy, IncAmt->getType()},
2019 {Address, IncAmt, Mask});
2020}
2021
2023 VPCostContext &Ctx) const {
2024 // FIXME: Take the gather and scatter into account as well. For now we're
2025 // generating the same cost as the fallback path, but we'll likely
2026 // need to create a new TTI method for determining the cost, including
2027 // whether we can use base + vec-of-smaller-indices or just
2028 // vec-of-pointers.
2029 assert(VF.isVector() && "Invalid VF for histogram cost");
2030 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2031 VPValue *IncAmt = getOperand(1);
2032 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2033 VectorType *VTy = VectorType::get(IncTy, VF);
2034
2035 // Assume that a non-constant update value (or a constant != 1) requires
2036 // a multiply, and add that into the cost.
2037 InstructionCost MulCost =
2038 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2039 if (auto *IncAmountIRV = dyn_cast<VPIRValue>(IncAmt)) {
2040 ConstantInt *CI = dyn_cast<ConstantInt>(IncAmountIRV->getValue());
2041
2042 if (CI && CI->getZExtValue() == 1)
2043 MulCost = TTI::TCC_Free;
2044 }
2045
2046 // Find the cost of the histogram operation itself.
2047 Type *PtrTy = VectorType::get(AddressTy, VF);
2048 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2049 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2050 Type::getVoidTy(Ctx.LLVMCtx),
2051 {PtrTy, IncTy, MaskTy});
2052
2053 // Add the costs together with the add/sub operation.
2054 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2055 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2056}
2057
2058#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2060 VPSlotTracker &SlotTracker) const {
2061 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2063
2064 if (Opcode == Instruction::Sub)
2065 O << ", dec: ";
2066 else {
2067 assert(Opcode == Instruction::Add);
2068 O << ", inc: ";
2069 }
2071
2072 if (VPValue *Mask = getMask()) {
2073 O << ", mask: ";
2074 Mask->printAsOperand(O, SlotTracker);
2075 }
2076}
2077#endif
2078
2079VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2080 AllowReassoc = FMF.allowReassoc();
2081 NoNaNs = FMF.noNaNs();
2082 NoInfs = FMF.noInfs();
2083 NoSignedZeros = FMF.noSignedZeros();
2084 AllowReciprocal = FMF.allowReciprocal();
2085 AllowContract = FMF.allowContract();
2086 ApproxFunc = FMF.approxFunc();
2087}
2088
2089#if !defined(NDEBUG)
2090bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2091 switch (OpType) {
2092 case OperationType::OverflowingBinOp:
2093 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2094 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2095 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2096 case OperationType::Trunc:
2097 return Opcode == Instruction::Trunc;
2098 case OperationType::DisjointOp:
2099 return Opcode == Instruction::Or;
2100 case OperationType::PossiblyExactOp:
2101 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2102 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2103 case OperationType::GEPOp:
2104 return Opcode == Instruction::GetElementPtr ||
2105 Opcode == VPInstruction::PtrAdd ||
2106 Opcode == VPInstruction::WidePtrAdd;
2107 case OperationType::FPMathOp:
2108 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2109 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2110 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2111 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2112 Opcode == Instruction::FPTrunc || Opcode == Instruction::Select ||
2113 Opcode == VPInstruction::WideIVStep ||
2115 case OperationType::FCmp:
2116 return Opcode == Instruction::FCmp;
2117 case OperationType::NonNegOp:
2118 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2119 case OperationType::Cmp:
2120 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2121 case OperationType::ReductionOp:
2123 case OperationType::Other:
2124 return true;
2125 }
2126 llvm_unreachable("Unknown OperationType enum");
2127}
2128#endif
2129
2130#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2132 switch (OpType) {
2133 case OperationType::Cmp:
2135 break;
2136 case OperationType::FCmp:
2139 break;
2140 case OperationType::DisjointOp:
2141 if (DisjointFlags.IsDisjoint)
2142 O << " disjoint";
2143 break;
2144 case OperationType::PossiblyExactOp:
2145 if (ExactFlags.IsExact)
2146 O << " exact";
2147 break;
2148 case OperationType::OverflowingBinOp:
2149 if (WrapFlags.HasNUW)
2150 O << " nuw";
2151 if (WrapFlags.HasNSW)
2152 O << " nsw";
2153 break;
2154 case OperationType::Trunc:
2155 if (TruncFlags.HasNUW)
2156 O << " nuw";
2157 if (TruncFlags.HasNSW)
2158 O << " nsw";
2159 break;
2160 case OperationType::FPMathOp:
2162 break;
2163 case OperationType::GEPOp:
2164 if (GEPFlags.isInBounds())
2165 O << " inbounds";
2166 else if (GEPFlags.hasNoUnsignedSignedWrap())
2167 O << " nusw";
2168 if (GEPFlags.hasNoUnsignedWrap())
2169 O << " nuw";
2170 break;
2171 case OperationType::NonNegOp:
2172 if (NonNegFlags.NonNeg)
2173 O << " nneg";
2174 break;
2175 case OperationType::ReductionOp: {
2176 RecurKind RK = getRecurKind();
2177 O << " (";
2178 switch (RK) {
2179 case RecurKind::SMax:
2180 O << "smax";
2181 break;
2182 case RecurKind::SMin:
2183 O << "smin";
2184 break;
2185 case RecurKind::UMax:
2186 O << "umax";
2187 break;
2188 case RecurKind::UMin:
2189 O << "umin";
2190 break;
2191 case RecurKind::FMinNum:
2192 O << "fminnum";
2193 break;
2194 case RecurKind::FMaxNum:
2195 O << "fmaxnum";
2196 break;
2198 O << "fminimum";
2199 break;
2201 O << "fmaximum";
2202 break;
2204 O << "fminimumnum";
2205 break;
2207 O << "fmaximumnum";
2208 break;
2209 default:
2211 break;
2212 }
2213 if (isReductionInLoop())
2214 O << ", in-loop";
2215 if (isReductionOrdered())
2216 O << ", ordered";
2217 O << ")";
2219 break;
2220 }
2221 case OperationType::Other:
2222 break;
2223 }
2224 O << " ";
2225}
2226#endif
2227
2229 auto &Builder = State.Builder;
2230 switch (Opcode) {
2231 case Instruction::Call:
2232 case Instruction::Br:
2233 case Instruction::PHI:
2234 case Instruction::GetElementPtr:
2235 llvm_unreachable("This instruction is handled by a different recipe.");
2236 case Instruction::UDiv:
2237 case Instruction::SDiv:
2238 case Instruction::SRem:
2239 case Instruction::URem:
2240 case Instruction::Add:
2241 case Instruction::FAdd:
2242 case Instruction::Sub:
2243 case Instruction::FSub:
2244 case Instruction::FNeg:
2245 case Instruction::Mul:
2246 case Instruction::FMul:
2247 case Instruction::FDiv:
2248 case Instruction::FRem:
2249 case Instruction::Shl:
2250 case Instruction::LShr:
2251 case Instruction::AShr:
2252 case Instruction::And:
2253 case Instruction::Or:
2254 case Instruction::Xor: {
2255 // Just widen unops and binops.
2257 for (VPValue *VPOp : operands())
2258 Ops.push_back(State.get(VPOp));
2259
2260 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2261
2262 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2263 applyFlags(*VecOp);
2264 applyMetadata(*VecOp);
2265 }
2266
2267 // Use this vector value for all users of the original instruction.
2268 State.set(this, V);
2269 break;
2270 }
2271 case Instruction::ExtractValue: {
2272 assert(getNumOperands() == 2 && "expected single level extractvalue");
2273 Value *Op = State.get(getOperand(0));
2275 Value *Extract = Builder.CreateExtractValue(Op, CI->getZExtValue());
2276 State.set(this, Extract);
2277 break;
2278 }
2279 case Instruction::Freeze: {
2280 Value *Op = State.get(getOperand(0));
2281 Value *Freeze = Builder.CreateFreeze(Op);
2282 State.set(this, Freeze);
2283 break;
2284 }
2285 case Instruction::ICmp:
2286 case Instruction::FCmp: {
2287 // Widen compares. Generate vector compares.
2288 bool FCmp = Opcode == Instruction::FCmp;
2289 Value *A = State.get(getOperand(0));
2290 Value *B = State.get(getOperand(1));
2291 Value *C = nullptr;
2292 if (FCmp) {
2293 C = Builder.CreateFCmp(getPredicate(), A, B);
2294 } else {
2295 C = Builder.CreateICmp(getPredicate(), A, B);
2296 }
2297 if (auto *I = dyn_cast<Instruction>(C)) {
2298 applyFlags(*I);
2299 applyMetadata(*I);
2300 }
2301 State.set(this, C);
2302 break;
2303 }
2304 case Instruction::Select: {
2305 VPValue *CondOp = getOperand(0);
2306 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2307 Value *Op0 = State.get(getOperand(1));
2308 Value *Op1 = State.get(getOperand(2));
2309 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2310 State.set(this, Sel);
2311 if (auto *I = dyn_cast<Instruction>(Sel)) {
2313 applyFlags(*I);
2314 applyMetadata(*I);
2315 }
2316 break;
2317 }
2318 default:
2319 // This instruction is not vectorized by simple widening.
2320 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2321 << Instruction::getOpcodeName(Opcode));
2322 llvm_unreachable("Unhandled instruction!");
2323 } // end of switch.
2324
2325#if !defined(NDEBUG)
2326 // Verify that VPlan type inference results agree with the type of the
2327 // generated values.
2328 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2329 State.get(this)->getType() &&
2330 "inferred type and type from generated instructions do not match");
2331#endif
2332}
2333
2335 VPCostContext &Ctx) const {
2336 switch (Opcode) {
2337 case Instruction::UDiv:
2338 case Instruction::SDiv:
2339 case Instruction::SRem:
2340 case Instruction::URem:
2341 // If the div/rem operation isn't safe to speculate and requires
2342 // predication, then the only way we can even create a vplan is to insert
2343 // a select on the second input operand to ensure we use the value of 1
2344 // for the inactive lanes. The select will be costed separately.
2345 case Instruction::FNeg:
2346 case Instruction::Add:
2347 case Instruction::FAdd:
2348 case Instruction::Sub:
2349 case Instruction::FSub:
2350 case Instruction::Mul:
2351 case Instruction::FMul:
2352 case Instruction::FDiv:
2353 case Instruction::FRem:
2354 case Instruction::Shl:
2355 case Instruction::LShr:
2356 case Instruction::AShr:
2357 case Instruction::And:
2358 case Instruction::Or:
2359 case Instruction::Xor:
2360 case Instruction::Freeze:
2361 case Instruction::ExtractValue:
2362 case Instruction::ICmp:
2363 case Instruction::FCmp:
2364 case Instruction::Select:
2365 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2366 default:
2367 llvm_unreachable("Unsupported opcode for instruction");
2368 }
2369}
2370
2371#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2373 VPSlotTracker &SlotTracker) const {
2374 O << Indent << "WIDEN ";
2376 O << " = " << Instruction::getOpcodeName(Opcode);
2377 printFlags(O);
2379}
2380#endif
2381
2383 auto &Builder = State.Builder;
2384 /// Vectorize casts.
2385 assert(State.VF.isVector() && "Not vectorizing?");
2386 Type *DestTy = VectorType::get(getResultType(), State.VF);
2387 VPValue *Op = getOperand(0);
2388 Value *A = State.get(Op);
2389 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2390 State.set(this, Cast);
2391 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2392 applyFlags(*CastOp);
2393 applyMetadata(*CastOp);
2394 }
2395}
2396
2398 VPCostContext &Ctx) const {
2399 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2400 // the legacy cost model, including truncates/extends when evaluating a
2401 // reduction in a smaller type.
2402 if (!getUnderlyingValue())
2403 return 0;
2404 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2405}
2406
2407#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2409 VPSlotTracker &SlotTracker) const {
2410 O << Indent << "WIDEN-CAST ";
2412 O << " = " << Instruction::getOpcodeName(Opcode);
2413 printFlags(O);
2415 O << " to " << *getResultType();
2416}
2417#endif
2418
2420 VPCostContext &Ctx) const {
2421 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2422}
2423
2424#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2426 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2427 O << Indent;
2429 O << " = WIDEN-INDUCTION";
2430 printFlags(O);
2432
2433 if (auto *TI = getTruncInst())
2434 O << " (truncated to " << *TI->getType() << ")";
2435}
2436#endif
2437
2439 // The step may be defined by a recipe in the preheader (e.g. if it requires
2440 // SCEV expansion), but for the canonical induction the step is required to be
2441 // 1, which is represented as live-in.
2443 if (!Step)
2444 return false;
2445 ;
2446 auto *StepC = dyn_cast<ConstantInt>(Step->getValue());
2447 auto *StartC = dyn_cast<ConstantInt>(getStartValue()->getValue());
2448 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2449 getScalarType() == getRegion()->getCanonicalIVType();
2450}
2451
2452#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2454 VPSlotTracker &SlotTracker) const {
2455 O << Indent;
2457 O << " = DERIVED-IV ";
2458 getStartValue()->printAsOperand(O, SlotTracker);
2459 O << " + ";
2460 getOperand(1)->printAsOperand(O, SlotTracker);
2461 O << " * ";
2462 getStepValue()->printAsOperand(O, SlotTracker);
2463}
2464#endif
2465
2467 // Fast-math-flags propagate from the original induction instruction.
2468 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2469 if (hasFastMathFlags())
2470 State.Builder.setFastMathFlags(getFastMathFlags());
2471
2472 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2473 /// variable on which to base the steps, \p Step is the size of the step.
2474
2475 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2476 Value *Step = State.get(getStepValue(), VPLane(0));
2477 IRBuilderBase &Builder = State.Builder;
2478
2479 // Ensure step has the same type as that of scalar IV.
2480 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2481 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2482
2483 // We build scalar steps for both integer and floating-point induction
2484 // variables. Here, we determine the kind of arithmetic we will perform.
2487 if (BaseIVTy->isIntegerTy()) {
2488 AddOp = Instruction::Add;
2489 MulOp = Instruction::Mul;
2490 } else {
2491 AddOp = InductionOpcode;
2492 MulOp = Instruction::FMul;
2493 }
2494
2495 // Determine the number of scalars we need to generate for each unroll
2496 // iteration.
2497 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2498 // Compute the scalar steps and save the results in State.
2499 Type *IntStepTy =
2500 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
2501
2502 unsigned StartLane = 0;
2503 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2504 if (State.Lane) {
2505 StartLane = State.Lane->getKnownLane();
2506 EndLane = StartLane + 1;
2507 }
2508 Value *StartIdx0;
2509 if (getUnrollPart(*this) == 0)
2510 StartIdx0 = ConstantInt::get(IntStepTy, 0);
2511 else {
2512 StartIdx0 = State.get(getOperand(2), true);
2513 if (getUnrollPart(*this) != 1) {
2514 StartIdx0 =
2515 Builder.CreateMul(StartIdx0, ConstantInt::get(StartIdx0->getType(),
2516 getUnrollPart(*this)));
2517 }
2518 StartIdx0 = Builder.CreateSExtOrTrunc(StartIdx0, IntStepTy);
2519 }
2520
2521 if (BaseIVTy->isFloatingPointTy())
2522 StartIdx0 = Builder.CreateSIToFP(StartIdx0, BaseIVTy);
2523
2524 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2525 // It is okay if the induction variable type cannot hold the lane number,
2526 // we expect truncation in this case.
2527 Constant *LaneValue =
2528 BaseIVTy->isIntegerTy()
2529 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2530 /*ImplicitTrunc=*/true)
2531 : ConstantFP::get(BaseIVTy, Lane);
2532 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2533 // The step returned by `createStepForVF` is a runtime-evaluated value
2534 // when VF is scalable. Otherwise, it should be folded into a Constant.
2535 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2536 "Expected StartIdx to be folded to a constant when VF is not "
2537 "scalable");
2538 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2539 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2540 State.set(this, Add, VPLane(Lane));
2541 }
2542}
2543
2544#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2546 VPSlotTracker &SlotTracker) const {
2547 O << Indent;
2549 O << " = SCALAR-STEPS ";
2551}
2552#endif
2553
2555 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2557}
2558
2560 assert(State.VF.isVector() && "not widening");
2561 // Construct a vector GEP by widening the operands of the scalar GEP as
2562 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2563 // results in a vector of pointers when at least one operand of the GEP
2564 // is vector-typed. Thus, to keep the representation compact, we only use
2565 // vector-typed operands for loop-varying values.
2566
2567 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2568 return Op->isDefinedOutsideLoopRegions();
2569 });
2570 if (AllOperandsAreInvariant) {
2571 // If we are vectorizing, but the GEP has only loop-invariant operands,
2572 // the GEP we build (by only using vector-typed operands for
2573 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2574 // produce a vector of pointers, we need to either arbitrarily pick an
2575 // operand to broadcast, or broadcast a clone of the original GEP.
2576 // Here, we broadcast a clone of the original.
2577
2579 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2580 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2581
2582 auto *NewGEP =
2583 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2584 "", getGEPNoWrapFlags());
2585 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2586 State.set(this, Splat);
2587 return;
2588 }
2589
2590 // If the GEP has at least one loop-varying operand, we are sure to
2591 // produce a vector of pointers unless VF is scalar.
2592 // The pointer operand of the new GEP. If it's loop-invariant, we
2593 // won't broadcast it.
2594 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2595
2596 // Collect all the indices for the new GEP. If any index is
2597 // loop-invariant, we won't broadcast it.
2599 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2600 VPValue *Operand = getOperand(I);
2601 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2602 }
2603
2604 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2605 // but it should be a vector, otherwise.
2606 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2607 "", getGEPNoWrapFlags());
2608 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2609 "NewGEP is not a pointer vector");
2610 State.set(this, NewGEP);
2611}
2612
2613#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2615 VPSlotTracker &SlotTracker) const {
2616 O << Indent << "WIDEN-GEP ";
2617 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2618 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2619 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2620
2621 O << " ";
2623 O << " = getelementptr";
2624 printFlags(O);
2626}
2627#endif
2628
2630 auto &Builder = State.Builder;
2631 unsigned CurrentPart = getUnrollPart(*this);
2632 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2633 Type *IndexTy = DL.getIndexType(State.TypeAnalysis.inferScalarType(this));
2634
2635 // The wide store needs to start at the last vector element.
2636 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2637 if (IndexTy != RunTimeVF->getType())
2638 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2639 // NumElt = Stride * CurrentPart * RunTimeVF
2640 Value *NumElt = Builder.CreateMul(
2641 ConstantInt::getSigned(IndexTy, Stride * (int64_t)CurrentPart),
2642 RunTimeVF);
2643 // LastLane = Stride * (RunTimeVF - 1)
2644 Value *LastLane = Builder.CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2645 if (Stride != 1)
2646 LastLane =
2647 Builder.CreateMul(ConstantInt::getSigned(IndexTy, Stride), LastLane);
2648 Value *Ptr = State.get(getOperand(0), VPLane(0));
2649 Value *ResultPtr =
2650 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2651 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2653
2654 State.set(this, ResultPtr, /*IsScalar*/ true);
2655}
2656
2657#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2659 VPSlotTracker &SlotTracker) const {
2660 O << Indent;
2662 O << " = vector-end-pointer";
2663 printFlags(O);
2665}
2666#endif
2667
2669 auto &Builder = State.Builder;
2670 assert(getOffset() &&
2671 "Expected prior simplification of recipe without offset");
2672 Value *Ptr = State.get(getOperand(0), VPLane(0));
2673 Value *Offset = State.get(getOffset(), true);
2674 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2676 State.set(this, ResultPtr, /*IsScalar*/ true);
2677}
2678
2679#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2681 VPSlotTracker &SlotTracker) const {
2682 O << Indent;
2684 O << " = vector-pointer";
2685 printFlags(O);
2687}
2688#endif
2689
2691 VPCostContext &Ctx) const {
2692 // A blend will be expanded to a select VPInstruction, which will generate a
2693 // scalar select if only the first lane is used.
2695 VF = ElementCount::getFixed(1);
2696
2697 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2698 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2699 return (getNumIncomingValues() - 1) *
2700 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2701 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2702}
2703
2704#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2706 VPSlotTracker &SlotTracker) const {
2707 O << Indent << "BLEND ";
2709 O << " =";
2710 if (getNumIncomingValues() == 1) {
2711 // Not a User of any mask: not really blending, this is a
2712 // single-predecessor phi.
2713 O << " ";
2714 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2715 } else {
2716 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2717 O << " ";
2718 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2719 if (I == 0)
2720 continue;
2721 O << "/";
2722 getMask(I)->printAsOperand(O, SlotTracker);
2723 }
2724 }
2725}
2726#endif
2727
2729 assert(!State.Lane && "Reduction being replicated.");
2732 "In-loop AnyOf reductions aren't currently supported");
2733 // Propagate the fast-math flags carried by the underlying instruction.
2734 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2735 State.Builder.setFastMathFlags(getFastMathFlags());
2736 Value *NewVecOp = State.get(getVecOp());
2737 if (VPValue *Cond = getCondOp()) {
2738 Value *NewCond = State.get(Cond, State.VF.isScalar());
2739 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2740 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2741
2742 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2743 if (State.VF.isVector())
2744 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2745
2746 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2747 NewVecOp = Select;
2748 }
2749 Value *NewRed;
2750 Value *NextInChain;
2751 if (isOrdered()) {
2752 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2753 if (State.VF.isVector())
2754 NewRed =
2755 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2756 else
2757 NewRed = State.Builder.CreateBinOp(
2759 PrevInChain, NewVecOp);
2760 PrevInChain = NewRed;
2761 NextInChain = NewRed;
2762 } else if (isPartialReduction()) {
2763 assert(Kind == RecurKind::Add && "Unexpected partial reduction kind");
2764 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2765 NewRed = State.Builder.CreateIntrinsic(
2766 PrevInChain->getType(), Intrinsic::vector_partial_reduce_add,
2767 {PrevInChain, NewVecOp}, nullptr, "partial.reduce");
2768 PrevInChain = NewRed;
2769 NextInChain = NewRed;
2770 } else {
2771 assert(isInLoop() &&
2772 "The reduction must either be ordered, partial or in-loop");
2773 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2774 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2776 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2777 else
2778 NextInChain = State.Builder.CreateBinOp(
2780 PrevInChain, NewRed);
2781 }
2782 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2783}
2784
2786 assert(!State.Lane && "Reduction being replicated.");
2787
2788 auto &Builder = State.Builder;
2789 // Propagate the fast-math flags carried by the underlying instruction.
2790 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2791 Builder.setFastMathFlags(getFastMathFlags());
2792
2794 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2795 Value *VecOp = State.get(getVecOp());
2796 Value *EVL = State.get(getEVL(), VPLane(0));
2797
2798 Value *Mask;
2799 if (VPValue *CondOp = getCondOp())
2800 Mask = State.get(CondOp);
2801 else
2802 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2803
2804 Value *NewRed;
2805 if (isOrdered()) {
2806 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2807 } else {
2808 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2810 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2811 else
2812 NewRed = Builder.CreateBinOp(
2814 Prev);
2815 }
2816 State.set(this, NewRed, /*IsScalar*/ true);
2817}
2818
2820 VPCostContext &Ctx) const {
2821 RecurKind RdxKind = getRecurrenceKind();
2822 Type *ElementTy = Ctx.Types.inferScalarType(this);
2823 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2824 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2826 std::optional<FastMathFlags> OptionalFMF =
2827 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2828
2829 if (isPartialReduction()) {
2830 InstructionCost CondCost = 0;
2831 if (isConditional()) {
2833 auto *CondTy = cast<VectorType>(
2834 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2835 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2836 CondTy, Pred, Ctx.CostKind);
2837 }
2838 return CondCost + Ctx.TTI.getPartialReductionCost(
2839 Opcode, ElementTy, ElementTy, ElementTy, VF,
2841 TargetTransformInfo::PR_None, std::nullopt,
2842 Ctx.CostKind);
2843 }
2844
2845 // TODO: Support any-of reductions.
2846 assert(
2848 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2849 "Any-of reduction not implemented in VPlan-based cost model currently.");
2850
2851 // Note that TTI should model the cost of moving result to the scalar register
2852 // and the BinOp cost in the getMinMaxReductionCost().
2855 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2856 }
2857
2858 // Note that TTI should model the cost of moving result to the scalar register
2859 // and the BinOp cost in the getArithmeticReductionCost().
2860 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2861 Ctx.CostKind);
2862}
2863
2864VPExpressionRecipe::VPExpressionRecipe(
2865 ExpressionTypes ExpressionType,
2866 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2867 : VPSingleDefRecipe(VPDef::VPExpressionSC, {}, {}),
2868 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2869 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2870 assert(
2871 none_of(ExpressionRecipes,
2872 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2873 "expression cannot contain recipes with side-effects");
2874
2875 // Maintain a copy of the expression recipes as a set of users.
2876 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2877 for (auto *R : ExpressionRecipes)
2878 ExpressionRecipesAsSetOfUsers.insert(R);
2879
2880 // Recipes in the expression, except the last one, must only be used by
2881 // (other) recipes inside the expression. If there are other users, external
2882 // to the expression, use a clone of the recipe for external users.
2883 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2884 if (R != ExpressionRecipes.back() &&
2885 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2886 return !ExpressionRecipesAsSetOfUsers.contains(U);
2887 })) {
2888 // There are users outside of the expression. Clone the recipe and use the
2889 // clone those external users.
2890 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2891 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2892 VPUser &U, unsigned) {
2893 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2894 });
2895 CopyForExtUsers->insertBefore(R);
2896 }
2897 if (R->getParent())
2898 R->removeFromParent();
2899 }
2900
2901 // Internalize all external operands to the expression recipes. To do so,
2902 // create new temporary VPValues for all operands defined by a recipe outside
2903 // the expression. The original operands are added as operands of the
2904 // VPExpressionRecipe itself.
2905 for (auto *R : ExpressionRecipes) {
2906 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2907 auto *Def = Op->getDefiningRecipe();
2908 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2909 continue;
2910 addOperand(Op);
2911 LiveInPlaceholders.push_back(new VPSymbolicValue());
2912 }
2913 }
2914
2915 // Replace each external operand with the first one created for it in
2916 // LiveInPlaceholders.
2917 for (auto *R : ExpressionRecipes)
2918 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2919 R->replaceUsesOfWith(LiveIn, Tmp);
2920}
2921
2923 for (auto *R : ExpressionRecipes)
2924 // Since the list could contain duplicates, make sure the recipe hasn't
2925 // already been inserted.
2926 if (!R->getParent())
2927 R->insertBefore(this);
2928
2929 for (const auto &[Idx, Op] : enumerate(operands()))
2930 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
2931
2932 replaceAllUsesWith(ExpressionRecipes.back());
2933 ExpressionRecipes.clear();
2934}
2935
2937 VPCostContext &Ctx) const {
2938 Type *RedTy = Ctx.Types.inferScalarType(this);
2939 auto *SrcVecTy = cast<VectorType>(
2940 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
2941 assert(RedTy->isIntegerTy() &&
2942 "VPExpressionRecipe only supports integer types currently.");
2943 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2944 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
2945 switch (ExpressionType) {
2946 case ExpressionTypes::ExtendedReduction: {
2947 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2948 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
2949 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2950
2951 return cast<VPReductionRecipe>(ExpressionRecipes.back())
2952 ->isPartialReduction()
2953 ? Ctx.TTI.getPartialReductionCost(
2954 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr,
2955 RedTy, VF,
2957 ExtR->getOpcode()),
2958 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind)
2959 : Ctx.TTI.getExtendedReductionCost(
2960 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy,
2961 SrcVecTy, std::nullopt, Ctx.CostKind);
2962 }
2963 case ExpressionTypes::MulAccReduction:
2964 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
2965 Ctx.CostKind);
2966
2967 case ExpressionTypes::ExtNegatedMulAccReduction:
2968 assert(Opcode == Instruction::Add && "Unexpected opcode");
2969 Opcode = Instruction::Sub;
2970 [[fallthrough]];
2971 case ExpressionTypes::ExtMulAccReduction: {
2972 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
2973 if (RedR->isPartialReduction()) {
2974 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2975 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2976 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2977 return Ctx.TTI.getPartialReductionCost(
2978 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
2979 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
2981 Ext0R->getOpcode()),
2983 Ext1R->getOpcode()),
2984 Mul->getOpcode(), Ctx.CostKind);
2985 }
2986 return Ctx.TTI.getMulAccReductionCost(
2987 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2988 Instruction::ZExt,
2989 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
2990 }
2991 }
2992 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
2993}
2994
2996 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
2997 return R->mayReadFromMemory() || R->mayWriteToMemory();
2998 });
2999}
3000
3002 assert(
3003 none_of(ExpressionRecipes,
3004 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3005 "expression cannot contain recipes with side-effects");
3006 return false;
3007}
3008
3010 // Cannot use vputils::isSingleScalar(), because all external operands
3011 // of the expression will be live-ins while bundled.
3012 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3013 return RR && !RR->isPartialReduction();
3014}
3015
3016#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3017
3019 VPSlotTracker &SlotTracker) const {
3020 O << Indent << "EXPRESSION ";
3022 O << " = ";
3023 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3024 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3025
3026 switch (ExpressionType) {
3027 case ExpressionTypes::ExtendedReduction: {
3029 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3030 O << Instruction::getOpcodeName(Opcode) << " (";
3032 Red->printFlags(O);
3033
3034 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3035 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3036 << *Ext0->getResultType();
3037 if (Red->isConditional()) {
3038 O << ", ";
3039 Red->getCondOp()->printAsOperand(O, SlotTracker);
3040 }
3041 O << ")";
3042 break;
3043 }
3044 case ExpressionTypes::ExtNegatedMulAccReduction: {
3046 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3048 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3049 << " (sub (0, mul";
3050 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3051 Mul->printFlags(O);
3052 O << "(";
3054 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3055 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3056 << *Ext0->getResultType() << "), (";
3058 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3059 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3060 << *Ext1->getResultType() << ")";
3061 if (Red->isConditional()) {
3062 O << ", ";
3063 Red->getCondOp()->printAsOperand(O, SlotTracker);
3064 }
3065 O << "))";
3066 break;
3067 }
3068 case ExpressionTypes::MulAccReduction:
3069 case ExpressionTypes::ExtMulAccReduction: {
3071 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3073 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3074 << " (";
3075 O << "mul";
3076 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3077 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3078 : ExpressionRecipes[0]);
3079 Mul->printFlags(O);
3080 if (IsExtended)
3081 O << "(";
3083 if (IsExtended) {
3084 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3085 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3086 << *Ext0->getResultType() << "), (";
3087 } else {
3088 O << ", ";
3089 }
3091 if (IsExtended) {
3092 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3093 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3094 << *Ext1->getResultType() << ")";
3095 }
3096 if (Red->isConditional()) {
3097 O << ", ";
3098 Red->getCondOp()->printAsOperand(O, SlotTracker);
3099 }
3100 O << ")";
3101 break;
3102 }
3103 }
3104}
3105
3107 VPSlotTracker &SlotTracker) const {
3108 if (isPartialReduction())
3109 O << Indent << "PARTIAL-REDUCE ";
3110 else
3111 O << Indent << "REDUCE ";
3113 O << " = ";
3115 O << " +";
3116 printFlags(O);
3117 O << " reduce."
3120 << " (";
3122 if (isConditional()) {
3123 O << ", ";
3125 }
3126 O << ")";
3127}
3128
3130 VPSlotTracker &SlotTracker) const {
3131 O << Indent << "REDUCE ";
3133 O << " = ";
3135 O << " +";
3136 printFlags(O);
3137 O << " vp.reduce."
3140 << " (";
3142 O << ", ";
3144 if (isConditional()) {
3145 O << ", ";
3147 }
3148 O << ")";
3149}
3150
3151#endif
3152
3153/// A helper function to scalarize a single Instruction in the innermost loop.
3154/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3155/// operands from \p RepRecipe instead of \p Instr's operands.
3156static void scalarizeInstruction(const Instruction *Instr,
3157 VPReplicateRecipe *RepRecipe,
3158 const VPLane &Lane, VPTransformState &State) {
3159 assert((!Instr->getType()->isAggregateType() ||
3160 canVectorizeTy(Instr->getType())) &&
3161 "Expected vectorizable or non-aggregate type.");
3162
3163 // Does this instruction return a value ?
3164 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3165
3166 Instruction *Cloned = Instr->clone();
3167 if (!IsVoidRetTy) {
3168 Cloned->setName(Instr->getName() + ".cloned");
3169 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3170 // The operands of the replicate recipe may have been narrowed, resulting in
3171 // a narrower result type. Update the type of the cloned instruction to the
3172 // correct type.
3173 if (ResultTy != Cloned->getType())
3174 Cloned->mutateType(ResultTy);
3175 }
3176
3177 RepRecipe->applyFlags(*Cloned);
3178 RepRecipe->applyMetadata(*Cloned);
3179
3180 if (RepRecipe->hasPredicate())
3181 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3182
3183 if (auto DL = RepRecipe->getDebugLoc())
3184 State.setDebugLocFrom(DL);
3185
3186 // Replace the operands of the cloned instructions with their scalar
3187 // equivalents in the new loop.
3188 for (const auto &I : enumerate(RepRecipe->operands())) {
3189 auto InputLane = Lane;
3190 VPValue *Operand = I.value();
3191 if (vputils::isSingleScalar(Operand))
3192 InputLane = VPLane::getFirstLane();
3193 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3194 }
3195
3196 // Place the cloned scalar in the new loop.
3197 State.Builder.Insert(Cloned);
3198
3199 State.set(RepRecipe, Cloned, Lane);
3200
3201 // If we just cloned a new assumption, add it the assumption cache.
3202 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3203 State.AC->registerAssumption(II);
3204
3205 assert(
3206 (RepRecipe->getRegion() ||
3207 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3208 all_of(RepRecipe->operands(),
3209 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3210 "Expected a recipe is either within a region or all of its operands "
3211 "are defined outside the vectorized region.");
3212}
3213
3216
3217 if (!State.Lane) {
3218 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3219 "must have already been unrolled");
3220 scalarizeInstruction(UI, this, VPLane(0), State);
3221 return;
3222 }
3223
3224 assert((State.VF.isScalar() || !isSingleScalar()) &&
3225 "uniform recipe shouldn't be predicated");
3226 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3227 scalarizeInstruction(UI, this, *State.Lane, State);
3228 // Insert scalar instance packing it into a vector.
3229 if (State.VF.isVector() && shouldPack()) {
3230 Value *WideValue =
3231 State.Lane->isFirstLane()
3232 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3233 : State.get(this);
3234 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3235 *State.Lane));
3236 }
3237}
3238
3240 // Find if the recipe is used by a widened recipe via an intervening
3241 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3242 return any_of(users(), [](const VPUser *U) {
3243 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3244 return !vputils::onlyScalarValuesUsed(PredR);
3245 return false;
3246 });
3247}
3248
3249/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3250/// which the legacy cost model computes a SCEV expression when computing the
3251/// address cost. Computing SCEVs for VPValues is incomplete and returns
3252/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3253/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3254static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3256 const Loop *L) {
3257 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3258 if (isa<SCEVCouldNotCompute>(Addr))
3259 return Addr;
3260
3261 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3262}
3263
3264/// Returns true if \p V is used as part of the address of another load or
3265/// store.
3266static bool isUsedByLoadStoreAddress(const VPUser *V) {
3268 SmallVector<const VPUser *> WorkList = {V};
3269
3270 while (!WorkList.empty()) {
3271 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3272 if (!Cur || !Seen.insert(Cur).second)
3273 continue;
3274
3275 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3276 // Skip blends that use V only through a compare by checking if any incoming
3277 // value was already visited.
3278 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3279 [&](unsigned I) {
3280 return Seen.contains(
3281 Blend->getIncomingValue(I)->getDefiningRecipe());
3282 }))
3283 continue;
3284
3285 for (VPUser *U : Cur->users()) {
3286 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3287 if (InterleaveR->getAddr() == Cur)
3288 return true;
3289 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3290 if (RepR->getOpcode() == Instruction::Load &&
3291 RepR->getOperand(0) == Cur)
3292 return true;
3293 if (RepR->getOpcode() == Instruction::Store &&
3294 RepR->getOperand(1) == Cur)
3295 return true;
3296 }
3297 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3298 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3299 return true;
3300 }
3301 }
3302
3303 // The legacy cost model only supports scalarization loads/stores with phi
3304 // addresses, if the phi is directly used as load/store address. Don't
3305 // traverse further for Blends.
3306 if (Blend)
3307 continue;
3308
3309 append_range(WorkList, Cur->users());
3310 }
3311 return false;
3312}
3313
3315 VPCostContext &Ctx) const {
3317 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3318 // transform, avoid computing their cost multiple times for now.
3319 Ctx.SkipCostComputation.insert(UI);
3320
3321 if (VF.isScalable() && !isSingleScalar())
3323
3324 switch (UI->getOpcode()) {
3325 case Instruction::Alloca:
3326 if (VF.isScalable())
3328 return Ctx.TTI.getArithmeticInstrCost(
3329 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3330 case Instruction::GetElementPtr:
3331 // We mark this instruction as zero-cost because the cost of GEPs in
3332 // vectorized code depends on whether the corresponding memory instruction
3333 // is scalarized or not. Therefore, we handle GEPs with the memory
3334 // instruction cost.
3335 return 0;
3336 case Instruction::Call: {
3337 auto *CalledFn =
3339
3342 for (const VPValue *ArgOp : ArgOps)
3343 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3344
3345 if (CalledFn->isIntrinsic())
3346 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3347 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3348 switch (CalledFn->getIntrinsicID()) {
3349 case Intrinsic::assume:
3350 case Intrinsic::lifetime_end:
3351 case Intrinsic::lifetime_start:
3352 case Intrinsic::sideeffect:
3353 case Intrinsic::pseudoprobe:
3354 case Intrinsic::experimental_noalias_scope_decl: {
3355 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3356 ElementCount::getFixed(1), Ctx) == 0 &&
3357 "scalarizing intrinsic should be free");
3358 return InstructionCost(0);
3359 }
3360 default:
3361 break;
3362 }
3363
3364 Type *ResultTy = Ctx.Types.inferScalarType(this);
3365 InstructionCost ScalarCallCost =
3366 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3367 if (isSingleScalar()) {
3368 if (CalledFn->isIntrinsic())
3369 ScalarCallCost = std::min(
3370 ScalarCallCost,
3371 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3372 ElementCount::getFixed(1), Ctx));
3373 return ScalarCallCost;
3374 }
3375
3376 return ScalarCallCost * VF.getFixedValue() +
3377 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3378 }
3379 case Instruction::Add:
3380 case Instruction::Sub:
3381 case Instruction::FAdd:
3382 case Instruction::FSub:
3383 case Instruction::Mul:
3384 case Instruction::FMul:
3385 case Instruction::FDiv:
3386 case Instruction::FRem:
3387 case Instruction::Shl:
3388 case Instruction::LShr:
3389 case Instruction::AShr:
3390 case Instruction::And:
3391 case Instruction::Or:
3392 case Instruction::Xor:
3393 case Instruction::ICmp:
3394 case Instruction::FCmp:
3396 Ctx) *
3397 (isSingleScalar() ? 1 : VF.getFixedValue());
3398 case Instruction::SDiv:
3399 case Instruction::UDiv:
3400 case Instruction::SRem:
3401 case Instruction::URem: {
3402 InstructionCost ScalarCost =
3404 if (isSingleScalar())
3405 return ScalarCost;
3406
3407 ScalarCost = ScalarCost * VF.getFixedValue() +
3408 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3409 to_vector(operands()), VF);
3410 // If the recipe is not predicated (i.e. not in a replicate region), return
3411 // the scalar cost. Otherwise handle predicated cost.
3412 if (!getRegion()->isReplicator())
3413 return ScalarCost;
3414
3415 // Account for the phi nodes that we will create.
3416 ScalarCost += VF.getFixedValue() *
3417 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3418 // Scale the cost by the probability of executing the predicated blocks.
3419 // This assumes the predicated block for each vector lane is equally
3420 // likely.
3421 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3422 return ScalarCost;
3423 }
3424 case Instruction::Load:
3425 case Instruction::Store: {
3426 // TODO: See getMemInstScalarizationCost for how to handle replicating and
3427 // predicated cases.
3428 const VPRegionBlock *ParentRegion = getRegion();
3429 if (ParentRegion && ParentRegion->isReplicator())
3430 break;
3431
3432 bool IsLoad = UI->getOpcode() == Instruction::Load;
3433 const VPValue *PtrOp = getOperand(!IsLoad);
3434 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3436 break;
3437
3438 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3439 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3440 const Align Alignment = getLoadStoreAlignment(UI);
3441 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3443 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3444 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo);
3445
3446 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3447 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3448 bool UsedByLoadStoreAddress =
3449 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3450 InstructionCost ScalarCost =
3451 ScalarMemOpCost +
3452 Ctx.TTI.getAddressComputationCost(
3453 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3454 Ctx.CostKind);
3455 if (isSingleScalar())
3456 return ScalarCost;
3457
3458 SmallVector<const VPValue *> OpsToScalarize;
3459 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3460 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3461 // don't assign scalarization overhead in general, if the target prefers
3462 // vectorized addressing or the loaded value is used as part of an address
3463 // of another load or store.
3464 if (!UsedByLoadStoreAddress) {
3465 bool EfficientVectorLoadStore =
3466 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3467 if (!(IsLoad && !PreferVectorizedAddressing) &&
3468 !(!IsLoad && EfficientVectorLoadStore))
3469 append_range(OpsToScalarize, operands());
3470
3471 if (!EfficientVectorLoadStore)
3472 ResultTy = Ctx.Types.inferScalarType(this);
3473 }
3474
3475 return (ScalarCost * VF.getFixedValue()) +
3476 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, true);
3477 }
3478 case Instruction::SExt:
3479 case Instruction::ZExt:
3480 case Instruction::FPToUI:
3481 case Instruction::FPToSI:
3482 case Instruction::FPExt:
3483 case Instruction::PtrToInt:
3484 case Instruction::PtrToAddr:
3485 case Instruction::IntToPtr:
3486 case Instruction::SIToFP:
3487 case Instruction::UIToFP:
3488 case Instruction::Trunc:
3489 case Instruction::FPTrunc:
3490 case Instruction::AddrSpaceCast: {
3492 Ctx) *
3493 (isSingleScalar() ? 1 : VF.getFixedValue());
3494 }
3495 case Instruction::ExtractValue:
3496 case Instruction::InsertValue:
3497 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3498 }
3499
3500 return Ctx.getLegacyCost(UI, VF);
3501}
3502
3503#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3505 VPSlotTracker &SlotTracker) const {
3506 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3507
3508 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3510 O << " = ";
3511 }
3512 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3513 O << "call";
3514 printFlags(O);
3515 O << "@" << CB->getCalledFunction()->getName() << "(";
3517 O, [&O, &SlotTracker](VPValue *Op) {
3518 Op->printAsOperand(O, SlotTracker);
3519 });
3520 O << ")";
3521 } else {
3523 printFlags(O);
3525 }
3526
3527 if (shouldPack())
3528 O << " (S->V)";
3529}
3530#endif
3531
3533 assert(State.Lane && "Branch on Mask works only on single instance.");
3534
3535 VPValue *BlockInMask = getOperand(0);
3536 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3537
3538 // Replace the temporary unreachable terminator with a new conditional branch,
3539 // whose two destinations will be set later when they are created.
3540 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3541 assert(isa<UnreachableInst>(CurrentTerminator) &&
3542 "Expected to replace unreachable terminator with conditional branch.");
3543 auto CondBr =
3544 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3545 CondBr->setSuccessor(0, nullptr);
3546 CurrentTerminator->eraseFromParent();
3547}
3548
3550 VPCostContext &Ctx) const {
3551 // The legacy cost model doesn't assign costs to branches for individual
3552 // replicate regions. Match the current behavior in the VPlan cost model for
3553 // now.
3554 return 0;
3555}
3556
3558 assert(State.Lane && "Predicated instruction PHI works per instance.");
3559 Instruction *ScalarPredInst =
3560 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3561 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3562 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3563 assert(PredicatingBB && "Predicated block has no single predecessor.");
3565 "operand must be VPReplicateRecipe");
3566
3567 // By current pack/unpack logic we need to generate only a single phi node: if
3568 // a vector value for the predicated instruction exists at this point it means
3569 // the instruction has vector users only, and a phi for the vector value is
3570 // needed. In this case the recipe of the predicated instruction is marked to
3571 // also do that packing, thereby "hoisting" the insert-element sequence.
3572 // Otherwise, a phi node for the scalar value is needed.
3573 if (State.hasVectorValue(getOperand(0))) {
3574 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3576 "Packed operands must generate an insertelement or insertvalue");
3577
3578 // If VectorI is a struct, it will be a sequence like:
3579 // %1 = insertvalue %unmodified, %x, 0
3580 // %2 = insertvalue %1, %y, 1
3581 // %VectorI = insertvalue %2, %z, 2
3582 // To get the unmodified vector we need to look through the chain.
3583 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3584 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3585 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3586
3587 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3588 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3589 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3590 if (State.hasVectorValue(this))
3591 State.reset(this, VPhi);
3592 else
3593 State.set(this, VPhi);
3594 // NOTE: Currently we need to update the value of the operand, so the next
3595 // predicated iteration inserts its generated value in the correct vector.
3596 State.reset(getOperand(0), VPhi);
3597 } else {
3598 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3599 return;
3600
3601 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3602 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3603 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3604 PredicatingBB);
3605 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3606 if (State.hasScalarValue(this, *State.Lane))
3607 State.reset(this, Phi, *State.Lane);
3608 else
3609 State.set(this, Phi, *State.Lane);
3610 // NOTE: Currently we need to update the value of the operand, so the next
3611 // predicated iteration inserts its generated value in the correct vector.
3612 State.reset(getOperand(0), Phi, *State.Lane);
3613 }
3614}
3615
3616#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3618 VPSlotTracker &SlotTracker) const {
3619 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3621 O << " = ";
3623}
3624#endif
3625
3627 VPCostContext &Ctx) const {
3629 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3630 ->getAddressSpace();
3631 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3632 ? Instruction::Load
3633 : Instruction::Store;
3634
3635 if (!Consecutive) {
3636 // TODO: Using the original IR may not be accurate.
3637 // Currently, ARM will use the underlying IR to calculate gather/scatter
3638 // instruction cost.
3639 assert(!Reverse &&
3640 "Inconsecutive memory access should not have the order.");
3641
3643 Type *PtrTy = Ptr->getType();
3644
3645 // If the address value is uniform across all lanes, then the address can be
3646 // calculated with scalar type and broadcast.
3648 PtrTy = toVectorTy(PtrTy, VF);
3649
3650 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3651 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3652 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3653 : Intrinsic::vp_scatter;
3654 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3655 Ctx.CostKind) +
3656 Ctx.TTI.getMemIntrinsicInstrCost(
3658 &Ingredient),
3659 Ctx.CostKind);
3660 }
3661
3663 if (IsMasked) {
3664 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3665 : Intrinsic::masked_store;
3666 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3667 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3668 } else {
3669 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3671 : getOperand(1));
3672 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3673 OpInfo, &Ingredient);
3674 }
3675 return Cost;
3676}
3677
3679 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3680 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3681 bool CreateGather = !isConsecutive();
3682
3683 auto &Builder = State.Builder;
3684 Value *Mask = nullptr;
3685 if (auto *VPMask = getMask()) {
3686 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3687 // of a null all-one mask is a null mask.
3688 Mask = State.get(VPMask);
3689 if (isReverse())
3690 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3691 }
3692
3693 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3694 Value *NewLI;
3695 if (CreateGather) {
3696 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3697 "wide.masked.gather");
3698 } else if (Mask) {
3699 NewLI =
3700 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3701 PoisonValue::get(DataTy), "wide.masked.load");
3702 } else {
3703 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3704 }
3706 State.set(this, NewLI);
3707}
3708
3709#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3711 VPSlotTracker &SlotTracker) const {
3712 O << Indent << "WIDEN ";
3714 O << " = load ";
3716}
3717#endif
3718
3719/// Use all-true mask for reverse rather than actual mask, as it avoids a
3720/// dependence w/o affecting the result.
3722 Value *EVL, const Twine &Name) {
3723 VectorType *ValTy = cast<VectorType>(Operand->getType());
3724 Value *AllTrueMask =
3725 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3726 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3727 {Operand, AllTrueMask, EVL}, nullptr, Name);
3728}
3729
3731 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3732 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3733 bool CreateGather = !isConsecutive();
3734
3735 auto &Builder = State.Builder;
3736 CallInst *NewLI;
3737 Value *EVL = State.get(getEVL(), VPLane(0));
3738 Value *Addr = State.get(getAddr(), !CreateGather);
3739 Value *Mask = nullptr;
3740 if (VPValue *VPMask = getMask()) {
3741 Mask = State.get(VPMask);
3742 if (isReverse())
3743 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3744 } else {
3745 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3746 }
3747
3748 if (CreateGather) {
3749 NewLI =
3750 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3751 nullptr, "wide.masked.gather");
3752 } else {
3753 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3754 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3755 }
3756 NewLI->addParamAttr(
3758 applyMetadata(*NewLI);
3759 Instruction *Res = NewLI;
3760 State.set(this, Res);
3761}
3762
3764 VPCostContext &Ctx) const {
3765 if (!Consecutive || IsMasked)
3766 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3767
3768 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3769 // here because the EVL recipes using EVL to replace the tail mask. But in the
3770 // legacy model, it will always calculate the cost of mask.
3771 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3772 // don't need to compare to the legacy cost model.
3774 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3775 ->getAddressSpace();
3776 return Ctx.TTI.getMemIntrinsicInstrCost(
3777 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3778 Ctx.CostKind);
3779}
3780
3781#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3783 VPSlotTracker &SlotTracker) const {
3784 O << Indent << "WIDEN ";
3786 O << " = vp.load ";
3788}
3789#endif
3790
3792 VPValue *StoredVPValue = getStoredValue();
3793 bool CreateScatter = !isConsecutive();
3794
3795 auto &Builder = State.Builder;
3796
3797 Value *Mask = nullptr;
3798 if (auto *VPMask = getMask()) {
3799 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3800 // of a null all-one mask is a null mask.
3801 Mask = State.get(VPMask);
3802 if (isReverse())
3803 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3804 }
3805
3806 Value *StoredVal = State.get(StoredVPValue);
3807 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3808 Instruction *NewSI = nullptr;
3809 if (CreateScatter)
3810 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3811 else if (Mask)
3812 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3813 else
3814 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3815 applyMetadata(*NewSI);
3816}
3817
3818#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3820 VPSlotTracker &SlotTracker) const {
3821 O << Indent << "WIDEN store ";
3823}
3824#endif
3825
3827 VPValue *StoredValue = getStoredValue();
3828 bool CreateScatter = !isConsecutive();
3829
3830 auto &Builder = State.Builder;
3831
3832 CallInst *NewSI = nullptr;
3833 Value *StoredVal = State.get(StoredValue);
3834 Value *EVL = State.get(getEVL(), VPLane(0));
3835 Value *Mask = nullptr;
3836 if (VPValue *VPMask = getMask()) {
3837 Mask = State.get(VPMask);
3838 if (isReverse())
3839 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3840 } else {
3841 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3842 }
3843 Value *Addr = State.get(getAddr(), !CreateScatter);
3844 if (CreateScatter) {
3845 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3846 Intrinsic::vp_scatter,
3847 {StoredVal, Addr, Mask, EVL});
3848 } else {
3849 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3850 Intrinsic::vp_store,
3851 {StoredVal, Addr, Mask, EVL});
3852 }
3853 NewSI->addParamAttr(
3855 applyMetadata(*NewSI);
3856}
3857
3859 VPCostContext &Ctx) const {
3860 if (!Consecutive || IsMasked)
3861 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3862
3863 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3864 // here because the EVL recipes using EVL to replace the tail mask. But in the
3865 // legacy model, it will always calculate the cost of mask.
3866 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3867 // don't need to compare to the legacy cost model.
3869 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3870 ->getAddressSpace();
3871 return Ctx.TTI.getMemIntrinsicInstrCost(
3872 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3873 Ctx.CostKind);
3874}
3875
3876#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3878 VPSlotTracker &SlotTracker) const {
3879 O << Indent << "WIDEN vp.store ";
3881}
3882#endif
3883
3885 VectorType *DstVTy, const DataLayout &DL) {
3886 // Verify that V is a vector type with same number of elements as DstVTy.
3887 auto VF = DstVTy->getElementCount();
3888 auto *SrcVecTy = cast<VectorType>(V->getType());
3889 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3890 Type *SrcElemTy = SrcVecTy->getElementType();
3891 Type *DstElemTy = DstVTy->getElementType();
3892 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3893 "Vector elements must have same size");
3894
3895 // Do a direct cast if element types are castable.
3896 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3897 return Builder.CreateBitOrPointerCast(V, DstVTy);
3898 }
3899 // V cannot be directly casted to desired vector type.
3900 // May happen when V is a floating point vector but DstVTy is a vector of
3901 // pointers or vice-versa. Handle this using a two-step bitcast using an
3902 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3903 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3904 "Only one type should be a pointer type");
3905 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3906 "Only one type should be a floating point type");
3907 Type *IntTy =
3908 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3909 auto *VecIntTy = VectorType::get(IntTy, VF);
3910 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3911 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3912}
3913
3914/// Return a vector containing interleaved elements from multiple
3915/// smaller input vectors.
3917 const Twine &Name) {
3918 unsigned Factor = Vals.size();
3919 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
3920
3921 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
3922#ifndef NDEBUG
3923 for (Value *Val : Vals)
3924 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
3925#endif
3926
3927 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
3928 // must use intrinsics to interleave.
3929 if (VecTy->isScalableTy()) {
3930 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
3931 return Builder.CreateVectorInterleave(Vals, Name);
3932 }
3933
3934 // Fixed length. Start by concatenating all vectors into a wide vector.
3935 Value *WideVec = concatenateVectors(Builder, Vals);
3936
3937 // Interleave the elements into the wide vector.
3938 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3939 return Builder.CreateShuffleVector(
3940 WideVec, createInterleaveMask(NumElts, Factor), Name);
3941}
3942
3943// Try to vectorize the interleave group that \p Instr belongs to.
3944//
3945// E.g. Translate following interleaved load group (factor = 3):
3946// for (i = 0; i < N; i+=3) {
3947// R = Pic[i]; // Member of index 0
3948// G = Pic[i+1]; // Member of index 1
3949// B = Pic[i+2]; // Member of index 2
3950// ... // do something to R, G, B
3951// }
3952// To:
3953// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
3954// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
3955// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
3956// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
3957//
3958// Or translate following interleaved store group (factor = 3):
3959// for (i = 0; i < N; i+=3) {
3960// ... do something to R, G, B
3961// Pic[i] = R; // Member of index 0
3962// Pic[i+1] = G; // Member of index 1
3963// Pic[i+2] = B; // Member of index 2
3964// }
3965// To:
3966// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
3967// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
3968// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
3969// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
3970// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
3972 assert(!State.Lane && "Interleave group being replicated.");
3973 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
3974 "Masking gaps for scalable vectors is not yet supported.");
3976 Instruction *Instr = Group->getInsertPos();
3977
3978 // Prepare for the vector type of the interleaved load/store.
3979 Type *ScalarTy = getLoadStoreType(Instr);
3980 unsigned InterleaveFactor = Group->getFactor();
3981 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
3982
3983 VPValue *BlockInMask = getMask();
3984 VPValue *Addr = getAddr();
3985 Value *ResAddr = State.get(Addr, VPLane(0));
3986
3987 auto CreateGroupMask = [&BlockInMask, &State,
3988 &InterleaveFactor](Value *MaskForGaps) -> Value * {
3989 if (State.VF.isScalable()) {
3990 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
3991 assert(InterleaveFactor <= 8 &&
3992 "Unsupported deinterleave factor for scalable vectors");
3993 auto *ResBlockInMask = State.get(BlockInMask);
3994 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
3995 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
3996 }
3997
3998 if (!BlockInMask)
3999 return MaskForGaps;
4000
4001 Value *ResBlockInMask = State.get(BlockInMask);
4002 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4003 ResBlockInMask,
4004 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4005 "interleaved.mask");
4006 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4007 ShuffledMask, MaskForGaps)
4008 : ShuffledMask;
4009 };
4010
4011 const DataLayout &DL = Instr->getDataLayout();
4012 // Vectorize the interleaved load group.
4013 if (isa<LoadInst>(Instr)) {
4014 Value *MaskForGaps = nullptr;
4015 if (needsMaskForGaps()) {
4016 MaskForGaps =
4017 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4018 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4019 }
4020
4021 Instruction *NewLoad;
4022 if (BlockInMask || MaskForGaps) {
4023 Value *GroupMask = CreateGroupMask(MaskForGaps);
4024 Value *PoisonVec = PoisonValue::get(VecTy);
4025 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4026 Group->getAlign(), GroupMask,
4027 PoisonVec, "wide.masked.vec");
4028 } else
4029 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4030 Group->getAlign(), "wide.vec");
4031 applyMetadata(*NewLoad);
4032 // TODO: Also manage existing metadata using VPIRMetadata.
4033 Group->addMetadata(NewLoad);
4034
4036 if (VecTy->isScalableTy()) {
4037 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4038 // so must use intrinsics to deinterleave.
4039 assert(InterleaveFactor <= 8 &&
4040 "Unsupported deinterleave factor for scalable vectors");
4041 NewLoad = State.Builder.CreateIntrinsic(
4042 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4043 NewLoad->getType(), NewLoad,
4044 /*FMFSource=*/nullptr, "strided.vec");
4045 }
4046
4047 auto CreateStridedVector = [&InterleaveFactor, &State,
4048 &NewLoad](unsigned Index) -> Value * {
4049 assert(Index < InterleaveFactor && "Illegal group index");
4050 if (State.VF.isScalable())
4051 return State.Builder.CreateExtractValue(NewLoad, Index);
4052
4053 // For fixed length VF, use shuffle to extract the sub-vectors from the
4054 // wide load.
4055 auto StrideMask =
4056 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4057 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4058 "strided.vec");
4059 };
4060
4061 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4062 Instruction *Member = Group->getMember(I);
4063
4064 // Skip the gaps in the group.
4065 if (!Member)
4066 continue;
4067
4068 Value *StridedVec = CreateStridedVector(I);
4069
4070 // If this member has different type, cast the result type.
4071 if (Member->getType() != ScalarTy) {
4072 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4073 StridedVec =
4074 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4075 }
4076
4077 if (Group->isReverse())
4078 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4079
4080 State.set(VPDefs[J], StridedVec);
4081 ++J;
4082 }
4083 return;
4084 }
4085
4086 // The sub vector type for current instruction.
4087 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4088
4089 // Vectorize the interleaved store group.
4090 Value *MaskForGaps =
4091 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4092 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4093 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4094 ArrayRef<VPValue *> StoredValues = getStoredValues();
4095 // Collect the stored vector from each member.
4096 SmallVector<Value *, 4> StoredVecs;
4097 unsigned StoredIdx = 0;
4098 for (unsigned i = 0; i < InterleaveFactor; i++) {
4099 assert((Group->getMember(i) || MaskForGaps) &&
4100 "Fail to get a member from an interleaved store group");
4101 Instruction *Member = Group->getMember(i);
4102
4103 // Skip the gaps in the group.
4104 if (!Member) {
4105 Value *Undef = PoisonValue::get(SubVT);
4106 StoredVecs.push_back(Undef);
4107 continue;
4108 }
4109
4110 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4111 ++StoredIdx;
4112
4113 if (Group->isReverse())
4114 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4115
4116 // If this member has different type, cast it to a unified type.
4117
4118 if (StoredVec->getType() != SubVT)
4119 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4120
4121 StoredVecs.push_back(StoredVec);
4122 }
4123
4124 // Interleave all the smaller vectors into one wider vector.
4125 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4126 Instruction *NewStoreInstr;
4127 if (BlockInMask || MaskForGaps) {
4128 Value *GroupMask = CreateGroupMask(MaskForGaps);
4129 NewStoreInstr = State.Builder.CreateMaskedStore(
4130 IVec, ResAddr, Group->getAlign(), GroupMask);
4131 } else
4132 NewStoreInstr =
4133 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4134
4135 applyMetadata(*NewStoreInstr);
4136 // TODO: Also manage existing metadata using VPIRMetadata.
4137 Group->addMetadata(NewStoreInstr);
4138}
4139
4140#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4142 VPSlotTracker &SlotTracker) const {
4144 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4145 IG->getInsertPos()->printAsOperand(O, false);
4146 O << ", ";
4148 VPValue *Mask = getMask();
4149 if (Mask) {
4150 O << ", ";
4151 Mask->printAsOperand(O, SlotTracker);
4152 }
4153
4154 unsigned OpIdx = 0;
4155 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4156 if (!IG->getMember(i))
4157 continue;
4158 if (getNumStoreOperands() > 0) {
4159 O << "\n" << Indent << " store ";
4161 O << " to index " << i;
4162 } else {
4163 O << "\n" << Indent << " ";
4165 O << " = load from index " << i;
4166 }
4167 ++OpIdx;
4168 }
4169}
4170#endif
4171
4173 assert(!State.Lane && "Interleave group being replicated.");
4174 assert(State.VF.isScalable() &&
4175 "Only support scalable VF for EVL tail-folding.");
4177 "Masking gaps for scalable vectors is not yet supported.");
4179 Instruction *Instr = Group->getInsertPos();
4180
4181 // Prepare for the vector type of the interleaved load/store.
4182 Type *ScalarTy = getLoadStoreType(Instr);
4183 unsigned InterleaveFactor = Group->getFactor();
4184 assert(InterleaveFactor <= 8 &&
4185 "Unsupported deinterleave/interleave factor for scalable vectors");
4186 ElementCount WideVF = State.VF * InterleaveFactor;
4187 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4188
4189 VPValue *Addr = getAddr();
4190 Value *ResAddr = State.get(Addr, VPLane(0));
4191 Value *EVL = State.get(getEVL(), VPLane(0));
4192 Value *InterleaveEVL = State.Builder.CreateMul(
4193 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4194 /* NUW= */ true, /* NSW= */ true);
4195 LLVMContext &Ctx = State.Builder.getContext();
4196
4197 Value *GroupMask = nullptr;
4198 if (VPValue *BlockInMask = getMask()) {
4199 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4200 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4201 } else {
4202 GroupMask =
4203 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4204 }
4205
4206 // Vectorize the interleaved load group.
4207 if (isa<LoadInst>(Instr)) {
4208 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4209 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4210 "wide.vp.load");
4211 NewLoad->addParamAttr(0,
4212 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4213
4214 applyMetadata(*NewLoad);
4215 // TODO: Also manage existing metadata using VPIRMetadata.
4216 Group->addMetadata(NewLoad);
4217
4218 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4219 // so must use intrinsics to deinterleave.
4220 NewLoad = State.Builder.CreateIntrinsic(
4221 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4222 NewLoad->getType(), NewLoad,
4223 /*FMFSource=*/nullptr, "strided.vec");
4224
4225 const DataLayout &DL = Instr->getDataLayout();
4226 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4227 Instruction *Member = Group->getMember(I);
4228 // Skip the gaps in the group.
4229 if (!Member)
4230 continue;
4231
4232 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4233 // If this member has different type, cast the result type.
4234 if (Member->getType() != ScalarTy) {
4235 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4236 StridedVec =
4237 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4238 }
4239
4240 State.set(getVPValue(J), StridedVec);
4241 ++J;
4242 }
4243 return;
4244 } // End for interleaved load.
4245
4246 // The sub vector type for current instruction.
4247 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4248 // Vectorize the interleaved store group.
4249 ArrayRef<VPValue *> StoredValues = getStoredValues();
4250 // Collect the stored vector from each member.
4251 SmallVector<Value *, 4> StoredVecs;
4252 const DataLayout &DL = Instr->getDataLayout();
4253 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4254 Instruction *Member = Group->getMember(I);
4255 // Skip the gaps in the group.
4256 if (!Member) {
4257 StoredVecs.push_back(PoisonValue::get(SubVT));
4258 continue;
4259 }
4260
4261 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4262 // If this member has different type, cast it to a unified type.
4263 if (StoredVec->getType() != SubVT)
4264 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4265
4266 StoredVecs.push_back(StoredVec);
4267 ++StoredIdx;
4268 }
4269
4270 // Interleave all the smaller vectors into one wider vector.
4271 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4272 CallInst *NewStore =
4273 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4274 {IVec, ResAddr, GroupMask, InterleaveEVL});
4275 NewStore->addParamAttr(1,
4276 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4277
4278 applyMetadata(*NewStore);
4279 // TODO: Also manage existing metadata using VPIRMetadata.
4280 Group->addMetadata(NewStore);
4281}
4282
4283#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4285 VPSlotTracker &SlotTracker) const {
4287 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4288 IG->getInsertPos()->printAsOperand(O, false);
4289 O << ", ";
4291 O << ", ";
4293 if (VPValue *Mask = getMask()) {
4294 O << ", ";
4295 Mask->printAsOperand(O, SlotTracker);
4296 }
4297
4298 unsigned OpIdx = 0;
4299 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4300 if (!IG->getMember(i))
4301 continue;
4302 if (getNumStoreOperands() > 0) {
4303 O << "\n" << Indent << " vp.store ";
4305 O << " to index " << i;
4306 } else {
4307 O << "\n" << Indent << " ";
4309 O << " = vp.load from index " << i;
4310 }
4311 ++OpIdx;
4312 }
4313}
4314#endif
4315
4317 VPCostContext &Ctx) const {
4318 Instruction *InsertPos = getInsertPos();
4319 // Find the VPValue index of the interleave group. We need to skip gaps.
4320 unsigned InsertPosIdx = 0;
4321 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4322 if (auto *Member = IG->getMember(Idx)) {
4323 if (Member == InsertPos)
4324 break;
4325 InsertPosIdx++;
4326 }
4327 Type *ValTy = Ctx.Types.inferScalarType(
4328 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4329 : getStoredValues()[InsertPosIdx]);
4330 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4331 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4332 ->getAddressSpace();
4333
4334 unsigned InterleaveFactor = IG->getFactor();
4335 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4336
4337 // Holds the indices of existing members in the interleaved group.
4339 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4340 if (IG->getMember(IF))
4341 Indices.push_back(IF);
4342
4343 // Calculate the cost of the whole interleaved group.
4344 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4345 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4346 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4347
4348 if (!IG->isReverse())
4349 return Cost;
4350
4351 return Cost + IG->getNumMembers() *
4352 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4353 VectorTy, VectorTy, {}, Ctx.CostKind,
4354 0);
4355}
4356
4357#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4359 VPSlotTracker &SlotTracker) const {
4360 O << Indent << "EMIT ";
4362 O << " = CANONICAL-INDUCTION ";
4364}
4365#endif
4366
4368 return vputils::onlyScalarValuesUsed(this) &&
4369 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4370}
4371
4372#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4374 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4375 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4376 "unexpected number of operands");
4377 O << Indent << "EMIT ";
4379 O << " = WIDEN-POINTER-INDUCTION ";
4381 O << ", ";
4383 O << ", ";
4385 if (getNumOperands() == 5) {
4386 O << ", ";
4388 O << ", ";
4390 }
4391}
4392
4394 VPSlotTracker &SlotTracker) const {
4395 O << Indent << "EMIT ";
4397 O << " = EXPAND SCEV " << *Expr;
4398}
4399#endif
4400
4402 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4403 Type *STy = CanonicalIV->getType();
4404 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4405 ElementCount VF = State.VF;
4406 Value *VStart = VF.isScalar()
4407 ? CanonicalIV
4408 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4409 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4410 if (VF.isVector()) {
4411 VStep = Builder.CreateVectorSplat(VF, VStep);
4412 VStep =
4413 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4414 }
4415 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4416 State.set(this, CanonicalVectorIV);
4417}
4418
4419#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4421 VPSlotTracker &SlotTracker) const {
4422 O << Indent << "EMIT ";
4424 O << " = WIDEN-CANONICAL-INDUCTION ";
4426}
4427#endif
4428
4430 auto &Builder = State.Builder;
4431 // Create a vector from the initial value.
4432 auto *VectorInit = getStartValue()->getLiveInIRValue();
4433
4434 Type *VecTy = State.VF.isScalar()
4435 ? VectorInit->getType()
4436 : VectorType::get(VectorInit->getType(), State.VF);
4437
4438 BasicBlock *VectorPH =
4439 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4440 if (State.VF.isVector()) {
4441 auto *IdxTy = Builder.getInt32Ty();
4442 auto *One = ConstantInt::get(IdxTy, 1);
4443 IRBuilder<>::InsertPointGuard Guard(Builder);
4444 Builder.SetInsertPoint(VectorPH->getTerminator());
4445 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4446 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4447 VectorInit = Builder.CreateInsertElement(
4448 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4449 }
4450
4451 // Create a phi node for the new recurrence.
4452 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4453 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4454 Phi->addIncoming(VectorInit, VectorPH);
4455 State.set(this, Phi);
4456}
4457
4460 VPCostContext &Ctx) const {
4461 if (VF.isScalar())
4462 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4463
4464 return 0;
4465}
4466
4467#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4469 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4470 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4472 O << " = phi ";
4474}
4475#endif
4476
4478 // Reductions do not have to start at zero. They can start with
4479 // any loop invariant values.
4480 VPValue *StartVPV = getStartValue();
4481
4482 // In order to support recurrences we need to be able to vectorize Phi nodes.
4483 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4484 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4485 // this value when we vectorize all of the instructions that use the PHI.
4486 BasicBlock *VectorPH =
4487 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4488 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4489 Value *StartV = State.get(StartVPV, ScalarPHI);
4490 Type *VecTy = StartV->getType();
4491
4492 BasicBlock *HeaderBB = State.CFG.PrevBB;
4493 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4494 "recipe must be in the vector loop header");
4495 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4496 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4497 State.set(this, Phi, isInLoop());
4498
4499 Phi->addIncoming(StartV, VectorPH);
4500}
4501
4502#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4504 VPSlotTracker &SlotTracker) const {
4505 O << Indent << "WIDEN-REDUCTION-PHI ";
4506
4508 O << " = phi ";
4510 if (getVFScaleFactor() > 1)
4511 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4512}
4513#endif
4514
4516 Value *Op0 = State.get(getOperand(0));
4517 Type *VecTy = Op0->getType();
4518 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4519 State.set(this, VecPhi);
4520}
4521
4523 VPCostContext &Ctx) const {
4524 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4525}
4526
4527#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4529 VPSlotTracker &SlotTracker) const {
4530 O << Indent << "WIDEN-PHI ";
4531
4533 O << " = phi ";
4535}
4536#endif
4537
4539 BasicBlock *VectorPH =
4540 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4541 Value *StartMask = State.get(getOperand(0));
4542 PHINode *Phi =
4543 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4544 Phi->addIncoming(StartMask, VectorPH);
4545 State.set(this, Phi);
4546}
4547
4548#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4550 VPSlotTracker &SlotTracker) const {
4551 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4552
4554 O << " = phi ";
4556}
4557#endif
4558
4559#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4561 VPSlotTracker &SlotTracker) const {
4562 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
4563
4565 O << " = phi ";
4567}
4568#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 GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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, LoopVectorizationLegality *Legal, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
#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
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 InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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 the shared class of boolean and integer constants.
Definition Constants.h:87
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
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
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:22
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:272
void setAllowContract(bool B=true)
Definition FMF.h:90
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setAllowReciprocal(bool B=true)
Definition FMF.h:87
bool allowReciprocal() const
Definition FMF.h:68
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool approxFunc() const
Definition FMF.h:70
void setNoNaNs(bool B=true)
Definition FMF.h:78
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:75
bool noNaNs() const
Definition FMF.h:65
void setApproxFunc(bool B=true)
Definition FMF.h:93
void setNoInfs(bool B=true)
Definition FMF.h:81
bool allowContract() const
Definition FMF.h:69
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:661
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:594
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:214
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:2553
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:547
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2607
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2541
LLVM_ABI Value * CreateVectorSplice(Value *V1, Value *V2, int64_t Imm, const Twine &Name="")
Return a vector splice intrinsic if using scalable vectors, otherwise return a shufflevector.
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:2600
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:2619
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:562
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2007
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:567
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:2304
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:1725
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:2434
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1808
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2300
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1134
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1420
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:1197
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2053
LLVM_ABI CallInst * CreateIntMaxReduce(Value *Src, bool IsSigned=false)
Create a vector integer max reduction intrinsic of the source vector.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1403
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:1708
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2312
LLVM_ABI CallInst * CreateIntMinReduce(Value *Src, bool IsSigned=false)
Create a vector integer min reduction intrinsic of the source vector.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2410
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1573
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1437
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2762
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
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:318
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 bool isSignedRecurrenceKind(RecurKind Kind)
Returns true if recurrece kind is a signed redux kind.
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 isFindLastIVRecurrenceKind(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 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
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 getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) 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.
@ 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.
@ None
The cast is not used with a load/store of any kind.
@ 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
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:314
void setOperand(unsigned i, Value *Val)
Definition User.h:238
Value * getOperand(unsigned i) const
Definition User.h:233
value_op_iterator value_op_begin()
Definition User.h:311
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.
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4062
iterator end()
Definition VPlan.h:4046
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4075
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:2587
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2582
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:204
VPlan * getPlan()
Definition VPlan.cpp:173
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:349
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.
This class augments a recipe with a set of VPValues defined by the recipe.
Definition VPlanValue.h:332
LLVM_ABI_FOR_TEST void dump() const
Dump the VPDef to stderr (for debugging).
Definition VPlan.cpp:110
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:453
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:426
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:438
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:448
unsigned getVPDefID() const
Definition VPlanValue.h:458
VPIRValue * getStartValue() const
Definition VPlan.h:3810
VPValue * getStepValue() const
Definition VPlan.h:3811
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.
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:2107
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:1858
Class to record and manage LLVM IR flags.
Definition VPlan.h:608
FastMathFlagsTy FMFs
Definition VPlan.h:695
ReductionFlagsTy ReductionFlags
Definition VPlan.h:697
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:689
CmpInst::Predicate CmpPredicate
Definition VPlan.h:688
void printFlags(raw_ostream &O) const
GEPNoWrapFlags GEPFlags
Definition VPlan.h:693
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:882
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
bool isReductionOrdered() const
Definition VPlan.h:932
TruncFlagsTy TruncFlags
Definition VPlan.h:690
CmpInst::Predicate getPredicate() const
Definition VPlan.h:859
ExactFlagsTy ExactFlags
Definition VPlan.h:692
bool hasNoSignedWrap() const
Definition VPlan.h:909
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:874
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:877
DisjointFlagsTy DisjointFlags
Definition VPlan.h:691
unsigned AllFlags
Definition VPlan.h:698
bool hasNoUnsignedWrap() const
Definition VPlan.h:898
FCmpFlagsTy FCmpFlags
Definition VPlan.h:696
NonNegFlagsTy NonNegFlags
Definition VPlan.h:694
bool isReductionInLoop() const
Definition VPlan.h:938
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:816
RecurKind getRecurKind() const
Definition VPlan.h:926
Instruction & getInstruction() const
Definition VPlan.h:1512
void extractLastLaneOfLastPartOfFirstOperand(VPBuilder &Builder)
Update the recipe's first operand to the last lane of the last part of the operand using Builder.
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:1487
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.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
static unsigned getNumOperandsForOpcode(unsigned Opcode)
Return the number of operands determined by the opcode of the VPInstruction.
bool doesGeneratePerAllLanes() const
Returns true if this VPInstruction generates scalar values for all lanes.
@ ExtractLastActive
Extracts the lane from the first operand corresponding to the last active (non-zero) lane in the mask...
Definition VPlan.h:1195
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1188
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1133
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1178
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1191
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1130
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1182
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1125
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1122
@ VScale
Returns the value for vscale.
Definition VPlan.h:1198
@ CanonicalIVIncrementForPart
Definition VPlan.h:1106
bool hasResult() const
Definition VPlan.h:1262
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:1303
unsigned getOpcode() const
Definition VPlan.h:1246
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...
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:2699
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2703
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2701
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2693
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2722
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2687
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2797
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:2810
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:2760
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.
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1402
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:4153
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:1427
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1394
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
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:387
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:4314
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override final
Print the recipe, delegating to printRecipe().
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:408
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:479
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 removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
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:398
friend class VPValue
Definition VPlanValue.h:212
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:2960
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:2504
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2528
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:2902
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:2913
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:2915
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:2898
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:2904
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:2911
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:2906
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:4197
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4265
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:2982
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3023
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:3052
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:3877
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:531
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:594
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:533
This class can be used to assign names to 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:1020
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:229
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1428
operand_range operands()
Definition VPlanValue.h:297
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:273
unsigned getNumOperands() const
Definition VPlanValue.h:267
operand_iterator op_begin()
Definition VPlanValue.h:293
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:268
virtual bool usesFirstLaneOnly(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:312
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:45
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:133
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1382
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:119
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1424
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:72
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1385
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:2012
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:1814
Function * getCalledScalarFunction() const
Definition VPlan.h:1810
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:1664
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:1910
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:2170
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2173
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2268
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2283
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2292
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:1746
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:1749
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:3307
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3304
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3347
Instruction & Ingredient
Definition VPlan.h:3295
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:3301
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3361
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3298
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3354
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3351
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.
unsigned getUF() const
Definition VPlan.h:4544
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1022
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
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1106
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:838
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 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)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
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:829
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:1737
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
InstructionCost Cost
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:2544
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:2198
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2303
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:1744
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:406
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:1751
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
@ 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.
@ 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.
@ 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
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
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.
@ Default
The result values are uniform if and only if all operands are uniform.
Definition Uniformity.h:20
LLVM_ABI Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, Value *InitVal, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of kind RecurKind::AnyOf.
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.
TargetTransformInfo::OperandValueInfo getOperandInfo(VPValue *V) const
Returns the OperandInfo for V, if it is a live-in.
Definition VPlan.cpp:1737
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:1550
PHINode & getIRPhi()
Definition VPlan.h:1558
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,...
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:184
Value * getValue() const
Returns the underlying IR value.
Definition VPlanValue.h:190
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:974
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:975
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:202
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:275
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:3439
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:3522
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:3525
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:3485