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