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<VPConstantInt>(UnrollPartOp)->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:
479 return 3;
480 case Instruction::Call:
481 case Instruction::GetElementPtr:
482 case Instruction::PHI:
483 case Instruction::Switch:
490 // Cannot determine the number of operands from the opcode.
491 return -1u;
492 }
493 llvm_unreachable("all cases should be handled above");
494}
495#endif
496
500
501bool VPInstruction::canGenerateScalarForFirstLane() const {
503 return true;
505 return true;
506 switch (Opcode) {
507 case Instruction::Freeze:
508 case Instruction::ICmp:
509 case Instruction::PHI:
510 case Instruction::Select:
520 return true;
521 default:
522 return false;
523 }
524}
525
526Value *VPInstruction::generate(VPTransformState &State) {
527 IRBuilderBase &Builder = State.Builder;
528
530 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
531 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
532 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
533 auto *Res =
534 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
535 if (auto *I = dyn_cast<Instruction>(Res))
536 applyFlags(*I);
537 return Res;
538 }
539
540 switch (getOpcode()) {
541 case VPInstruction::Not: {
542 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
543 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
544 return Builder.CreateNot(A, Name);
545 }
546 case Instruction::ExtractElement: {
547 assert(State.VF.isVector() && "Only extract elements from vectors");
548 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
549 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
550 Value *Vec = State.get(getOperand(0));
551 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
552 return Builder.CreateExtractElement(Vec, Idx, Name);
553 }
554 case Instruction::Freeze: {
556 return Builder.CreateFreeze(Op, Name);
557 }
558 case Instruction::FCmp:
559 case Instruction::ICmp: {
560 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
561 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
562 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
563 return Builder.CreateCmp(getPredicate(), A, B, Name);
564 }
565 case Instruction::PHI: {
566 llvm_unreachable("should be handled by VPPhi::execute");
567 }
568 case Instruction::Select: {
569 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
570 Value *Cond =
571 State.get(getOperand(0),
572 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
573 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
574 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
575 return Builder.CreateSelect(Cond, Op1, Op2, Name);
576 }
578 // Get first lane of vector induction variable.
579 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
580 // Get the original loop tripcount.
581 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
582
583 // If this part of the active lane mask is scalar, generate the CMP directly
584 // to avoid unnecessary extracts.
585 if (State.VF.isScalar())
586 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
587 Name);
588
589 ElementCount EC = State.VF.multiplyCoefficientBy(
590 cast<VPConstantInt>(getOperand(2))->getZExtValue());
591 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
592 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
593 {PredTy, ScalarTC->getType()},
594 {VIVElem0, ScalarTC}, nullptr, Name);
595 }
597 // Generate code to combine the previous and current values in vector v3.
598 //
599 // vector.ph:
600 // v_init = vector(..., ..., ..., a[-1])
601 // br vector.body
602 //
603 // vector.body
604 // i = phi [0, vector.ph], [i+4, vector.body]
605 // v1 = phi [v_init, vector.ph], [v2, vector.body]
606 // v2 = a[i, i+1, i+2, i+3];
607 // v3 = vector(v1(3), v2(0, 1, 2))
608
609 auto *V1 = State.get(getOperand(0));
610 if (!V1->getType()->isVectorTy())
611 return V1;
612 Value *V2 = State.get(getOperand(1));
613 return Builder.CreateVectorSplice(V1, V2, -1, Name);
614 }
616 unsigned UF = getParent()->getPlan()->getUF();
617 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
618 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
619 Value *Sub = Builder.CreateSub(ScalarTC, Step);
620 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
622 return Builder.CreateSelect(Cmp, Sub, Zero);
623 }
625 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
626 // be outside of the main loop.
627 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
628 // Compute EVL
629 assert(AVL->getType()->isIntegerTy() &&
630 "Requested vector length should be an integer.");
631
632 assert(State.VF.isScalable() && "Expected scalable vector factor.");
633 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
634
635 Value *EVL = Builder.CreateIntrinsic(
636 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
637 {AVL, VFArg, Builder.getTrue()});
638 return EVL;
639 }
641 unsigned Part = getUnrollPart(*this);
642 auto *IV = State.get(getOperand(0), VPLane(0));
643 assert(Part != 0 && "Must have a positive part");
644 // The canonical IV is incremented by the vectorization factor (num of
645 // SIMD elements) times the unroll part.
646 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
647 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
649 }
651 Value *Cond = State.get(getOperand(0), VPLane(0));
652 // Replace the temporary unreachable terminator with a new conditional
653 // branch, hooking it up to backward destination for latch blocks now, and
654 // to forward destination(s) later when they are created.
655 // Second successor may be backwards - iff it is already in VPBB2IRBB.
656 VPBasicBlock *SecondVPSucc =
657 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
658 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
659 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
660 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
661 // First successor is always forward, reset it to nullptr.
662 Br->setSuccessor(0, nullptr);
664 applyMetadata(*Br);
665 return Br;
666 }
668 return Builder.CreateVectorSplat(
669 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
670 }
672 // For struct types, we need to build a new 'wide' struct type, where each
673 // element is widened, i.e., we create a struct of vectors.
674 auto *StructTy =
676 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
677 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
678 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
679 FieldIndex++) {
680 Value *ScalarValue =
681 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
682 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
683 VectorValue =
684 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
685 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
686 }
687 }
688 return Res;
689 }
691 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
692 auto NumOfElements = ElementCount::getFixed(getNumOperands());
693 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
694 for (const auto &[Idx, Op] : enumerate(operands()))
695 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
696 Builder.getInt32(Idx));
697 return Res;
698 }
700 if (State.VF.isScalar())
701 return State.get(getOperand(0), true);
702 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
704 // If this start vector is scaled then it should produce a vector with fewer
705 // elements than the VF.
706 ElementCount VF = State.VF.divideCoefficientBy(
707 cast<VPConstantInt>(getOperand(2))->getZExtValue());
708 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
709 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
710 Builder.getInt32(0));
711 }
713 Value *Start = State.get(getOperand(0), VPLane(0));
714 Value *NewVal = State.get(getOperand(1), VPLane(0));
715 Value *ReducedResult = State.get(getOperand(2));
716 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
717 ReducedResult =
718 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
719 ReducedResult, "bin.rdx");
720 // If any predicate is true it means that we want to select the new value.
721 if (ReducedResult->getType()->isVectorTy())
722 ReducedResult = Builder.CreateOrReduce(ReducedResult);
723 // The compares in the loop may yield poison, which propagates through the
724 // bitwise ORs. Freeze it here before the condition is used.
725 ReducedResult = Builder.CreateFreeze(ReducedResult);
726 return Builder.CreateSelect(ReducedResult, NewVal, Start, "rdx.select");
727 }
729 // The recipe's operands are the start value, the sentinel value, followed
730 // by one operand for each part of the reduction.
731 unsigned UF = getNumOperands() - 2;
732 Value *ReducedResult = State.get(getOperand(2));
733 RecurKind MinMaxKind = getRecurKind();
734 assert((MinMaxKind == RecurKind::SMin || MinMaxKind == RecurKind::SMax ||
735 MinMaxKind == RecurKind::UMin || MinMaxKind == RecurKind::UMax) &&
736 "unexpected recurrence kind for ComputeFindIVResult");
737 for (unsigned Part = 1; Part < UF; ++Part)
738 ReducedResult = createMinMaxOp(Builder, MinMaxKind, ReducedResult,
739 State.get(getOperand(2 + Part)));
740
741 // Reduce the vector to a scalar.
742 bool IsMaxRdx =
743 MinMaxKind == RecurKind::SMax || MinMaxKind == RecurKind::UMax;
744 bool IsSigned =
745 MinMaxKind == RecurKind::SMin || MinMaxKind == RecurKind::SMax;
746 if (ReducedResult->getType()->isVectorTy())
747 ReducedResult = IsMaxRdx
748 ? Builder.CreateIntMaxReduce(ReducedResult, IsSigned)
749 : Builder.CreateIntMinReduce(ReducedResult, IsSigned);
750 // Correct the final reduction result back to the start value if the
751 // reduction result is the sentinel value.
752 Value *Start = State.get(getOperand(0), true);
754 Value *Cmp =
755 Builder.CreateICmpNE(ReducedResult, Sentinel, "rdx.select.cmp");
756 return Builder.CreateSelect(Cmp, ReducedResult, Start, "rdx.select");
757 }
759 RecurKind RK = getRecurKind();
760 bool IsOrdered = isReductionOrdered();
761 bool IsInLoop = isReductionInLoop();
763 "should be handled by ComputeFindIVResult");
764
765 // The recipe may have multiple operands to be reduced together.
766 unsigned NumOperandsToReduce = getNumOperands();
767 VectorParts RdxParts(NumOperandsToReduce);
768 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
769 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
770
771 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
772 if (hasFastMathFlags())
774
775 // Reduce multiple operands into one.
776 Value *ReducedPartRdx = RdxParts[0];
777 if (IsOrdered) {
778 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
779 } else {
780 // Floating-point operations should have some FMF to enable the reduction.
781 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
782 Value *RdxPart = RdxParts[Part];
784 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
785 else {
786 // For sub-recurrences, each part's reduction variable is already
787 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
789 RK == RecurKind::Sub
790 ? Instruction::Add
792 ReducedPartRdx =
793 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
794 }
795 }
796 }
797
798 // Create the reduction after the loop. Note that inloop reductions create
799 // the target reduction in the loop using a Reduction recipe.
800 if (State.VF.isVector() && !IsInLoop) {
801 // TODO: Support in-order reductions based on the recurrence descriptor.
802 // All ops in the reduction inherit fast-math-flags from the recurrence
803 // descriptor.
804 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
805 }
806
807 return ReducedPartRdx;
808 }
811 unsigned Offset =
813 Value *Res;
814 if (State.VF.isVector()) {
815 assert(Offset <= State.VF.getKnownMinValue() &&
816 "invalid offset to extract from");
817 // Extract lane VF - Offset from the operand.
818 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
819 } else {
820 // TODO: Remove ExtractLastLane for scalar VFs.
821 assert(Offset <= 1 && "invalid offset to extract from");
822 Res = State.get(getOperand(0));
823 }
825 Res->setName(Name);
826 return Res;
827 }
829 Value *A = State.get(getOperand(0));
830 Value *B = State.get(getOperand(1));
831 return Builder.CreateLogicalAnd(A, B, Name);
832 }
835 "can only generate first lane for PtrAdd");
836 Value *Ptr = State.get(getOperand(0), VPLane(0));
837 Value *Addend = State.get(getOperand(1), VPLane(0));
838 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
839 }
841 Value *Ptr =
843 Value *Addend = State.get(getOperand(1));
844 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
845 }
847 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
848 for (VPValue *Op : drop_begin(operands()))
849 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
850 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
851 }
853 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
854 "simplified to ExtractElement.");
855 Value *LaneToExtract = State.get(getOperand(0), true);
856 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
857 Value *Res = nullptr;
858 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
859
860 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
861 Value *VectorStart =
862 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
863 Value *VectorIdx = Idx == 1
864 ? LaneToExtract
865 : Builder.CreateSub(LaneToExtract, VectorStart);
866 Value *Ext = State.VF.isScalar()
867 ? State.get(getOperand(Idx))
868 : Builder.CreateExtractElement(
869 State.get(getOperand(Idx)), VectorIdx);
870 if (Res) {
871 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
872 Res = Builder.CreateSelect(Cmp, Ext, Res);
873 } else {
874 Res = Ext;
875 }
876 }
877 return Res;
878 }
880 if (getNumOperands() == 1) {
881 Value *Mask = State.get(getOperand(0));
882 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
883 /*ZeroIsPoison=*/false, Name);
884 }
885 // If there are multiple operands, create a chain of selects to pick the
886 // first operand with an active lane and add the number of lanes of the
887 // preceding operands.
888 Value *RuntimeVF = getRuntimeVF(Builder, Builder.getInt64Ty(), State.VF);
889 unsigned LastOpIdx = getNumOperands() - 1;
890 Value *Res = nullptr;
891 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
892 Value *TrailingZeros =
893 State.VF.isScalar()
894 ? Builder.CreateZExt(
895 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
896 Builder.getFalse()),
897 Builder.getInt64Ty())
899 Builder.getInt64Ty(), State.get(getOperand(Idx)),
900 /*ZeroIsPoison=*/false, Name);
901 Value *Current = Builder.CreateAdd(
902 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
903 if (Res) {
904 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
905 Res = Builder.CreateSelect(Cmp, Current, Res);
906 } else {
907 Res = Current;
908 }
909 }
910
911 return Res;
912 }
914 return State.get(getOperand(0), true);
916 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
918 Value *Data = State.get(getOperand(0));
919 Value *Mask = State.get(getOperand(1));
920 Value *Default = State.get(getOperand(2), /*IsScalar=*/true);
921 Type *VTy = Data->getType();
922 return Builder.CreateIntrinsic(
923 Intrinsic::experimental_vector_extract_last_active, {VTy},
924 {Data, Mask, Default});
925 }
926 default:
927 llvm_unreachable("Unsupported opcode for instruction");
928 }
929}
930
932 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
933 Type *ScalarTy = Ctx.Types.inferScalarType(this);
934 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
935 switch (Opcode) {
936 case Instruction::FNeg:
937 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
938 case Instruction::UDiv:
939 case Instruction::SDiv:
940 case Instruction::SRem:
941 case Instruction::URem:
942 case Instruction::Add:
943 case Instruction::FAdd:
944 case Instruction::Sub:
945 case Instruction::FSub:
946 case Instruction::Mul:
947 case Instruction::FMul:
948 case Instruction::FDiv:
949 case Instruction::FRem:
950 case Instruction::Shl:
951 case Instruction::LShr:
952 case Instruction::AShr:
953 case Instruction::And:
954 case Instruction::Or:
955 case Instruction::Xor: {
958
959 if (VF.isVector()) {
960 // Certain instructions can be cheaper to vectorize if they have a
961 // constant second vector operand. One example of this are shifts on x86.
962 VPValue *RHS = getOperand(1);
963 RHSInfo = Ctx.getOperandInfo(RHS);
964
965 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
968 }
969
972 if (CtxI)
973 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
974 return Ctx.TTI.getArithmeticInstrCost(
975 Opcode, ResultTy, Ctx.CostKind,
976 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
977 RHSInfo, Operands, CtxI, &Ctx.TLI);
978 }
979 case Instruction::Freeze:
980 // This opcode is unknown. Assume that it is the same as 'mul'.
981 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
982 Ctx.CostKind);
983 case Instruction::ExtractValue:
984 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
985 Ctx.CostKind);
986 case Instruction::ICmp:
987 case Instruction::FCmp: {
988 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
989 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
991 return Ctx.TTI.getCmpSelInstrCost(
992 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
993 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
994 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
995 }
996 case Instruction::BitCast: {
997 Type *ScalarTy = Ctx.Types.inferScalarType(this);
998 if (ScalarTy->isPointerTy())
999 return 0;
1000 [[fallthrough]];
1001 }
1002 case Instruction::SExt:
1003 case Instruction::ZExt:
1004 case Instruction::FPToUI:
1005 case Instruction::FPToSI:
1006 case Instruction::FPExt:
1007 case Instruction::PtrToInt:
1008 case Instruction::PtrToAddr:
1009 case Instruction::IntToPtr:
1010 case Instruction::SIToFP:
1011 case Instruction::UIToFP:
1012 case Instruction::Trunc:
1013 case Instruction::FPTrunc:
1014 case Instruction::AddrSpaceCast: {
1015 // Computes the CastContextHint from a recipe that may access memory.
1016 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1017 if (isa<VPInterleaveBase>(R))
1019 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1020 // Only compute CCH for memory operations, matching the legacy model
1021 // which only considers loads/stores for cast context hints.
1022 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1023 if (!isa<LoadInst, StoreInst>(UI))
1025 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1028 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1029 if (WidenMemoryRecipe == nullptr)
1031 if (VF.isScalar())
1033 if (!WidenMemoryRecipe->isConsecutive())
1035 if (WidenMemoryRecipe->isReverse())
1037 if (WidenMemoryRecipe->isMasked())
1040 };
1041
1042 VPValue *Operand = getOperand(0);
1044 // For Trunc/FPTrunc, get the context from the only user.
1045 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1046 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
1047 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
1048 return nullptr;
1049 return dyn_cast<VPRecipeBase>(*R->user_begin());
1050 };
1051 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
1052 if (match(Recipe, m_Reverse(m_VPValue())))
1053 Recipe = GetOnlyUser(cast<VPInstruction>(Recipe));
1054 if (Recipe)
1055 CCH = ComputeCCH(Recipe);
1056 }
1057 }
1058 // For Z/Sext, get the context from the operand.
1059 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1060 Opcode == Instruction::FPExt) {
1061 if (auto *Recipe = Operand->getDefiningRecipe()) {
1062 VPValue *ReverseOp;
1063 if (match(Recipe, m_Reverse(m_VPValue(ReverseOp))))
1064 Recipe = ReverseOp->getDefiningRecipe();
1065 if (Recipe)
1066 CCH = ComputeCCH(Recipe);
1067 }
1068 }
1069
1070 auto *ScalarSrcTy = Ctx.Types.inferScalarType(Operand);
1071 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1072 // Arm TTI will use the underlying instruction to determine the cost.
1073 return Ctx.TTI.getCastInstrCost(
1074 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1076 }
1077 case Instruction::Select: {
1079 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1080 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1081
1082 VPValue *Op0, *Op1;
1083 bool IsLogicalAnd =
1084 match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1085 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1086 // Also match the inverted forms:
1087 // select x, false, y --> !x & y (still AND)
1088 // select x, y, true --> !x | y (still OR)
1089 IsLogicalAnd |=
1090 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1091 IsLogicalOr |=
1092 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1093
1094 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1095 (IsLogicalAnd || IsLogicalOr)) {
1096 // select x, y, false --> x & y
1097 // select x, true, y --> x | y
1098 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1099 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1100
1101 SmallVector<const Value *, 2> Operands;
1102 if (SI && all_of(operands(),
1103 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1104 append_range(Operands, SI->operands());
1105 return Ctx.TTI.getArithmeticInstrCost(
1106 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1107 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1108 }
1109
1110 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1111 if (!IsScalarCond)
1112 CondTy = VectorType::get(CondTy, VF);
1113
1114 llvm::CmpPredicate Pred;
1115 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1116 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1117 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1118 Pred = Cmp->getPredicate();
1119 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1120 return Ctx.TTI.getCmpSelInstrCost(
1121 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1122 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1123 }
1124 }
1125 llvm_unreachable("called for unsupported opcode");
1126}
1127
1129 VPCostContext &Ctx) const {
1131 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1132 // TODO: Compute cost for VPInstructions without underlying values once
1133 // the legacy cost model has been retired.
1134 return 0;
1135 }
1136
1138 "Should only generate a vector value or single scalar, not scalars "
1139 "for all lanes.");
1141 getOpcode(),
1143 }
1144
1145 switch (getOpcode()) {
1146 case Instruction::Select: {
1148 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1149 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1150 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1151 if (!vputils::onlyFirstLaneUsed(this)) {
1152 CondTy = toVectorTy(CondTy, VF);
1153 VecTy = toVectorTy(VecTy, VF);
1154 }
1155 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1156 Ctx.CostKind);
1157 }
1158 case Instruction::ExtractElement:
1160 if (VF.isScalar()) {
1161 // ExtractLane with VF=1 takes care of handling extracting across multiple
1162 // parts.
1163 return 0;
1164 }
1165
1166 // Add on the cost of extracting the element.
1167 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1168 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1169 Ctx.CostKind);
1170 }
1171 case VPInstruction::AnyOf: {
1172 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1173 return Ctx.TTI.getArithmeticReductionCost(
1174 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1175 }
1177 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1178 if (VF.isScalar())
1179 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1181 CmpInst::ICMP_EQ, Ctx.CostKind);
1182 // Calculate the cost of determining the lane index.
1183 auto *PredTy = toVectorTy(ScalarTy, VF);
1184 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1185 Type::getInt64Ty(Ctx.LLVMCtx),
1186 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1187 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1188 }
1190 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1191 if (VF.isScalar())
1192 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1194 CmpInst::ICMP_EQ, Ctx.CostKind);
1195 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1196 auto *PredTy = toVectorTy(ScalarTy, VF);
1197 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1198 Type::getInt64Ty(Ctx.LLVMCtx),
1199 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1200 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1201 // Add cost of NOT operation on the predicate.
1202 Cost += Ctx.TTI.getArithmeticInstrCost(
1203 Instruction::Xor, PredTy, Ctx.CostKind,
1204 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1205 {TargetTransformInfo::OK_UniformConstantValue,
1206 TargetTransformInfo::OP_None});
1207 // Add cost of SUB operation on the index.
1208 Cost += Ctx.TTI.getArithmeticInstrCost(
1209 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1210 return Cost;
1211 }
1213 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1214 Type *VecTy = toVectorTy(ScalarTy, VF);
1215 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1217 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1218 {VecTy, MaskTy, ScalarTy});
1219 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1220 }
1222 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1224 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1225 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1226
1227 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1228 cast<VectorType>(VectorTy),
1229 cast<VectorType>(VectorTy), Mask,
1230 Ctx.CostKind, VF.getKnownMinValue() - 1);
1231 }
1233 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1234 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1235 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1236 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1237 {ArgTy, ArgTy});
1238 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1239 }
1241 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1242 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1243 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1244 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1245 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1246 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1247 }
1249 assert(VF.isVector() && "Reverse operation must be vector type");
1250 auto *VectorTy = cast<VectorType>(
1251 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
1252 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1253 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1254 /*Index=*/0);
1255 }
1257 // Add on the cost of extracting the element.
1258 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1259 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1260 VecTy, Ctx.CostKind, 0);
1261 }
1263 if (VF == ElementCount::getScalable(1))
1265 [[fallthrough]];
1266 default:
1267 // TODO: Compute cost other VPInstructions once the legacy cost model has
1268 // been retired.
1270 "unexpected VPInstruction witht underlying value");
1271 return 0;
1272 }
1273}
1274
1288
1290 switch (getOpcode()) {
1291 case Instruction::PHI:
1295 return true;
1296 default:
1297 return isScalarCast();
1298 }
1299}
1300
1302 assert(!State.Lane && "VPInstruction executing an Lane");
1303 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1305 "Set flags not supported for the provided opcode");
1306 if (hasFastMathFlags())
1307 State.Builder.setFastMathFlags(getFastMathFlags());
1308 Value *GeneratedValue = generate(State);
1309 if (!hasResult())
1310 return;
1311 assert(GeneratedValue && "generate must produce a value");
1312 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1315 assert((((GeneratedValue->getType()->isVectorTy() ||
1316 GeneratedValue->getType()->isStructTy()) ==
1317 !GeneratesPerFirstLaneOnly) ||
1318 State.VF.isScalar()) &&
1319 "scalar value but not only first lane defined");
1320 State.set(this, GeneratedValue,
1321 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1322}
1323
1326 return false;
1327 switch (getOpcode()) {
1328 case Instruction::GetElementPtr:
1329 case Instruction::ExtractElement:
1330 case Instruction::Freeze:
1331 case Instruction::FCmp:
1332 case Instruction::ICmp:
1333 case Instruction::Select:
1334 case Instruction::PHI:
1355 case VPInstruction::Not:
1364 return false;
1365 default:
1366 return true;
1367 }
1368}
1369
1371 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1373 return vputils::onlyFirstLaneUsed(this);
1374
1375 switch (getOpcode()) {
1376 default:
1377 return false;
1378 case Instruction::ExtractElement:
1379 return Op == getOperand(1);
1380 case Instruction::PHI:
1381 return true;
1382 case Instruction::FCmp:
1383 case Instruction::ICmp:
1384 case Instruction::Select:
1385 case Instruction::Or:
1386 case Instruction::Freeze:
1387 case VPInstruction::Not:
1388 // TODO: Cover additional opcodes.
1389 return vputils::onlyFirstLaneUsed(this);
1398 return true;
1401 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1402 // operand, after replicating its operands only the first lane is used.
1403 // Before replicating, it will have only a single operand.
1404 return getNumOperands() > 1;
1406 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1408 // WidePtrAdd supports scalar and vector base addresses.
1409 return false;
1411 return Op == getOperand(0) || Op == getOperand(1);
1413 return Op == getOperand(0);
1415 return Op == getOperand(0);
1416 };
1417 llvm_unreachable("switch should return");
1418}
1419
1421 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1423 return vputils::onlyFirstPartUsed(this);
1424
1425 switch (getOpcode()) {
1426 default:
1427 return false;
1428 case Instruction::FCmp:
1429 case Instruction::ICmp:
1430 case Instruction::Select:
1431 return vputils::onlyFirstPartUsed(this);
1436 return true;
1437 };
1438 llvm_unreachable("switch should return");
1439}
1440
1441#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1443 VPSlotTracker SlotTracker(getParent()->getPlan());
1445}
1446
1448 VPSlotTracker &SlotTracker) const {
1449 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1450
1451 if (hasResult()) {
1453 O << " = ";
1454 }
1455
1456 switch (getOpcode()) {
1457 case VPInstruction::Not:
1458 O << "not";
1459 break;
1461 O << "combined load";
1462 break;
1464 O << "combined store";
1465 break;
1467 O << "active lane mask";
1468 break;
1470 O << "EXPLICIT-VECTOR-LENGTH";
1471 break;
1473 O << "first-order splice";
1474 break;
1476 O << "branch-on-cond";
1477 break;
1479 O << "branch-on-two-conds";
1480 break;
1482 O << "TC > VF ? TC - VF : 0";
1483 break;
1485 O << "VF * Part +";
1486 break;
1488 O << "branch-on-count";
1489 break;
1491 O << "broadcast";
1492 break;
1494 O << "buildstructvector";
1495 break;
1497 O << "buildvector";
1498 break;
1500 O << "extract-lane";
1501 break;
1503 O << "extract-last-lane";
1504 break;
1506 O << "extract-last-part";
1507 break;
1509 O << "extract-penultimate-element";
1510 break;
1512 O << "compute-anyof-result";
1513 break;
1515 O << "compute-find-iv-result";
1516 break;
1518 O << "compute-reduction-result";
1519 break;
1521 O << "logical-and";
1522 break;
1524 O << "ptradd";
1525 break;
1527 O << "wide-ptradd";
1528 break;
1530 O << "any-of";
1531 break;
1533 O << "first-active-lane";
1534 break;
1536 O << "last-active-lane";
1537 break;
1539 O << "reduction-start-vector";
1540 break;
1542 O << "resume-for-epilogue";
1543 break;
1545 O << "reverse";
1546 break;
1548 O << "unpack";
1549 break;
1551 O << "extract-last-active";
1552 break;
1553 default:
1555 }
1556
1557 printFlags(O);
1559}
1560#endif
1561
1563 State.setDebugLocFrom(getDebugLoc());
1564 if (isScalarCast()) {
1565 Value *Op = State.get(getOperand(0), VPLane(0));
1566 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1567 Op, ResultTy);
1568 State.set(this, Cast, VPLane(0));
1569 return;
1570 }
1571 switch (getOpcode()) {
1573 Value *StepVector =
1574 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1575 State.set(this, StepVector);
1576 break;
1577 }
1578 case VPInstruction::VScale: {
1579 Value *VScale = State.Builder.CreateVScale(ResultTy);
1580 State.set(this, VScale, true);
1581 break;
1582 }
1583
1584 default:
1585 llvm_unreachable("opcode not implemented yet");
1586 }
1587}
1588
1589#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1591 VPSlotTracker &SlotTracker) const {
1592 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1594 O << " = ";
1595
1596 switch (getOpcode()) {
1598 O << "wide-iv-step ";
1600 break;
1602 O << "step-vector " << *ResultTy;
1603 break;
1605 O << "vscale " << *ResultTy;
1606 break;
1607 default:
1608 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1611 O << " to " << *ResultTy;
1612 }
1613}
1614#endif
1615
1617 State.setDebugLocFrom(getDebugLoc());
1618 PHINode *NewPhi = State.Builder.CreatePHI(
1619 State.TypeAnalysis.inferScalarType(this), 2, getName());
1620 unsigned NumIncoming = getNumIncoming();
1621 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1622 // TODO: Fixup all incoming values of header phis once recipes defining them
1623 // are introduced.
1624 NumIncoming = 1;
1625 }
1626 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1627 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1628 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1629 NewPhi->addIncoming(IncV, PredBB);
1630 }
1631 State.set(this, NewPhi, VPLane(0));
1632}
1633
1634#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1635void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1636 VPSlotTracker &SlotTracker) const {
1637 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1639 O << " = phi ";
1641}
1642#endif
1643
1644VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1645 if (auto *Phi = dyn_cast<PHINode>(&I))
1646 return new VPIRPhi(*Phi);
1647 return new VPIRInstruction(I);
1648}
1649
1651 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1652 "PHINodes must be handled by VPIRPhi");
1653 // Advance the insert point after the wrapped IR instruction. This allows
1654 // interleaving VPIRInstructions and other recipes.
1655 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1656}
1657
1659 VPCostContext &Ctx) const {
1660 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1661 // hence it does not contribute to the cost-modeling for the VPlan.
1662 return 0;
1663}
1664
1666 VPBuilder &Builder) {
1668 "can only update exiting operands to phi nodes");
1669 assert(getNumOperands() > 0 && "must have at least one operand");
1670 VPValue *Exiting = getOperand(0);
1671 if (isa<VPIRValue>(Exiting))
1672 return;
1673
1674 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
1675 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
1676 setOperand(0, Exiting);
1677}
1678
1679#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1681 VPSlotTracker &SlotTracker) const {
1682 O << Indent << "IR " << I;
1683}
1684#endif
1685
1687 PHINode *Phi = &getIRPhi();
1688 for (const auto &[Idx, Op] : enumerate(operands())) {
1689 VPValue *ExitValue = Op;
1690 auto Lane = vputils::isSingleScalar(ExitValue)
1692 : VPLane::getLastLaneForVF(State.VF);
1693 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1694 auto *PredVPBB = Pred->getExitingBasicBlock();
1695 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1696 // Set insertion point in PredBB in case an extract needs to be generated.
1697 // TODO: Model extracts explicitly.
1698 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
1699 Value *V = State.get(ExitValue, VPLane(Lane));
1700 // If there is no existing block for PredBB in the phi, add a new incoming
1701 // value. Otherwise update the existing incoming value for PredBB.
1702 if (Phi->getBasicBlockIndex(PredBB) == -1)
1703 Phi->addIncoming(V, PredBB);
1704 else
1705 Phi->setIncomingValueForBlock(PredBB, V);
1706 }
1707
1708 // Advance the insert point after the wrapped IR instruction. This allows
1709 // interleaving VPIRInstructions and other recipes.
1710 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1711}
1712
1714 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1715 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1716 "Number of phi operands must match number of predecessors");
1717 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1718 R->removeOperand(Position);
1719}
1720
1721#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1723 VPSlotTracker &SlotTracker) const {
1724 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1725 [this, &O, &SlotTracker](auto Op) {
1726 O << "[ ";
1727 Op.value()->printAsOperand(O, SlotTracker);
1728 O << ", ";
1729 getIncomingBlock(Op.index())->printAsOperand(O);
1730 O << " ]";
1731 });
1732}
1733#endif
1734
1735#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1737 VPSlotTracker &SlotTracker) const {
1739
1740 if (getNumOperands() != 0) {
1741 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1743 [&O, &SlotTracker](auto Op) {
1744 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1745 O << " from ";
1746 std::get<1>(Op)->printAsOperand(O);
1747 });
1748 O << ")";
1749 }
1750}
1751#endif
1752
1754 for (const auto &[Kind, Node] : Metadata)
1755 I.setMetadata(Kind, Node);
1756}
1757
1759 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1760 for (const auto &[KindA, MDA] : Metadata) {
1761 for (const auto &[KindB, MDB] : Other.Metadata) {
1762 if (KindA == KindB && MDA == MDB) {
1763 MetadataIntersection.emplace_back(KindA, MDA);
1764 break;
1765 }
1766 }
1767 }
1768 Metadata = std::move(MetadataIntersection);
1769}
1770
1771#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1773 const Module *M = SlotTracker.getModule();
1774 if (Metadata.empty() || !M)
1775 return;
1776
1777 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1778 O << " (";
1779 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1780 auto [Kind, Node] = KindNodePair;
1781 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1782 "Unexpected unnamed metadata kind");
1783 O << "!" << MDNames[Kind] << " ";
1784 Node->printAsOperand(O, M);
1785 });
1786 O << ")";
1787}
1788#endif
1789
1791 assert(State.VF.isVector() && "not widening");
1792 assert(Variant != nullptr && "Can't create vector function.");
1793
1794 FunctionType *VFTy = Variant->getFunctionType();
1795 // Add return type if intrinsic is overloaded on it.
1797 for (const auto &I : enumerate(args())) {
1798 Value *Arg;
1799 // Some vectorized function variants may also take a scalar argument,
1800 // e.g. linear parameters for pointers. This needs to be the scalar value
1801 // from the start of the respective part when interleaving.
1802 if (!VFTy->getParamType(I.index())->isVectorTy())
1803 Arg = State.get(I.value(), VPLane(0));
1804 else
1805 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1806 Args.push_back(Arg);
1807 }
1808
1811 if (CI)
1812 CI->getOperandBundlesAsDefs(OpBundles);
1813
1814 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1815 applyFlags(*V);
1816 applyMetadata(*V);
1817 V->setCallingConv(Variant->getCallingConv());
1818
1819 if (!V->getType()->isVoidTy())
1820 State.set(this, V);
1821}
1822
1824 VPCostContext &Ctx) const {
1825 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1826 Variant->getFunctionType()->params(),
1827 Ctx.CostKind);
1828}
1829
1830#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1832 VPSlotTracker &SlotTracker) const {
1833 O << Indent << "WIDEN-CALL ";
1834
1835 Function *CalledFn = getCalledScalarFunction();
1836 if (CalledFn->getReturnType()->isVoidTy())
1837 O << "void ";
1838 else {
1840 O << " = ";
1841 }
1842
1843 O << "call";
1844 printFlags(O);
1845 O << " @" << CalledFn->getName() << "(";
1846 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1847 Op->printAsOperand(O, SlotTracker);
1848 });
1849 O << ")";
1850
1851 O << " (using library function";
1852 if (Variant->hasName())
1853 O << ": " << Variant->getName();
1854 O << ")";
1855}
1856#endif
1857
1859 assert(State.VF.isVector() && "not widening");
1860
1861 SmallVector<Type *, 2> TysForDecl;
1862 // Add return type if intrinsic is overloaded on it.
1863 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
1864 State.TTI)) {
1865 Type *RetTy = toVectorizedTy(getResultType(), State.VF);
1866 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
1867 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
1869 Idx, State.TTI))
1870 TysForDecl.push_back(Ty);
1871 }
1872 }
1874 for (const auto &I : enumerate(operands())) {
1875 // Some intrinsics have a scalar argument - don't replace it with a
1876 // vector.
1877 Value *Arg;
1878 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1879 State.TTI))
1880 Arg = State.get(I.value(), VPLane(0));
1881 else
1882 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1883 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1884 State.TTI))
1885 TysForDecl.push_back(Arg->getType());
1886 Args.push_back(Arg);
1887 }
1888
1889 // Use vector version of the intrinsic.
1890 Module *M = State.Builder.GetInsertBlock()->getModule();
1891 Function *VectorF =
1892 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1893 assert(VectorF &&
1894 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1895
1898 if (CI)
1899 CI->getOperandBundlesAsDefs(OpBundles);
1900
1901 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1902
1903 applyFlags(*V);
1904 applyMetadata(*V);
1905
1906 if (!V->getType()->isVoidTy())
1907 State.set(this, V);
1908}
1909
1910/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1913 const VPRecipeWithIRFlags &R,
1914 ElementCount VF,
1915 VPCostContext &Ctx) {
1916 // Some backends analyze intrinsic arguments to determine cost. Use the
1917 // underlying value for the operand if it has one. Otherwise try to use the
1918 // operand of the underlying call instruction, if there is one. Otherwise
1919 // clear Arguments.
1920 // TODO: Rework TTI interface to be independent of concrete IR values.
1922 for (const auto &[Idx, Op] : enumerate(Operands)) {
1923 auto *V = Op->getUnderlyingValue();
1924 if (!V) {
1925 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1926 Arguments.push_back(UI->getArgOperand(Idx));
1927 continue;
1928 }
1929 Arguments.clear();
1930 break;
1931 }
1932 Arguments.push_back(V);
1933 }
1934
1935 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1936 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1937 SmallVector<Type *> ParamTys;
1938 for (const VPValue *Op : Operands) {
1939 ParamTys.push_back(VF.isVector()
1940 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1941 : Ctx.Types.inferScalarType(Op));
1942 }
1943
1944 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1945 FastMathFlags FMF =
1946 R.hasFastMathFlags() ? R.getFastMathFlags() : FastMathFlags();
1947 IntrinsicCostAttributes CostAttrs(
1948 ID, RetTy, Arguments, ParamTys, FMF,
1949 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1950 InstructionCost::getInvalid(), &Ctx.TLI);
1951 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1952}
1953
1955 VPCostContext &Ctx) const {
1957 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1958}
1959
1961 return Intrinsic::getBaseName(VectorIntrinsicID);
1962}
1963
1965 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1966 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1967 auto [Idx, V] = X;
1969 Idx, nullptr);
1970 });
1971}
1972
1973#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1975 VPSlotTracker &SlotTracker) const {
1976 O << Indent << "WIDEN-INTRINSIC ";
1977 if (ResultTy->isVoidTy()) {
1978 O << "void ";
1979 } else {
1981 O << " = ";
1982 }
1983
1984 O << "call";
1985 printFlags(O);
1986 O << getIntrinsicName() << "(";
1987
1989 Op->printAsOperand(O, SlotTracker);
1990 });
1991 O << ")";
1992}
1993#endif
1994
1996 IRBuilderBase &Builder = State.Builder;
1997
1998 Value *Address = State.get(getOperand(0));
1999 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2000 VectorType *VTy = cast<VectorType>(Address->getType());
2001
2002 // The histogram intrinsic requires a mask even if the recipe doesn't;
2003 // if the mask operand was omitted then all lanes should be executed and
2004 // we just need to synthesize an all-true mask.
2005 Value *Mask = nullptr;
2006 if (VPValue *VPMask = getMask())
2007 Mask = State.get(VPMask);
2008 else
2009 Mask =
2010 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2011
2012 // If this is a subtract, we want to invert the increment amount. We may
2013 // add a separate intrinsic in future, but for now we'll try this.
2014 if (Opcode == Instruction::Sub)
2015 IncAmt = Builder.CreateNeg(IncAmt);
2016 else
2017 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2018
2019 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
2020 {VTy, IncAmt->getType()},
2021 {Address, IncAmt, Mask});
2022}
2023
2025 VPCostContext &Ctx) const {
2026 // FIXME: Take the gather and scatter into account as well. For now we're
2027 // generating the same cost as the fallback path, but we'll likely
2028 // need to create a new TTI method for determining the cost, including
2029 // whether we can use base + vec-of-smaller-indices or just
2030 // vec-of-pointers.
2031 assert(VF.isVector() && "Invalid VF for histogram cost");
2032 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
2033 VPValue *IncAmt = getOperand(1);
2034 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
2035 VectorType *VTy = VectorType::get(IncTy, VF);
2036
2037 // Assume that a non-constant update value (or a constant != 1) requires
2038 // a multiply, and add that into the cost.
2039 InstructionCost MulCost =
2040 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2041 if (auto *CI = dyn_cast<VPConstantInt>(IncAmt))
2042 if (CI->isOne())
2043 MulCost = TTI::TCC_Free;
2044
2045 // Find the cost of the histogram operation itself.
2046 Type *PtrTy = VectorType::get(AddressTy, VF);
2047 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2048 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2049 Type::getVoidTy(Ctx.LLVMCtx),
2050 {PtrTy, IncTy, MaskTy});
2051
2052 // Add the costs together with the add/sub operation.
2053 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2054 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2055}
2056
2057#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2059 VPSlotTracker &SlotTracker) const {
2060 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2062
2063 if (Opcode == Instruction::Sub)
2064 O << ", dec: ";
2065 else {
2066 assert(Opcode == Instruction::Add);
2067 O << ", inc: ";
2068 }
2070
2071 if (VPValue *Mask = getMask()) {
2072 O << ", mask: ";
2073 Mask->printAsOperand(O, SlotTracker);
2074 }
2075}
2076#endif
2077
2078VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2079 AllowReassoc = FMF.allowReassoc();
2080 NoNaNs = FMF.noNaNs();
2081 NoInfs = FMF.noInfs();
2082 NoSignedZeros = FMF.noSignedZeros();
2083 AllowReciprocal = FMF.allowReciprocal();
2084 AllowContract = FMF.allowContract();
2085 ApproxFunc = FMF.approxFunc();
2086}
2087
2088#if !defined(NDEBUG)
2089bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2090 switch (OpType) {
2091 case OperationType::OverflowingBinOp:
2092 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2093 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2094 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2095 case OperationType::Trunc:
2096 return Opcode == Instruction::Trunc;
2097 case OperationType::DisjointOp:
2098 return Opcode == Instruction::Or;
2099 case OperationType::PossiblyExactOp:
2100 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2101 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2102 case OperationType::GEPOp:
2103 return Opcode == Instruction::GetElementPtr ||
2104 Opcode == VPInstruction::PtrAdd ||
2105 Opcode == VPInstruction::WidePtrAdd;
2106 case OperationType::FPMathOp:
2107 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2108 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2109 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2110 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2111 Opcode == Instruction::FPTrunc || Opcode == Instruction::Select ||
2112 Opcode == VPInstruction::WideIVStep ||
2114 case OperationType::FCmp:
2115 return Opcode == Instruction::FCmp;
2116 case OperationType::NonNegOp:
2117 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2118 case OperationType::Cmp:
2119 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2120 case OperationType::ReductionOp:
2121 return Opcode == VPInstruction::ComputeReductionResult ||
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::AnyOf:
2180 O << "any-of";
2181 break;
2182 case RecurKind::SMax:
2183 O << "smax";
2184 break;
2185 case RecurKind::SMin:
2186 O << "smin";
2187 break;
2188 case RecurKind::UMax:
2189 O << "umax";
2190 break;
2191 case RecurKind::UMin:
2192 O << "umin";
2193 break;
2194 case RecurKind::FMinNum:
2195 O << "fminnum";
2196 break;
2197 case RecurKind::FMaxNum:
2198 O << "fmaxnum";
2199 break;
2201 O << "fminimum";
2202 break;
2204 O << "fmaximum";
2205 break;
2207 O << "fminimumnum";
2208 break;
2210 O << "fmaximumnum";
2211 break;
2212 default:
2214 break;
2215 }
2216 if (isReductionInLoop())
2217 O << ", in-loop";
2218 if (isReductionOrdered())
2219 O << ", ordered";
2220 O << ")";
2222 break;
2223 }
2224 case OperationType::Other:
2225 break;
2226 }
2227 O << " ";
2228}
2229#endif
2230
2232 auto &Builder = State.Builder;
2233 switch (Opcode) {
2234 case Instruction::Call:
2235 case Instruction::Br:
2236 case Instruction::PHI:
2237 case Instruction::GetElementPtr:
2238 llvm_unreachable("This instruction is handled by a different recipe.");
2239 case Instruction::UDiv:
2240 case Instruction::SDiv:
2241 case Instruction::SRem:
2242 case Instruction::URem:
2243 case Instruction::Add:
2244 case Instruction::FAdd:
2245 case Instruction::Sub:
2246 case Instruction::FSub:
2247 case Instruction::FNeg:
2248 case Instruction::Mul:
2249 case Instruction::FMul:
2250 case Instruction::FDiv:
2251 case Instruction::FRem:
2252 case Instruction::Shl:
2253 case Instruction::LShr:
2254 case Instruction::AShr:
2255 case Instruction::And:
2256 case Instruction::Or:
2257 case Instruction::Xor: {
2258 // Just widen unops and binops.
2260 for (VPValue *VPOp : operands())
2261 Ops.push_back(State.get(VPOp));
2262
2263 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2264
2265 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2266 applyFlags(*VecOp);
2267 applyMetadata(*VecOp);
2268 }
2269
2270 // Use this vector value for all users of the original instruction.
2271 State.set(this, V);
2272 break;
2273 }
2274 case Instruction::ExtractValue: {
2275 assert(getNumOperands() == 2 && "expected single level extractvalue");
2276 Value *Op = State.get(getOperand(0));
2277 Value *Extract = Builder.CreateExtractValue(
2278 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2279 State.set(this, Extract);
2280 break;
2281 }
2282 case Instruction::Freeze: {
2283 Value *Op = State.get(getOperand(0));
2284 Value *Freeze = Builder.CreateFreeze(Op);
2285 State.set(this, Freeze);
2286 break;
2287 }
2288 case Instruction::ICmp:
2289 case Instruction::FCmp: {
2290 // Widen compares. Generate vector compares.
2291 bool FCmp = Opcode == Instruction::FCmp;
2292 Value *A = State.get(getOperand(0));
2293 Value *B = State.get(getOperand(1));
2294 Value *C = nullptr;
2295 if (FCmp) {
2296 C = Builder.CreateFCmp(getPredicate(), A, B);
2297 } else {
2298 C = Builder.CreateICmp(getPredicate(), A, B);
2299 }
2300 if (auto *I = dyn_cast<Instruction>(C)) {
2301 applyFlags(*I);
2302 applyMetadata(*I);
2303 }
2304 State.set(this, C);
2305 break;
2306 }
2307 case Instruction::Select: {
2308 VPValue *CondOp = getOperand(0);
2309 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2310 Value *Op0 = State.get(getOperand(1));
2311 Value *Op1 = State.get(getOperand(2));
2312 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2313 State.set(this, Sel);
2314 if (auto *I = dyn_cast<Instruction>(Sel)) {
2316 applyFlags(*I);
2317 applyMetadata(*I);
2318 }
2319 break;
2320 }
2321 default:
2322 // This instruction is not vectorized by simple widening.
2323 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2324 << Instruction::getOpcodeName(Opcode));
2325 llvm_unreachable("Unhandled instruction!");
2326 } // end of switch.
2327
2328#if !defined(NDEBUG)
2329 // Verify that VPlan type inference results agree with the type of the
2330 // generated values.
2331 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2332 State.get(this)->getType() &&
2333 "inferred type and type from generated instructions do not match");
2334#endif
2335}
2336
2338 VPCostContext &Ctx) const {
2339 switch (Opcode) {
2340 case Instruction::UDiv:
2341 case Instruction::SDiv:
2342 case Instruction::SRem:
2343 case Instruction::URem:
2344 // If the div/rem operation isn't safe to speculate and requires
2345 // predication, then the only way we can even create a vplan is to insert
2346 // a select on the second input operand to ensure we use the value of 1
2347 // for the inactive lanes. The select will be costed separately.
2348 case Instruction::FNeg:
2349 case Instruction::Add:
2350 case Instruction::FAdd:
2351 case Instruction::Sub:
2352 case Instruction::FSub:
2353 case Instruction::Mul:
2354 case Instruction::FMul:
2355 case Instruction::FDiv:
2356 case Instruction::FRem:
2357 case Instruction::Shl:
2358 case Instruction::LShr:
2359 case Instruction::AShr:
2360 case Instruction::And:
2361 case Instruction::Or:
2362 case Instruction::Xor:
2363 case Instruction::Freeze:
2364 case Instruction::ExtractValue:
2365 case Instruction::ICmp:
2366 case Instruction::FCmp:
2367 case Instruction::Select:
2368 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2369 default:
2370 llvm_unreachable("Unsupported opcode for instruction");
2371 }
2372}
2373
2374#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2376 VPSlotTracker &SlotTracker) const {
2377 O << Indent << "WIDEN ";
2379 O << " = " << Instruction::getOpcodeName(Opcode);
2380 printFlags(O);
2382}
2383#endif
2384
2386 auto &Builder = State.Builder;
2387 /// Vectorize casts.
2388 assert(State.VF.isVector() && "Not vectorizing?");
2389 Type *DestTy = VectorType::get(getResultType(), State.VF);
2390 VPValue *Op = getOperand(0);
2391 Value *A = State.get(Op);
2392 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2393 State.set(this, Cast);
2394 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2395 applyFlags(*CastOp);
2396 applyMetadata(*CastOp);
2397 }
2398}
2399
2401 VPCostContext &Ctx) const {
2402 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2403 // the legacy cost model, including truncates/extends when evaluating a
2404 // reduction in a smaller type.
2405 if (!getUnderlyingValue())
2406 return 0;
2407 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2408}
2409
2410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2412 VPSlotTracker &SlotTracker) const {
2413 O << Indent << "WIDEN-CAST ";
2415 O << " = " << Instruction::getOpcodeName(Opcode);
2416 printFlags(O);
2418 O << " to " << *getResultType();
2419}
2420#endif
2421
2423 VPCostContext &Ctx) const {
2424 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2425}
2426
2427#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2429 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2430 O << Indent;
2432 O << " = WIDEN-INDUCTION";
2433 printFlags(O);
2435
2436 if (auto *TI = getTruncInst())
2437 O << " (truncated to " << *TI->getType() << ")";
2438}
2439#endif
2440
2442 // The step may be defined by a recipe in the preheader (e.g. if it requires
2443 // SCEV expansion), but for the canonical induction the step is required to be
2444 // 1, which is represented as live-in.
2445 auto *StepC = dyn_cast<VPConstantInt>(getStepValue());
2446 auto *StartC = dyn_cast<VPConstantInt>(getStartValue());
2447 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2448 getScalarType() == getRegion()->getCanonicalIVType();
2449}
2450
2452 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
2453
2454 // Fast-math-flags propagate from the original induction instruction.
2455 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2456 if (FPBinOp)
2457 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
2458
2459 Value *Step = State.get(getStepValue(), VPLane(0));
2460 Value *Index = State.get(getOperand(1), VPLane(0));
2461 Value *DerivedIV = emitTransformedIndex(
2462 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
2464 DerivedIV->setName(Name);
2465 State.set(this, DerivedIV, VPLane(0));
2466}
2467
2468#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2470 VPSlotTracker &SlotTracker) const {
2471 O << Indent;
2473 O << " = DERIVED-IV ";
2474 getStartValue()->printAsOperand(O, SlotTracker);
2475 O << " + ";
2476 getOperand(1)->printAsOperand(O, SlotTracker);
2477 O << " * ";
2478 getStepValue()->printAsOperand(O, SlotTracker);
2479}
2480#endif
2481
2483 // Fast-math-flags propagate from the original induction instruction.
2484 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2485 if (hasFastMathFlags())
2486 State.Builder.setFastMathFlags(getFastMathFlags());
2487
2488 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2489 /// variable on which to base the steps, \p Step is the size of the step.
2490
2491 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2492 Value *Step = State.get(getStepValue(), VPLane(0));
2493 IRBuilderBase &Builder = State.Builder;
2494
2495 // Ensure step has the same type as that of scalar IV.
2496 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2497 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2498
2499 // We build scalar steps for both integer and floating-point induction
2500 // variables. Here, we determine the kind of arithmetic we will perform.
2503 if (BaseIVTy->isIntegerTy()) {
2504 AddOp = Instruction::Add;
2505 MulOp = Instruction::Mul;
2506 } else {
2507 AddOp = InductionOpcode;
2508 MulOp = Instruction::FMul;
2509 }
2510
2511 // Determine the number of scalars we need to generate for each unroll
2512 // iteration.
2513 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2514 // Compute the scalar steps and save the results in State.
2515 Type *IntStepTy =
2516 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
2517
2518 unsigned StartLane = 0;
2519 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2520 if (State.Lane) {
2521 StartLane = State.Lane->getKnownLane();
2522 EndLane = StartLane + 1;
2523 }
2524 Value *StartIdx0;
2525 if (getUnrollPart(*this) == 0)
2526 StartIdx0 = ConstantInt::get(IntStepTy, 0);
2527 else {
2528 StartIdx0 = State.get(getOperand(2), true);
2529 if (getUnrollPart(*this) != 1) {
2530 StartIdx0 =
2531 Builder.CreateMul(StartIdx0, ConstantInt::get(StartIdx0->getType(),
2532 getUnrollPart(*this)));
2533 }
2534 StartIdx0 = Builder.CreateSExtOrTrunc(StartIdx0, IntStepTy);
2535 }
2536
2537 if (BaseIVTy->isFloatingPointTy())
2538 StartIdx0 = Builder.CreateSIToFP(StartIdx0, BaseIVTy);
2539
2540 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2541 // It is okay if the induction variable type cannot hold the lane number,
2542 // we expect truncation in this case.
2543 Constant *LaneValue =
2544 BaseIVTy->isIntegerTy()
2545 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
2546 /*ImplicitTrunc=*/true)
2547 : ConstantFP::get(BaseIVTy, Lane);
2548 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
2549 // The step returned by `createStepForVF` is a runtime-evaluated value
2550 // when VF is scalable. Otherwise, it should be folded into a Constant.
2551 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2552 "Expected StartIdx to be folded to a constant when VF is not "
2553 "scalable");
2554 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2555 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2556 State.set(this, Add, VPLane(Lane));
2557 }
2558}
2559
2560#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2562 VPSlotTracker &SlotTracker) const {
2563 O << Indent;
2565 O << " = SCALAR-STEPS ";
2567}
2568#endif
2569
2571 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2573}
2574
2576 assert(State.VF.isVector() && "not widening");
2577 // Construct a vector GEP by widening the operands of the scalar GEP as
2578 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2579 // results in a vector of pointers when at least one operand of the GEP
2580 // is vector-typed. Thus, to keep the representation compact, we only use
2581 // vector-typed operands for loop-varying values.
2582
2583 bool AllOperandsAreInvariant = all_of(operands(), [](VPValue *Op) {
2584 return Op->isDefinedOutsideLoopRegions();
2585 });
2586 if (AllOperandsAreInvariant) {
2587 // If we are vectorizing, but the GEP has only loop-invariant operands,
2588 // the GEP we build (by only using vector-typed operands for
2589 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2590 // produce a vector of pointers, we need to either arbitrarily pick an
2591 // operand to broadcast, or broadcast a clone of the original GEP.
2592 // Here, we broadcast a clone of the original.
2593
2595 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2596 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2597
2598 auto *NewGEP =
2599 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2600 "", getGEPNoWrapFlags());
2601 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2602 State.set(this, Splat);
2603 return;
2604 }
2605
2606 // If the GEP has at least one loop-varying operand, we are sure to
2607 // produce a vector of pointers unless VF is scalar.
2608 // The pointer operand of the new GEP. If it's loop-invariant, we
2609 // won't broadcast it.
2610 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2611
2612 // Collect all the indices for the new GEP. If any index is
2613 // loop-invariant, we won't broadcast it.
2615 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2616 VPValue *Operand = getOperand(I);
2617 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2618 }
2619
2620 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2621 // but it should be a vector, otherwise.
2622 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2623 "", getGEPNoWrapFlags());
2624 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2625 "NewGEP is not a pointer vector");
2626 State.set(this, NewGEP);
2627}
2628
2629#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2631 VPSlotTracker &SlotTracker) const {
2632 O << Indent << "WIDEN-GEP ";
2633 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2634 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2635 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2636
2637 O << " ";
2639 O << " = getelementptr";
2640 printFlags(O);
2642}
2643#endif
2644
2646 auto &Builder = State.Builder;
2647 unsigned CurrentPart = getUnrollPart(*this);
2648 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2649 Type *IndexTy = DL.getIndexType(State.TypeAnalysis.inferScalarType(this));
2650
2651 // The wide store needs to start at the last vector element.
2652 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2653 if (IndexTy != RunTimeVF->getType())
2654 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2655 // NumElt = Stride * CurrentPart * RunTimeVF
2656 Value *NumElt = Builder.CreateMul(
2657 ConstantInt::getSigned(IndexTy, Stride * (int64_t)CurrentPart),
2658 RunTimeVF);
2659 // LastLane = Stride * (RunTimeVF - 1)
2660 Value *LastLane = Builder.CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2661 if (Stride != 1)
2662 LastLane =
2663 Builder.CreateMul(ConstantInt::getSigned(IndexTy, Stride), LastLane);
2664 Value *Ptr = State.get(getOperand(0), VPLane(0));
2665 Value *ResultPtr =
2666 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2667 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2669
2670 State.set(this, ResultPtr, /*IsScalar*/ true);
2671}
2672
2673#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2675 VPSlotTracker &SlotTracker) const {
2676 O << Indent;
2678 O << " = vector-end-pointer";
2679 printFlags(O);
2681}
2682#endif
2683
2685 auto &Builder = State.Builder;
2686 assert(getOffset() &&
2687 "Expected prior simplification of recipe without offset");
2688 Value *Ptr = State.get(getOperand(0), VPLane(0));
2689 Value *Offset = State.get(getOffset(), true);
2690 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2692 State.set(this, ResultPtr, /*IsScalar*/ true);
2693}
2694
2695#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2697 VPSlotTracker &SlotTracker) const {
2698 O << Indent;
2700 O << " = vector-pointer";
2701 printFlags(O);
2703}
2704#endif
2705
2707 VPCostContext &Ctx) const {
2708 // A blend will be expanded to a select VPInstruction, which will generate a
2709 // scalar select if only the first lane is used.
2711 VF = ElementCount::getFixed(1);
2712
2713 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2714 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2715 return (getNumIncomingValues() - 1) *
2716 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2717 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2718}
2719
2720#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2722 VPSlotTracker &SlotTracker) const {
2723 O << Indent << "BLEND ";
2725 O << " =";
2726 if (getNumIncomingValues() == 1) {
2727 // Not a User of any mask: not really blending, this is a
2728 // single-predecessor phi.
2729 O << " ";
2730 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2731 } else {
2732 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2733 O << " ";
2734 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2735 if (I == 0)
2736 continue;
2737 O << "/";
2738 getMask(I)->printAsOperand(O, SlotTracker);
2739 }
2740 }
2741}
2742#endif
2743
2745 assert(!State.Lane && "Reduction being replicated.");
2748 "In-loop AnyOf reductions aren't currently supported");
2749 // Propagate the fast-math flags carried by the underlying instruction.
2750 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2751 State.Builder.setFastMathFlags(getFastMathFlags());
2752 Value *NewVecOp = State.get(getVecOp());
2753 if (VPValue *Cond = getCondOp()) {
2754 Value *NewCond = State.get(Cond, State.VF.isScalar());
2755 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2756 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2757
2758 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2759 if (State.VF.isVector())
2760 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2761
2762 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2763 NewVecOp = Select;
2764 }
2765 Value *NewRed;
2766 Value *NextInChain;
2767 if (isOrdered()) {
2768 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2769 if (State.VF.isVector())
2770 NewRed =
2771 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2772 else
2773 NewRed = State.Builder.CreateBinOp(
2775 PrevInChain, NewVecOp);
2776 PrevInChain = NewRed;
2777 NextInChain = NewRed;
2778 } else if (isPartialReduction()) {
2779 assert(Kind == RecurKind::Add && "Unexpected partial reduction kind");
2780 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2781 NewRed = State.Builder.CreateIntrinsic(
2782 PrevInChain->getType(), Intrinsic::vector_partial_reduce_add,
2783 {PrevInChain, NewVecOp}, nullptr, "partial.reduce");
2784 PrevInChain = NewRed;
2785 NextInChain = NewRed;
2786 } else {
2787 assert(isInLoop() &&
2788 "The reduction must either be ordered, partial or in-loop");
2789 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2790 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2792 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2793 else
2794 NextInChain = State.Builder.CreateBinOp(
2796 PrevInChain, NewRed);
2797 }
2798 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2799}
2800
2802 assert(!State.Lane && "Reduction being replicated.");
2803
2804 auto &Builder = State.Builder;
2805 // Propagate the fast-math flags carried by the underlying instruction.
2806 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2807 Builder.setFastMathFlags(getFastMathFlags());
2808
2810 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2811 Value *VecOp = State.get(getVecOp());
2812 Value *EVL = State.get(getEVL(), VPLane(0));
2813
2814 Value *Mask;
2815 if (VPValue *CondOp = getCondOp())
2816 Mask = State.get(CondOp);
2817 else
2818 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2819
2820 Value *NewRed;
2821 if (isOrdered()) {
2822 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2823 } else {
2824 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2826 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2827 else
2828 NewRed = Builder.CreateBinOp(
2830 Prev);
2831 }
2832 State.set(this, NewRed, /*IsScalar*/ true);
2833}
2834
2836 VPCostContext &Ctx) const {
2837 RecurKind RdxKind = getRecurrenceKind();
2838 Type *ElementTy = Ctx.Types.inferScalarType(this);
2839 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2840 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2842 std::optional<FastMathFlags> OptionalFMF =
2843 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2844
2845 if (isPartialReduction()) {
2846 InstructionCost CondCost = 0;
2847 if (isConditional()) {
2849 auto *CondTy = cast<VectorType>(
2850 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2851 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2852 CondTy, Pred, Ctx.CostKind);
2853 }
2854 return CondCost + Ctx.TTI.getPartialReductionCost(
2855 Opcode, ElementTy, ElementTy, ElementTy, VF,
2857 TargetTransformInfo::PR_None, std::nullopt,
2858 Ctx.CostKind);
2859 }
2860
2861 // TODO: Support any-of reductions.
2862 assert(
2864 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2865 "Any-of reduction not implemented in VPlan-based cost model currently.");
2866
2867 // Note that TTI should model the cost of moving result to the scalar register
2868 // and the BinOp cost in the getMinMaxReductionCost().
2871 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2872 }
2873
2874 // Note that TTI should model the cost of moving result to the scalar register
2875 // and the BinOp cost in the getArithmeticReductionCost().
2876 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2877 Ctx.CostKind);
2878}
2879
2880VPExpressionRecipe::VPExpressionRecipe(
2881 ExpressionTypes ExpressionType,
2882 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2883 : VPSingleDefRecipe(VPDef::VPExpressionSC, {}, {}),
2884 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2885 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2886 assert(
2887 none_of(ExpressionRecipes,
2888 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2889 "expression cannot contain recipes with side-effects");
2890
2891 // Maintain a copy of the expression recipes as a set of users.
2892 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2893 for (auto *R : ExpressionRecipes)
2894 ExpressionRecipesAsSetOfUsers.insert(R);
2895
2896 // Recipes in the expression, except the last one, must only be used by
2897 // (other) recipes inside the expression. If there are other users, external
2898 // to the expression, use a clone of the recipe for external users.
2899 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2900 if (R != ExpressionRecipes.back() &&
2901 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2902 return !ExpressionRecipesAsSetOfUsers.contains(U);
2903 })) {
2904 // There are users outside of the expression. Clone the recipe and use the
2905 // clone those external users.
2906 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2907 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2908 VPUser &U, unsigned) {
2909 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2910 });
2911 CopyForExtUsers->insertBefore(R);
2912 }
2913 if (R->getParent())
2914 R->removeFromParent();
2915 }
2916
2917 // Internalize all external operands to the expression recipes. To do so,
2918 // create new temporary VPValues for all operands defined by a recipe outside
2919 // the expression. The original operands are added as operands of the
2920 // VPExpressionRecipe itself.
2921 for (auto *R : ExpressionRecipes) {
2922 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2923 auto *Def = Op->getDefiningRecipe();
2924 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2925 continue;
2926 addOperand(Op);
2927 LiveInPlaceholders.push_back(new VPSymbolicValue());
2928 }
2929 }
2930
2931 // Replace each external operand with the first one created for it in
2932 // LiveInPlaceholders.
2933 for (auto *R : ExpressionRecipes)
2934 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2935 R->replaceUsesOfWith(LiveIn, Tmp);
2936}
2937
2939 for (auto *R : ExpressionRecipes)
2940 // Since the list could contain duplicates, make sure the recipe hasn't
2941 // already been inserted.
2942 if (!R->getParent())
2943 R->insertBefore(this);
2944
2945 for (const auto &[Idx, Op] : enumerate(operands()))
2946 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
2947
2948 replaceAllUsesWith(ExpressionRecipes.back());
2949 ExpressionRecipes.clear();
2950}
2951
2953 VPCostContext &Ctx) const {
2954 Type *RedTy = Ctx.Types.inferScalarType(this);
2955 auto *SrcVecTy = cast<VectorType>(
2956 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
2957 assert(RedTy->isIntegerTy() &&
2958 "VPExpressionRecipe only supports integer types currently.");
2959 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2960 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
2961 switch (ExpressionType) {
2962 case ExpressionTypes::ExtendedReduction: {
2963 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2964 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
2965 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2966
2967 return cast<VPReductionRecipe>(ExpressionRecipes.back())
2968 ->isPartialReduction()
2969 ? Ctx.TTI.getPartialReductionCost(
2970 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr,
2971 RedTy, VF,
2973 ExtR->getOpcode()),
2974 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind)
2975 : Ctx.TTI.getExtendedReductionCost(
2976 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy,
2977 SrcVecTy, std::nullopt, Ctx.CostKind);
2978 }
2979 case ExpressionTypes::MulAccReduction:
2980 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
2981 Ctx.CostKind);
2982
2983 case ExpressionTypes::ExtNegatedMulAccReduction:
2984 assert(Opcode == Instruction::Add && "Unexpected opcode");
2985 Opcode = Instruction::Sub;
2986 [[fallthrough]];
2987 case ExpressionTypes::ExtMulAccReduction: {
2988 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
2989 if (RedR->isPartialReduction()) {
2990 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2991 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2992 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2993 return Ctx.TTI.getPartialReductionCost(
2994 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
2995 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
2997 Ext0R->getOpcode()),
2999 Ext1R->getOpcode()),
3000 Mul->getOpcode(), Ctx.CostKind);
3001 }
3002 return Ctx.TTI.getMulAccReductionCost(
3003 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3004 Instruction::ZExt,
3005 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3006 }
3007 }
3008 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3009}
3010
3012 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3013 return R->mayReadFromMemory() || R->mayWriteToMemory();
3014 });
3015}
3016
3018 assert(
3019 none_of(ExpressionRecipes,
3020 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3021 "expression cannot contain recipes with side-effects");
3022 return false;
3023}
3024
3026 // Cannot use vputils::isSingleScalar(), because all external operands
3027 // of the expression will be live-ins while bundled.
3028 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3029 return RR && !RR->isPartialReduction();
3030}
3031
3032#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3033
3035 VPSlotTracker &SlotTracker) const {
3036 O << Indent << "EXPRESSION ";
3038 O << " = ";
3039 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3040 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3041
3042 switch (ExpressionType) {
3043 case ExpressionTypes::ExtendedReduction: {
3045 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3046 O << Instruction::getOpcodeName(Opcode) << " (";
3048 Red->printFlags(O);
3049
3050 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3051 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3052 << *Ext0->getResultType();
3053 if (Red->isConditional()) {
3054 O << ", ";
3055 Red->getCondOp()->printAsOperand(O, SlotTracker);
3056 }
3057 O << ")";
3058 break;
3059 }
3060 case ExpressionTypes::ExtNegatedMulAccReduction: {
3062 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3064 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3065 << " (sub (0, mul";
3066 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3067 Mul->printFlags(O);
3068 O << "(";
3070 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3071 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3072 << *Ext0->getResultType() << "), (";
3074 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3075 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3076 << *Ext1->getResultType() << ")";
3077 if (Red->isConditional()) {
3078 O << ", ";
3079 Red->getCondOp()->printAsOperand(O, SlotTracker);
3080 }
3081 O << "))";
3082 break;
3083 }
3084 case ExpressionTypes::MulAccReduction:
3085 case ExpressionTypes::ExtMulAccReduction: {
3087 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3089 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3090 << " (";
3091 O << "mul";
3092 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3093 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3094 : ExpressionRecipes[0]);
3095 Mul->printFlags(O);
3096 if (IsExtended)
3097 O << "(";
3099 if (IsExtended) {
3100 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3101 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3102 << *Ext0->getResultType() << "), (";
3103 } else {
3104 O << ", ";
3105 }
3107 if (IsExtended) {
3108 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3109 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3110 << *Ext1->getResultType() << ")";
3111 }
3112 if (Red->isConditional()) {
3113 O << ", ";
3114 Red->getCondOp()->printAsOperand(O, SlotTracker);
3115 }
3116 O << ")";
3117 break;
3118 }
3119 }
3120}
3121
3123 VPSlotTracker &SlotTracker) const {
3124 if (isPartialReduction())
3125 O << Indent << "PARTIAL-REDUCE ";
3126 else
3127 O << Indent << "REDUCE ";
3129 O << " = ";
3131 O << " +";
3132 printFlags(O);
3133 O << " reduce."
3136 << " (";
3138 if (isConditional()) {
3139 O << ", ";
3141 }
3142 O << ")";
3143}
3144
3146 VPSlotTracker &SlotTracker) const {
3147 O << Indent << "REDUCE ";
3149 O << " = ";
3151 O << " +";
3152 printFlags(O);
3153 O << " vp.reduce."
3156 << " (";
3158 O << ", ";
3160 if (isConditional()) {
3161 O << ", ";
3163 }
3164 O << ")";
3165}
3166
3167#endif
3168
3169/// A helper function to scalarize a single Instruction in the innermost loop.
3170/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3171/// operands from \p RepRecipe instead of \p Instr's operands.
3172static void scalarizeInstruction(const Instruction *Instr,
3173 VPReplicateRecipe *RepRecipe,
3174 const VPLane &Lane, VPTransformState &State) {
3175 assert((!Instr->getType()->isAggregateType() ||
3176 canVectorizeTy(Instr->getType())) &&
3177 "Expected vectorizable or non-aggregate type.");
3178
3179 // Does this instruction return a value ?
3180 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3181
3182 Instruction *Cloned = Instr->clone();
3183 if (!IsVoidRetTy) {
3184 Cloned->setName(Instr->getName() + ".cloned");
3185 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3186 // The operands of the replicate recipe may have been narrowed, resulting in
3187 // a narrower result type. Update the type of the cloned instruction to the
3188 // correct type.
3189 if (ResultTy != Cloned->getType())
3190 Cloned->mutateType(ResultTy);
3191 }
3192
3193 RepRecipe->applyFlags(*Cloned);
3194 RepRecipe->applyMetadata(*Cloned);
3195
3196 if (RepRecipe->hasPredicate())
3197 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3198
3199 if (auto DL = RepRecipe->getDebugLoc())
3200 State.setDebugLocFrom(DL);
3201
3202 // Replace the operands of the cloned instructions with their scalar
3203 // equivalents in the new loop.
3204 for (const auto &I : enumerate(RepRecipe->operands())) {
3205 auto InputLane = Lane;
3206 VPValue *Operand = I.value();
3207 if (vputils::isSingleScalar(Operand))
3208 InputLane = VPLane::getFirstLane();
3209 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3210 }
3211
3212 // Place the cloned scalar in the new loop.
3213 State.Builder.Insert(Cloned);
3214
3215 State.set(RepRecipe, Cloned, Lane);
3216
3217 // If we just cloned a new assumption, add it the assumption cache.
3218 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3219 State.AC->registerAssumption(II);
3220
3221 assert(
3222 (RepRecipe->getRegion() ||
3223 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3224 all_of(RepRecipe->operands(),
3225 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3226 "Expected a recipe is either within a region or all of its operands "
3227 "are defined outside the vectorized region.");
3228}
3229
3232
3233 if (!State.Lane) {
3234 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3235 "must have already been unrolled");
3236 scalarizeInstruction(UI, this, VPLane(0), State);
3237 return;
3238 }
3239
3240 assert((State.VF.isScalar() || !isSingleScalar()) &&
3241 "uniform recipe shouldn't be predicated");
3242 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3243 scalarizeInstruction(UI, this, *State.Lane, State);
3244 // Insert scalar instance packing it into a vector.
3245 if (State.VF.isVector() && shouldPack()) {
3246 Value *WideValue =
3247 State.Lane->isFirstLane()
3248 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3249 : State.get(this);
3250 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3251 *State.Lane));
3252 }
3253}
3254
3256 // Find if the recipe is used by a widened recipe via an intervening
3257 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3258 return any_of(users(), [](const VPUser *U) {
3259 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3260 return !vputils::onlyScalarValuesUsed(PredR);
3261 return false;
3262 });
3263}
3264
3265/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3266/// which the legacy cost model computes a SCEV expression when computing the
3267/// address cost. Computing SCEVs for VPValues is incomplete and returns
3268/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3269/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3270static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3272 const Loop *L) {
3273 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3274 if (isa<SCEVCouldNotCompute>(Addr))
3275 return Addr;
3276
3277 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3278}
3279
3280/// Returns true if \p V is used as part of the address of another load or
3281/// store.
3282static bool isUsedByLoadStoreAddress(const VPUser *V) {
3284 SmallVector<const VPUser *> WorkList = {V};
3285
3286 while (!WorkList.empty()) {
3287 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3288 if (!Cur || !Seen.insert(Cur).second)
3289 continue;
3290
3291 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3292 // Skip blends that use V only through a compare by checking if any incoming
3293 // value was already visited.
3294 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3295 [&](unsigned I) {
3296 return Seen.contains(
3297 Blend->getIncomingValue(I)->getDefiningRecipe());
3298 }))
3299 continue;
3300
3301 for (VPUser *U : Cur->users()) {
3302 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3303 if (InterleaveR->getAddr() == Cur)
3304 return true;
3305 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3306 if (RepR->getOpcode() == Instruction::Load &&
3307 RepR->getOperand(0) == Cur)
3308 return true;
3309 if (RepR->getOpcode() == Instruction::Store &&
3310 RepR->getOperand(1) == Cur)
3311 return true;
3312 }
3313 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3314 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3315 return true;
3316 }
3317 }
3318
3319 // The legacy cost model only supports scalarization loads/stores with phi
3320 // addresses, if the phi is directly used as load/store address. Don't
3321 // traverse further for Blends.
3322 if (Blend)
3323 continue;
3324
3325 append_range(WorkList, Cur->users());
3326 }
3327 return false;
3328}
3329
3331 VPCostContext &Ctx) const {
3333 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3334 // transform, avoid computing their cost multiple times for now.
3335 Ctx.SkipCostComputation.insert(UI);
3336
3337 if (VF.isScalable() && !isSingleScalar())
3339
3340 switch (UI->getOpcode()) {
3341 case Instruction::Alloca:
3342 if (VF.isScalable())
3344 return Ctx.TTI.getArithmeticInstrCost(
3345 Instruction::Mul, Ctx.Types.inferScalarType(this), Ctx.CostKind);
3346 case Instruction::GetElementPtr:
3347 // We mark this instruction as zero-cost because the cost of GEPs in
3348 // vectorized code depends on whether the corresponding memory instruction
3349 // is scalarized or not. Therefore, we handle GEPs with the memory
3350 // instruction cost.
3351 return 0;
3352 case Instruction::Call: {
3353 auto *CalledFn =
3355
3358 for (const VPValue *ArgOp : ArgOps)
3359 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3360
3361 if (CalledFn->isIntrinsic())
3362 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3363 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3364 switch (CalledFn->getIntrinsicID()) {
3365 case Intrinsic::assume:
3366 case Intrinsic::lifetime_end:
3367 case Intrinsic::lifetime_start:
3368 case Intrinsic::sideeffect:
3369 case Intrinsic::pseudoprobe:
3370 case Intrinsic::experimental_noalias_scope_decl: {
3371 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3372 ElementCount::getFixed(1), Ctx) == 0 &&
3373 "scalarizing intrinsic should be free");
3374 return InstructionCost(0);
3375 }
3376 default:
3377 break;
3378 }
3379
3380 Type *ResultTy = Ctx.Types.inferScalarType(this);
3381 InstructionCost ScalarCallCost =
3382 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3383 if (isSingleScalar()) {
3384 if (CalledFn->isIntrinsic())
3385 ScalarCallCost = std::min(
3386 ScalarCallCost,
3387 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3388 ElementCount::getFixed(1), Ctx));
3389 return ScalarCallCost;
3390 }
3391
3392 return ScalarCallCost * VF.getFixedValue() +
3393 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3394 }
3395 case Instruction::Add:
3396 case Instruction::Sub:
3397 case Instruction::FAdd:
3398 case Instruction::FSub:
3399 case Instruction::Mul:
3400 case Instruction::FMul:
3401 case Instruction::FDiv:
3402 case Instruction::FRem:
3403 case Instruction::Shl:
3404 case Instruction::LShr:
3405 case Instruction::AShr:
3406 case Instruction::And:
3407 case Instruction::Or:
3408 case Instruction::Xor:
3409 case Instruction::ICmp:
3410 case Instruction::FCmp:
3412 Ctx) *
3413 (isSingleScalar() ? 1 : VF.getFixedValue());
3414 case Instruction::SDiv:
3415 case Instruction::UDiv:
3416 case Instruction::SRem:
3417 case Instruction::URem: {
3418 InstructionCost ScalarCost =
3420 if (isSingleScalar())
3421 return ScalarCost;
3422
3423 // If any of the operands is from a different replicate region and has its
3424 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3425 // model to avoid cost mis-match.
3426 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3427 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3428 if (!PredR)
3429 return false;
3430 return Ctx.skipCostComputation(
3432 PredR->getOperand(0)->getUnderlyingValue()),
3433 VF.isVector());
3434 }))
3435 break;
3436
3437 ScalarCost = ScalarCost * VF.getFixedValue() +
3438 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3439 to_vector(operands()), VF);
3440 // If the recipe is not predicated (i.e. not in a replicate region), return
3441 // the scalar cost. Otherwise handle predicated cost.
3442 if (!getRegion()->isReplicator())
3443 return ScalarCost;
3444
3445 // Account for the phi nodes that we will create.
3446 ScalarCost += VF.getFixedValue() *
3447 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3448 // Scale the cost by the probability of executing the predicated blocks.
3449 // This assumes the predicated block for each vector lane is equally
3450 // likely.
3451 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3452 return ScalarCost;
3453 }
3454 case Instruction::Load:
3455 case Instruction::Store: {
3456 // TODO: See getMemInstScalarizationCost for how to handle replicating and
3457 // predicated cases.
3458 const VPRegionBlock *ParentRegion = getRegion();
3459 if (ParentRegion && ParentRegion->isReplicator())
3460 break;
3461
3462 bool IsLoad = UI->getOpcode() == Instruction::Load;
3463 const VPValue *PtrOp = getOperand(!IsLoad);
3464 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3466 break;
3467
3468 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3469 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3470 const Align Alignment = getLoadStoreAlignment(UI);
3471 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3473 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3474 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo);
3475
3476 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3477 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3478 bool UsedByLoadStoreAddress =
3479 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3480 InstructionCost ScalarCost =
3481 ScalarMemOpCost +
3482 Ctx.TTI.getAddressComputationCost(
3483 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3484 Ctx.CostKind);
3485 if (isSingleScalar())
3486 return ScalarCost;
3487
3488 SmallVector<const VPValue *> OpsToScalarize;
3489 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3490 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3491 // don't assign scalarization overhead in general, if the target prefers
3492 // vectorized addressing or the loaded value is used as part of an address
3493 // of another load or store.
3494 if (!UsedByLoadStoreAddress) {
3495 bool EfficientVectorLoadStore =
3496 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3497 if (!(IsLoad && !PreferVectorizedAddressing) &&
3498 !(!IsLoad && EfficientVectorLoadStore))
3499 append_range(OpsToScalarize, operands());
3500
3501 if (!EfficientVectorLoadStore)
3502 ResultTy = Ctx.Types.inferScalarType(this);
3503 }
3504
3505 return (ScalarCost * VF.getFixedValue()) +
3506 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, true);
3507 }
3508 case Instruction::SExt:
3509 case Instruction::ZExt:
3510 case Instruction::FPToUI:
3511 case Instruction::FPToSI:
3512 case Instruction::FPExt:
3513 case Instruction::PtrToInt:
3514 case Instruction::PtrToAddr:
3515 case Instruction::IntToPtr:
3516 case Instruction::SIToFP:
3517 case Instruction::UIToFP:
3518 case Instruction::Trunc:
3519 case Instruction::FPTrunc:
3520 case Instruction::AddrSpaceCast: {
3522 Ctx) *
3523 (isSingleScalar() ? 1 : VF.getFixedValue());
3524 }
3525 case Instruction::ExtractValue:
3526 case Instruction::InsertValue:
3527 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3528 }
3529
3530 return Ctx.getLegacyCost(UI, VF);
3531}
3532
3533#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3535 VPSlotTracker &SlotTracker) const {
3536 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3537
3538 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3540 O << " = ";
3541 }
3542 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3543 O << "call";
3544 printFlags(O);
3545 O << "@" << CB->getCalledFunction()->getName() << "(";
3547 O, [&O, &SlotTracker](VPValue *Op) {
3548 Op->printAsOperand(O, SlotTracker);
3549 });
3550 O << ")";
3551 } else {
3553 printFlags(O);
3555 }
3556
3557 if (shouldPack())
3558 O << " (S->V)";
3559}
3560#endif
3561
3563 assert(State.Lane && "Branch on Mask works only on single instance.");
3564
3565 VPValue *BlockInMask = getOperand(0);
3566 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3567
3568 // Replace the temporary unreachable terminator with a new conditional branch,
3569 // whose two destinations will be set later when they are created.
3570 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3571 assert(isa<UnreachableInst>(CurrentTerminator) &&
3572 "Expected to replace unreachable terminator with conditional branch.");
3573 auto CondBr =
3574 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3575 CondBr->setSuccessor(0, nullptr);
3576 CurrentTerminator->eraseFromParent();
3577}
3578
3580 VPCostContext &Ctx) const {
3581 // The legacy cost model doesn't assign costs to branches for individual
3582 // replicate regions. Match the current behavior in the VPlan cost model for
3583 // now.
3584 return 0;
3585}
3586
3588 assert(State.Lane && "Predicated instruction PHI works per instance.");
3589 Instruction *ScalarPredInst =
3590 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3591 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3592 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3593 assert(PredicatingBB && "Predicated block has no single predecessor.");
3595 "operand must be VPReplicateRecipe");
3596
3597 // By current pack/unpack logic we need to generate only a single phi node: if
3598 // a vector value for the predicated instruction exists at this point it means
3599 // the instruction has vector users only, and a phi for the vector value is
3600 // needed. In this case the recipe of the predicated instruction is marked to
3601 // also do that packing, thereby "hoisting" the insert-element sequence.
3602 // Otherwise, a phi node for the scalar value is needed.
3603 if (State.hasVectorValue(getOperand(0))) {
3604 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3606 "Packed operands must generate an insertelement or insertvalue");
3607
3608 // If VectorI is a struct, it will be a sequence like:
3609 // %1 = insertvalue %unmodified, %x, 0
3610 // %2 = insertvalue %1, %y, 1
3611 // %VectorI = insertvalue %2, %z, 2
3612 // To get the unmodified vector we need to look through the chain.
3613 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3614 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3615 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3616
3617 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3618 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3619 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3620 if (State.hasVectorValue(this))
3621 State.reset(this, VPhi);
3622 else
3623 State.set(this, VPhi);
3624 // NOTE: Currently we need to update the value of the operand, so the next
3625 // predicated iteration inserts its generated value in the correct vector.
3626 State.reset(getOperand(0), VPhi);
3627 } else {
3628 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3629 return;
3630
3631 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3632 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3633 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3634 PredicatingBB);
3635 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3636 if (State.hasScalarValue(this, *State.Lane))
3637 State.reset(this, Phi, *State.Lane);
3638 else
3639 State.set(this, Phi, *State.Lane);
3640 // NOTE: Currently we need to update the value of the operand, so the next
3641 // predicated iteration inserts its generated value in the correct vector.
3642 State.reset(getOperand(0), Phi, *State.Lane);
3643 }
3644}
3645
3646#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3648 VPSlotTracker &SlotTracker) const {
3649 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3651 O << " = ";
3653}
3654#endif
3655
3657 VPCostContext &Ctx) const {
3659 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3660 ->getAddressSpace();
3661 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3662 ? Instruction::Load
3663 : Instruction::Store;
3664
3665 if (!Consecutive) {
3666 // TODO: Using the original IR may not be accurate.
3667 // Currently, ARM will use the underlying IR to calculate gather/scatter
3668 // instruction cost.
3669 assert(!Reverse &&
3670 "Inconsecutive memory access should not have the order.");
3671
3673 Type *PtrTy = Ptr->getType();
3674
3675 // If the address value is uniform across all lanes, then the address can be
3676 // calculated with scalar type and broadcast.
3678 PtrTy = toVectorTy(PtrTy, VF);
3679
3680 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3681 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3682 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3683 : Intrinsic::vp_scatter;
3684 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3685 Ctx.CostKind) +
3686 Ctx.TTI.getMemIntrinsicInstrCost(
3688 &Ingredient),
3689 Ctx.CostKind);
3690 }
3691
3693 if (IsMasked) {
3694 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3695 : Intrinsic::masked_store;
3696 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3697 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3698 } else {
3699 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3701 : getOperand(1));
3702 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3703 OpInfo, &Ingredient);
3704 }
3705 return Cost;
3706}
3707
3709 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3710 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3711 bool CreateGather = !isConsecutive();
3712
3713 auto &Builder = State.Builder;
3714 Value *Mask = nullptr;
3715 if (auto *VPMask = getMask()) {
3716 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3717 // of a null all-one mask is a null mask.
3718 Mask = State.get(VPMask);
3719 if (isReverse())
3720 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3721 }
3722
3723 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3724 Value *NewLI;
3725 if (CreateGather) {
3726 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3727 "wide.masked.gather");
3728 } else if (Mask) {
3729 NewLI =
3730 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3731 PoisonValue::get(DataTy), "wide.masked.load");
3732 } else {
3733 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3734 }
3736 State.set(this, NewLI);
3737}
3738
3739#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3741 VPSlotTracker &SlotTracker) const {
3742 O << Indent << "WIDEN ";
3744 O << " = load ";
3746}
3747#endif
3748
3749/// Use all-true mask for reverse rather than actual mask, as it avoids a
3750/// dependence w/o affecting the result.
3752 Value *EVL, const Twine &Name) {
3753 VectorType *ValTy = cast<VectorType>(Operand->getType());
3754 Value *AllTrueMask =
3755 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3756 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3757 {Operand, AllTrueMask, EVL}, nullptr, Name);
3758}
3759
3761 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3762 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3763 bool CreateGather = !isConsecutive();
3764
3765 auto &Builder = State.Builder;
3766 CallInst *NewLI;
3767 Value *EVL = State.get(getEVL(), VPLane(0));
3768 Value *Addr = State.get(getAddr(), !CreateGather);
3769 Value *Mask = nullptr;
3770 if (VPValue *VPMask = getMask()) {
3771 Mask = State.get(VPMask);
3772 if (isReverse())
3773 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3774 } else {
3775 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3776 }
3777
3778 if (CreateGather) {
3779 NewLI =
3780 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3781 nullptr, "wide.masked.gather");
3782 } else {
3783 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3784 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3785 }
3786 NewLI->addParamAttr(
3788 applyMetadata(*NewLI);
3789 Instruction *Res = NewLI;
3790 State.set(this, Res);
3791}
3792
3794 VPCostContext &Ctx) const {
3795 if (!Consecutive || IsMasked)
3796 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3797
3798 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3799 // here because the EVL recipes using EVL to replace the tail mask. But in the
3800 // legacy model, it will always calculate the cost of mask.
3801 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3802 // don't need to compare to the legacy cost model.
3804 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3805 ->getAddressSpace();
3806 return Ctx.TTI.getMemIntrinsicInstrCost(
3807 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3808 Ctx.CostKind);
3809}
3810
3811#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3813 VPSlotTracker &SlotTracker) const {
3814 O << Indent << "WIDEN ";
3816 O << " = vp.load ";
3818}
3819#endif
3820
3822 VPValue *StoredVPValue = getStoredValue();
3823 bool CreateScatter = !isConsecutive();
3824
3825 auto &Builder = State.Builder;
3826
3827 Value *Mask = nullptr;
3828 if (auto *VPMask = getMask()) {
3829 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3830 // of a null all-one mask is a null mask.
3831 Mask = State.get(VPMask);
3832 if (isReverse())
3833 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3834 }
3835
3836 Value *StoredVal = State.get(StoredVPValue);
3837 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3838 Instruction *NewSI = nullptr;
3839 if (CreateScatter)
3840 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3841 else if (Mask)
3842 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3843 else
3844 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3845 applyMetadata(*NewSI);
3846}
3847
3848#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3850 VPSlotTracker &SlotTracker) const {
3851 O << Indent << "WIDEN store ";
3853}
3854#endif
3855
3857 VPValue *StoredValue = getStoredValue();
3858 bool CreateScatter = !isConsecutive();
3859
3860 auto &Builder = State.Builder;
3861
3862 CallInst *NewSI = nullptr;
3863 Value *StoredVal = State.get(StoredValue);
3864 Value *EVL = State.get(getEVL(), VPLane(0));
3865 Value *Mask = nullptr;
3866 if (VPValue *VPMask = getMask()) {
3867 Mask = State.get(VPMask);
3868 if (isReverse())
3869 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3870 } else {
3871 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3872 }
3873 Value *Addr = State.get(getAddr(), !CreateScatter);
3874 if (CreateScatter) {
3875 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3876 Intrinsic::vp_scatter,
3877 {StoredVal, Addr, Mask, EVL});
3878 } else {
3879 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3880 Intrinsic::vp_store,
3881 {StoredVal, Addr, Mask, EVL});
3882 }
3883 NewSI->addParamAttr(
3885 applyMetadata(*NewSI);
3886}
3887
3889 VPCostContext &Ctx) const {
3890 if (!Consecutive || IsMasked)
3891 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3892
3893 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3894 // here because the EVL recipes using EVL to replace the tail mask. But in the
3895 // legacy model, it will always calculate the cost of mask.
3896 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3897 // don't need to compare to the legacy cost model.
3899 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3900 ->getAddressSpace();
3901 return Ctx.TTI.getMemIntrinsicInstrCost(
3902 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3903 Ctx.CostKind);
3904}
3905
3906#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3908 VPSlotTracker &SlotTracker) const {
3909 O << Indent << "WIDEN vp.store ";
3911}
3912#endif
3913
3915 VectorType *DstVTy, const DataLayout &DL) {
3916 // Verify that V is a vector type with same number of elements as DstVTy.
3917 auto VF = DstVTy->getElementCount();
3918 auto *SrcVecTy = cast<VectorType>(V->getType());
3919 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3920 Type *SrcElemTy = SrcVecTy->getElementType();
3921 Type *DstElemTy = DstVTy->getElementType();
3922 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3923 "Vector elements must have same size");
3924
3925 // Do a direct cast if element types are castable.
3926 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3927 return Builder.CreateBitOrPointerCast(V, DstVTy);
3928 }
3929 // V cannot be directly casted to desired vector type.
3930 // May happen when V is a floating point vector but DstVTy is a vector of
3931 // pointers or vice-versa. Handle this using a two-step bitcast using an
3932 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3933 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3934 "Only one type should be a pointer type");
3935 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3936 "Only one type should be a floating point type");
3937 Type *IntTy =
3938 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3939 auto *VecIntTy = VectorType::get(IntTy, VF);
3940 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3941 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3942}
3943
3944/// Return a vector containing interleaved elements from multiple
3945/// smaller input vectors.
3947 const Twine &Name) {
3948 unsigned Factor = Vals.size();
3949 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
3950
3951 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
3952#ifndef NDEBUG
3953 for (Value *Val : Vals)
3954 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
3955#endif
3956
3957 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
3958 // must use intrinsics to interleave.
3959 if (VecTy->isScalableTy()) {
3960 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
3961 return Builder.CreateVectorInterleave(Vals, Name);
3962 }
3963
3964 // Fixed length. Start by concatenating all vectors into a wide vector.
3965 Value *WideVec = concatenateVectors(Builder, Vals);
3966
3967 // Interleave the elements into the wide vector.
3968 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3969 return Builder.CreateShuffleVector(
3970 WideVec, createInterleaveMask(NumElts, Factor), Name);
3971}
3972
3973// Try to vectorize the interleave group that \p Instr belongs to.
3974//
3975// E.g. Translate following interleaved load group (factor = 3):
3976// for (i = 0; i < N; i+=3) {
3977// R = Pic[i]; // Member of index 0
3978// G = Pic[i+1]; // Member of index 1
3979// B = Pic[i+2]; // Member of index 2
3980// ... // do something to R, G, B
3981// }
3982// To:
3983// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
3984// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
3985// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
3986// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
3987//
3988// Or translate following interleaved store group (factor = 3):
3989// for (i = 0; i < N; i+=3) {
3990// ... do something to R, G, B
3991// Pic[i] = R; // Member of index 0
3992// Pic[i+1] = G; // Member of index 1
3993// Pic[i+2] = B; // Member of index 2
3994// }
3995// To:
3996// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
3997// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
3998// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
3999// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4000// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4002 assert(!State.Lane && "Interleave group being replicated.");
4003 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4004 "Masking gaps for scalable vectors is not yet supported.");
4006 Instruction *Instr = Group->getInsertPos();
4007
4008 // Prepare for the vector type of the interleaved load/store.
4009 Type *ScalarTy = getLoadStoreType(Instr);
4010 unsigned InterleaveFactor = Group->getFactor();
4011 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4012
4013 VPValue *BlockInMask = getMask();
4014 VPValue *Addr = getAddr();
4015 Value *ResAddr = State.get(Addr, VPLane(0));
4016
4017 auto CreateGroupMask = [&BlockInMask, &State,
4018 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4019 if (State.VF.isScalable()) {
4020 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4021 assert(InterleaveFactor <= 8 &&
4022 "Unsupported deinterleave factor for scalable vectors");
4023 auto *ResBlockInMask = State.get(BlockInMask);
4024 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4025 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4026 }
4027
4028 if (!BlockInMask)
4029 return MaskForGaps;
4030
4031 Value *ResBlockInMask = State.get(BlockInMask);
4032 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4033 ResBlockInMask,
4034 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4035 "interleaved.mask");
4036 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4037 ShuffledMask, MaskForGaps)
4038 : ShuffledMask;
4039 };
4040
4041 const DataLayout &DL = Instr->getDataLayout();
4042 // Vectorize the interleaved load group.
4043 if (isa<LoadInst>(Instr)) {
4044 Value *MaskForGaps = nullptr;
4045 if (needsMaskForGaps()) {
4046 MaskForGaps =
4047 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4048 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4049 }
4050
4051 Instruction *NewLoad;
4052 if (BlockInMask || MaskForGaps) {
4053 Value *GroupMask = CreateGroupMask(MaskForGaps);
4054 Value *PoisonVec = PoisonValue::get(VecTy);
4055 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4056 Group->getAlign(), GroupMask,
4057 PoisonVec, "wide.masked.vec");
4058 } else
4059 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4060 Group->getAlign(), "wide.vec");
4061 applyMetadata(*NewLoad);
4062 // TODO: Also manage existing metadata using VPIRMetadata.
4063 Group->addMetadata(NewLoad);
4064
4066 if (VecTy->isScalableTy()) {
4067 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4068 // so must use intrinsics to deinterleave.
4069 assert(InterleaveFactor <= 8 &&
4070 "Unsupported deinterleave factor for scalable vectors");
4071 NewLoad = State.Builder.CreateIntrinsic(
4072 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4073 NewLoad->getType(), NewLoad,
4074 /*FMFSource=*/nullptr, "strided.vec");
4075 }
4076
4077 auto CreateStridedVector = [&InterleaveFactor, &State,
4078 &NewLoad](unsigned Index) -> Value * {
4079 assert(Index < InterleaveFactor && "Illegal group index");
4080 if (State.VF.isScalable())
4081 return State.Builder.CreateExtractValue(NewLoad, Index);
4082
4083 // For fixed length VF, use shuffle to extract the sub-vectors from the
4084 // wide load.
4085 auto StrideMask =
4086 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4087 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4088 "strided.vec");
4089 };
4090
4091 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4092 Instruction *Member = Group->getMember(I);
4093
4094 // Skip the gaps in the group.
4095 if (!Member)
4096 continue;
4097
4098 Value *StridedVec = CreateStridedVector(I);
4099
4100 // If this member has different type, cast the result type.
4101 if (Member->getType() != ScalarTy) {
4102 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4103 StridedVec =
4104 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4105 }
4106
4107 if (Group->isReverse())
4108 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4109
4110 State.set(VPDefs[J], StridedVec);
4111 ++J;
4112 }
4113 return;
4114 }
4115
4116 // The sub vector type for current instruction.
4117 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4118
4119 // Vectorize the interleaved store group.
4120 Value *MaskForGaps =
4121 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4122 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4123 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4124 ArrayRef<VPValue *> StoredValues = getStoredValues();
4125 // Collect the stored vector from each member.
4126 SmallVector<Value *, 4> StoredVecs;
4127 unsigned StoredIdx = 0;
4128 for (unsigned i = 0; i < InterleaveFactor; i++) {
4129 assert((Group->getMember(i) || MaskForGaps) &&
4130 "Fail to get a member from an interleaved store group");
4131 Instruction *Member = Group->getMember(i);
4132
4133 // Skip the gaps in the group.
4134 if (!Member) {
4135 Value *Undef = PoisonValue::get(SubVT);
4136 StoredVecs.push_back(Undef);
4137 continue;
4138 }
4139
4140 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4141 ++StoredIdx;
4142
4143 if (Group->isReverse())
4144 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4145
4146 // If this member has different type, cast it to a unified type.
4147
4148 if (StoredVec->getType() != SubVT)
4149 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4150
4151 StoredVecs.push_back(StoredVec);
4152 }
4153
4154 // Interleave all the smaller vectors into one wider vector.
4155 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4156 Instruction *NewStoreInstr;
4157 if (BlockInMask || MaskForGaps) {
4158 Value *GroupMask = CreateGroupMask(MaskForGaps);
4159 NewStoreInstr = State.Builder.CreateMaskedStore(
4160 IVec, ResAddr, Group->getAlign(), GroupMask);
4161 } else
4162 NewStoreInstr =
4163 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4164
4165 applyMetadata(*NewStoreInstr);
4166 // TODO: Also manage existing metadata using VPIRMetadata.
4167 Group->addMetadata(NewStoreInstr);
4168}
4169
4170#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4172 VPSlotTracker &SlotTracker) const {
4174 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4175 IG->getInsertPos()->printAsOperand(O, false);
4176 O << ", ";
4178 VPValue *Mask = getMask();
4179 if (Mask) {
4180 O << ", ";
4181 Mask->printAsOperand(O, SlotTracker);
4182 }
4183
4184 unsigned OpIdx = 0;
4185 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4186 if (!IG->getMember(i))
4187 continue;
4188 if (getNumStoreOperands() > 0) {
4189 O << "\n" << Indent << " store ";
4191 O << " to index " << i;
4192 } else {
4193 O << "\n" << Indent << " ";
4195 O << " = load from index " << i;
4196 }
4197 ++OpIdx;
4198 }
4199}
4200#endif
4201
4203 assert(!State.Lane && "Interleave group being replicated.");
4204 assert(State.VF.isScalable() &&
4205 "Only support scalable VF for EVL tail-folding.");
4207 "Masking gaps for scalable vectors is not yet supported.");
4209 Instruction *Instr = Group->getInsertPos();
4210
4211 // Prepare for the vector type of the interleaved load/store.
4212 Type *ScalarTy = getLoadStoreType(Instr);
4213 unsigned InterleaveFactor = Group->getFactor();
4214 assert(InterleaveFactor <= 8 &&
4215 "Unsupported deinterleave/interleave factor for scalable vectors");
4216 ElementCount WideVF = State.VF * InterleaveFactor;
4217 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4218
4219 VPValue *Addr = getAddr();
4220 Value *ResAddr = State.get(Addr, VPLane(0));
4221 Value *EVL = State.get(getEVL(), VPLane(0));
4222 Value *InterleaveEVL = State.Builder.CreateMul(
4223 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4224 /* NUW= */ true, /* NSW= */ true);
4225 LLVMContext &Ctx = State.Builder.getContext();
4226
4227 Value *GroupMask = nullptr;
4228 if (VPValue *BlockInMask = getMask()) {
4229 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4230 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4231 } else {
4232 GroupMask =
4233 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4234 }
4235
4236 // Vectorize the interleaved load group.
4237 if (isa<LoadInst>(Instr)) {
4238 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4239 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4240 "wide.vp.load");
4241 NewLoad->addParamAttr(0,
4242 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4243
4244 applyMetadata(*NewLoad);
4245 // TODO: Also manage existing metadata using VPIRMetadata.
4246 Group->addMetadata(NewLoad);
4247
4248 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4249 // so must use intrinsics to deinterleave.
4250 NewLoad = State.Builder.CreateIntrinsic(
4251 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4252 NewLoad->getType(), NewLoad,
4253 /*FMFSource=*/nullptr, "strided.vec");
4254
4255 const DataLayout &DL = Instr->getDataLayout();
4256 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4257 Instruction *Member = Group->getMember(I);
4258 // Skip the gaps in the group.
4259 if (!Member)
4260 continue;
4261
4262 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4263 // If this member has different type, cast the result type.
4264 if (Member->getType() != ScalarTy) {
4265 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4266 StridedVec =
4267 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4268 }
4269
4270 State.set(getVPValue(J), StridedVec);
4271 ++J;
4272 }
4273 return;
4274 } // End for interleaved load.
4275
4276 // The sub vector type for current instruction.
4277 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4278 // Vectorize the interleaved store group.
4279 ArrayRef<VPValue *> StoredValues = getStoredValues();
4280 // Collect the stored vector from each member.
4281 SmallVector<Value *, 4> StoredVecs;
4282 const DataLayout &DL = Instr->getDataLayout();
4283 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4284 Instruction *Member = Group->getMember(I);
4285 // Skip the gaps in the group.
4286 if (!Member) {
4287 StoredVecs.push_back(PoisonValue::get(SubVT));
4288 continue;
4289 }
4290
4291 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4292 // If this member has different type, cast it to a unified type.
4293 if (StoredVec->getType() != SubVT)
4294 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4295
4296 StoredVecs.push_back(StoredVec);
4297 ++StoredIdx;
4298 }
4299
4300 // Interleave all the smaller vectors into one wider vector.
4301 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4302 CallInst *NewStore =
4303 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4304 {IVec, ResAddr, GroupMask, InterleaveEVL});
4305 NewStore->addParamAttr(1,
4306 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4307
4308 applyMetadata(*NewStore);
4309 // TODO: Also manage existing metadata using VPIRMetadata.
4310 Group->addMetadata(NewStore);
4311}
4312
4313#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4315 VPSlotTracker &SlotTracker) const {
4317 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4318 IG->getInsertPos()->printAsOperand(O, false);
4319 O << ", ";
4321 O << ", ";
4323 if (VPValue *Mask = getMask()) {
4324 O << ", ";
4325 Mask->printAsOperand(O, SlotTracker);
4326 }
4327
4328 unsigned OpIdx = 0;
4329 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4330 if (!IG->getMember(i))
4331 continue;
4332 if (getNumStoreOperands() > 0) {
4333 O << "\n" << Indent << " vp.store ";
4335 O << " to index " << i;
4336 } else {
4337 O << "\n" << Indent << " ";
4339 O << " = vp.load from index " << i;
4340 }
4341 ++OpIdx;
4342 }
4343}
4344#endif
4345
4347 VPCostContext &Ctx) const {
4348 Instruction *InsertPos = getInsertPos();
4349 // Find the VPValue index of the interleave group. We need to skip gaps.
4350 unsigned InsertPosIdx = 0;
4351 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4352 if (auto *Member = IG->getMember(Idx)) {
4353 if (Member == InsertPos)
4354 break;
4355 InsertPosIdx++;
4356 }
4357 Type *ValTy = Ctx.Types.inferScalarType(
4358 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4359 : getStoredValues()[InsertPosIdx]);
4360 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4361 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4362 ->getAddressSpace();
4363
4364 unsigned InterleaveFactor = IG->getFactor();
4365 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4366
4367 // Holds the indices of existing members in the interleaved group.
4369 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4370 if (IG->getMember(IF))
4371 Indices.push_back(IF);
4372
4373 // Calculate the cost of the whole interleaved group.
4374 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4375 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4376 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4377
4378 if (!IG->isReverse())
4379 return Cost;
4380
4381 return Cost + IG->getNumMembers() *
4382 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4383 VectorTy, VectorTy, {}, Ctx.CostKind,
4384 0);
4385}
4386
4387#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4389 VPSlotTracker &SlotTracker) const {
4390 O << Indent << "EMIT ";
4392 O << " = CANONICAL-INDUCTION ";
4394}
4395#endif
4396
4398 return vputils::onlyScalarValuesUsed(this) &&
4399 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4400}
4401
4402#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4404 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4405 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4406 "unexpected number of operands");
4407 O << Indent << "EMIT ";
4409 O << " = WIDEN-POINTER-INDUCTION ";
4411 O << ", ";
4413 O << ", ";
4415 if (getNumOperands() == 5) {
4416 O << ", ";
4418 O << ", ";
4420 }
4421}
4422
4424 VPSlotTracker &SlotTracker) const {
4425 O << Indent << "EMIT ";
4427 O << " = EXPAND SCEV " << *Expr;
4428}
4429#endif
4430
4432 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4433 Type *STy = CanonicalIV->getType();
4434 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4435 ElementCount VF = State.VF;
4436 Value *VStart = VF.isScalar()
4437 ? CanonicalIV
4438 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4439 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4440 if (VF.isVector()) {
4441 VStep = Builder.CreateVectorSplat(VF, VStep);
4442 VStep =
4443 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4444 }
4445 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4446 State.set(this, CanonicalVectorIV);
4447}
4448
4449#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4451 VPSlotTracker &SlotTracker) const {
4452 O << Indent << "EMIT ";
4454 O << " = WIDEN-CANONICAL-INDUCTION ";
4456}
4457#endif
4458
4460 auto &Builder = State.Builder;
4461 // Create a vector from the initial value.
4462 auto *VectorInit = getStartValue()->getLiveInIRValue();
4463
4464 Type *VecTy = State.VF.isScalar()
4465 ? VectorInit->getType()
4466 : VectorType::get(VectorInit->getType(), State.VF);
4467
4468 BasicBlock *VectorPH =
4469 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4470 if (State.VF.isVector()) {
4471 auto *IdxTy = Builder.getInt32Ty();
4472 auto *One = ConstantInt::get(IdxTy, 1);
4473 IRBuilder<>::InsertPointGuard Guard(Builder);
4474 Builder.SetInsertPoint(VectorPH->getTerminator());
4475 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4476 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4477 VectorInit = Builder.CreateInsertElement(
4478 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4479 }
4480
4481 // Create a phi node for the new recurrence.
4482 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4483 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4484 Phi->addIncoming(VectorInit, VectorPH);
4485 State.set(this, Phi);
4486}
4487
4490 VPCostContext &Ctx) const {
4491 if (VF.isScalar())
4492 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4493
4494 return 0;
4495}
4496
4497#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4499 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4500 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4502 O << " = phi ";
4504}
4505#endif
4506
4508 // Reductions do not have to start at zero. They can start with
4509 // any loop invariant values.
4510 VPValue *StartVPV = getStartValue();
4511
4512 // In order to support recurrences we need to be able to vectorize Phi nodes.
4513 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4514 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4515 // this value when we vectorize all of the instructions that use the PHI.
4516 BasicBlock *VectorPH =
4517 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4518 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4519 Value *StartV = State.get(StartVPV, ScalarPHI);
4520 Type *VecTy = StartV->getType();
4521
4522 BasicBlock *HeaderBB = State.CFG.PrevBB;
4523 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4524 "recipe must be in the vector loop header");
4525 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4526 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4527 State.set(this, Phi, isInLoop());
4528
4529 Phi->addIncoming(StartV, VectorPH);
4530}
4531
4532#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4534 VPSlotTracker &SlotTracker) const {
4535 O << Indent << "WIDEN-REDUCTION-PHI ";
4536
4538 O << " = phi ";
4540 if (getVFScaleFactor() > 1)
4541 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4542}
4543#endif
4544
4546 Value *Op0 = State.get(getOperand(0));
4547 Type *VecTy = Op0->getType();
4548 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4549 State.set(this, VecPhi);
4550}
4551
4553 VPCostContext &Ctx) const {
4554 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4555}
4556
4557#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4559 VPSlotTracker &SlotTracker) const {
4560 O << Indent << "WIDEN-PHI ";
4561
4563 O << " = phi ";
4565}
4566#endif
4567
4569 BasicBlock *VectorPH =
4570 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4571 Value *StartMask = State.get(getOperand(0));
4572 PHINode *Phi =
4573 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4574 Phi->addIncoming(StartMask, VectorPH);
4575 State.set(this, Phi);
4576}
4577
4578#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4580 VPSlotTracker &SlotTracker) const {
4581 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4582
4584 O << " = phi ";
4586}
4587#endif
4588
4589#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4591 VPSlotTracker &SlotTracker) const {
4592 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
4593
4595 O << " = phi ";
4597}
4598#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, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isOrdered(const Instruction *I)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static InstructionCost getCostForIntrinsics(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost for the intrinsic ID with Operands, produced by R.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
SmallVector< Value *, 2 > VectorParts
static bool isUsedByLoadStoreAddress(const VPUser *V)
Returns true if V is used as part of the address of another load or store.
static void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
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...
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
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:283
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 LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
This class 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:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
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:356
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:476
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:449
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:461
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:471
unsigned getVPDefID() const
Definition VPlanValue.h:481
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
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:236
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:253
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1428
operand_range operands()
Definition VPlanValue.h:321
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:297
unsigned getNumOperands() const
Definition VPlanValue.h:291
operand_iterator op_begin()
Definition VPlanValue.h:317
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:292
virtual bool usesFirstLaneOnly(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:336
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:47
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:74
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
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h: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)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
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.
specific_intval< 1 > m_False()
specific_intval< 1 > m_True()
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:532
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:829
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h: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
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
@ Other
Any other memory.
Definition ModRef.h:68
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ FMaximum
FP max with llvm.maximum semantics.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
DWARFExpression::Operation Op
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Value * emitTransformedIndex(IRBuilderBase &B, Value *Index, Value *StartValue, Value *Step, InductionDescriptor::InductionKind InductionKind, const BinaryOperator *InductionBinOp)
Compute the transformed value of Index at offset StartValue using step StepValue.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h: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 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,...
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:226
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