LLVM 22.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"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Type.h"
32#include "llvm/IR/Value.h"
35#include "llvm/Support/Debug.h"
39#include <cassert>
40
41using namespace llvm;
42using namespace llvm::VPlanPatternMatch;
43
45
46#define LV_NAME "loop-vectorize"
47#define DEBUG_TYPE LV_NAME
48
50 switch (getVPDefID()) {
51 case VPExpressionSC:
52 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
53 case VPInstructionSC: {
54 auto *VPI = cast<VPInstruction>(this);
55 // Loads read from memory but don't write to memory.
56 if (VPI->getOpcode() == Instruction::Load)
57 return false;
58 return VPI->opcodeMayReadOrWriteFromMemory();
59 }
60 case VPInterleaveEVLSC:
61 case VPInterleaveSC:
62 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
63 case VPWidenStoreEVLSC:
64 case VPWidenStoreSC:
65 return true;
66 case VPReplicateSC:
67 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
68 ->mayWriteToMemory();
69 case VPWidenCallSC:
70 return !cast<VPWidenCallRecipe>(this)
71 ->getCalledScalarFunction()
72 ->onlyReadsMemory();
73 case VPWidenIntrinsicSC:
74 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
75 case VPCanonicalIVPHISC:
76 case VPBranchOnMaskSC:
77 case VPDerivedIVSC:
78 case VPFirstOrderRecurrencePHISC:
79 case VPReductionPHISC:
80 case VPScalarIVStepsSC:
81 case VPPredInstPHISC:
82 return false;
83 case VPBlendSC:
84 case VPReductionEVLSC:
85 case VPReductionSC:
86 case VPVectorPointerSC:
87 case VPWidenCanonicalIVSC:
88 case VPWidenCastSC:
89 case VPWidenGEPSC:
90 case VPWidenIntOrFpInductionSC:
91 case VPWidenLoadEVLSC:
92 case VPWidenLoadSC:
93 case VPWidenPHISC:
94 case VPWidenPointerInductionSC:
95 case VPWidenSC:
96 case VPWidenSelectSC: {
97 const Instruction *I =
98 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
99 (void)I;
100 assert((!I || !I->mayWriteToMemory()) &&
101 "underlying instruction may write to memory");
102 return false;
103 }
104 default:
105 return true;
106 }
107}
108
110 switch (getVPDefID()) {
111 case VPExpressionSC:
112 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
113 case VPInstructionSC:
114 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
115 case VPWidenLoadEVLSC:
116 case VPWidenLoadSC:
117 return true;
118 case VPReplicateSC:
119 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
120 ->mayReadFromMemory();
121 case VPWidenCallSC:
122 return !cast<VPWidenCallRecipe>(this)
123 ->getCalledScalarFunction()
124 ->onlyWritesMemory();
125 case VPWidenIntrinsicSC:
126 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
127 case VPBranchOnMaskSC:
128 case VPDerivedIVSC:
129 case VPFirstOrderRecurrencePHISC:
130 case VPPredInstPHISC:
131 case VPScalarIVStepsSC:
132 case VPWidenStoreEVLSC:
133 case VPWidenStoreSC:
134 return false;
135 case VPBlendSC:
136 case VPReductionEVLSC:
137 case VPReductionSC:
138 case VPVectorPointerSC:
139 case VPWidenCanonicalIVSC:
140 case VPWidenCastSC:
141 case VPWidenGEPSC:
142 case VPWidenIntOrFpInductionSC:
143 case VPWidenPHISC:
144 case VPWidenPointerInductionSC:
145 case VPWidenSC:
146 case VPWidenSelectSC: {
147 const Instruction *I =
148 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
149 (void)I;
150 assert((!I || !I->mayReadFromMemory()) &&
151 "underlying instruction may read from memory");
152 return false;
153 }
154 default:
155 // FIXME: Return false if the recipe represents an interleaved store.
156 return true;
157 }
158}
159
161 switch (getVPDefID()) {
162 case VPExpressionSC:
163 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
164 case VPDerivedIVSC:
165 case VPFirstOrderRecurrencePHISC:
166 case VPPredInstPHISC:
167 case VPVectorEndPointerSC:
168 return false;
169 case VPInstructionSC: {
170 auto *VPI = cast<VPInstruction>(this);
171 return mayWriteToMemory() ||
172 VPI->getOpcode() == VPInstruction::BranchOnCount ||
173 VPI->getOpcode() == VPInstruction::BranchOnCond;
174 }
175 case VPWidenCallSC: {
176 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
177 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
178 }
179 case VPWidenIntrinsicSC:
180 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
181 case VPBlendSC:
182 case VPReductionEVLSC:
183 case VPReductionSC:
184 case VPScalarIVStepsSC:
185 case VPVectorPointerSC:
186 case VPWidenCanonicalIVSC:
187 case VPWidenCastSC:
188 case VPWidenGEPSC:
189 case VPWidenIntOrFpInductionSC:
190 case VPWidenPHISC:
191 case VPWidenPointerInductionSC:
192 case VPWidenSC:
193 case VPWidenSelectSC: {
194 const Instruction *I =
195 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
196 (void)I;
197 assert((!I || !I->mayHaveSideEffects()) &&
198 "underlying instruction has side-effects");
199 return false;
200 }
201 case VPInterleaveEVLSC:
202 case VPInterleaveSC:
203 return mayWriteToMemory();
204 case VPWidenLoadEVLSC:
205 case VPWidenLoadSC:
206 case VPWidenStoreEVLSC:
207 case VPWidenStoreSC:
208 assert(
209 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
211 "mayHaveSideffects result for ingredient differs from this "
212 "implementation");
213 return mayWriteToMemory();
214 case VPReplicateSC: {
215 auto *R = cast<VPReplicateRecipe>(this);
216 return R->getUnderlyingInstr()->mayHaveSideEffects();
217 }
218 default:
219 return true;
220 }
221}
222
224 assert(!Parent && "Recipe already in some VPBasicBlock");
225 assert(InsertPos->getParent() &&
226 "Insertion position not in any VPBasicBlock");
227 InsertPos->getParent()->insert(this, InsertPos->getIterator());
228}
229
230void VPRecipeBase::insertBefore(VPBasicBlock &BB,
232 assert(!Parent && "Recipe already in some VPBasicBlock");
233 assert(I == BB.end() || I->getParent() == &BB);
234 BB.insert(this, I);
235}
236
238 assert(!Parent && "Recipe already in some VPBasicBlock");
239 assert(InsertPos->getParent() &&
240 "Insertion position not in any VPBasicBlock");
241 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
242}
243
245 assert(getParent() && "Recipe not in any VPBasicBlock");
247 Parent = nullptr;
248}
249
251 assert(getParent() && "Recipe not in any VPBasicBlock");
253}
254
257 insertAfter(InsertPos);
258}
259
265
267 // Get the underlying instruction for the recipe, if there is one. It is used
268 // to
269 // * decide if cost computation should be skipped for this recipe,
270 // * apply forced target instruction cost.
271 Instruction *UI = nullptr;
272 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
273 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
274 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
275 UI = IG->getInsertPos();
276 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
277 UI = &WidenMem->getIngredient();
278
279 InstructionCost RecipeCost;
280 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
281 RecipeCost = 0;
282 } else {
283 RecipeCost = computeCost(VF, Ctx);
284 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
285 RecipeCost.isValid()) {
286 if (UI)
288 else
289 RecipeCost = InstructionCost(0);
290 }
291 }
292
293 LLVM_DEBUG({
294 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
295 dump();
296 });
297 return RecipeCost;
298}
299
301 VPCostContext &Ctx) const {
302 llvm_unreachable("subclasses should implement computeCost");
303}
304
306 return (getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC) ||
308}
309
311 auto *VPI = dyn_cast<VPInstruction>(this);
312 return VPI && Instruction::isCast(VPI->getOpcode());
313}
314
316 assert(OpType == Other.OpType && "OpType must match");
317 switch (OpType) {
318 case OperationType::OverflowingBinOp:
319 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
320 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
321 break;
322 case OperationType::Trunc:
323 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
324 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
325 break;
326 case OperationType::DisjointOp:
327 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
328 break;
329 case OperationType::PossiblyExactOp:
330 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
331 break;
332 case OperationType::GEPOp:
333 GEPFlags &= Other.GEPFlags;
334 break;
335 case OperationType::FPMathOp:
336 case OperationType::FCmp:
337 assert((OpType != OperationType::FCmp ||
338 FCmpFlags.Pred == Other.FCmpFlags.Pred) &&
339 "Cannot drop CmpPredicate");
340 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
341 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
342 break;
343 case OperationType::NonNegOp:
344 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
345 break;
346 case OperationType::Cmp:
347 assert(CmpPredicate == Other.CmpPredicate && "Cannot drop CmpPredicate");
348 break;
349 case OperationType::Other:
350 assert(AllFlags == Other.AllFlags && "Cannot drop other flags");
351 break;
352 }
353}
354
356 assert((OpType == OperationType::FPMathOp || OpType == OperationType::FCmp) &&
357 "recipe doesn't have fast math flags");
358 const FastMathFlagsTy &F = getFMFsRef();
359 FastMathFlags Res;
360 Res.setAllowReassoc(F.AllowReassoc);
361 Res.setNoNaNs(F.NoNaNs);
362 Res.setNoInfs(F.NoInfs);
363 Res.setNoSignedZeros(F.NoSignedZeros);
364 Res.setAllowReciprocal(F.AllowReciprocal);
365 Res.setAllowContract(F.AllowContract);
366 Res.setApproxFunc(F.ApproxFunc);
367 return Res;
368}
369
370#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
372
373void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
374 VPSlotTracker &SlotTracker) const {
375 printRecipe(O, Indent, SlotTracker);
376 if (auto DL = getDebugLoc()) {
377 O << ", !dbg ";
378 DL.print(O);
379 }
380
381 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
383}
384#endif
385
386template <unsigned PartOpIdx>
387VPValue *
389 if (U.getNumOperands() == PartOpIdx + 1)
390 return U.getOperand(PartOpIdx);
391 return nullptr;
392}
393
394template <unsigned PartOpIdx>
396 if (auto *UnrollPartOp = getUnrollPartOperand(U))
397 return cast<ConstantInt>(UnrollPartOp->getLiveInIRValue())->getZExtValue();
398 return 0;
399}
400
401namespace llvm {
402template class VPUnrollPartAccessor<1>;
403template class VPUnrollPartAccessor<2>;
404template class VPUnrollPartAccessor<3>;
405}
406
408 const VPIRFlags &Flags, const VPIRMetadata &MD,
409 DebugLoc DL, const Twine &Name)
410 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, Flags, DL),
411 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
413 "Set flags not supported for the provided opcode");
414 assert((getNumOperandsForOpcode(Opcode) == -1u ||
415 getNumOperandsForOpcode(Opcode) == getNumOperands()) &&
416 "number of operands does not match opcode");
417}
418
419#ifndef NDEBUG
420unsigned VPInstruction::getNumOperandsForOpcode(unsigned Opcode) {
421 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
422 return 1;
423
424 if (Instruction::isBinaryOp(Opcode))
425 return 2;
426
427 switch (Opcode) {
430 return 0;
431 case Instruction::Alloca:
432 case Instruction::ExtractValue:
433 case Instruction::Freeze:
434 case Instruction::Load:
449 return 1;
450 case Instruction::ICmp:
451 case Instruction::FCmp:
452 case Instruction::ExtractElement:
453 case Instruction::Store:
462 return 2;
463 case Instruction::Select:
467 return 3;
469 return 4;
470 case Instruction::Call:
471 case Instruction::GetElementPtr:
472 case Instruction::PHI:
473 case Instruction::Switch:
479 // Cannot determine the number of operands from the opcode.
480 return -1u;
481 }
482 llvm_unreachable("all cases should be handled above");
483}
484#endif
485
489
490bool VPInstruction::canGenerateScalarForFirstLane() const {
492 return true;
494 return true;
495 switch (Opcode) {
496 case Instruction::Freeze:
497 case Instruction::ICmp:
498 case Instruction::PHI:
499 case Instruction::Select:
508 return true;
509 default:
510 return false;
511 }
512}
513
514Value *VPInstruction::generate(VPTransformState &State) {
515 IRBuilderBase &Builder = State.Builder;
516
518 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
519 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
520 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
521 auto *Res =
522 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
523 if (auto *I = dyn_cast<Instruction>(Res))
524 applyFlags(*I);
525 return Res;
526 }
527
528 switch (getOpcode()) {
529 case VPInstruction::Not: {
530 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
531 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
532 return Builder.CreateNot(A, Name);
533 }
534 case Instruction::ExtractElement: {
535 assert(State.VF.isVector() && "Only extract elements from vectors");
536 if (getOperand(1)->isLiveIn()) {
537 unsigned IdxToExtract =
538 cast<ConstantInt>(getOperand(1)->getLiveInIRValue())->getZExtValue();
539 return State.get(getOperand(0), VPLane(IdxToExtract));
540 }
541 Value *Vec = State.get(getOperand(0));
542 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
543 return Builder.CreateExtractElement(Vec, Idx, Name);
544 }
545 case Instruction::Freeze: {
547 return Builder.CreateFreeze(Op, Name);
548 }
549 case Instruction::FCmp:
550 case Instruction::ICmp: {
551 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
552 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
553 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
554 return Builder.CreateCmp(getPredicate(), A, B, Name);
555 }
556 case Instruction::PHI: {
557 llvm_unreachable("should be handled by VPPhi::execute");
558 }
559 case Instruction::Select: {
560 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
561 Value *Cond =
562 State.get(getOperand(0),
563 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
564 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
565 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
566 return Builder.CreateSelect(Cond, Op1, Op2, Name);
567 }
569 // Get first lane of vector induction variable.
570 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
571 // Get the original loop tripcount.
572 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
573
574 // If this part of the active lane mask is scalar, generate the CMP directly
575 // to avoid unnecessary extracts.
576 if (State.VF.isScalar())
577 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
578 Name);
579
580 ElementCount EC = State.VF.multiplyCoefficientBy(
581 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue());
582 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
583 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
584 {PredTy, ScalarTC->getType()},
585 {VIVElem0, ScalarTC}, nullptr, Name);
586 }
588 // Generate code to combine the previous and current values in vector v3.
589 //
590 // vector.ph:
591 // v_init = vector(..., ..., ..., a[-1])
592 // br vector.body
593 //
594 // vector.body
595 // i = phi [0, vector.ph], [i+4, vector.body]
596 // v1 = phi [v_init, vector.ph], [v2, vector.body]
597 // v2 = a[i, i+1, i+2, i+3];
598 // v3 = vector(v1(3), v2(0, 1, 2))
599
600 auto *V1 = State.get(getOperand(0));
601 if (!V1->getType()->isVectorTy())
602 return V1;
603 Value *V2 = State.get(getOperand(1));
604 return Builder.CreateVectorSplice(V1, V2, -1, Name);
605 }
607 unsigned UF = getParent()->getPlan()->getUF();
608 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
609 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
610 Value *Sub = Builder.CreateSub(ScalarTC, Step);
611 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
613 return Builder.CreateSelect(Cmp, Sub, Zero);
614 }
616 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
617 // be outside of the main loop.
618 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
619 // Compute EVL
620 assert(AVL->getType()->isIntegerTy() &&
621 "Requested vector length should be an integer.");
622
623 assert(State.VF.isScalable() && "Expected scalable vector factor.");
624 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
625
626 Value *EVL = Builder.CreateIntrinsic(
627 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
628 {AVL, VFArg, Builder.getTrue()});
629 return EVL;
630 }
632 unsigned Part = getUnrollPart(*this);
633 auto *IV = State.get(getOperand(0), VPLane(0));
634 assert(Part != 0 && "Must have a positive part");
635 // The canonical IV is incremented by the vectorization factor (num of
636 // SIMD elements) times the unroll part.
637 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
638 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
640 }
642 Value *Cond = State.get(getOperand(0), VPLane(0));
643 // Replace the temporary unreachable terminator with a new conditional
644 // branch, hooking it up to backward destination for latch blocks now, and
645 // to forward destination(s) later when they are created.
646 // Second successor may be backwards - iff it is already in VPBB2IRBB.
647 VPBasicBlock *SecondVPSucc =
648 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
649 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
650 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
651 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
652 // First successor is always forward, reset it to nullptr.
653 Br->setSuccessor(0, nullptr);
655 applyMetadata(*Br);
656 return Br;
657 }
659 return Builder.CreateVectorSplat(
660 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
661 }
663 // For struct types, we need to build a new 'wide' struct type, where each
664 // element is widened, i.e., we create a struct of vectors.
665 auto *StructTy =
667 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
668 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
669 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
670 FieldIndex++) {
671 Value *ScalarValue =
672 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
673 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
674 VectorValue =
675 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
676 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
677 }
678 }
679 return Res;
680 }
682 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
683 auto NumOfElements = ElementCount::getFixed(getNumOperands());
684 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
685 for (const auto &[Idx, Op] : enumerate(operands()))
686 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
687 Builder.getInt32(Idx));
688 return Res;
689 }
691 if (State.VF.isScalar())
692 return State.get(getOperand(0), true);
693 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
695 // If this start vector is scaled then it should produce a vector with fewer
696 // elements than the VF.
697 ElementCount VF = State.VF.divideCoefficientBy(
698 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue());
699 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
700 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
701 Builder.getInt32(0));
702 }
704 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
705 // and will be removed by breaking up the recipe further.
706 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
707 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
708 Value *ReducedPartRdx = State.get(getOperand(2));
709 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
710 ReducedPartRdx =
711 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
712 ReducedPartRdx, "bin.rdx");
713 return createAnyOfReduction(Builder, ReducedPartRdx,
714 State.get(getOperand(1), VPLane(0)), OrigPhi);
715 }
717 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
718 // and will be removed by breaking up the recipe further.
719 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
720 // Get its reduction variable descriptor.
721 RecurKind RK = PhiR->getRecurrenceKind();
723 "Unexpected reduction kind");
724 assert(!PhiR->isInLoop() &&
725 "In-loop FindLastIV reduction is not supported yet");
726
727 // The recipe's operands are the reduction phi, the start value, the
728 // sentinel value, followed by one operand for each part of the reduction.
729 unsigned UF = getNumOperands() - 3;
730 Value *ReducedPartRdx = State.get(getOperand(3));
731 RecurKind MinMaxKind;
734 MinMaxKind = IsSigned ? RecurKind::SMax : RecurKind::UMax;
735 else
736 MinMaxKind = IsSigned ? RecurKind::SMin : RecurKind::UMin;
737 for (unsigned Part = 1; Part < UF; ++Part)
738 ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
739 State.get(getOperand(3 + Part)));
740
741 Value *Start = State.get(getOperand(1), true);
743 return createFindLastIVReduction(Builder, ReducedPartRdx, RK, Start,
744 Sentinel);
745 }
747 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
748 // and will be removed by breaking up the recipe further.
749 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
750 // Get its reduction variable descriptor.
751
752 RecurKind RK = PhiR->getRecurrenceKind();
754 "should be handled by ComputeFindIVResult");
755
756 // The recipe's operands are the reduction phi, followed by one operand for
757 // each part of the reduction.
758 unsigned UF = getNumOperands() - 1;
759 VectorParts RdxParts(UF);
760 for (unsigned Part = 0; Part < UF; ++Part)
761 RdxParts[Part] = State.get(getOperand(1 + Part), PhiR->isInLoop());
762
763 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
764 if (hasFastMathFlags())
766
767 // Reduce all of the unrolled parts into a single vector.
768 Value *ReducedPartRdx = RdxParts[0];
769 if (PhiR->isOrdered()) {
770 ReducedPartRdx = RdxParts[UF - 1];
771 } else {
772 // Floating-point operations should have some FMF to enable the reduction.
773 for (unsigned Part = 1; Part < UF; ++Part) {
774 Value *RdxPart = RdxParts[Part];
776 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
777 else {
778 // For sub-recurrences, each UF's reduction variable is already
779 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
781 RK == RecurKind::Sub
782 ? Instruction::Add
784 ReducedPartRdx =
785 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
786 }
787 }
788 }
789
790 // Create the reduction after the loop. Note that inloop reductions create
791 // the target reduction in the loop using a Reduction recipe.
792 if (State.VF.isVector() && !PhiR->isInLoop()) {
793 // TODO: Support in-order reductions based on the recurrence descriptor.
794 // All ops in the reduction inherit fast-math-flags from the recurrence
795 // descriptor.
796 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
797 }
798
799 return ReducedPartRdx;
800 }
803 unsigned Offset =
805 Value *Res;
806 if (State.VF.isVector()) {
807 assert(Offset <= State.VF.getKnownMinValue() &&
808 "invalid offset to extract from");
809 // Extract lane VF - Offset from the operand.
810 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
811 } else {
812 // TODO: Remove ExtractLastLane for scalar VFs.
813 assert(Offset <= 1 && "invalid offset to extract from");
814 Res = State.get(getOperand(0));
815 }
817 Res->setName(Name);
818 return Res;
819 }
821 Value *A = State.get(getOperand(0));
822 Value *B = State.get(getOperand(1));
823 return Builder.CreateLogicalAnd(A, B, Name);
824 }
827 "can only generate first lane for PtrAdd");
828 Value *Ptr = State.get(getOperand(0), VPLane(0));
829 Value *Addend = State.get(getOperand(1), VPLane(0));
830 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
831 }
833 Value *Ptr =
835 Value *Addend = State.get(getOperand(1));
836 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
837 }
839 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
840 for (VPValue *Op : drop_begin(operands()))
841 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
842 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
843 }
845 Value *LaneToExtract = State.get(getOperand(0), true);
846 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
847 Value *Res = nullptr;
848 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
849
850 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
851 Value *VectorStart =
852 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
853 Value *VectorIdx = Idx == 1
854 ? LaneToExtract
855 : Builder.CreateSub(LaneToExtract, VectorStart);
856 Value *Ext = State.VF.isScalar()
857 ? State.get(getOperand(Idx))
858 : Builder.CreateExtractElement(
859 State.get(getOperand(Idx)), VectorIdx);
860 if (Res) {
861 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
862 Res = Builder.CreateSelect(Cmp, Ext, Res);
863 } else {
864 Res = Ext;
865 }
866 }
867 return Res;
868 }
870 if (getNumOperands() == 1) {
871 Value *Mask = State.get(getOperand(0));
872 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
873 /*ZeroIsPoison=*/false, Name);
874 }
875 // If there are multiple operands, create a chain of selects to pick the
876 // first operand with an active lane and add the number of lanes of the
877 // preceding operands.
878 Value *RuntimeVF = getRuntimeVF(Builder, Builder.getInt64Ty(), State.VF);
879 unsigned LastOpIdx = getNumOperands() - 1;
880 Value *Res = nullptr;
881 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
882 Value *TrailingZeros =
883 State.VF.isScalar()
884 ? Builder.CreateZExt(
885 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
886 Builder.getFalse()),
887 Builder.getInt64Ty())
889 Builder.getInt64Ty(), State.get(getOperand(Idx)),
890 /*ZeroIsPoison=*/false, Name);
891 Value *Current = Builder.CreateAdd(
892 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
893 if (Res) {
894 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
895 Res = Builder.CreateSelect(Cmp, Current, Res);
896 } else {
897 Res = Current;
898 }
899 }
900
901 return Res;
902 }
904 return State.get(getOperand(0), true);
906 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
907 default:
908 llvm_unreachable("Unsupported opcode for instruction");
909 }
910}
911
913 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
914 Type *ScalarTy = Ctx.Types.inferScalarType(this);
915 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
916 switch (Opcode) {
917 case Instruction::FNeg:
918 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
919 case Instruction::UDiv:
920 case Instruction::SDiv:
921 case Instruction::SRem:
922 case Instruction::URem:
923 case Instruction::Add:
924 case Instruction::FAdd:
925 case Instruction::Sub:
926 case Instruction::FSub:
927 case Instruction::Mul:
928 case Instruction::FMul:
929 case Instruction::FDiv:
930 case Instruction::FRem:
931 case Instruction::Shl:
932 case Instruction::LShr:
933 case Instruction::AShr:
934 case Instruction::And:
935 case Instruction::Or:
936 case Instruction::Xor: {
939
940 if (VF.isVector()) {
941 // Certain instructions can be cheaper to vectorize if they have a
942 // constant second vector operand. One example of this are shifts on x86.
943 VPValue *RHS = getOperand(1);
944 RHSInfo = Ctx.getOperandInfo(RHS);
945
946 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
949 }
950
953 if (CtxI)
954 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
955 return Ctx.TTI.getArithmeticInstrCost(
956 Opcode, ResultTy, Ctx.CostKind,
957 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
958 RHSInfo, Operands, CtxI, &Ctx.TLI);
959 }
960 case Instruction::Freeze:
961 // This opcode is unknown. Assume that it is the same as 'mul'.
962 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
963 Ctx.CostKind);
964 case Instruction::ExtractValue:
965 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
966 Ctx.CostKind);
967 case Instruction::ICmp:
968 case Instruction::FCmp: {
969 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
970 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
972 return Ctx.TTI.getCmpSelInstrCost(
973 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
974 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
975 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
976 }
978 llvm_unreachable("called for unsupported opcode");
979}
980
982 VPCostContext &Ctx) const {
984 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
985 // TODO: Compute cost for VPInstructions without underlying values once
986 // the legacy cost model has been retired.
987 return 0;
988 }
989
991 "Should only generate a vector value or single scalar, not scalars "
992 "for all lanes.");
994 getOpcode(),
996 }
997
998 switch (getOpcode()) {
999 case Instruction::Select: {
1001 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1002 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1003 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1004 if (!vputils::onlyFirstLaneUsed(this)) {
1005 CondTy = toVectorTy(CondTy, VF);
1006 VecTy = toVectorTy(VecTy, VF);
1007 }
1008 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1009 Ctx.CostKind);
1010 }
1011 case Instruction::ExtractElement:
1013 if (VF.isScalar()) {
1014 // ExtractLane with VF=1 takes care of handling extracting across multiple
1015 // parts.
1016 return 0;
1017 }
1018
1019 // Add on the cost of extracting the element.
1020 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1021 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1022 Ctx.CostKind);
1023 }
1024 case VPInstruction::AnyOf: {
1025 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1026 return Ctx.TTI.getArithmeticReductionCost(
1027 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1028 }
1030 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1031 if (VF.isScalar())
1032 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1034 CmpInst::ICMP_EQ, Ctx.CostKind);
1035 // Calculate the cost of determining the lane index.
1036 auto *PredTy = toVectorTy(ScalarTy, VF);
1037 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1038 Type::getInt64Ty(Ctx.LLVMCtx),
1039 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1040 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1041 }
1043 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1044 if (VF.isScalar())
1045 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1047 CmpInst::ICMP_EQ, Ctx.CostKind);
1048 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1049 auto *PredTy = toVectorTy(ScalarTy, VF);
1050 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1051 Type::getInt64Ty(Ctx.LLVMCtx),
1052 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1053 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1054 // Add cost of NOT operation on the predicate.
1055 Cost += Ctx.TTI.getArithmeticInstrCost(
1056 Instruction::Xor, PredTy, Ctx.CostKind,
1057 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1058 {TargetTransformInfo::OK_UniformConstantValue,
1059 TargetTransformInfo::OP_None});
1060 // Add cost of SUB operation on the index.
1061 Cost += Ctx.TTI.getArithmeticInstrCost(
1062 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1063 return Cost;
1064 }
1066 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1068 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1069 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1070
1071 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1072 cast<VectorType>(VectorTy),
1073 cast<VectorType>(VectorTy), Mask,
1074 Ctx.CostKind, VF.getKnownMinValue() - 1);
1075 }
1077 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1078 unsigned Multiplier =
1079 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue();
1080 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1081 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1082 {ArgTy, ArgTy});
1083 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1084 }
1086 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1087 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1088 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1089 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1090 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1091 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1092 }
1094 assert(VF.isVector() && "Reverse operation must be vector type");
1095 auto *VectorTy = cast<VectorType>(
1096 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
1097 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1098 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1099 /*Index=*/0);
1100 }
1102 // Add on the cost of extracting the element.
1103 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1104 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1105 VecTy, Ctx.CostKind, 0);
1106 }
1108 if (VF == ElementCount::getScalable(1))
1110 [[fallthrough]];
1111 default:
1112 // TODO: Compute cost other VPInstructions once the legacy cost model has
1113 // been retired.
1115 "unexpected VPInstruction witht underlying value");
1116 return 0;
1117 }
1118}
1119
1132
1134 switch (getOpcode()) {
1135 case Instruction::PHI:
1139 return true;
1140 default:
1141 return isScalarCast();
1142 }
1143}
1144
1146 assert(!State.Lane && "VPInstruction executing an Lane");
1147 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1149 "Set flags not supported for the provided opcode");
1150 if (hasFastMathFlags())
1151 State.Builder.setFastMathFlags(getFastMathFlags());
1152 Value *GeneratedValue = generate(State);
1153 if (!hasResult())
1154 return;
1155 assert(GeneratedValue && "generate must produce a value");
1156 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1159 assert((((GeneratedValue->getType()->isVectorTy() ||
1160 GeneratedValue->getType()->isStructTy()) ==
1161 !GeneratesPerFirstLaneOnly) ||
1162 State.VF.isScalar()) &&
1163 "scalar value but not only first lane defined");
1164 State.set(this, GeneratedValue,
1165 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1166}
1167
1170 return false;
1171 switch (getOpcode()) {
1172 case Instruction::GetElementPtr:
1173 case Instruction::ExtractElement:
1174 case Instruction::Freeze:
1175 case Instruction::FCmp:
1176 case Instruction::ICmp:
1177 case Instruction::Select:
1178 case Instruction::PHI:
1197 case VPInstruction::Not:
1206 return false;
1207 default:
1208 return true;
1209 }
1210}
1211
1213 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1215 return vputils::onlyFirstLaneUsed(this);
1216
1217 switch (getOpcode()) {
1218 default:
1219 return false;
1220 case Instruction::ExtractElement:
1221 return Op == getOperand(1);
1222 case Instruction::PHI:
1223 return true;
1224 case Instruction::FCmp:
1225 case Instruction::ICmp:
1226 case Instruction::Select:
1227 case Instruction::Or:
1228 case Instruction::Freeze:
1229 case VPInstruction::Not:
1230 // TODO: Cover additional opcodes.
1231 return vputils::onlyFirstLaneUsed(this);
1240 return true;
1243 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1244 // operand, after replicating its operands only the first lane is used.
1245 // Before replicating, it will have only a single operand.
1246 return getNumOperands() > 1;
1248 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1250 // WidePtrAdd supports scalar and vector base addresses.
1251 return false;
1254 return Op == getOperand(1);
1256 return Op == getOperand(0);
1257 };
1258 llvm_unreachable("switch should return");
1259}
1260
1262 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1264 return vputils::onlyFirstPartUsed(this);
1265
1266 switch (getOpcode()) {
1267 default:
1268 return false;
1269 case Instruction::FCmp:
1270 case Instruction::ICmp:
1271 case Instruction::Select:
1272 return vputils::onlyFirstPartUsed(this);
1276 return true;
1277 };
1278 llvm_unreachable("switch should return");
1279}
1280
1281#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1283 VPSlotTracker SlotTracker(getParent()->getPlan());
1285}
1286
1288 VPSlotTracker &SlotTracker) const {
1289 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1290
1291 if (hasResult()) {
1293 O << " = ";
1294 }
1295
1296 switch (getOpcode()) {
1297 case VPInstruction::Not:
1298 O << "not";
1299 break;
1301 O << "combined load";
1302 break;
1304 O << "combined store";
1305 break;
1307 O << "active lane mask";
1308 break;
1310 O << "EXPLICIT-VECTOR-LENGTH";
1311 break;
1313 O << "first-order splice";
1314 break;
1316 O << "branch-on-cond";
1317 break;
1319 O << "TC > VF ? TC - VF : 0";
1320 break;
1322 O << "VF * Part +";
1323 break;
1325 O << "branch-on-count";
1326 break;
1328 O << "broadcast";
1329 break;
1331 O << "buildstructvector";
1332 break;
1334 O << "buildvector";
1335 break;
1337 O << "extract-lane";
1338 break;
1340 O << "extract-last-lane";
1341 break;
1343 O << "extract-last-part";
1344 break;
1346 O << "extract-penultimate-element";
1347 break;
1349 O << "compute-anyof-result";
1350 break;
1352 O << "compute-find-iv-result";
1353 break;
1355 O << "compute-reduction-result";
1356 break;
1358 O << "logical-and";
1359 break;
1361 O << "ptradd";
1362 break;
1364 O << "wide-ptradd";
1365 break;
1367 O << "any-of";
1368 break;
1370 O << "first-active-lane";
1371 break;
1373 O << "last-active-lane";
1374 break;
1376 O << "reduction-start-vector";
1377 break;
1379 O << "resume-for-epilogue";
1380 break;
1382 O << "reverse";
1383 break;
1385 O << "unpack";
1386 break;
1387 default:
1389 }
1390
1391 printFlags(O);
1393}
1394#endif
1395
1397 State.setDebugLocFrom(getDebugLoc());
1398 if (isScalarCast()) {
1399 Value *Op = State.get(getOperand(0), VPLane(0));
1400 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1401 Op, ResultTy);
1402 State.set(this, Cast, VPLane(0));
1403 return;
1404 }
1405 switch (getOpcode()) {
1407 Value *StepVector =
1408 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1409 State.set(this, StepVector);
1410 break;
1411 }
1412 case VPInstruction::VScale: {
1413 Value *VScale = State.Builder.CreateVScale(ResultTy);
1414 State.set(this, VScale, true);
1415 break;
1416 }
1417
1418 default:
1419 llvm_unreachable("opcode not implemented yet");
1420 }
1421}
1422
1423#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1425 VPSlotTracker &SlotTracker) const {
1426 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1428 O << " = ";
1429
1430 switch (getOpcode()) {
1432 O << "wide-iv-step ";
1434 break;
1436 O << "step-vector " << *ResultTy;
1437 break;
1439 O << "vscale " << *ResultTy;
1440 break;
1441 default:
1442 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1445 O << " to " << *ResultTy;
1446 }
1447}
1448#endif
1449
1451 State.setDebugLocFrom(getDebugLoc());
1452 PHINode *NewPhi = State.Builder.CreatePHI(
1453 State.TypeAnalysis.inferScalarType(this), 2, getName());
1454 unsigned NumIncoming = getNumIncoming();
1455 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1456 // TODO: Fixup all incoming values of header phis once recipes defining them
1457 // are introduced.
1458 NumIncoming = 1;
1459 }
1460 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1461 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1462 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1463 NewPhi->addIncoming(IncV, PredBB);
1464 }
1465 State.set(this, NewPhi, VPLane(0));
1466}
1467
1468#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1469void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1470 VPSlotTracker &SlotTracker) const {
1471 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1473 O << " = phi ";
1475}
1476#endif
1477
1478VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1479 if (auto *Phi = dyn_cast<PHINode>(&I))
1480 return new VPIRPhi(*Phi);
1481 return new VPIRInstruction(I);
1482}
1483
1485 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1486 "PHINodes must be handled by VPIRPhi");
1487 // Advance the insert point after the wrapped IR instruction. This allows
1488 // interleaving VPIRInstructions and other recipes.
1489 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1490}
1491
1493 VPCostContext &Ctx) const {
1494 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1495 // hence it does not contribute to the cost-modeling for the VPlan.
1496 return 0;
1497}
1498
1500 VPBuilder &Builder) {
1502 "can only update exiting operands to phi nodes");
1503 assert(getNumOperands() > 0 && "must have at least one operand");
1504 VPValue *Exiting = getOperand(0);
1505 if (Exiting->isLiveIn())
1506 return;
1507
1508 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastPart, Exiting);
1509 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastLane, Exiting);
1510 setOperand(0, Exiting);
1511}
1512
1513#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1515 VPSlotTracker &SlotTracker) const {
1516 O << Indent << "IR " << I;
1517}
1518#endif
1519
1521 PHINode *Phi = &getIRPhi();
1522 for (const auto &[Idx, Op] : enumerate(operands())) {
1523 VPValue *ExitValue = Op;
1524 auto Lane = vputils::isSingleScalar(ExitValue)
1526 : VPLane::getLastLaneForVF(State.VF);
1527 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1528 auto *PredVPBB = Pred->getExitingBasicBlock();
1529 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1530 // Set insertion point in PredBB in case an extract needs to be generated.
1531 // TODO: Model extracts explicitly.
1532 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
1533 Value *V = State.get(ExitValue, VPLane(Lane));
1534 // If there is no existing block for PredBB in the phi, add a new incoming
1535 // value. Otherwise update the existing incoming value for PredBB.
1536 if (Phi->getBasicBlockIndex(PredBB) == -1)
1537 Phi->addIncoming(V, PredBB);
1538 else
1539 Phi->setIncomingValueForBlock(PredBB, V);
1540 }
1541
1542 // Advance the insert point after the wrapped IR instruction. This allows
1543 // interleaving VPIRInstructions and other recipes.
1544 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1545}
1546
1548 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1549 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1550 "Number of phi operands must match number of predecessors");
1551 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1552 R->removeOperand(Position);
1553}
1554
1555#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1557 VPSlotTracker &SlotTracker) const {
1558 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1559 [this, &O, &SlotTracker](auto Op) {
1560 O << "[ ";
1561 Op.value()->printAsOperand(O, SlotTracker);
1562 O << ", ";
1563 getIncomingBlock(Op.index())->printAsOperand(O);
1564 O << " ]";
1565 });
1566}
1567#endif
1568
1569#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1571 VPSlotTracker &SlotTracker) const {
1573
1574 if (getNumOperands() != 0) {
1575 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1577 [&O, &SlotTracker](auto Op) {
1578 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1579 O << " from ";
1580 std::get<1>(Op)->printAsOperand(O);
1581 });
1582 O << ")";
1583 }
1584}
1585#endif
1586
1588 for (const auto &[Kind, Node] : Metadata)
1589 I.setMetadata(Kind, Node);
1590}
1591
1593 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1594 for (const auto &[KindA, MDA] : Metadata) {
1595 for (const auto &[KindB, MDB] : Other.Metadata) {
1596 if (KindA == KindB && MDA == MDB) {
1597 MetadataIntersection.emplace_back(KindA, MDA);
1598 break;
1599 }
1600 }
1601 }
1602 Metadata = std::move(MetadataIntersection);
1603}
1604
1605#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1607 const Module *M = SlotTracker.getModule();
1608 if (Metadata.empty() || !M)
1609 return;
1610
1611 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
1612 O << " (";
1613 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
1614 auto [Kind, Node] = KindNodePair;
1615 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
1616 "Unexpected unnamed metadata kind");
1617 O << "!" << MDNames[Kind] << " ";
1618 Node->printAsOperand(O, M);
1619 });
1620 O << ")";
1621}
1622#endif
1623
1625 assert(State.VF.isVector() && "not widening");
1626 assert(Variant != nullptr && "Can't create vector function.");
1627
1628 FunctionType *VFTy = Variant->getFunctionType();
1629 // Add return type if intrinsic is overloaded on it.
1631 for (const auto &I : enumerate(args())) {
1632 Value *Arg;
1633 // Some vectorized function variants may also take a scalar argument,
1634 // e.g. linear parameters for pointers. This needs to be the scalar value
1635 // from the start of the respective part when interleaving.
1636 if (!VFTy->getParamType(I.index())->isVectorTy())
1637 Arg = State.get(I.value(), VPLane(0));
1638 else
1639 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1640 Args.push_back(Arg);
1641 }
1642
1645 if (CI)
1646 CI->getOperandBundlesAsDefs(OpBundles);
1647
1648 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1649 applyFlags(*V);
1650 applyMetadata(*V);
1651 V->setCallingConv(Variant->getCallingConv());
1652
1653 if (!V->getType()->isVoidTy())
1654 State.set(this, V);
1655}
1656
1658 VPCostContext &Ctx) const {
1659 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1660 Variant->getFunctionType()->params(),
1661 Ctx.CostKind);
1662}
1663
1664#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1666 VPSlotTracker &SlotTracker) const {
1667 O << Indent << "WIDEN-CALL ";
1668
1669 Function *CalledFn = getCalledScalarFunction();
1670 if (CalledFn->getReturnType()->isVoidTy())
1671 O << "void ";
1672 else {
1674 O << " = ";
1675 }
1676
1677 O << "call";
1678 printFlags(O);
1679 O << " @" << CalledFn->getName() << "(";
1680 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1681 Op->printAsOperand(O, SlotTracker);
1682 });
1683 O << ")";
1684
1685 O << " (using library function";
1686 if (Variant->hasName())
1687 O << ": " << Variant->getName();
1688 O << ")";
1689}
1690#endif
1691
1693 assert(State.VF.isVector() && "not widening");
1694
1695 SmallVector<Type *, 2> TysForDecl;
1696 // Add return type if intrinsic is overloaded on it.
1697 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1, State.TTI))
1698 TysForDecl.push_back(VectorType::get(getResultType(), State.VF));
1700 for (const auto &I : enumerate(operands())) {
1701 // Some intrinsics have a scalar argument - don't replace it with a
1702 // vector.
1703 Value *Arg;
1704 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1705 State.TTI))
1706 Arg = State.get(I.value(), VPLane(0));
1707 else
1708 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1709 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1710 State.TTI))
1711 TysForDecl.push_back(Arg->getType());
1712 Args.push_back(Arg);
1713 }
1714
1715 // Use vector version of the intrinsic.
1716 Module *M = State.Builder.GetInsertBlock()->getModule();
1717 Function *VectorF =
1718 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1719 assert(VectorF &&
1720 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1721
1724 if (CI)
1725 CI->getOperandBundlesAsDefs(OpBundles);
1726
1727 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1728
1729 applyFlags(*V);
1730 applyMetadata(*V);
1731
1732 if (!V->getType()->isVoidTy())
1733 State.set(this, V);
1734}
1735
1736/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1739 const VPRecipeWithIRFlags &R,
1740 ElementCount VF,
1741 VPCostContext &Ctx) {
1742 // Some backends analyze intrinsic arguments to determine cost. Use the
1743 // underlying value for the operand if it has one. Otherwise try to use the
1744 // operand of the underlying call instruction, if there is one. Otherwise
1745 // clear Arguments.
1746 // TODO: Rework TTI interface to be independent of concrete IR values.
1748 for (const auto &[Idx, Op] : enumerate(Operands)) {
1749 auto *V = Op->getUnderlyingValue();
1750 if (!V) {
1751 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1752 Arguments.push_back(UI->getArgOperand(Idx));
1753 continue;
1754 }
1755 Arguments.clear();
1756 break;
1757 }
1758 Arguments.push_back(V);
1759 }
1760
1761 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1762 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1763 SmallVector<Type *> ParamTys;
1764 for (const VPValue *Op : Operands) {
1765 ParamTys.push_back(VF.isVector()
1766 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1767 : Ctx.Types.inferScalarType(Op));
1768 }
1769
1770 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1771 FastMathFlags FMF =
1772 R.hasFastMathFlags() ? R.getFastMathFlags() : FastMathFlags();
1773 IntrinsicCostAttributes CostAttrs(
1774 ID, RetTy, Arguments, ParamTys, FMF,
1775 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1776 InstructionCost::getInvalid(), &Ctx.TLI);
1777 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1778}
1779
1781 VPCostContext &Ctx) const {
1783 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1784}
1785
1787 return Intrinsic::getBaseName(VectorIntrinsicID);
1788}
1789
1791 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1792 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1793 auto [Idx, V] = X;
1795 Idx, nullptr);
1796 });
1797}
1798
1799#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1801 VPSlotTracker &SlotTracker) const {
1802 O << Indent << "WIDEN-INTRINSIC ";
1803 if (ResultTy->isVoidTy()) {
1804 O << "void ";
1805 } else {
1807 O << " = ";
1808 }
1809
1810 O << "call";
1811 printFlags(O);
1812 O << getIntrinsicName() << "(";
1813
1815 Op->printAsOperand(O, SlotTracker);
1816 });
1817 O << ")";
1818}
1819#endif
1820
1822 IRBuilderBase &Builder = State.Builder;
1823
1824 Value *Address = State.get(getOperand(0));
1825 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
1826 VectorType *VTy = cast<VectorType>(Address->getType());
1827
1828 // The histogram intrinsic requires a mask even if the recipe doesn't;
1829 // if the mask operand was omitted then all lanes should be executed and
1830 // we just need to synthesize an all-true mask.
1831 Value *Mask = nullptr;
1832 if (VPValue *VPMask = getMask())
1833 Mask = State.get(VPMask);
1834 else
1835 Mask =
1836 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
1837
1838 // If this is a subtract, we want to invert the increment amount. We may
1839 // add a separate intrinsic in future, but for now we'll try this.
1840 if (Opcode == Instruction::Sub)
1841 IncAmt = Builder.CreateNeg(IncAmt);
1842 else
1843 assert(Opcode == Instruction::Add && "only add or sub supported for now");
1844
1845 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
1846 {VTy, IncAmt->getType()},
1847 {Address, IncAmt, Mask});
1848}
1849
1851 VPCostContext &Ctx) const {
1852 // FIXME: Take the gather and scatter into account as well. For now we're
1853 // generating the same cost as the fallback path, but we'll likely
1854 // need to create a new TTI method for determining the cost, including
1855 // whether we can use base + vec-of-smaller-indices or just
1856 // vec-of-pointers.
1857 assert(VF.isVector() && "Invalid VF for histogram cost");
1858 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
1859 VPValue *IncAmt = getOperand(1);
1860 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
1861 VectorType *VTy = VectorType::get(IncTy, VF);
1862
1863 // Assume that a non-constant update value (or a constant != 1) requires
1864 // a multiply, and add that into the cost.
1865 InstructionCost MulCost =
1866 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
1867 if (IncAmt->isLiveIn()) {
1869
1870 if (CI && CI->getZExtValue() == 1)
1871 MulCost = TTI::TCC_Free;
1872 }
1873
1874 // Find the cost of the histogram operation itself.
1875 Type *PtrTy = VectorType::get(AddressTy, VF);
1876 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1877 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
1878 Type::getVoidTy(Ctx.LLVMCtx),
1879 {PtrTy, IncTy, MaskTy});
1880
1881 // Add the costs together with the add/sub operation.
1882 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
1883 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
1884}
1885
1886#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1888 VPSlotTracker &SlotTracker) const {
1889 O << Indent << "WIDEN-HISTOGRAM buckets: ";
1891
1892 if (Opcode == Instruction::Sub)
1893 O << ", dec: ";
1894 else {
1895 assert(Opcode == Instruction::Add);
1896 O << ", inc: ";
1897 }
1899
1900 if (VPValue *Mask = getMask()) {
1901 O << ", mask: ";
1902 Mask->printAsOperand(O, SlotTracker);
1903 }
1904}
1905
1907 VPSlotTracker &SlotTracker) const {
1908 O << Indent << "WIDEN-SELECT ";
1910 O << " = select";
1911 printFlags(O);
1913 O << ", ";
1915 O << ", ";
1917 O << (vputils::isSingleScalar(getCond()) ? " (condition is single-scalar)"
1918 : "");
1919}
1920#endif
1921
1923 Value *Cond = State.get(getCond(), vputils::isSingleScalar(getCond()));
1924
1925 Value *Op0 = State.get(getOperand(1));
1926 Value *Op1 = State.get(getOperand(2));
1927 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
1928 State.set(this, Sel);
1929 if (auto *I = dyn_cast<Instruction>(Sel)) {
1931 applyFlags(*I);
1932 applyMetadata(*I);
1933 }
1934}
1935
1937 VPCostContext &Ctx) const {
1939 bool ScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1940 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1941 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1942
1943 VPValue *Op0, *Op1;
1944 if (!ScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1945 (match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1))) ||
1946 match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1))))) {
1947 // select x, y, false --> x & y
1948 // select x, true, y --> x | y
1949 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1950 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1951
1953 if (all_of(operands(),
1954 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1955 Operands.append(SI->op_begin(), SI->op_end());
1956 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1957 return Ctx.TTI.getArithmeticInstrCost(
1958 IsLogicalOr ? Instruction::Or : Instruction::And, VectorTy,
1959 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1960 }
1961
1962 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1963 if (!ScalarCond)
1964 CondTy = VectorType::get(CondTy, VF);
1965
1967 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
1968 Pred = Cmp->getPredicate();
1969 return Ctx.TTI.getCmpSelInstrCost(
1970 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1971 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1972}
1973
1974VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
1975 AllowReassoc = FMF.allowReassoc();
1976 NoNaNs = FMF.noNaNs();
1977 NoInfs = FMF.noInfs();
1978 NoSignedZeros = FMF.noSignedZeros();
1979 AllowReciprocal = FMF.allowReciprocal();
1980 AllowContract = FMF.allowContract();
1981 ApproxFunc = FMF.approxFunc();
1982}
1983
1984#if !defined(NDEBUG)
1985bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
1986 switch (OpType) {
1987 case OperationType::OverflowingBinOp:
1988 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
1989 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
1990 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
1991 case OperationType::Trunc:
1992 return Opcode == Instruction::Trunc;
1993 case OperationType::DisjointOp:
1994 return Opcode == Instruction::Or;
1995 case OperationType::PossiblyExactOp:
1996 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
1997 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
1998 case OperationType::GEPOp:
1999 return Opcode == Instruction::GetElementPtr ||
2000 Opcode == VPInstruction::PtrAdd ||
2001 Opcode == VPInstruction::WidePtrAdd;
2002 case OperationType::FPMathOp:
2003 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2004 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2005 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2006 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2007 Opcode == Instruction::FPTrunc || Opcode == Instruction::Select ||
2008 Opcode == VPInstruction::WideIVStep ||
2011 case OperationType::FCmp:
2012 return Opcode == Instruction::FCmp;
2013 case OperationType::NonNegOp:
2014 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2015 case OperationType::Cmp:
2016 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2017 case OperationType::Other:
2018 return true;
2019 }
2020 llvm_unreachable("Unknown OperationType enum");
2021}
2022#endif
2023
2024#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2026 switch (OpType) {
2027 case OperationType::Cmp:
2029 break;
2030 case OperationType::FCmp:
2033 break;
2034 case OperationType::DisjointOp:
2035 if (DisjointFlags.IsDisjoint)
2036 O << " disjoint";
2037 break;
2038 case OperationType::PossiblyExactOp:
2039 if (ExactFlags.IsExact)
2040 O << " exact";
2041 break;
2042 case OperationType::OverflowingBinOp:
2043 if (WrapFlags.HasNUW)
2044 O << " nuw";
2045 if (WrapFlags.HasNSW)
2046 O << " nsw";
2047 break;
2048 case OperationType::Trunc:
2049 if (TruncFlags.HasNUW)
2050 O << " nuw";
2051 if (TruncFlags.HasNSW)
2052 O << " nsw";
2053 break;
2054 case OperationType::FPMathOp:
2056 break;
2057 case OperationType::GEPOp:
2058 if (GEPFlags.isInBounds())
2059 O << " inbounds";
2060 else if (GEPFlags.hasNoUnsignedSignedWrap())
2061 O << " nusw";
2062 if (GEPFlags.hasNoUnsignedWrap())
2063 O << " nuw";
2064 break;
2065 case OperationType::NonNegOp:
2066 if (NonNegFlags.NonNeg)
2067 O << " nneg";
2068 break;
2069 case OperationType::Other:
2070 break;
2071 }
2072 O << " ";
2073}
2074#endif
2075
2077 auto &Builder = State.Builder;
2078 switch (Opcode) {
2079 case Instruction::Call:
2080 case Instruction::Br:
2081 case Instruction::PHI:
2082 case Instruction::GetElementPtr:
2083 case Instruction::Select:
2084 llvm_unreachable("This instruction is handled by a different recipe.");
2085 case Instruction::UDiv:
2086 case Instruction::SDiv:
2087 case Instruction::SRem:
2088 case Instruction::URem:
2089 case Instruction::Add:
2090 case Instruction::FAdd:
2091 case Instruction::Sub:
2092 case Instruction::FSub:
2093 case Instruction::FNeg:
2094 case Instruction::Mul:
2095 case Instruction::FMul:
2096 case Instruction::FDiv:
2097 case Instruction::FRem:
2098 case Instruction::Shl:
2099 case Instruction::LShr:
2100 case Instruction::AShr:
2101 case Instruction::And:
2102 case Instruction::Or:
2103 case Instruction::Xor: {
2104 // Just widen unops and binops.
2106 for (VPValue *VPOp : operands())
2107 Ops.push_back(State.get(VPOp));
2108
2109 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2110
2111 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2112 applyFlags(*VecOp);
2113 applyMetadata(*VecOp);
2114 }
2115
2116 // Use this vector value for all users of the original instruction.
2117 State.set(this, V);
2118 break;
2119 }
2120 case Instruction::ExtractValue: {
2121 assert(getNumOperands() == 2 && "expected single level extractvalue");
2122 Value *Op = State.get(getOperand(0));
2124 Value *Extract = Builder.CreateExtractValue(Op, CI->getZExtValue());
2125 State.set(this, Extract);
2126 break;
2127 }
2128 case Instruction::Freeze: {
2129 Value *Op = State.get(getOperand(0));
2130 Value *Freeze = Builder.CreateFreeze(Op);
2131 State.set(this, Freeze);
2132 break;
2133 }
2134 case Instruction::ICmp:
2135 case Instruction::FCmp: {
2136 // Widen compares. Generate vector compares.
2137 bool FCmp = Opcode == Instruction::FCmp;
2138 Value *A = State.get(getOperand(0));
2139 Value *B = State.get(getOperand(1));
2140 Value *C = nullptr;
2141 if (FCmp) {
2142 C = Builder.CreateFCmp(getPredicate(), A, B);
2143 } else {
2144 C = Builder.CreateICmp(getPredicate(), A, B);
2145 }
2146 if (auto *I = dyn_cast<Instruction>(C)) {
2147 applyFlags(*I);
2148 applyMetadata(*I);
2149 }
2150 State.set(this, C);
2151 break;
2152 }
2153 default:
2154 // This instruction is not vectorized by simple widening.
2155 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2156 << Instruction::getOpcodeName(Opcode));
2157 llvm_unreachable("Unhandled instruction!");
2158 } // end of switch.
2159
2160#if !defined(NDEBUG)
2161 // Verify that VPlan type inference results agree with the type of the
2162 // generated values.
2163 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2164 State.get(this)->getType() &&
2165 "inferred type and type from generated instructions do not match");
2166#endif
2167}
2168
2170 VPCostContext &Ctx) const {
2171 switch (Opcode) {
2172 case Instruction::UDiv:
2173 case Instruction::SDiv:
2174 case Instruction::SRem:
2175 case Instruction::URem:
2176 // If the div/rem operation isn't safe to speculate and requires
2177 // predication, then the only way we can even create a vplan is to insert
2178 // a select on the second input operand to ensure we use the value of 1
2179 // for the inactive lanes. The select will be costed separately.
2180 case Instruction::FNeg:
2181 case Instruction::Add:
2182 case Instruction::FAdd:
2183 case Instruction::Sub:
2184 case Instruction::FSub:
2185 case Instruction::Mul:
2186 case Instruction::FMul:
2187 case Instruction::FDiv:
2188 case Instruction::FRem:
2189 case Instruction::Shl:
2190 case Instruction::LShr:
2191 case Instruction::AShr:
2192 case Instruction::And:
2193 case Instruction::Or:
2194 case Instruction::Xor:
2195 case Instruction::Freeze:
2196 case Instruction::ExtractValue:
2197 case Instruction::ICmp:
2198 case Instruction::FCmp:
2199 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2200 default:
2201 llvm_unreachable("Unsupported opcode for instruction");
2202 }
2203}
2204
2205#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2207 VPSlotTracker &SlotTracker) const {
2208 O << Indent << "WIDEN ";
2210 O << " = " << Instruction::getOpcodeName(Opcode);
2211 printFlags(O);
2213}
2214#endif
2215
2217 auto &Builder = State.Builder;
2218 /// Vectorize casts.
2219 assert(State.VF.isVector() && "Not vectorizing?");
2220 Type *DestTy = VectorType::get(getResultType(), State.VF);
2221 VPValue *Op = getOperand(0);
2222 Value *A = State.get(Op);
2223 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2224 State.set(this, Cast);
2225 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2226 applyFlags(*CastOp);
2227 applyMetadata(*CastOp);
2228 }
2229}
2230
2232 VPCostContext &Ctx) const {
2233 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2234 // the legacy cost model, including truncates/extends when evaluating a
2235 // reduction in a smaller type.
2236 if (!getUnderlyingValue())
2237 return 0;
2238 // Computes the CastContextHint from a recipes that may access memory.
2239 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
2240 if (VF.isScalar())
2242 if (isa<VPInterleaveBase>(R))
2244 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R))
2245 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
2247 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
2248 if (WidenMemoryRecipe == nullptr)
2250 if (!WidenMemoryRecipe->isConsecutive())
2252 if (WidenMemoryRecipe->isReverse())
2254 if (WidenMemoryRecipe->isMasked())
2257 };
2258
2259 VPValue *Operand = getOperand(0);
2261 // For Trunc/FPTrunc, get the context from the only user.
2262 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
2263 auto GetOnlyUser = [](const VPSingleDefRecipe *R) -> VPRecipeBase * {
2264 if (R->getNumUsers() == 0 || R->hasMoreThanOneUniqueUser())
2265 return nullptr;
2266 return dyn_cast<VPRecipeBase>(*R->user_begin());
2267 };
2268
2269 if (VPRecipeBase *Recipe = GetOnlyUser(this)) {
2270 if (match(Recipe, m_Reverse(m_VPValue())))
2271 Recipe = GetOnlyUser(cast<VPInstruction>(Recipe));
2272 if (Recipe)
2273 CCH = ComputeCCH(Recipe);
2274 }
2275 }
2276 // For Z/Sext, get the context from the operand.
2277 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
2278 Opcode == Instruction::FPExt) {
2279 if (Operand->isLiveIn())
2281 else if (auto *Recipe = Operand->getDefiningRecipe()) {
2282 VPValue *ReverseOp;
2283 if (match(Recipe, m_Reverse(m_VPValue(ReverseOp))))
2284 Recipe = ReverseOp->getDefiningRecipe();
2285 if (Recipe)
2286 CCH = ComputeCCH(Recipe);
2287 }
2288 }
2289
2290 auto *SrcTy =
2291 cast<VectorType>(toVectorTy(Ctx.Types.inferScalarType(Operand), VF));
2292 auto *DestTy = cast<VectorType>(toVectorTy(getResultType(), VF));
2293 // Arm TTI will use the underlying instruction to determine the cost.
2294 return Ctx.TTI.getCastInstrCost(
2295 Opcode, DestTy, SrcTy, CCH, Ctx.CostKind,
2297}
2298
2299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2301 VPSlotTracker &SlotTracker) const {
2302 O << Indent << "WIDEN-CAST ";
2304 O << " = " << Instruction::getOpcodeName(Opcode);
2305 printFlags(O);
2307 O << " to " << *getResultType();
2308}
2309#endif
2310
2312 VPCostContext &Ctx) const {
2313 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2314}
2315
2316/// A helper function that returns an integer or floating-point constant with
2317/// value C.
2319 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
2320 : ConstantFP::get(Ty, C);
2321}
2322
2323#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2325 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2326 O << Indent;
2328 O << " = WIDEN-INDUCTION";
2329 printFlags(O);
2331
2332 if (auto *TI = getTruncInst())
2333 O << " (truncated to " << *TI->getType() << ")";
2334}
2335#endif
2336
2338 // The step may be defined by a recipe in the preheader (e.g. if it requires
2339 // SCEV expansion), but for the canonical induction the step is required to be
2340 // 1, which is represented as live-in.
2342 return false;
2345 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2346 getScalarType() == getRegion()->getCanonicalIVType();
2347}
2348
2349#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2351 VPSlotTracker &SlotTracker) const {
2352 O << Indent;
2354 O << " = DERIVED-IV ";
2355 getStartValue()->printAsOperand(O, SlotTracker);
2356 O << " + ";
2357 getOperand(1)->printAsOperand(O, SlotTracker);
2358 O << " * ";
2359 getStepValue()->printAsOperand(O, SlotTracker);
2360}
2361#endif
2362
2364 // Fast-math-flags propagate from the original induction instruction.
2365 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2366 if (hasFastMathFlags())
2367 State.Builder.setFastMathFlags(getFastMathFlags());
2368
2369 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2370 /// variable on which to base the steps, \p Step is the size of the step.
2371
2372 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2373 Value *Step = State.get(getStepValue(), VPLane(0));
2374 IRBuilderBase &Builder = State.Builder;
2375
2376 // Ensure step has the same type as that of scalar IV.
2377 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2378 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2379
2380 // We build scalar steps for both integer and floating-point induction
2381 // variables. Here, we determine the kind of arithmetic we will perform.
2384 if (BaseIVTy->isIntegerTy()) {
2385 AddOp = Instruction::Add;
2386 MulOp = Instruction::Mul;
2387 } else {
2388 AddOp = InductionOpcode;
2389 MulOp = Instruction::FMul;
2390 }
2391
2392 // Determine the number of scalars we need to generate for each unroll
2393 // iteration.
2394 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2395 // Compute the scalar steps and save the results in State.
2396 Type *IntStepTy =
2397 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
2398
2399 unsigned StartLane = 0;
2400 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2401 if (State.Lane) {
2402 StartLane = State.Lane->getKnownLane();
2403 EndLane = StartLane + 1;
2404 }
2405 Value *StartIdx0;
2406 if (getUnrollPart(*this) == 0)
2407 StartIdx0 = ConstantInt::get(IntStepTy, 0);
2408 else {
2409 StartIdx0 = State.get(getOperand(2), true);
2410 if (getUnrollPart(*this) != 1) {
2411 StartIdx0 =
2412 Builder.CreateMul(StartIdx0, ConstantInt::get(StartIdx0->getType(),
2413 getUnrollPart(*this)));
2414 }
2415 StartIdx0 = Builder.CreateSExtOrTrunc(StartIdx0, IntStepTy);
2416 }
2417
2418 if (BaseIVTy->isFloatingPointTy())
2419 StartIdx0 = Builder.CreateSIToFP(StartIdx0, BaseIVTy);
2420
2421 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2422 Value *StartIdx = Builder.CreateBinOp(
2423 AddOp, StartIdx0, getSignedIntOrFpConstant(BaseIVTy, Lane));
2424 // The step returned by `createStepForVF` is a runtime-evaluated value
2425 // when VF is scalable. Otherwise, it should be folded into a Constant.
2426 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2427 "Expected StartIdx to be folded to a constant when VF is not "
2428 "scalable");
2429 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2430 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2431 State.set(this, Add, VPLane(Lane));
2432 }
2433}
2434
2435#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2437 VPSlotTracker &SlotTracker) const {
2438 O << Indent;
2440 O << " = SCALAR-STEPS ";
2442}
2443#endif
2444
2446 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2448}
2449
2451 assert(State.VF.isVector() && "not widening");
2452 // Construct a vector GEP by widening the operands of the scalar GEP as
2453 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2454 // results in a vector of pointers when at least one operand of the GEP
2455 // is vector-typed. Thus, to keep the representation compact, we only use
2456 // vector-typed operands for loop-varying values.
2457
2458 assert(
2459 any_of(operands(),
2460 [](VPValue *Op) { return !Op->isDefinedOutsideLoopRegions(); }) &&
2461 "Expected at least one loop-variant operand");
2462
2463 // If the GEP has at least one loop-varying operand, we are sure to
2464 // produce a vector of pointers unless VF is scalar.
2465 // The pointer operand of the new GEP. If it's loop-invariant, we
2466 // won't broadcast it.
2467 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2468
2469 // Collect all the indices for the new GEP. If any index is
2470 // loop-invariant, we won't broadcast it.
2472 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2473 VPValue *Operand = getOperand(I);
2474 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2475 }
2476
2477 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2478 // but it should be a vector, otherwise.
2479 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2480 "", getGEPNoWrapFlags());
2481 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2482 "NewGEP is not a pointer vector");
2483 State.set(this, NewGEP);
2484}
2485
2486#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2488 VPSlotTracker &SlotTracker) const {
2489 O << Indent << "WIDEN-GEP ";
2490 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2491 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2492 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2493
2494 O << " ";
2496 O << " = getelementptr";
2497 printFlags(O);
2499}
2500#endif
2501
2503 auto &Builder = State.Builder;
2504 unsigned CurrentPart = getUnrollPart(*this);
2505 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2506 Type *IndexTy = DL.getIndexType(State.TypeAnalysis.inferScalarType(this));
2507
2508 // The wide store needs to start at the last vector element.
2509 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2510 if (IndexTy != RunTimeVF->getType())
2511 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2512 // NumElt = Stride * CurrentPart * RunTimeVF
2513 Value *NumElt = Builder.CreateMul(
2514 ConstantInt::get(IndexTy, Stride * (int64_t)CurrentPart), RunTimeVF);
2515 // LastLane = Stride * (RunTimeVF - 1)
2516 Value *LastLane = Builder.CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2517 if (Stride != 1)
2518 LastLane =
2519 Builder.CreateMul(ConstantInt::getSigned(IndexTy, Stride), LastLane);
2520 Value *Ptr = State.get(getOperand(0), VPLane(0));
2521 Value *ResultPtr =
2522 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2523 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2525
2526 State.set(this, ResultPtr, /*IsScalar*/ true);
2527}
2528
2529#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2531 VPSlotTracker &SlotTracker) const {
2532 O << Indent;
2534 O << " = vector-end-pointer";
2535 printFlags(O);
2537}
2538#endif
2539
2541 auto &Builder = State.Builder;
2542 assert(getOffset() &&
2543 "Expected prior simplification of recipe without offset");
2544 Value *Ptr = State.get(getOperand(0), VPLane(0));
2545 Value *Offset = State.get(getOffset(), true);
2546 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
2548 State.set(this, ResultPtr, /*IsScalar*/ true);
2549}
2550
2551#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2553 VPSlotTracker &SlotTracker) const {
2554 O << Indent;
2556 O << " = vector-pointer";
2557 printFlags(O);
2559}
2560#endif
2561
2563 VPCostContext &Ctx) const {
2564 // A blend will be expanded to a select VPInstruction, which will generate a
2565 // scalar select if only the first lane is used.
2567 VF = ElementCount::getFixed(1);
2568
2569 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2570 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2571 return (getNumIncomingValues() - 1) *
2572 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2573 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2574}
2575
2576#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2578 VPSlotTracker &SlotTracker) const {
2579 O << Indent << "BLEND ";
2581 O << " =";
2582 if (getNumIncomingValues() == 1) {
2583 // Not a User of any mask: not really blending, this is a
2584 // single-predecessor phi.
2585 O << " ";
2586 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2587 } else {
2588 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2589 O << " ";
2590 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2591 if (I == 0)
2592 continue;
2593 O << "/";
2594 getMask(I)->printAsOperand(O, SlotTracker);
2595 }
2596 }
2597}
2598#endif
2599
2601 assert(!State.Lane && "Reduction being replicated.");
2604 "In-loop AnyOf reductions aren't currently supported");
2605 // Propagate the fast-math flags carried by the underlying instruction.
2606 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2607 State.Builder.setFastMathFlags(getFastMathFlags());
2608 Value *NewVecOp = State.get(getVecOp());
2609 if (VPValue *Cond = getCondOp()) {
2610 Value *NewCond = State.get(Cond, State.VF.isScalar());
2611 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2612 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2613
2614 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2615 if (State.VF.isVector())
2616 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2617
2618 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2619 NewVecOp = Select;
2620 }
2621 Value *NewRed;
2622 Value *NextInChain;
2623 if (isOrdered()) {
2624 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2625 if (State.VF.isVector())
2626 NewRed =
2627 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2628 else
2629 NewRed = State.Builder.CreateBinOp(
2631 PrevInChain, NewVecOp);
2632 PrevInChain = NewRed;
2633 NextInChain = NewRed;
2634 } else if (isPartialReduction()) {
2635 assert(Kind == RecurKind::Add && "Unexpected partial reduction kind");
2636 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2637 NewRed = State.Builder.CreateIntrinsic(
2638 PrevInChain->getType(), Intrinsic::vector_partial_reduce_add,
2639 {PrevInChain, NewVecOp}, nullptr, "partial.reduce");
2640 PrevInChain = NewRed;
2641 NextInChain = NewRed;
2642 } else {
2643 assert(isInLoop() &&
2644 "The reduction must either be ordered, partial or in-loop");
2645 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2646 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2648 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2649 else
2650 NextInChain = State.Builder.CreateBinOp(
2652 PrevInChain, NewRed);
2653 }
2654 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2655}
2656
2658 assert(!State.Lane && "Reduction being replicated.");
2659
2660 auto &Builder = State.Builder;
2661 // Propagate the fast-math flags carried by the underlying instruction.
2662 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2663 Builder.setFastMathFlags(getFastMathFlags());
2664
2666 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2667 Value *VecOp = State.get(getVecOp());
2668 Value *EVL = State.get(getEVL(), VPLane(0));
2669
2670 Value *Mask;
2671 if (VPValue *CondOp = getCondOp())
2672 Mask = State.get(CondOp);
2673 else
2674 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2675
2676 Value *NewRed;
2677 if (isOrdered()) {
2678 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2679 } else {
2680 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2682 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2683 else
2684 NewRed = Builder.CreateBinOp(
2686 Prev);
2687 }
2688 State.set(this, NewRed, /*IsScalar*/ true);
2689}
2690
2692 VPCostContext &Ctx) const {
2693 RecurKind RdxKind = getRecurrenceKind();
2694 Type *ElementTy = Ctx.Types.inferScalarType(this);
2695 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2696 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2698 std::optional<FastMathFlags> OptionalFMF =
2699 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2700
2701 if (isPartialReduction()) {
2702 InstructionCost CondCost = 0;
2703 if (isConditional()) {
2705 auto *CondTy = cast<VectorType>(
2706 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2707 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2708 CondTy, Pred, Ctx.CostKind);
2709 }
2710 return CondCost + Ctx.TTI.getPartialReductionCost(
2711 Opcode, ElementTy, ElementTy, ElementTy, VF,
2713 TargetTransformInfo::PR_None, std::nullopt,
2714 Ctx.CostKind);
2715 }
2716
2717 // TODO: Support any-of reductions.
2718 assert(
2720 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2721 "Any-of reduction not implemented in VPlan-based cost model currently.");
2722
2723 // Note that TTI should model the cost of moving result to the scalar register
2724 // and the BinOp cost in the getMinMaxReductionCost().
2727 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2728 }
2729
2730 // Note that TTI should model the cost of moving result to the scalar register
2731 // and the BinOp cost in the getArithmeticReductionCost().
2732 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2733 Ctx.CostKind);
2734}
2735
2737 ExpressionTypes ExpressionType,
2738 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2739 : VPSingleDefRecipe(VPDef::VPExpressionSC, {}, {}),
2740 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2741 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2742 assert(
2743 none_of(ExpressionRecipes,
2744 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2745 "expression cannot contain recipes with side-effects");
2746
2747 // Maintain a copy of the expression recipes as a set of users.
2748 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2749 for (auto *R : ExpressionRecipes)
2750 ExpressionRecipesAsSetOfUsers.insert(R);
2751
2752 // Recipes in the expression, except the last one, must only be used by
2753 // (other) recipes inside the expression. If there are other users, external
2754 // to the expression, use a clone of the recipe for external users.
2755 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2756 if (R != ExpressionRecipes.back() &&
2757 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2758 return !ExpressionRecipesAsSetOfUsers.contains(U);
2759 })) {
2760 // There are users outside of the expression. Clone the recipe and use the
2761 // clone those external users.
2762 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2763 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2764 VPUser &U, unsigned) {
2765 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2766 });
2767 CopyForExtUsers->insertBefore(R);
2768 }
2769 if (R->getParent())
2770 R->removeFromParent();
2771 }
2772
2773 // Internalize all external operands to the expression recipes. To do so,
2774 // create new temporary VPValues for all operands defined by a recipe outside
2775 // the expression. The original operands are added as operands of the
2776 // VPExpressionRecipe itself.
2777 for (auto *R : ExpressionRecipes) {
2778 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2779 auto *Def = Op->getDefiningRecipe();
2780 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2781 continue;
2782 addOperand(Op);
2783 LiveInPlaceholders.push_back(new VPValue());
2784 }
2785 }
2786
2787 // Replace each external operand with the first one created for it in
2788 // LiveInPlaceholders.
2789 for (auto *R : ExpressionRecipes)
2790 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2791 R->replaceUsesOfWith(LiveIn, Tmp);
2792}
2793
2795 for (auto *R : ExpressionRecipes)
2796 // Since the list could contain duplicates, make sure the recipe hasn't
2797 // already been inserted.
2798 if (!R->getParent())
2799 R->insertBefore(this);
2800
2801 for (const auto &[Idx, Op] : enumerate(operands()))
2802 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
2803
2804 replaceAllUsesWith(ExpressionRecipes.back());
2805 ExpressionRecipes.clear();
2806}
2807
2809 VPCostContext &Ctx) const {
2810 Type *RedTy = Ctx.Types.inferScalarType(this);
2811 auto *SrcVecTy = cast<VectorType>(
2812 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
2813 assert(RedTy->isIntegerTy() &&
2814 "VPExpressionRecipe only supports integer types currently.");
2815 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2816 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
2817 switch (ExpressionType) {
2818 case ExpressionTypes::ExtendedReduction: {
2819 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2820 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
2821 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2822
2823 return cast<VPReductionRecipe>(ExpressionRecipes.back())
2824 ->isPartialReduction()
2825 ? Ctx.TTI.getPartialReductionCost(
2826 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr,
2827 RedTy, VF,
2829 ExtR->getOpcode()),
2830 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind)
2831 : Ctx.TTI.getExtendedReductionCost(
2832 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy,
2833 SrcVecTy, std::nullopt, Ctx.CostKind);
2834 }
2835 case ExpressionTypes::MulAccReduction:
2836 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
2837 Ctx.CostKind);
2838
2839 case ExpressionTypes::ExtNegatedMulAccReduction:
2840 assert(Opcode == Instruction::Add && "Unexpected opcode");
2841 Opcode = Instruction::Sub;
2842 [[fallthrough]];
2843 case ExpressionTypes::ExtMulAccReduction: {
2844 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
2845 if (RedR->isPartialReduction()) {
2846 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2847 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2848 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2849 return Ctx.TTI.getPartialReductionCost(
2850 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
2851 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
2853 Ext0R->getOpcode()),
2855 Ext1R->getOpcode()),
2856 Mul->getOpcode(), Ctx.CostKind);
2857 }
2858 return Ctx.TTI.getMulAccReductionCost(
2859 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2860 Instruction::ZExt,
2861 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
2862 }
2863 }
2864 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
2865}
2866
2868 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
2869 return R->mayReadFromMemory() || R->mayWriteToMemory();
2870 });
2871}
2872
2874 assert(
2875 none_of(ExpressionRecipes,
2876 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2877 "expression cannot contain recipes with side-effects");
2878 return false;
2879}
2880
2882 // Cannot use vputils::isSingleScalar(), because all external operands
2883 // of the expression will be live-ins while bundled.
2884 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
2885 return RR && !RR->isPartialReduction();
2886}
2887
2888#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2889
2891 VPSlotTracker &SlotTracker) const {
2892 O << Indent << "EXPRESSION ";
2894 O << " = ";
2895 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
2896 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
2897
2898 switch (ExpressionType) {
2899 case ExpressionTypes::ExtendedReduction: {
2901 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
2902 O << Instruction::getOpcodeName(Opcode) << " (";
2904 Red->printFlags(O);
2905
2906 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2907 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2908 << *Ext0->getResultType();
2909 if (Red->isConditional()) {
2910 O << ", ";
2911 Red->getCondOp()->printAsOperand(O, SlotTracker);
2912 }
2913 O << ")";
2914 break;
2915 }
2916 case ExpressionTypes::ExtNegatedMulAccReduction: {
2918 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
2920 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
2921 << " (sub (0, mul";
2922 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2923 Mul->printFlags(O);
2924 O << "(";
2926 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2927 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2928 << *Ext0->getResultType() << "), (";
2930 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2931 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
2932 << *Ext1->getResultType() << ")";
2933 if (Red->isConditional()) {
2934 O << ", ";
2935 Red->getCondOp()->printAsOperand(O, SlotTracker);
2936 }
2937 O << "))";
2938 break;
2939 }
2940 case ExpressionTypes::MulAccReduction:
2941 case ExpressionTypes::ExtMulAccReduction: {
2943 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
2945 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
2946 << " (";
2947 O << "mul";
2948 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
2949 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
2950 : ExpressionRecipes[0]);
2951 Mul->printFlags(O);
2952 if (IsExtended)
2953 O << "(";
2955 if (IsExtended) {
2956 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2957 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2958 << *Ext0->getResultType() << "), (";
2959 } else {
2960 O << ", ";
2961 }
2963 if (IsExtended) {
2964 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2965 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
2966 << *Ext1->getResultType() << ")";
2967 }
2968 if (Red->isConditional()) {
2969 O << ", ";
2970 Red->getCondOp()->printAsOperand(O, SlotTracker);
2971 }
2972 O << ")";
2973 break;
2974 }
2975 }
2976}
2977
2979 VPSlotTracker &SlotTracker) const {
2980 if (isPartialReduction())
2981 O << Indent << "PARTIAL-REDUCE ";
2982 else
2983 O << Indent << "REDUCE ";
2985 O << " = ";
2987 O << " +";
2988 printFlags(O);
2989 O << " reduce."
2992 << " (";
2994 if (isConditional()) {
2995 O << ", ";
2997 }
2998 O << ")";
2999}
3000
3002 VPSlotTracker &SlotTracker) const {
3003 O << Indent << "REDUCE ";
3005 O << " = ";
3007 O << " +";
3008 printFlags(O);
3009 O << " vp.reduce."
3012 << " (";
3014 O << ", ";
3016 if (isConditional()) {
3017 O << ", ";
3019 }
3020 O << ")";
3021}
3022
3023#endif
3024
3025/// A helper function to scalarize a single Instruction in the innermost loop.
3026/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3027/// operands from \p RepRecipe instead of \p Instr's operands.
3028static void scalarizeInstruction(const Instruction *Instr,
3029 VPReplicateRecipe *RepRecipe,
3030 const VPLane &Lane, VPTransformState &State) {
3031 assert((!Instr->getType()->isAggregateType() ||
3032 canVectorizeTy(Instr->getType())) &&
3033 "Expected vectorizable or non-aggregate type.");
3034
3035 // Does this instruction return a value ?
3036 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3037
3038 Instruction *Cloned = Instr->clone();
3039 if (!IsVoidRetTy) {
3040 Cloned->setName(Instr->getName() + ".cloned");
3041 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3042 // The operands of the replicate recipe may have been narrowed, resulting in
3043 // a narrower result type. Update the type of the cloned instruction to the
3044 // correct type.
3045 if (ResultTy != Cloned->getType())
3046 Cloned->mutateType(ResultTy);
3047 }
3048
3049 RepRecipe->applyFlags(*Cloned);
3050 RepRecipe->applyMetadata(*Cloned);
3051
3052 if (RepRecipe->hasPredicate())
3053 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3054
3055 if (auto DL = RepRecipe->getDebugLoc())
3056 State.setDebugLocFrom(DL);
3057
3058 // Replace the operands of the cloned instructions with their scalar
3059 // equivalents in the new loop.
3060 for (const auto &I : enumerate(RepRecipe->operands())) {
3061 auto InputLane = Lane;
3062 VPValue *Operand = I.value();
3063 if (vputils::isSingleScalar(Operand))
3064 InputLane = VPLane::getFirstLane();
3065 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3066 }
3067
3068 // Place the cloned scalar in the new loop.
3069 State.Builder.Insert(Cloned);
3070
3071 State.set(RepRecipe, Cloned, Lane);
3072
3073 // If we just cloned a new assumption, add it the assumption cache.
3074 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3075 State.AC->registerAssumption(II);
3076
3077 assert(
3078 (RepRecipe->getRegion() ||
3079 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3080 all_of(RepRecipe->operands(),
3081 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3082 "Expected a recipe is either within a region or all of its operands "
3083 "are defined outside the vectorized region.");
3084}
3085
3088
3089 if (!State.Lane) {
3090 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3091 "must have already been unrolled");
3092 scalarizeInstruction(UI, this, VPLane(0), State);
3093 return;
3094 }
3095
3096 assert((State.VF.isScalar() || !isSingleScalar()) &&
3097 "uniform recipe shouldn't be predicated");
3098 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3099 scalarizeInstruction(UI, this, *State.Lane, State);
3100 // Insert scalar instance packing it into a vector.
3101 if (State.VF.isVector() && shouldPack()) {
3102 Value *WideValue =
3103 State.Lane->isFirstLane()
3104 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3105 : State.get(this);
3106 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3107 *State.Lane));
3108 }
3109}
3110
3112 // Find if the recipe is used by a widened recipe via an intervening
3113 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3114 return any_of(users(), [](const VPUser *U) {
3115 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3116 return !vputils::onlyScalarValuesUsed(PredR);
3117 return false;
3118 });
3119}
3120
3121/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3122/// which the legacy cost model computes a SCEV expression when computing the
3123/// address cost. Computing SCEVs for VPValues is incomplete and returns
3124/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3125/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3126static const SCEV *getAddressAccessSCEV(const VPValue *Ptr, ScalarEvolution &SE,
3127 const Loop *L) {
3128 auto *PtrR = Ptr->getDefiningRecipe();
3129 if (!PtrR || !((isa<VPReplicateRecipe>(Ptr) &&
3131 Instruction::GetElementPtr) ||
3132 isa<VPWidenGEPRecipe>(Ptr) ||
3134 return nullptr;
3135
3136 // We are looking for a GEP where all indices are either loop invariant or
3137 // inductions.
3138 for (VPValue *Opd : drop_begin(PtrR->operands())) {
3139 if (!Opd->isDefinedOutsideLoopRegions() &&
3141 return nullptr;
3142 }
3143
3144 return vputils::getSCEVExprForVPValue(Ptr, SE, L);
3145}
3146
3147/// Returns true if \p V is used as part of the address of another load or
3148/// store.
3149static bool isUsedByLoadStoreAddress(const VPUser *V) {
3151 SmallVector<const VPUser *> WorkList = {V};
3152
3153 while (!WorkList.empty()) {
3154 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3155 if (!Cur || !Seen.insert(Cur).second)
3156 continue;
3157
3158 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3159 // Skip blends that use V only through a compare by checking if any incoming
3160 // value was already visited.
3161 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3162 [&](unsigned I) {
3163 return Seen.contains(
3164 Blend->getIncomingValue(I)->getDefiningRecipe());
3165 }))
3166 continue;
3167
3168 for (VPUser *U : Cur->users()) {
3169 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3170 if (InterleaveR->getAddr() == Cur)
3171 return true;
3172 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3173 if (RepR->getOpcode() == Instruction::Load &&
3174 RepR->getOperand(0) == Cur)
3175 return true;
3176 if (RepR->getOpcode() == Instruction::Store &&
3177 RepR->getOperand(1) == Cur)
3178 return true;
3179 }
3180 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3181 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3182 return true;
3183 }
3184 }
3185
3186 // The legacy cost model only supports scalarization loads/stores with phi
3187 // addresses, if the phi is directly used as load/store address. Don't
3188 // traverse further for Blends.
3189 if (Blend)
3190 continue;
3191
3192 append_range(WorkList, Cur->users());
3193 }
3194 return false;
3195}
3196
3198 VPCostContext &Ctx) const {
3200 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3201 // transform, avoid computing their cost multiple times for now.
3202 Ctx.SkipCostComputation.insert(UI);
3203
3204 if (VF.isScalable() && !isSingleScalar())
3206
3207 switch (UI->getOpcode()) {
3208 case Instruction::GetElementPtr:
3209 // We mark this instruction as zero-cost because the cost of GEPs in
3210 // vectorized code depends on whether the corresponding memory instruction
3211 // is scalarized or not. Therefore, we handle GEPs with the memory
3212 // instruction cost.
3213 return 0;
3214 case Instruction::Call: {
3215 auto *CalledFn =
3217
3220 for (const VPValue *ArgOp : ArgOps)
3221 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3222
3223 if (CalledFn->isIntrinsic())
3224 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3225 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3226 switch (CalledFn->getIntrinsicID()) {
3227 case Intrinsic::assume:
3228 case Intrinsic::lifetime_end:
3229 case Intrinsic::lifetime_start:
3230 case Intrinsic::sideeffect:
3231 case Intrinsic::pseudoprobe:
3232 case Intrinsic::experimental_noalias_scope_decl: {
3233 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3234 ElementCount::getFixed(1), Ctx) == 0 &&
3235 "scalarizing intrinsic should be free");
3236 return InstructionCost(0);
3237 }
3238 default:
3239 break;
3240 }
3241
3242 Type *ResultTy = Ctx.Types.inferScalarType(this);
3243 InstructionCost ScalarCallCost =
3244 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3245 if (isSingleScalar()) {
3246 if (CalledFn->isIntrinsic())
3247 ScalarCallCost = std::min(
3248 ScalarCallCost,
3249 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3250 ElementCount::getFixed(1), Ctx));
3251 return ScalarCallCost;
3252 }
3253
3254 return ScalarCallCost * VF.getFixedValue() +
3255 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3256 }
3257 case Instruction::Add:
3258 case Instruction::Sub:
3259 case Instruction::FAdd:
3260 case Instruction::FSub:
3261 case Instruction::Mul:
3262 case Instruction::FMul:
3263 case Instruction::FDiv:
3264 case Instruction::FRem:
3265 case Instruction::Shl:
3266 case Instruction::LShr:
3267 case Instruction::AShr:
3268 case Instruction::And:
3269 case Instruction::Or:
3270 case Instruction::Xor:
3271 case Instruction::ICmp:
3272 case Instruction::FCmp:
3274 Ctx) *
3275 (isSingleScalar() ? 1 : VF.getFixedValue());
3276 case Instruction::SDiv:
3277 case Instruction::UDiv:
3278 case Instruction::SRem:
3279 case Instruction::URem: {
3280 InstructionCost ScalarCost =
3282 if (isSingleScalar())
3283 return ScalarCost;
3284
3285 ScalarCost = ScalarCost * VF.getFixedValue() +
3286 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3287 to_vector(operands()), VF);
3288 // If the recipe is not predicated (i.e. not in a replicate region), return
3289 // the scalar cost. Otherwise handle predicated cost.
3290 if (!getRegion()->isReplicator())
3291 return ScalarCost;
3292
3293 // Account for the phi nodes that we will create.
3294 ScalarCost += VF.getFixedValue() *
3295 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3296 // Scale the cost by the probability of executing the predicated blocks.
3297 // This assumes the predicated block for each vector lane is equally
3298 // likely.
3299 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3300 return ScalarCost;
3301 }
3302 case Instruction::Load:
3303 case Instruction::Store: {
3304 // TODO: See getMemInstScalarizationCost for how to handle replicating and
3305 // predicated cases.
3306 const VPRegionBlock *ParentRegion = getRegion();
3307 if (ParentRegion && ParentRegion->isReplicator())
3308 break;
3309
3310 bool IsLoad = UI->getOpcode() == Instruction::Load;
3311 const VPValue *PtrOp = getOperand(!IsLoad);
3312 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.SE, Ctx.L);
3314 break;
3315
3316 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3317 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3318 const Align Alignment = getLoadStoreAlignment(UI);
3319 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3321 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3322 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo);
3323
3324 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3325 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3326 bool UsedByLoadStoreAddress =
3327 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3328 InstructionCost ScalarCost =
3329 ScalarMemOpCost + Ctx.TTI.getAddressComputationCost(
3330 PtrTy, UsedByLoadStoreAddress ? nullptr : &Ctx.SE,
3331 PtrSCEV, Ctx.CostKind);
3332 if (isSingleScalar())
3333 return ScalarCost;
3334
3335 SmallVector<const VPValue *> OpsToScalarize;
3336 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3337 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3338 // don't assign scalarization overhead in general, if the target prefers
3339 // vectorized addressing or the loaded value is used as part of an address
3340 // of another load or store.
3341 if (!UsedByLoadStoreAddress) {
3342 bool EfficientVectorLoadStore =
3343 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3344 if (!(IsLoad && !PreferVectorizedAddressing) &&
3345 !(!IsLoad && EfficientVectorLoadStore))
3346 append_range(OpsToScalarize, operands());
3347
3348 if (!EfficientVectorLoadStore)
3349 ResultTy = Ctx.Types.inferScalarType(this);
3350 }
3351
3352 return (ScalarCost * VF.getFixedValue()) +
3353 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, true);
3354 }
3355 }
3356
3357 return Ctx.getLegacyCost(UI, VF);
3358}
3359
3360#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3362 VPSlotTracker &SlotTracker) const {
3363 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3364
3365 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3367 O << " = ";
3368 }
3369 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3370 O << "call";
3371 printFlags(O);
3372 O << "@" << CB->getCalledFunction()->getName() << "(";
3374 O, [&O, &SlotTracker](VPValue *Op) {
3375 Op->printAsOperand(O, SlotTracker);
3376 });
3377 O << ")";
3378 } else {
3380 printFlags(O);
3382 }
3383
3384 if (shouldPack())
3385 O << " (S->V)";
3386}
3387#endif
3388
3390 assert(State.Lane && "Branch on Mask works only on single instance.");
3391
3392 VPValue *BlockInMask = getOperand(0);
3393 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3394
3395 // Replace the temporary unreachable terminator with a new conditional branch,
3396 // whose two destinations will be set later when they are created.
3397 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3398 assert(isa<UnreachableInst>(CurrentTerminator) &&
3399 "Expected to replace unreachable terminator with conditional branch.");
3400 auto CondBr =
3401 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3402 CondBr->setSuccessor(0, nullptr);
3403 CurrentTerminator->eraseFromParent();
3404}
3405
3407 VPCostContext &Ctx) const {
3408 // The legacy cost model doesn't assign costs to branches for individual
3409 // replicate regions. Match the current behavior in the VPlan cost model for
3410 // now.
3411 return 0;
3412}
3413
3415 assert(State.Lane && "Predicated instruction PHI works per instance.");
3416 Instruction *ScalarPredInst =
3417 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3418 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3419 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3420 assert(PredicatingBB && "Predicated block has no single predecessor.");
3422 "operand must be VPReplicateRecipe");
3423
3424 // By current pack/unpack logic we need to generate only a single phi node: if
3425 // a vector value for the predicated instruction exists at this point it means
3426 // the instruction has vector users only, and a phi for the vector value is
3427 // needed. In this case the recipe of the predicated instruction is marked to
3428 // also do that packing, thereby "hoisting" the insert-element sequence.
3429 // Otherwise, a phi node for the scalar value is needed.
3430 if (State.hasVectorValue(getOperand(0))) {
3431 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3433 "Packed operands must generate an insertelement or insertvalue");
3434
3435 // If VectorI is a struct, it will be a sequence like:
3436 // %1 = insertvalue %unmodified, %x, 0
3437 // %2 = insertvalue %1, %y, 1
3438 // %VectorI = insertvalue %2, %z, 2
3439 // To get the unmodified vector we need to look through the chain.
3440 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3441 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3442 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3443
3444 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3445 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3446 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3447 if (State.hasVectorValue(this))
3448 State.reset(this, VPhi);
3449 else
3450 State.set(this, VPhi);
3451 // NOTE: Currently we need to update the value of the operand, so the next
3452 // predicated iteration inserts its generated value in the correct vector.
3453 State.reset(getOperand(0), VPhi);
3454 } else {
3455 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3456 return;
3457
3458 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3459 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3460 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3461 PredicatingBB);
3462 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3463 if (State.hasScalarValue(this, *State.Lane))
3464 State.reset(this, Phi, *State.Lane);
3465 else
3466 State.set(this, Phi, *State.Lane);
3467 // NOTE: Currently we need to update the value of the operand, so the next
3468 // predicated iteration inserts its generated value in the correct vector.
3469 State.reset(getOperand(0), Phi, *State.Lane);
3470 }
3471}
3472
3473#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3475 VPSlotTracker &SlotTracker) const {
3476 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3478 O << " = ";
3480}
3481#endif
3482
3484 VPCostContext &Ctx) const {
3486 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3487 ->getAddressSpace();
3488 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3489 ? Instruction::Load
3490 : Instruction::Store;
3491
3492 if (!Consecutive) {
3493 // TODO: Using the original IR may not be accurate.
3494 // Currently, ARM will use the underlying IR to calculate gather/scatter
3495 // instruction cost.
3496 assert(!Reverse &&
3497 "Inconsecutive memory access should not have the order.");
3498
3500 Type *PtrTy = Ptr->getType();
3501
3502 // If the address value is uniform across all lanes, then the address can be
3503 // calculated with scalar type and broadcast.
3505 PtrTy = toVectorTy(PtrTy, VF);
3506
3507 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_gather
3508 : isa<VPWidenStoreRecipe>(this) ? Intrinsic::masked_scatter
3509 : isa<VPWidenLoadEVLRecipe>(this) ? Intrinsic::vp_gather
3510 : Intrinsic::vp_scatter;
3511 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3512 Ctx.CostKind) +
3513 Ctx.TTI.getMemIntrinsicInstrCost(
3515 &Ingredient),
3516 Ctx.CostKind);
3517 }
3518
3520 if (IsMasked) {
3521 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3522 : Intrinsic::masked_store;
3523 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
3524 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
3525 } else {
3526 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3528 : getOperand(1));
3529 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3530 OpInfo, &Ingredient);
3531 }
3532 return Cost;
3533}
3534
3536 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3537 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3538 bool CreateGather = !isConsecutive();
3539
3540 auto &Builder = State.Builder;
3541 Value *Mask = nullptr;
3542 if (auto *VPMask = getMask()) {
3543 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3544 // of a null all-one mask is a null mask.
3545 Mask = State.get(VPMask);
3546 if (isReverse())
3547 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3548 }
3549
3550 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3551 Value *NewLI;
3552 if (CreateGather) {
3553 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3554 "wide.masked.gather");
3555 } else if (Mask) {
3556 NewLI =
3557 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3558 PoisonValue::get(DataTy), "wide.masked.load");
3559 } else {
3560 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3561 }
3563 State.set(this, NewLI);
3564}
3565
3566#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3568 VPSlotTracker &SlotTracker) const {
3569 O << Indent << "WIDEN ";
3571 O << " = load ";
3573}
3574#endif
3575
3576/// Use all-true mask for reverse rather than actual mask, as it avoids a
3577/// dependence w/o affecting the result.
3579 Value *EVL, const Twine &Name) {
3580 VectorType *ValTy = cast<VectorType>(Operand->getType());
3581 Value *AllTrueMask =
3582 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3583 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3584 {Operand, AllTrueMask, EVL}, nullptr, Name);
3585}
3586
3588 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3589 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3590 bool CreateGather = !isConsecutive();
3591
3592 auto &Builder = State.Builder;
3593 CallInst *NewLI;
3594 Value *EVL = State.get(getEVL(), VPLane(0));
3595 Value *Addr = State.get(getAddr(), !CreateGather);
3596 Value *Mask = nullptr;
3597 if (VPValue *VPMask = getMask()) {
3598 Mask = State.get(VPMask);
3599 if (isReverse())
3600 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3601 } else {
3602 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3603 }
3604
3605 if (CreateGather) {
3606 NewLI =
3607 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3608 nullptr, "wide.masked.gather");
3609 } else {
3610 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3611 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3612 }
3613 NewLI->addParamAttr(
3615 applyMetadata(*NewLI);
3616 Instruction *Res = NewLI;
3617 State.set(this, Res);
3618}
3619
3621 VPCostContext &Ctx) const {
3622 if (!Consecutive || IsMasked)
3623 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3624
3625 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3626 // here because the EVL recipes using EVL to replace the tail mask. But in the
3627 // legacy model, it will always calculate the cost of mask.
3628 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3629 // don't need to compare to the legacy cost model.
3631 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3632 ->getAddressSpace();
3633 return Ctx.TTI.getMemIntrinsicInstrCost(
3634 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
3635 Ctx.CostKind);
3636}
3637
3638#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3640 VPSlotTracker &SlotTracker) const {
3641 O << Indent << "WIDEN ";
3643 O << " = vp.load ";
3645}
3646#endif
3647
3649 VPValue *StoredVPValue = getStoredValue();
3650 bool CreateScatter = !isConsecutive();
3651
3652 auto &Builder = State.Builder;
3653
3654 Value *Mask = nullptr;
3655 if (auto *VPMask = getMask()) {
3656 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3657 // of a null all-one mask is a null mask.
3658 Mask = State.get(VPMask);
3659 if (isReverse())
3660 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3661 }
3662
3663 Value *StoredVal = State.get(StoredVPValue);
3664 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3665 Instruction *NewSI = nullptr;
3666 if (CreateScatter)
3667 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3668 else if (Mask)
3669 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3670 else
3671 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3672 applyMetadata(*NewSI);
3673}
3674
3675#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3677 VPSlotTracker &SlotTracker) const {
3678 O << Indent << "WIDEN store ";
3680}
3681#endif
3682
3684 VPValue *StoredValue = getStoredValue();
3685 bool CreateScatter = !isConsecutive();
3686
3687 auto &Builder = State.Builder;
3688
3689 CallInst *NewSI = nullptr;
3690 Value *StoredVal = State.get(StoredValue);
3691 Value *EVL = State.get(getEVL(), VPLane(0));
3692 Value *Mask = nullptr;
3693 if (VPValue *VPMask = getMask()) {
3694 Mask = State.get(VPMask);
3695 if (isReverse())
3696 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3697 } else {
3698 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3699 }
3700 Value *Addr = State.get(getAddr(), !CreateScatter);
3701 if (CreateScatter) {
3702 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3703 Intrinsic::vp_scatter,
3704 {StoredVal, Addr, Mask, EVL});
3705 } else {
3706 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3707 Intrinsic::vp_store,
3708 {StoredVal, Addr, Mask, EVL});
3709 }
3710 NewSI->addParamAttr(
3712 applyMetadata(*NewSI);
3713}
3714
3716 VPCostContext &Ctx) const {
3717 if (!Consecutive || IsMasked)
3718 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3719
3720 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
3721 // here because the EVL recipes using EVL to replace the tail mask. But in the
3722 // legacy model, it will always calculate the cost of mask.
3723 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
3724 // don't need to compare to the legacy cost model.
3726 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3727 ->getAddressSpace();
3728 return Ctx.TTI.getMemIntrinsicInstrCost(
3729 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
3730 Ctx.CostKind);
3731}
3732
3733#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3735 VPSlotTracker &SlotTracker) const {
3736 O << Indent << "WIDEN vp.store ";
3738}
3739#endif
3740
3742 VectorType *DstVTy, const DataLayout &DL) {
3743 // Verify that V is a vector type with same number of elements as DstVTy.
3744 auto VF = DstVTy->getElementCount();
3745 auto *SrcVecTy = cast<VectorType>(V->getType());
3746 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3747 Type *SrcElemTy = SrcVecTy->getElementType();
3748 Type *DstElemTy = DstVTy->getElementType();
3749 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3750 "Vector elements must have same size");
3751
3752 // Do a direct cast if element types are castable.
3753 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3754 return Builder.CreateBitOrPointerCast(V, DstVTy);
3755 }
3756 // V cannot be directly casted to desired vector type.
3757 // May happen when V is a floating point vector but DstVTy is a vector of
3758 // pointers or vice-versa. Handle this using a two-step bitcast using an
3759 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3760 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3761 "Only one type should be a pointer type");
3762 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3763 "Only one type should be a floating point type");
3764 Type *IntTy =
3765 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3766 auto *VecIntTy = VectorType::get(IntTy, VF);
3767 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3768 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3769}
3770
3771/// Return a vector containing interleaved elements from multiple
3772/// smaller input vectors.
3774 const Twine &Name) {
3775 unsigned Factor = Vals.size();
3776 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
3777
3778 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
3779#ifndef NDEBUG
3780 for (Value *Val : Vals)
3781 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
3782#endif
3783
3784 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
3785 // must use intrinsics to interleave.
3786 if (VecTy->isScalableTy()) {
3787 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
3788 return Builder.CreateVectorInterleave(Vals, Name);
3789 }
3790
3791 // Fixed length. Start by concatenating all vectors into a wide vector.
3792 Value *WideVec = concatenateVectors(Builder, Vals);
3793
3794 // Interleave the elements into the wide vector.
3795 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3796 return Builder.CreateShuffleVector(
3797 WideVec, createInterleaveMask(NumElts, Factor), Name);
3798}
3799
3800// Try to vectorize the interleave group that \p Instr belongs to.
3801//
3802// E.g. Translate following interleaved load group (factor = 3):
3803// for (i = 0; i < N; i+=3) {
3804// R = Pic[i]; // Member of index 0
3805// G = Pic[i+1]; // Member of index 1
3806// B = Pic[i+2]; // Member of index 2
3807// ... // do something to R, G, B
3808// }
3809// To:
3810// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
3811// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
3812// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
3813// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
3814//
3815// Or translate following interleaved store group (factor = 3):
3816// for (i = 0; i < N; i+=3) {
3817// ... do something to R, G, B
3818// Pic[i] = R; // Member of index 0
3819// Pic[i+1] = G; // Member of index 1
3820// Pic[i+2] = B; // Member of index 2
3821// }
3822// To:
3823// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
3824// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
3825// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
3826// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
3827// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
3829 assert(!State.Lane && "Interleave group being replicated.");
3830 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
3831 "Masking gaps for scalable vectors is not yet supported.");
3833 Instruction *Instr = Group->getInsertPos();
3834
3835 // Prepare for the vector type of the interleaved load/store.
3836 Type *ScalarTy = getLoadStoreType(Instr);
3837 unsigned InterleaveFactor = Group->getFactor();
3838 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
3839
3840 VPValue *BlockInMask = getMask();
3841 VPValue *Addr = getAddr();
3842 Value *ResAddr = State.get(Addr, VPLane(0));
3843
3844 auto CreateGroupMask = [&BlockInMask, &State,
3845 &InterleaveFactor](Value *MaskForGaps) -> Value * {
3846 if (State.VF.isScalable()) {
3847 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
3848 assert(InterleaveFactor <= 8 &&
3849 "Unsupported deinterleave factor for scalable vectors");
3850 auto *ResBlockInMask = State.get(BlockInMask);
3851 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
3852 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
3853 }
3854
3855 if (!BlockInMask)
3856 return MaskForGaps;
3857
3858 Value *ResBlockInMask = State.get(BlockInMask);
3859 Value *ShuffledMask = State.Builder.CreateShuffleVector(
3860 ResBlockInMask,
3861 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
3862 "interleaved.mask");
3863 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
3864 ShuffledMask, MaskForGaps)
3865 : ShuffledMask;
3866 };
3867
3868 const DataLayout &DL = Instr->getDataLayout();
3869 // Vectorize the interleaved load group.
3870 if (isa<LoadInst>(Instr)) {
3871 Value *MaskForGaps = nullptr;
3872 if (needsMaskForGaps()) {
3873 MaskForGaps =
3874 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
3875 assert(MaskForGaps && "Mask for Gaps is required but it is null");
3876 }
3877
3878 Instruction *NewLoad;
3879 if (BlockInMask || MaskForGaps) {
3880 Value *GroupMask = CreateGroupMask(MaskForGaps);
3881 Value *PoisonVec = PoisonValue::get(VecTy);
3882 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
3883 Group->getAlign(), GroupMask,
3884 PoisonVec, "wide.masked.vec");
3885 } else
3886 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
3887 Group->getAlign(), "wide.vec");
3888 applyMetadata(*NewLoad);
3889 // TODO: Also manage existing metadata using VPIRMetadata.
3890 Group->addMetadata(NewLoad);
3891
3893 if (VecTy->isScalableTy()) {
3894 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
3895 // so must use intrinsics to deinterleave.
3896 assert(InterleaveFactor <= 8 &&
3897 "Unsupported deinterleave factor for scalable vectors");
3898 NewLoad = State.Builder.CreateIntrinsic(
3899 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
3900 NewLoad->getType(), NewLoad,
3901 /*FMFSource=*/nullptr, "strided.vec");
3902 }
3903
3904 auto CreateStridedVector = [&InterleaveFactor, &State,
3905 &NewLoad](unsigned Index) -> Value * {
3906 assert(Index < InterleaveFactor && "Illegal group index");
3907 if (State.VF.isScalable())
3908 return State.Builder.CreateExtractValue(NewLoad, Index);
3909
3910 // For fixed length VF, use shuffle to extract the sub-vectors from the
3911 // wide load.
3912 auto StrideMask =
3913 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
3914 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
3915 "strided.vec");
3916 };
3917
3918 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
3919 Instruction *Member = Group->getMember(I);
3920
3921 // Skip the gaps in the group.
3922 if (!Member)
3923 continue;
3924
3925 Value *StridedVec = CreateStridedVector(I);
3926
3927 // If this member has different type, cast the result type.
3928 if (Member->getType() != ScalarTy) {
3929 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
3930 StridedVec =
3931 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
3932 }
3933
3934 if (Group->isReverse())
3935 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
3936
3937 State.set(VPDefs[J], StridedVec);
3938 ++J;
3939 }
3940 return;
3941 }
3942
3943 // The sub vector type for current instruction.
3944 auto *SubVT = VectorType::get(ScalarTy, State.VF);
3945
3946 // Vectorize the interleaved store group.
3947 Value *MaskForGaps =
3948 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
3949 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
3950 "Mismatch between NeedsMaskForGaps and MaskForGaps");
3951 ArrayRef<VPValue *> StoredValues = getStoredValues();
3952 // Collect the stored vector from each member.
3953 SmallVector<Value *, 4> StoredVecs;
3954 unsigned StoredIdx = 0;
3955 for (unsigned i = 0; i < InterleaveFactor; i++) {
3956 assert((Group->getMember(i) || MaskForGaps) &&
3957 "Fail to get a member from an interleaved store group");
3958 Instruction *Member = Group->getMember(i);
3959
3960 // Skip the gaps in the group.
3961 if (!Member) {
3962 Value *Undef = PoisonValue::get(SubVT);
3963 StoredVecs.push_back(Undef);
3964 continue;
3965 }
3966
3967 Value *StoredVec = State.get(StoredValues[StoredIdx]);
3968 ++StoredIdx;
3969
3970 if (Group->isReverse())
3971 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
3972
3973 // If this member has different type, cast it to a unified type.
3974
3975 if (StoredVec->getType() != SubVT)
3976 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
3977
3978 StoredVecs.push_back(StoredVec);
3979 }
3980
3981 // Interleave all the smaller vectors into one wider vector.
3982 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
3983 Instruction *NewStoreInstr;
3984 if (BlockInMask || MaskForGaps) {
3985 Value *GroupMask = CreateGroupMask(MaskForGaps);
3986 NewStoreInstr = State.Builder.CreateMaskedStore(
3987 IVec, ResAddr, Group->getAlign(), GroupMask);
3988 } else
3989 NewStoreInstr =
3990 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
3991
3992 applyMetadata(*NewStoreInstr);
3993 // TODO: Also manage existing metadata using VPIRMetadata.
3994 Group->addMetadata(NewStoreInstr);
3995}
3996
3997#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3999 VPSlotTracker &SlotTracker) const {
4001 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4002 IG->getInsertPos()->printAsOperand(O, false);
4003 O << ", ";
4005 VPValue *Mask = getMask();
4006 if (Mask) {
4007 O << ", ";
4008 Mask->printAsOperand(O, SlotTracker);
4009 }
4010
4011 unsigned OpIdx = 0;
4012 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4013 if (!IG->getMember(i))
4014 continue;
4015 if (getNumStoreOperands() > 0) {
4016 O << "\n" << Indent << " store ";
4018 O << " to index " << i;
4019 } else {
4020 O << "\n" << Indent << " ";
4022 O << " = load from index " << i;
4023 }
4024 ++OpIdx;
4025 }
4026}
4027#endif
4028
4030 assert(!State.Lane && "Interleave group being replicated.");
4031 assert(State.VF.isScalable() &&
4032 "Only support scalable VF for EVL tail-folding.");
4034 "Masking gaps for scalable vectors is not yet supported.");
4036 Instruction *Instr = Group->getInsertPos();
4037
4038 // Prepare for the vector type of the interleaved load/store.
4039 Type *ScalarTy = getLoadStoreType(Instr);
4040 unsigned InterleaveFactor = Group->getFactor();
4041 assert(InterleaveFactor <= 8 &&
4042 "Unsupported deinterleave/interleave factor for scalable vectors");
4043 ElementCount WideVF = State.VF * InterleaveFactor;
4044 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4045
4046 VPValue *Addr = getAddr();
4047 Value *ResAddr = State.get(Addr, VPLane(0));
4048 Value *EVL = State.get(getEVL(), VPLane(0));
4049 Value *InterleaveEVL = State.Builder.CreateMul(
4050 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4051 /* NUW= */ true, /* NSW= */ true);
4052 LLVMContext &Ctx = State.Builder.getContext();
4053
4054 Value *GroupMask = nullptr;
4055 if (VPValue *BlockInMask = getMask()) {
4056 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4057 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4058 } else {
4059 GroupMask =
4060 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4061 }
4062
4063 // Vectorize the interleaved load group.
4064 if (isa<LoadInst>(Instr)) {
4065 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4066 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4067 "wide.vp.load");
4068 NewLoad->addParamAttr(0,
4069 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4070
4071 applyMetadata(*NewLoad);
4072 // TODO: Also manage existing metadata using VPIRMetadata.
4073 Group->addMetadata(NewLoad);
4074
4075 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4076 // so must use intrinsics to deinterleave.
4077 NewLoad = State.Builder.CreateIntrinsic(
4078 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4079 NewLoad->getType(), NewLoad,
4080 /*FMFSource=*/nullptr, "strided.vec");
4081
4082 const DataLayout &DL = Instr->getDataLayout();
4083 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4084 Instruction *Member = Group->getMember(I);
4085 // Skip the gaps in the group.
4086 if (!Member)
4087 continue;
4088
4089 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4090 // If this member has different type, cast the result type.
4091 if (Member->getType() != ScalarTy) {
4092 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4093 StridedVec =
4094 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4095 }
4096
4097 State.set(getVPValue(J), StridedVec);
4098 ++J;
4099 }
4100 return;
4101 } // End for interleaved load.
4102
4103 // The sub vector type for current instruction.
4104 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4105 // Vectorize the interleaved store group.
4106 ArrayRef<VPValue *> StoredValues = getStoredValues();
4107 // Collect the stored vector from each member.
4108 SmallVector<Value *, 4> StoredVecs;
4109 const DataLayout &DL = Instr->getDataLayout();
4110 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4111 Instruction *Member = Group->getMember(I);
4112 // Skip the gaps in the group.
4113 if (!Member) {
4114 StoredVecs.push_back(PoisonValue::get(SubVT));
4115 continue;
4116 }
4117
4118 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4119 // If this member has different type, cast it to a unified type.
4120 if (StoredVec->getType() != SubVT)
4121 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4122
4123 StoredVecs.push_back(StoredVec);
4124 ++StoredIdx;
4125 }
4126
4127 // Interleave all the smaller vectors into one wider vector.
4128 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4129 CallInst *NewStore =
4130 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4131 {IVec, ResAddr, GroupMask, InterleaveEVL});
4132 NewStore->addParamAttr(1,
4133 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4134
4135 applyMetadata(*NewStore);
4136 // TODO: Also manage existing metadata using VPIRMetadata.
4137 Group->addMetadata(NewStore);
4138}
4139
4140#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4142 VPSlotTracker &SlotTracker) const {
4144 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4145 IG->getInsertPos()->printAsOperand(O, false);
4146 O << ", ";
4148 O << ", ";
4150 if (VPValue *Mask = getMask()) {
4151 O << ", ";
4152 Mask->printAsOperand(O, SlotTracker);
4153 }
4154
4155 unsigned OpIdx = 0;
4156 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4157 if (!IG->getMember(i))
4158 continue;
4159 if (getNumStoreOperands() > 0) {
4160 O << "\n" << Indent << " vp.store ";
4162 O << " to index " << i;
4163 } else {
4164 O << "\n" << Indent << " ";
4166 O << " = vp.load from index " << i;
4167 }
4168 ++OpIdx;
4169 }
4170}
4171#endif
4172
4174 VPCostContext &Ctx) const {
4175 Instruction *InsertPos = getInsertPos();
4176 // Find the VPValue index of the interleave group. We need to skip gaps.
4177 unsigned InsertPosIdx = 0;
4178 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4179 if (auto *Member = IG->getMember(Idx)) {
4180 if (Member == InsertPos)
4181 break;
4182 InsertPosIdx++;
4183 }
4184 Type *ValTy = Ctx.Types.inferScalarType(
4185 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4186 : getStoredValues()[InsertPosIdx]);
4187 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4188 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4189 ->getAddressSpace();
4190
4191 unsigned InterleaveFactor = IG->getFactor();
4192 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4193
4194 // Holds the indices of existing members in the interleaved group.
4196 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4197 if (IG->getMember(IF))
4198 Indices.push_back(IF);
4199
4200 // Calculate the cost of the whole interleaved group.
4201 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4202 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4203 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4204
4205 if (!IG->isReverse())
4206 return Cost;
4207
4208 return Cost + IG->getNumMembers() *
4209 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4210 VectorTy, VectorTy, {}, Ctx.CostKind,
4211 0);
4212}
4213
4214#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4216 VPSlotTracker &SlotTracker) const {
4217 O << Indent << "EMIT ";
4219 O << " = CANONICAL-INDUCTION ";
4221}
4222#endif
4223
4225 return vputils::onlyScalarValuesUsed(this) &&
4226 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4227}
4228
4229#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4231 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4232 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4233 "unexpected number of operands");
4234 O << Indent << "EMIT ";
4236 O << " = WIDEN-POINTER-INDUCTION ";
4238 O << ", ";
4240 O << ", ";
4242 if (getNumOperands() == 5) {
4243 O << ", ";
4245 O << ", ";
4247 }
4248}
4249
4251 VPSlotTracker &SlotTracker) const {
4252 O << Indent << "EMIT ";
4254 O << " = EXPAND SCEV " << *Expr;
4255}
4256#endif
4257
4259 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4260 Type *STy = CanonicalIV->getType();
4261 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4262 ElementCount VF = State.VF;
4263 Value *VStart = VF.isScalar()
4264 ? CanonicalIV
4265 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4266 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4267 if (VF.isVector()) {
4268 VStep = Builder.CreateVectorSplat(VF, VStep);
4269 VStep =
4270 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4271 }
4272 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4273 State.set(this, CanonicalVectorIV);
4274}
4275
4276#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4278 VPSlotTracker &SlotTracker) const {
4279 O << Indent << "EMIT ";
4281 O << " = WIDEN-CANONICAL-INDUCTION ";
4283}
4284#endif
4285
4287 auto &Builder = State.Builder;
4288 // Create a vector from the initial value.
4289 auto *VectorInit = getStartValue()->getLiveInIRValue();
4290
4291 Type *VecTy = State.VF.isScalar()
4292 ? VectorInit->getType()
4293 : VectorType::get(VectorInit->getType(), State.VF);
4294
4295 BasicBlock *VectorPH =
4296 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4297 if (State.VF.isVector()) {
4298 auto *IdxTy = Builder.getInt32Ty();
4299 auto *One = ConstantInt::get(IdxTy, 1);
4300 IRBuilder<>::InsertPointGuard Guard(Builder);
4301 Builder.SetInsertPoint(VectorPH->getTerminator());
4302 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4303 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4304 VectorInit = Builder.CreateInsertElement(
4305 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4306 }
4307
4308 // Create a phi node for the new recurrence.
4309 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4310 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4311 Phi->addIncoming(VectorInit, VectorPH);
4312 State.set(this, Phi);
4313}
4314
4317 VPCostContext &Ctx) const {
4318 if (VF.isScalar())
4319 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4320
4321 return 0;
4322}
4323
4324#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4326 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4327 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4329 O << " = phi ";
4331}
4332#endif
4333
4335 // Reductions do not have to start at zero. They can start with
4336 // any loop invariant values.
4337 VPValue *StartVPV = getStartValue();
4338
4339 // In order to support recurrences we need to be able to vectorize Phi nodes.
4340 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4341 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4342 // this value when we vectorize all of the instructions that use the PHI.
4343 BasicBlock *VectorPH =
4344 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4345 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4346 Value *StartV = State.get(StartVPV, ScalarPHI);
4347 Type *VecTy = StartV->getType();
4348
4349 BasicBlock *HeaderBB = State.CFG.PrevBB;
4350 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4351 "recipe must be in the vector loop header");
4352 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4353 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4354 State.set(this, Phi, isInLoop());
4355
4356 Phi->addIncoming(StartV, VectorPH);
4357}
4358
4359#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4361 VPSlotTracker &SlotTracker) const {
4362 O << Indent << "WIDEN-REDUCTION-PHI ";
4363
4365 O << " = phi ";
4367 if (getVFScaleFactor() > 1)
4368 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4369}
4370#endif
4371
4373 Value *Op0 = State.get(getOperand(0));
4374 Type *VecTy = Op0->getType();
4375 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4376 State.set(this, VecPhi);
4377}
4378
4379#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4381 VPSlotTracker &SlotTracker) const {
4382 O << Indent << "WIDEN-PHI ";
4383
4385 O << " = phi ";
4387}
4388#endif
4389
4391 BasicBlock *VectorPH =
4392 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4393 Value *StartMask = State.get(getOperand(0));
4394 PHINode *Phi =
4395 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4396 Phi->addIncoming(StartMask, VectorPH);
4397 State.set(this, Phi);
4398}
4399
4400#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4402 VPSlotTracker &SlotTracker) const {
4403 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4404
4406 O << " = phi ";
4408}
4409#endif
4410
4411#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4413 VPSlotTracker &SlotTracker) const {
4414 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
4415
4417 O << " = phi ";
4419}
4420#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, LoopVectorizationLegality *Legal, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isOrdered(const Instruction *I)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static InstructionCost getCostForIntrinsics(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost for the intrinsic ID with Operands, produced by R.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
SmallVector< Value *, 2 > VectorParts
static bool isUsedByLoadStoreAddress(const VPUser *V)
Returns true if V is used as part of the address of another load or store.
static void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
static Constant * getSignedIntOrFpConstant(Type *Ty, int64_t C)
A helper function that returns an integer or floating-point constant with value C.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition InstrTypes.h:982
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:136
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:123
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:324
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:272
void setAllowContract(bool B=true)
Definition FMF.h:90
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setAllowReciprocal(bool B=true)
Definition FMF.h:87
bool allowReciprocal() const
Definition FMF.h:68
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool approxFunc() const
Definition FMF.h:70
void setNoNaNs(bool B=true)
Definition FMF.h:78
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:75
bool noNaNs() const
Definition FMF.h:65
void setApproxFunc(bool B=true)
Definition FMF.h:93
void setNoInfs(bool B=true)
Definition FMF.h:81
bool allowContract() const
Definition FMF.h:69
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
bool willReturn() const
Determine if the function will return.
Definition Function.h:661
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:594
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:214
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2579
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:547
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2633
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2567
LLVM_ABI Value * CreateVectorSplice(Value *V1, Value *V2, int64_t Imm, const Twine &Name="")
Return a vector splice intrinsic if using scalable vectors, otherwise return a shufflevector.
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2626
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:2645
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:562
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2039
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:345
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:567
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2336
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:527
LLVM_ABI CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1725
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:522
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2466
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1808
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2332
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1134
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1420
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1197
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2085
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1403
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:507
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1708
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2344
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2442
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1573
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1437
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
static InstructionCost getInvalid(CostType Val=0)
bool isCast() const
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const char * getOpcodeName() const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:318
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isReverse() const
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Information for memory intrinsic cost model.
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static bool isSignedRecurrenceKind(RecurKind Kind)
Returns true if recurrece kind is a signed redux kind.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindLastIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
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
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.
@ TCC_Free
Expected to fold away in lowering.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Reverse
Reverse the order of the vector.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ None
The cast is not used with a load/store of any kind.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
value_op_iterator value_op_end()
Definition User.h:313
void setOperand(unsigned i, Value *Val)
Definition User.h:237
Value * getOperand(unsigned i) const
Definition User.h:232
value_op_iterator value_op_begin()
Definition User.h:310
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4035
iterator end()
Definition VPlan.h:4019
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4048
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:2559
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2554
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:204
VPlan * getPlan()
Definition VPlan.cpp:161
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:349
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPBranchOnMaskRecipe.
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
VPlan-based builder utility analogous to IRBuilder.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
This class augments a recipe with a set of VPValues defined by the recipe.
Definition VPlanValue.h:305
LLVM_ABI_FOR_TEST void dump() const
Dump the VPDef to stderr (for debugging).
Definition VPlan.cpp:122
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:426
ArrayRef< VPValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:421
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:399
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:411
friend class VPValue
Definition VPlanValue.h:306
unsigned getVPDefID() const
Definition VPlanValue.h:431
VPValue * getStepValue() const
Definition VPlan.h:3782
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStartValue() const
Definition VPlan.h:3781
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
bool isSingleScalar() const
Returns true if the result of this VPExpressionRecipe is a single-scalar.
bool mayHaveSideEffects() const
Returns true if this expression contains recipes that may have side effects.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
bool mayReadOrWriteMemory() const
Returns true if this expression contains recipes that may read from or write to memory.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2088
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:1789
Class to record and manage LLVM IR flags.
Definition VPlan.h:609
FastMathFlagsTy FMFs
Definition VPlan.h:680
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:674
CmpInst::Predicate CmpPredicate
Definition VPlan.h:673
void printFlags(raw_ostream &O) const
GEPNoWrapFlags GEPFlags
Definition VPlan.h:678
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:858
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
TruncFlagsTy TruncFlags
Definition VPlan.h:675
CmpInst::Predicate getPredicate() const
Definition VPlan.h:835
ExactFlagsTy ExactFlags
Definition VPlan.h:677
bool hasNoSignedWrap() const
Definition VPlan.h:884
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:850
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:853
DisjointFlagsTy DisjointFlags
Definition VPlan.h:676
unsigned AllFlags
Definition VPlan.h:682
bool hasNoUnsignedWrap() const
Definition VPlan.h:873
FCmpFlagsTy FCmpFlags
Definition VPlan.h:681
NonNegFlagsTy NonNegFlags
Definition VPlan.h:679
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:795
Instruction & getInstruction() const
Definition VPlan.h:1451
void extractLastLaneOfLastPartOfFirstOperand(VPBuilder &Builder)
Update the recipe's first operand to the last lane of the last part of the operand using Builder.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1426
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
VPIRMetadata()=default
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print metadata with node IDs.
void applyMetadata(Instruction &I) const
Add all metadata to I.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the instruction.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
bool doesGeneratePerAllLanes() const
Returns true if this VPInstruction generates scalar values for all lanes.
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1131
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1076
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1121
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1134
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1073
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1125
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1068
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1065
@ VScale
Returns the value for vscale.
Definition VPlan.h:1136
@ CanonicalIVIncrementForPart
Definition VPlan.h:1056
bool hasResult() const
Definition VPlan.h:1202
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:1242
unsigned getOpcode() const
Definition VPlan.h:1186
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
bool isSingleScalar() const
Returns true if this VPInstruction's operands are single scalars and the result is also a single scal...
void execute(VPTransformState &State) override
Generate the instruction.
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:2670
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2674
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2672
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2664
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2693
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2658
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2768
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:2781
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:2731
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1341
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:4126
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:1366
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1333
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:387
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
virtual void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPRecipe prints itself, without printing common information, like debug info or metadat...
VPRegionBlock * getRegion()
Definition VPlan.h:4287
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override final
Print the recipe, delegating to printRecipe().
bool isPhi() const
Returns true for PHI-like recipes.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
virtual InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
VPBasicBlock * getParent()
Definition VPlan.h:408
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:479
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
bool isScalarCast() const
Return true if the recipe is a scalar cast.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:398
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:2931
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:2476
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2500
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:2873
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:2884
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:2886
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:2869
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:2875
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:2882
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:2877
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:4170
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4238
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:2953
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:2994
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:3023
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:3848
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:531
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:595
LLVM_ABI_FOR_TEST LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:533
This class can be used to assign names to VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
Helper to access the operand that contains the unroll part for this recipe after unrolling.
Definition VPlan.h:970
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:202
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1419
operand_range operands()
Definition VPlanValue.h:270
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:246
unsigned getNumOperands() const
Definition VPlanValue.h:240
operand_iterator op_begin()
Definition VPlanValue.h:266
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:241
virtual bool usesFirstLaneOnly(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:285
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:46
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1373
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:131
friend class VPExpressionRecipe
Definition VPlanValue.h:51
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1415
Value * getLiveInIRValue() const
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition VPlanValue.h:181
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:83
VPValue(const unsigned char SC, Value *UV=nullptr, VPDef *Def=nullptr)
Definition VPlan.cpp:94
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1376
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the VPlan.
Definition VPlanValue.h:176
user_range users()
Definition VPlanValue.h:132
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:1993
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:1745
Function * getCalledScalarFunction() const
Definition VPlan.h:1741
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:1595
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:1891
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.
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2151
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2258
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2267
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:1677
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:1680
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:3278
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3275
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3318
Instruction & Ingredient
Definition VPlan.h:3266
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:3272
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3332
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3269
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3325
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3322
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
void execute(VPTransformState &State) override
Produce a widened instruction using the opcode and operands of the recipe, processing State....
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getUF() const
Definition VPlan.h:4521
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1010
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:390
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1099
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:838
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition TypeSize.h:256
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
iterator erase(iterator where)
Definition ilist.h:204
pointer remove(iterator &IT)
Definition ilist.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
bool match(Val *V, const Pattern &P)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
GEPLikeRecipe_match< Op0_t, Op1_t > m_GetElementPtr(const Op0_t &Op0, const Op1_t &Op1)
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 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, ScalarEvolution &SE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:532
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:829
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI Value * createFindLastIVReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind, Value *Start, Value *Sentinel)
Create a reduction of the given vector Src for a reduction of the kind RecurKind::FindLastIV.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
constexpr 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:1759
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2503
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:2157
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2262
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.
constexpr bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
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)
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
cl::opt< unsigned > ForceTargetInstructionCost
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
@ Other
Any other memory.
Definition ModRef.h:68
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
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()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ 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
constexpr 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:1748
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1918
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.
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 Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, Value *InitVal, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of kind RecurKind::AnyOf.
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Struct to hold various analysis needed for cost computations.
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:1489
PHINode & getIRPhi()
Definition VPlan.h:1497
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:923
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:924
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:263
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:3409
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 * getCond() const
Definition VPlan.h:1832
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenSelectRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the select instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3492
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:3495
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:3455