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"
40#include <cassert>
41
42using namespace llvm;
43using namespace llvm::VPlanPatternMatch;
44
46
47#define LV_NAME "loop-vectorize"
48#define DEBUG_TYPE LV_NAME
49
51 switch (getVPDefID()) {
52 case VPExpressionSC:
53 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
54 case VPInstructionSC:
55 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
56 case VPInterleaveEVLSC:
57 case VPInterleaveSC:
58 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
59 case VPWidenStoreEVLSC:
60 case VPWidenStoreSC:
61 return true;
62 case VPReplicateSC:
63 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
64 ->mayWriteToMemory();
65 case VPWidenCallSC:
66 return !cast<VPWidenCallRecipe>(this)
67 ->getCalledScalarFunction()
68 ->onlyReadsMemory();
69 case VPWidenIntrinsicSC:
70 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
71 case VPCanonicalIVPHISC:
72 case VPBranchOnMaskSC:
73 case VPFirstOrderRecurrencePHISC:
74 case VPReductionPHISC:
75 case VPScalarIVStepsSC:
76 case VPPredInstPHISC:
77 return false;
78 case VPBlendSC:
79 case VPReductionEVLSC:
80 case VPReductionSC:
81 case VPVectorPointerSC:
82 case VPWidenCanonicalIVSC:
83 case VPWidenCastSC:
84 case VPWidenGEPSC:
85 case VPWidenIntOrFpInductionSC:
86 case VPWidenLoadEVLSC:
87 case VPWidenLoadSC:
88 case VPWidenPHISC:
89 case VPWidenSC:
90 case VPWidenSelectSC: {
91 const Instruction *I =
92 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
93 (void)I;
94 assert((!I || !I->mayWriteToMemory()) &&
95 "underlying instruction may write to memory");
96 return false;
97 }
98 default:
99 return true;
100 }
101}
102
104 switch (getVPDefID()) {
105 case VPExpressionSC:
106 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
107 case VPInstructionSC:
108 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
109 case VPWidenLoadEVLSC:
110 case VPWidenLoadSC:
111 return true;
112 case VPReplicateSC:
113 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
114 ->mayReadFromMemory();
115 case VPWidenCallSC:
116 return !cast<VPWidenCallRecipe>(this)
117 ->getCalledScalarFunction()
118 ->onlyWritesMemory();
119 case VPWidenIntrinsicSC:
120 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
121 case VPBranchOnMaskSC:
122 case VPFirstOrderRecurrencePHISC:
123 case VPPredInstPHISC:
124 case VPScalarIVStepsSC:
125 case VPWidenStoreEVLSC:
126 case VPWidenStoreSC:
127 return false;
128 case VPBlendSC:
129 case VPReductionEVLSC:
130 case VPReductionSC:
131 case VPVectorPointerSC:
132 case VPWidenCanonicalIVSC:
133 case VPWidenCastSC:
134 case VPWidenGEPSC:
135 case VPWidenIntOrFpInductionSC:
136 case VPWidenPHISC:
137 case VPWidenSC:
138 case VPWidenSelectSC: {
139 const Instruction *I =
140 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
141 (void)I;
142 assert((!I || !I->mayReadFromMemory()) &&
143 "underlying instruction may read from memory");
144 return false;
145 }
146 default:
147 // FIXME: Return false if the recipe represents an interleaved store.
148 return true;
149 }
150}
151
153 switch (getVPDefID()) {
154 case VPExpressionSC:
155 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
156 case VPDerivedIVSC:
157 case VPFirstOrderRecurrencePHISC:
158 case VPPredInstPHISC:
159 case VPVectorEndPointerSC:
160 return false;
161 case VPInstructionSC:
162 return mayWriteToMemory();
163 case VPWidenCallSC: {
164 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
165 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
166 }
167 case VPWidenIntrinsicSC:
168 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
169 case VPBlendSC:
170 case VPReductionEVLSC:
171 case VPReductionSC:
172 case VPScalarIVStepsSC:
173 case VPVectorPointerSC:
174 case VPWidenCanonicalIVSC:
175 case VPWidenCastSC:
176 case VPWidenGEPSC:
177 case VPWidenIntOrFpInductionSC:
178 case VPWidenPHISC:
179 case VPWidenPointerInductionSC:
180 case VPWidenSC:
181 case VPWidenSelectSC: {
182 const Instruction *I =
183 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
184 (void)I;
185 assert((!I || !I->mayHaveSideEffects()) &&
186 "underlying instruction has side-effects");
187 return false;
188 }
189 case VPInterleaveEVLSC:
190 case VPInterleaveSC:
191 return mayWriteToMemory();
192 case VPWidenLoadEVLSC:
193 case VPWidenLoadSC:
194 case VPWidenStoreEVLSC:
195 case VPWidenStoreSC:
196 assert(
197 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
199 "mayHaveSideffects result for ingredient differs from this "
200 "implementation");
201 return mayWriteToMemory();
202 case VPReplicateSC: {
203 auto *R = cast<VPReplicateRecipe>(this);
204 return R->getUnderlyingInstr()->mayHaveSideEffects();
205 }
206 default:
207 return true;
208 }
209}
210
212 assert(!Parent && "Recipe already in some VPBasicBlock");
213 assert(InsertPos->getParent() &&
214 "Insertion position not in any VPBasicBlock");
215 InsertPos->getParent()->insert(this, InsertPos->getIterator());
216}
217
218void VPRecipeBase::insertBefore(VPBasicBlock &BB,
220 assert(!Parent && "Recipe already in some VPBasicBlock");
221 assert(I == BB.end() || I->getParent() == &BB);
222 BB.insert(this, I);
223}
224
226 assert(!Parent && "Recipe already in some VPBasicBlock");
227 assert(InsertPos->getParent() &&
228 "Insertion position not in any VPBasicBlock");
229 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
230}
231
233 assert(getParent() && "Recipe not in any VPBasicBlock");
235 Parent = nullptr;
236}
237
239 assert(getParent() && "Recipe not in any VPBasicBlock");
241}
242
245 insertAfter(InsertPos);
246}
247
253
255 // Get the underlying instruction for the recipe, if there is one. It is used
256 // to
257 // * decide if cost computation should be skipped for this recipe,
258 // * apply forced target instruction cost.
259 Instruction *UI = nullptr;
260 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
261 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
262 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
263 UI = IG->getInsertPos();
264 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
265 UI = &WidenMem->getIngredient();
266
267 InstructionCost RecipeCost;
268 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
269 RecipeCost = 0;
270 } else {
271 RecipeCost = computeCost(VF, Ctx);
272 if (UI && ForceTargetInstructionCost.getNumOccurrences() > 0 &&
273 RecipeCost.isValid())
275 }
276
277 LLVM_DEBUG({
278 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
279 dump();
280 });
281 return RecipeCost;
282}
283
285 VPCostContext &Ctx) const {
286 llvm_unreachable("subclasses should implement computeCost");
287}
288
290 return (getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC) ||
292}
293
295 auto *VPI = dyn_cast<VPInstruction>(this);
296 return VPI && Instruction::isCast(VPI->getOpcode());
297}
298
301 VPCostContext &Ctx) const {
302 std::optional<unsigned> Opcode;
303 VPValue *Op = getOperand(0);
304 VPRecipeBase *OpR = Op->getDefiningRecipe();
305
306 // If the partial reduction is predicated, a select will be operand 0
308 OpR = Op->getDefiningRecipe();
309 }
310
311 Type *InputTypeA = nullptr, *InputTypeB = nullptr;
313 ExtBType = TTI::PR_None;
314
315 auto GetExtendKind = [](VPRecipeBase *R) {
316 if (!R)
317 return TTI::PR_None;
318 auto *WidenCastR = dyn_cast<VPWidenCastRecipe>(R);
319 if (!WidenCastR)
320 return TTI::PR_None;
321 if (WidenCastR->getOpcode() == Instruction::CastOps::ZExt)
322 return TTI::PR_ZeroExtend;
323 if (WidenCastR->getOpcode() == Instruction::CastOps::SExt)
324 return TTI::PR_SignExtend;
325 return TTI::PR_None;
326 };
327
328 // Pick out opcode, type/ext information and use sub side effects from a widen
329 // recipe.
330 auto HandleWiden = [&](VPWidenRecipe *Widen) {
331 if (match(Widen, m_Sub(m_ZeroInt(), m_VPValue(Op)))) {
332 Widen = dyn_cast<VPWidenRecipe>(Op->getDefiningRecipe());
333 }
334 Opcode = Widen->getOpcode();
335 VPRecipeBase *ExtAR = Widen->getOperand(0)->getDefiningRecipe();
336 VPRecipeBase *ExtBR = Widen->getOperand(1)->getDefiningRecipe();
337 InputTypeA = Ctx.Types.inferScalarType(ExtAR ? ExtAR->getOperand(0)
338 : Widen->getOperand(0));
339 InputTypeB = Ctx.Types.inferScalarType(ExtBR ? ExtBR->getOperand(0)
340 : Widen->getOperand(1));
341 ExtAType = GetExtendKind(ExtAR);
342 ExtBType = GetExtendKind(ExtBR);
343
344 if (!ExtBR && Widen->getOperand(1)->isLiveIn()) {
345 auto *CI = cast<ConstantInt>(Widen->getOperand(1)->getLiveInIRValue());
346 if (canConstantBeExtended(CI, InputTypeA, ExtAType)) {
347 InputTypeB = InputTypeA;
348 ExtBType = ExtAType;
349 }
350 }
351 };
352
353 if (isa<VPWidenCastRecipe>(OpR)) {
354 InputTypeA = Ctx.Types.inferScalarType(OpR->getOperand(0));
355 ExtAType = GetExtendKind(OpR);
356 } else if (isa<VPReductionPHIRecipe>(OpR)) {
357 auto RedPhiOp1R = getOperand(1)->getDefiningRecipe();
358 if (isa<VPWidenCastRecipe>(RedPhiOp1R)) {
359 InputTypeA = Ctx.Types.inferScalarType(RedPhiOp1R->getOperand(0));
360 ExtAType = GetExtendKind(RedPhiOp1R);
361 } else if (auto Widen = dyn_cast<VPWidenRecipe>(RedPhiOp1R))
362 HandleWiden(Widen);
363 } else if (auto Widen = dyn_cast<VPWidenRecipe>(OpR)) {
364 HandleWiden(Widen);
365 } else if (auto Reduction = dyn_cast<VPPartialReductionRecipe>(OpR)) {
366 return Reduction->computeCost(VF, Ctx);
367 }
368 auto *PhiType = Ctx.Types.inferScalarType(getOperand(1));
369 return Ctx.TTI.getPartialReductionCost(getOpcode(), InputTypeA, InputTypeB,
370 PhiType, VF, ExtAType, ExtBType,
371 Opcode, Ctx.CostKind);
372}
373
375 auto &Builder = State.Builder;
376
377 assert(getOpcode() == Instruction::Add &&
378 "Unhandled partial reduction opcode");
379
380 Value *BinOpVal = State.get(getOperand(1));
381 Value *PhiVal = State.get(getOperand(0));
382 assert(PhiVal && BinOpVal && "Phi and Mul must be set");
383
384 Type *RetTy = PhiVal->getType();
385
386 CallInst *V =
387 Builder.CreateIntrinsic(RetTy, Intrinsic::vector_partial_reduce_add,
388 {PhiVal, BinOpVal}, nullptr, "partial.reduce");
389
390 State.set(this, V);
391}
392
393#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
395 VPSlotTracker &SlotTracker) const {
396 O << Indent << "PARTIAL-REDUCE ";
398 O << " = " << Instruction::getOpcodeName(getOpcode()) << " ";
400}
401#endif
402
404 assert(OpType == Other.OpType && "OpType must match");
405 switch (OpType) {
406 case OperationType::OverflowingBinOp:
407 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
408 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
409 break;
410 case OperationType::Trunc:
411 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
412 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
413 break;
414 case OperationType::DisjointOp:
415 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
416 break;
417 case OperationType::PossiblyExactOp:
418 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
419 break;
420 case OperationType::GEPOp:
421 GEPFlags &= Other.GEPFlags;
422 break;
423 case OperationType::FPMathOp:
424 FMFs.NoNaNs &= Other.FMFs.NoNaNs;
425 FMFs.NoInfs &= Other.FMFs.NoInfs;
426 break;
427 case OperationType::NonNegOp:
428 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
429 break;
430 case OperationType::Cmp:
431 assert(CmpPredicate == Other.CmpPredicate && "Cannot drop CmpPredicate");
432 break;
433 case OperationType::Other:
434 assert(AllFlags == Other.AllFlags && "Cannot drop other flags");
435 break;
436 }
437}
438
440 assert(OpType == OperationType::FPMathOp &&
441 "recipe doesn't have fast math flags");
442 FastMathFlags Res;
443 Res.setAllowReassoc(FMFs.AllowReassoc);
444 Res.setNoNaNs(FMFs.NoNaNs);
445 Res.setNoInfs(FMFs.NoInfs);
446 Res.setNoSignedZeros(FMFs.NoSignedZeros);
447 Res.setAllowReciprocal(FMFs.AllowReciprocal);
448 Res.setAllowContract(FMFs.AllowContract);
449 Res.setApproxFunc(FMFs.ApproxFunc);
450 return Res;
451}
452
453#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
455#endif
456
457template <unsigned PartOpIdx>
458VPValue *
460 if (U.getNumOperands() == PartOpIdx + 1)
461 return U.getOperand(PartOpIdx);
462 return nullptr;
463}
464
465template <unsigned PartOpIdx>
467 if (auto *UnrollPartOp = getUnrollPartOperand(U))
468 return cast<ConstantInt>(UnrollPartOp->getLiveInIRValue())->getZExtValue();
469 return 0;
470}
471
472namespace llvm {
473template class VPUnrollPartAccessor<1>;
474template class VPUnrollPartAccessor<2>;
475template class VPUnrollPartAccessor<3>;
476}
477
479 const VPIRFlags &Flags, DebugLoc DL,
480 const Twine &Name)
481 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, Flags, DL),
482 VPIRMetadata(), Opcode(Opcode), Name(Name.str()) {
484 "Set flags not supported for the provided opcode");
485 assert((getNumOperandsForOpcode(Opcode) == -1u ||
486 getNumOperandsForOpcode(Opcode) == getNumOperands()) &&
487 "number of operands does not match opcode");
488}
489
490#ifndef NDEBUG
491unsigned VPInstruction::getNumOperandsForOpcode(unsigned Opcode) {
492 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
493 return 1;
494
495 if (Instruction::isBinaryOp(Opcode))
496 return 2;
497
498 switch (Opcode) {
501 return 0;
502 case Instruction::Alloca:
503 case Instruction::ExtractValue:
504 case Instruction::Freeze:
505 case Instruction::Load:
517 return 1;
518 case Instruction::ICmp:
519 case Instruction::FCmp:
520 case Instruction::Store:
528 return 2;
529 case Instruction::Select:
533 return 3;
535 return 4;
536 case Instruction::Call:
537 case Instruction::GetElementPtr:
538 case Instruction::PHI:
539 case Instruction::Switch:
540 // Cannot determine the number of operands from the opcode.
541 return -1u;
542 }
543 llvm_unreachable("all cases should be handled above");
544}
545#endif
546
550
551bool VPInstruction::canGenerateScalarForFirstLane() const {
553 return true;
555 return true;
556 switch (Opcode) {
557 case Instruction::Freeze:
558 case Instruction::ICmp:
559 case Instruction::PHI:
560 case Instruction::Select:
569 return true;
570 default:
571 return false;
572 }
573}
574
575/// Create a conditional branch using \p Cond branching to the successors of \p
576/// VPBB. Note that the first successor is always forward (i.e. not created yet)
577/// while the second successor may already have been created (if it is a header
578/// block and VPBB is a latch).
580 VPTransformState &State) {
581 // Replace the temporary unreachable terminator with a new conditional
582 // branch, hooking it up to backward destination (header) for latch blocks
583 // now, and to forward destination(s) later when they are created.
584 // Second successor may be backwards - iff it is already in VPBB2IRBB.
585 VPBasicBlock *SecondVPSucc = cast<VPBasicBlock>(VPBB->getSuccessors()[1]);
586 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
587 BasicBlock *IRBB = State.CFG.VPBB2IRBB[VPBB];
588 BranchInst *CondBr = State.Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
589 // First successor is always forward, reset it to nullptr
590 CondBr->setSuccessor(0, nullptr);
592 return CondBr;
593}
594
595Value *VPInstruction::generate(VPTransformState &State) {
596 IRBuilderBase &Builder = State.Builder;
597
599 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
600 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
601 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
602 auto *Res =
603 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
604 if (auto *I = dyn_cast<Instruction>(Res))
605 applyFlags(*I);
606 return Res;
607 }
608
609 switch (getOpcode()) {
610 case VPInstruction::Not: {
611 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
612 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
613 return Builder.CreateNot(A, Name);
614 }
615 case Instruction::ExtractElement: {
616 assert(State.VF.isVector() && "Only extract elements from vectors");
617 if (getOperand(1)->isLiveIn()) {
618 unsigned IdxToExtract =
619 cast<ConstantInt>(getOperand(1)->getLiveInIRValue())->getZExtValue();
620 return State.get(getOperand(0), VPLane(IdxToExtract));
621 }
622 Value *Vec = State.get(getOperand(0));
623 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
624 return Builder.CreateExtractElement(Vec, Idx, Name);
625 }
626 case Instruction::Freeze: {
628 return Builder.CreateFreeze(Op, Name);
629 }
630 case Instruction::FCmp:
631 case Instruction::ICmp: {
632 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
633 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
634 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
635 return Builder.CreateCmp(getPredicate(), A, B, Name);
636 }
637 case Instruction::PHI: {
638 llvm_unreachable("should be handled by VPPhi::execute");
639 }
640 case Instruction::Select: {
641 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
642 Value *Cond = State.get(getOperand(0), OnlyFirstLaneUsed);
643 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
644 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
645 return Builder.CreateSelect(Cond, Op1, Op2, Name);
646 }
648 // Get first lane of vector induction variable.
649 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
650 // Get the original loop tripcount.
651 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
652
653 // If this part of the active lane mask is scalar, generate the CMP directly
654 // to avoid unnecessary extracts.
655 if (State.VF.isScalar())
656 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
657 Name);
658
659 auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
660 auto PredTy = VectorType::get(
661 Int1Ty, State.VF * cast<ConstantInt>(getOperand(2)->getLiveInIRValue())
662 ->getZExtValue());
663 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
664 {PredTy, ScalarTC->getType()},
665 {VIVElem0, ScalarTC}, nullptr, Name);
666 }
668 // Generate code to combine the previous and current values in vector v3.
669 //
670 // vector.ph:
671 // v_init = vector(..., ..., ..., a[-1])
672 // br vector.body
673 //
674 // vector.body
675 // i = phi [0, vector.ph], [i+4, vector.body]
676 // v1 = phi [v_init, vector.ph], [v2, vector.body]
677 // v2 = a[i, i+1, i+2, i+3];
678 // v3 = vector(v1(3), v2(0, 1, 2))
679
680 auto *V1 = State.get(getOperand(0));
681 if (!V1->getType()->isVectorTy())
682 return V1;
683 Value *V2 = State.get(getOperand(1));
684 return Builder.CreateVectorSplice(V1, V2, -1, Name);
685 }
687 unsigned UF = getParent()->getPlan()->getUF();
688 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
689 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
690 Value *Sub = Builder.CreateSub(ScalarTC, Step);
691 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
692 Value *Zero = ConstantInt::get(ScalarTC->getType(), 0);
693 return Builder.CreateSelect(Cmp, Sub, Zero);
694 }
696 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
697 // be outside of the main loop.
698 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
699 // Compute EVL
700 assert(AVL->getType()->isIntegerTy() &&
701 "Requested vector length should be an integer.");
702
703 assert(State.VF.isScalable() && "Expected scalable vector factor.");
704 Value *VFArg = State.Builder.getInt32(State.VF.getKnownMinValue());
705
706 Value *EVL = State.Builder.CreateIntrinsic(
707 State.Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
708 {AVL, VFArg, State.Builder.getTrue()});
709 return EVL;
710 }
712 unsigned Part = getUnrollPart(*this);
713 auto *IV = State.get(getOperand(0), VPLane(0));
714 assert(Part != 0 && "Must have a positive part");
715 // The canonical IV is incremented by the vectorization factor (num of
716 // SIMD elements) times the unroll part.
717 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
718 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
720 }
722 Value *Cond = State.get(getOperand(0), VPLane(0));
723 auto *Br = createCondBranch(Cond, getParent(), State);
724 applyMetadata(*Br);
725 return Br;
726 }
728 // First create the compare.
729 Value *IV = State.get(getOperand(0), /*IsScalar*/ true);
730 Value *TC = State.get(getOperand(1), /*IsScalar*/ true);
731 Value *Cond = Builder.CreateICmpEQ(IV, TC);
732 return createCondBranch(Cond, getParent(), State);
733 }
735 return Builder.CreateVectorSplat(
736 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
737 }
739 // For struct types, we need to build a new 'wide' struct type, where each
740 // element is widened, i.e., we create a struct of vectors.
741 auto *StructTy =
743 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
744 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
745 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
746 FieldIndex++) {
747 Value *ScalarValue =
748 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
749 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
750 VectorValue =
751 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
752 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
753 }
754 }
755 return Res;
756 }
758 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
759 auto NumOfElements = ElementCount::getFixed(getNumOperands());
760 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
761 for (const auto &[Idx, Op] : enumerate(operands()))
762 Res = State.Builder.CreateInsertElement(Res, State.get(Op, true),
763 State.Builder.getInt32(Idx));
764 return Res;
765 }
767 if (State.VF.isScalar())
768 return State.get(getOperand(0), true);
769 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
771 // If this start vector is scaled then it should produce a vector with fewer
772 // elements than the VF.
773 ElementCount VF = State.VF.divideCoefficientBy(
774 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue());
775 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
776 Constant *Zero = Builder.getInt32(0);
777 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
778 Zero);
779 }
781 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
782 // and will be removed by breaking up the recipe further.
783 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
784 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
785 Value *ReducedPartRdx = State.get(getOperand(2));
786 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
787 ReducedPartRdx = Builder.CreateBinOp(
790 State.get(getOperand(Idx)), ReducedPartRdx, "bin.rdx");
791 return createAnyOfReduction(Builder, ReducedPartRdx,
792 State.get(getOperand(1), VPLane(0)), OrigPhi);
793 }
795 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
796 // and will be removed by breaking up the recipe further.
797 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
798 // Get its reduction variable descriptor.
799 RecurKind RK = PhiR->getRecurrenceKind();
801 "Unexpected reduction kind");
802 assert(!PhiR->isInLoop() &&
803 "In-loop FindLastIV reduction is not supported yet");
804
805 // The recipe's operands are the reduction phi, the start value, the
806 // sentinel value, followed by one operand for each part of the reduction.
807 unsigned UF = getNumOperands() - 3;
808 Value *ReducedPartRdx = State.get(getOperand(3));
809 RecurKind MinMaxKind;
812 MinMaxKind = IsSigned ? RecurKind::SMax : RecurKind::UMax;
813 else
814 MinMaxKind = IsSigned ? RecurKind::SMin : RecurKind::UMin;
815 for (unsigned Part = 1; Part < UF; ++Part)
816 ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
817 State.get(getOperand(3 + Part)));
818
819 Value *Start = State.get(getOperand(1), true);
821 return createFindLastIVReduction(Builder, ReducedPartRdx, RK, Start,
822 Sentinel);
823 }
825 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
826 // and will be removed by breaking up the recipe further.
827 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
828 // Get its reduction variable descriptor.
829
830 RecurKind RK = PhiR->getRecurrenceKind();
832 "should be handled by ComputeFindIVResult");
833
834 // The recipe's operands are the reduction phi, followed by one operand for
835 // each part of the reduction.
836 unsigned UF = getNumOperands() - 1;
837 VectorParts RdxParts(UF);
838 for (unsigned Part = 0; Part < UF; ++Part)
839 RdxParts[Part] = State.get(getOperand(1 + Part), PhiR->isInLoop());
840
841 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
842 if (hasFastMathFlags())
844
845 // Reduce all of the unrolled parts into a single vector.
846 Value *ReducedPartRdx = RdxParts[0];
847 if (PhiR->isOrdered()) {
848 ReducedPartRdx = RdxParts[UF - 1];
849 } else {
850 // Floating-point operations should have some FMF to enable the reduction.
851 for (unsigned Part = 1; Part < UF; ++Part) {
852 Value *RdxPart = RdxParts[Part];
854 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
855 else {
857 // For sub-recurrences, each UF's reduction variable is already
858 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
859 if (RK == RecurKind::Sub)
860 Opcode = Instruction::Add;
861 else
862 Opcode =
864 ReducedPartRdx =
865 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
866 }
867 }
868 }
869
870 // Create the reduction after the loop. Note that inloop reductions create
871 // the target reduction in the loop using a Reduction recipe.
872 if (State.VF.isVector() && !PhiR->isInLoop()) {
873 // TODO: Support in-order reductions based on the recurrence descriptor.
874 // All ops in the reduction inherit fast-math-flags from the recurrence
875 // descriptor.
876 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
877 }
878
879 return ReducedPartRdx;
880 }
883 unsigned Offset = getOpcode() == VPInstruction::ExtractLastElement ? 1 : 2;
884 Value *Res;
885 if (State.VF.isVector()) {
886 assert(Offset <= State.VF.getKnownMinValue() &&
887 "invalid offset to extract from");
888 // Extract lane VF - Offset from the operand.
889 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
890 } else {
891 assert(Offset <= 1 && "invalid offset to extract from");
892 Res = State.get(getOperand(0));
893 }
895 Res->setName(Name);
896 return Res;
897 }
899 Value *A = State.get(getOperand(0));
900 Value *B = State.get(getOperand(1));
901 return Builder.CreateLogicalAnd(A, B, Name);
902 }
905 "can only generate first lane for PtrAdd");
906 Value *Ptr = State.get(getOperand(0), VPLane(0));
907 Value *Addend = State.get(getOperand(1), VPLane(0));
908 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
909 }
911 Value *Ptr =
913 Value *Addend = State.get(getOperand(1));
914 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
915 }
917 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
918 for (VPValue *Op : drop_begin(operands()))
919 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
920 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
921 }
923 Value *LaneToExtract = State.get(getOperand(0), true);
924 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
925 Value *Res = nullptr;
926 Value *RuntimeVF = getRuntimeVF(State.Builder, IdxTy, State.VF);
927
928 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
929 Value *VectorStart =
930 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
931 Value *VectorIdx = Idx == 1
932 ? LaneToExtract
933 : Builder.CreateSub(LaneToExtract, VectorStart);
934 Value *Ext = State.VF.isScalar()
935 ? State.get(getOperand(Idx))
936 : Builder.CreateExtractElement(
937 State.get(getOperand(Idx)), VectorIdx);
938 if (Res) {
939 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
940 Res = Builder.CreateSelect(Cmp, Ext, Res);
941 } else {
942 Res = Ext;
943 }
944 }
945 return Res;
946 }
948 if (getNumOperands() == 1) {
949 Value *Mask = State.get(getOperand(0));
950 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
951 true, Name);
952 }
953 // If there are multiple operands, create a chain of selects to pick the
954 // first operand with an active lane and add the number of lanes of the
955 // preceding operands.
956 Value *RuntimeVF =
957 getRuntimeVF(State.Builder, State.Builder.getInt64Ty(), State.VF);
958 unsigned LastOpIdx = getNumOperands() - 1;
959 Value *Res = nullptr;
960 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
961 Value *TrailingZeros =
962 State.VF.isScalar()
963 ? Builder.CreateZExt(
964 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
965 Builder.getFalse()),
966 Builder.getInt64Ty())
967 : Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(),
968 State.get(getOperand(Idx)),
969 true, Name);
970 Value *Current = Builder.CreateAdd(
971 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
972 if (Res) {
973 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
974 Res = Builder.CreateSelect(Cmp, Current, Res);
975 } else {
976 Res = Current;
977 }
978 }
979
980 return Res;
981 }
983 return State.get(getOperand(0), true);
984 default:
985 llvm_unreachable("Unsupported opcode for instruction");
986 }
987}
988
990 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
991 Type *ScalarTy = Ctx.Types.inferScalarType(this);
992 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
993 switch (Opcode) {
994 case Instruction::FNeg:
995 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
996 case Instruction::UDiv:
997 case Instruction::SDiv:
998 case Instruction::SRem:
999 case Instruction::URem:
1000 case Instruction::Add:
1001 case Instruction::FAdd:
1002 case Instruction::Sub:
1003 case Instruction::FSub:
1004 case Instruction::Mul:
1005 case Instruction::FMul:
1006 case Instruction::FDiv:
1007 case Instruction::FRem:
1008 case Instruction::Shl:
1009 case Instruction::LShr:
1010 case Instruction::AShr:
1011 case Instruction::And:
1012 case Instruction::Or:
1013 case Instruction::Xor: {
1016
1017 if (VF.isVector()) {
1018 // Certain instructions can be cheaper to vectorize if they have a
1019 // constant second vector operand. One example of this are shifts on x86.
1020 VPValue *RHS = getOperand(1);
1021 RHSInfo = Ctx.getOperandInfo(RHS);
1022
1023 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1026 }
1027
1030 if (CtxI)
1031 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1032 return Ctx.TTI.getArithmeticInstrCost(
1033 Opcode, ResultTy, Ctx.CostKind,
1034 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1035 RHSInfo, Operands, CtxI, &Ctx.TLI);
1036 }
1037 case Instruction::Freeze:
1038 // This opcode is unknown. Assume that it is the same as 'mul'.
1039 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
1040 Ctx.CostKind);
1041 case Instruction::ExtractValue:
1042 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1043 Ctx.CostKind);
1044 case Instruction::ICmp:
1045 case Instruction::FCmp: {
1046 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
1047 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1049 return Ctx.TTI.getCmpSelInstrCost(
1050 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
1051 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1052 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1053 }
1054 }
1055 llvm_unreachable("called for unsupported opcode");
1056}
1057
1059 VPCostContext &Ctx) const {
1061 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1062 // TODO: Compute cost for VPInstructions without underlying values once
1063 // the legacy cost model has been retired.
1064 return 0;
1065 }
1066
1068 "Should only generate a vector value or single scalar, not scalars "
1069 "for all lanes.");
1071 getOpcode(),
1073 }
1074
1075 switch (getOpcode()) {
1076 case Instruction::Select: {
1077 // TODO: It may be possible to improve this by analyzing where the
1078 // condition operand comes from.
1080 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1081 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1082 if (!vputils::onlyFirstLaneUsed(this)) {
1083 CondTy = toVectorTy(CondTy, VF);
1084 VecTy = toVectorTy(VecTy, VF);
1085 }
1086 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1087 Ctx.CostKind);
1088 }
1089 case Instruction::ExtractElement:
1091 if (VF.isScalar()) {
1092 // ExtractLane with VF=1 takes care of handling extracting across multiple
1093 // parts.
1094 return 0;
1095 }
1096
1097 // Add on the cost of extracting the element.
1098 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1099 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1100 Ctx.CostKind);
1101 }
1102 case VPInstruction::AnyOf: {
1103 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1104 return Ctx.TTI.getArithmeticReductionCost(
1105 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1106 }
1108 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1109 if (VF.isScalar())
1110 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1112 CmpInst::ICMP_EQ, Ctx.CostKind);
1113 // Calculate the cost of determining the lane index.
1114 auto *PredTy = toVectorTy(ScalarTy, VF);
1115 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1116 Type::getInt64Ty(Ctx.LLVMCtx),
1117 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1118 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1119 }
1121 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1123 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1124 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1125
1126 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1127 cast<VectorType>(VectorTy),
1128 cast<VectorType>(VectorTy), Mask,
1129 Ctx.CostKind, VF.getKnownMinValue() - 1);
1130 }
1132 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1133 unsigned Multiplier =
1134 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue();
1135 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1136 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1137 {ArgTy, ArgTy});
1138 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1139 }
1141 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1142 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1143 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1144 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1145 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1146 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1147 }
1149 // Add on the cost of extracting the element.
1150 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1151 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1152 VecTy, Ctx.CostKind, 0);
1153 }
1155 if (VF == ElementCount::getScalable(1))
1158 default:
1159 // TODO: Compute cost other VPInstructions once the legacy cost model has
1160 // been retired.
1162 "unexpected VPInstruction witht underlying value");
1163 return 0;
1164 }
1165}
1166
1178
1180 switch (getOpcode()) {
1181 case Instruction::PHI:
1185 return true;
1186 default:
1187 return isScalarCast();
1188 }
1189}
1190
1192 assert(!State.Lane && "VPInstruction executing an Lane");
1193 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1195 "Set flags not supported for the provided opcode");
1196 if (hasFastMathFlags())
1197 State.Builder.setFastMathFlags(getFastMathFlags());
1198 Value *GeneratedValue = generate(State);
1199 if (!hasResult())
1200 return;
1201 assert(GeneratedValue && "generate must produce a value");
1202 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1205 assert((((GeneratedValue->getType()->isVectorTy() ||
1206 GeneratedValue->getType()->isStructTy()) ==
1207 !GeneratesPerFirstLaneOnly) ||
1208 State.VF.isScalar()) &&
1209 "scalar value but not only first lane defined");
1210 State.set(this, GeneratedValue,
1211 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1212}
1213
1216 return false;
1217 switch (getOpcode()) {
1218 case Instruction::ExtractElement:
1219 case Instruction::Freeze:
1220 case Instruction::FCmp:
1221 case Instruction::ICmp:
1222 case Instruction::Select:
1223 case Instruction::PHI:
1237 case VPInstruction::Not:
1244 return false;
1245 default:
1246 return true;
1247 }
1248}
1249
1251 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1253 return vputils::onlyFirstLaneUsed(this);
1254
1255 switch (getOpcode()) {
1256 default:
1257 return false;
1258 case Instruction::ExtractElement:
1259 return Op == getOperand(1);
1260 case Instruction::PHI:
1261 return true;
1262 case Instruction::FCmp:
1263 case Instruction::ICmp:
1264 case Instruction::Select:
1265 case Instruction::Or:
1266 case Instruction::Freeze:
1267 case VPInstruction::Not:
1268 // TODO: Cover additional opcodes.
1269 return vputils::onlyFirstLaneUsed(this);
1278 return true;
1281 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1282 // operand, after replicating its operands only the first lane is used.
1283 // Before replicating, it will have only a single operand.
1284 return getNumOperands() > 1;
1286 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1288 return Op == getOperand(0);
1291 return Op == getOperand(1);
1293 return Op == getOperand(0);
1294 };
1295 llvm_unreachable("switch should return");
1296}
1297
1299 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1301 return vputils::onlyFirstPartUsed(this);
1302
1303 switch (getOpcode()) {
1304 default:
1305 return false;
1306 case Instruction::FCmp:
1307 case Instruction::ICmp:
1308 case Instruction::Select:
1309 return vputils::onlyFirstPartUsed(this);
1313 return true;
1314 };
1315 llvm_unreachable("switch should return");
1316}
1317
1318#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1320 VPSlotTracker SlotTracker(getParent()->getPlan());
1321 print(dbgs(), "", SlotTracker);
1322}
1323
1325 VPSlotTracker &SlotTracker) const {
1326 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1327
1328 if (hasResult()) {
1330 O << " = ";
1331 }
1332
1333 switch (getOpcode()) {
1334 case VPInstruction::Not:
1335 O << "not";
1336 break;
1338 O << "combined load";
1339 break;
1341 O << "combined store";
1342 break;
1344 O << "active lane mask";
1345 break;
1347 O << "EXPLICIT-VECTOR-LENGTH";
1348 break;
1350 O << "first-order splice";
1351 break;
1353 O << "branch-on-cond";
1354 break;
1356 O << "TC > VF ? TC - VF : 0";
1357 break;
1359 O << "VF * Part +";
1360 break;
1362 O << "branch-on-count";
1363 break;
1365 O << "broadcast";
1366 break;
1368 O << "buildstructvector";
1369 break;
1371 O << "buildvector";
1372 break;
1374 O << "extract-lane";
1375 break;
1377 O << "extract-last-element";
1378 break;
1380 O << "extract-penultimate-element";
1381 break;
1383 O << "compute-anyof-result";
1384 break;
1386 O << "compute-find-iv-result";
1387 break;
1389 O << "compute-reduction-result";
1390 break;
1392 O << "logical-and";
1393 break;
1395 O << "ptradd";
1396 break;
1398 O << "wide-ptradd";
1399 break;
1401 O << "any-of";
1402 break;
1404 O << "first-active-lane";
1405 break;
1407 O << "reduction-start-vector";
1408 break;
1410 O << "resume-for-epilogue";
1411 break;
1412 default:
1414 }
1415
1416 printFlags(O);
1418
1419 if (auto DL = getDebugLoc()) {
1420 O << ", !dbg ";
1421 DL.print(O);
1422 }
1423}
1424#endif
1425
1427 State.setDebugLocFrom(getDebugLoc());
1428 if (isScalarCast()) {
1429 Value *Op = State.get(getOperand(0), VPLane(0));
1430 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1431 Op, ResultTy);
1432 State.set(this, Cast, VPLane(0));
1433 return;
1434 }
1435 switch (getOpcode()) {
1437 Value *StepVector =
1438 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1439 State.set(this, StepVector);
1440 break;
1441 }
1442 case VPInstruction::VScale: {
1443 Value *VScale = State.Builder.CreateVScale(ResultTy);
1444 State.set(this, VScale, true);
1445 break;
1446 }
1447
1448 default:
1449 llvm_unreachable("opcode not implemented yet");
1450 }
1451}
1452
1453#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1455 VPSlotTracker &SlotTracker) const {
1456 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1458 O << " = ";
1459
1460 switch (getOpcode()) {
1462 O << "wide-iv-step ";
1464 break;
1466 O << "step-vector " << *ResultTy;
1467 break;
1469 O << "vscale " << *ResultTy;
1470 break;
1471 default:
1472 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1475 O << " to " << *ResultTy;
1476 }
1477}
1478#endif
1479
1481 State.setDebugLocFrom(getDebugLoc());
1482 PHINode *NewPhi = State.Builder.CreatePHI(
1483 State.TypeAnalysis.inferScalarType(this), 2, getName());
1484 unsigned NumIncoming = getNumIncoming();
1485 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1486 // TODO: Fixup all incoming values of header phis once recipes defining them
1487 // are introduced.
1488 NumIncoming = 1;
1489 }
1490 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1491 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1492 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1493 NewPhi->addIncoming(IncV, PredBB);
1494 }
1495 State.set(this, NewPhi, VPLane(0));
1496}
1497
1498#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1499void VPPhi::print(raw_ostream &O, const Twine &Indent,
1500 VPSlotTracker &SlotTracker) const {
1501 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1503 O << " = phi ";
1505}
1506#endif
1507
1508VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1509 if (auto *Phi = dyn_cast<PHINode>(&I))
1510 return new VPIRPhi(*Phi);
1511 return new VPIRInstruction(I);
1512}
1513
1515 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1516 "PHINodes must be handled by VPIRPhi");
1517 // Advance the insert point after the wrapped IR instruction. This allows
1518 // interleaving VPIRInstructions and other recipes.
1519 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1520}
1521
1523 VPCostContext &Ctx) const {
1524 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1525 // hence it does not contribute to the cost-modeling for the VPlan.
1526 return 0;
1527}
1528
1531 "can only update exiting operands to phi nodes");
1532 assert(getNumOperands() > 0 && "must have at least one operand");
1533 VPValue *Exiting = getOperand(0);
1534 if (Exiting->isLiveIn())
1535 return;
1536
1537 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastElement, {Exiting});
1538 setOperand(0, Exiting);
1539}
1540
1541#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1543 VPSlotTracker &SlotTracker) const {
1544 O << Indent << "IR " << I;
1545}
1546#endif
1547
1549 PHINode *Phi = &getIRPhi();
1550 for (const auto &[Idx, Op] : enumerate(operands())) {
1551 VPValue *ExitValue = Op;
1552 auto Lane = vputils::isSingleScalar(ExitValue)
1554 : VPLane::getLastLaneForVF(State.VF);
1555 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1556 auto *PredVPBB = Pred->getExitingBasicBlock();
1557 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1558 // Set insertion point in PredBB in case an extract needs to be generated.
1559 // TODO: Model extracts explicitly.
1560 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
1561 Value *V = State.get(ExitValue, VPLane(Lane));
1562 // If there is no existing block for PredBB in the phi, add a new incoming
1563 // value. Otherwise update the existing incoming value for PredBB.
1564 if (Phi->getBasicBlockIndex(PredBB) == -1)
1565 Phi->addIncoming(V, PredBB);
1566 else
1567 Phi->setIncomingValueForBlock(PredBB, V);
1568 }
1569
1570 // Advance the insert point after the wrapped IR instruction. This allows
1571 // interleaving VPIRInstructions and other recipes.
1572 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1573}
1574
1576 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1577 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1578 "Number of phi operands must match number of predecessors");
1579 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1580 R->removeOperand(Position);
1581}
1582
1583#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1585 VPSlotTracker &SlotTracker) const {
1586 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1587 [this, &O, &SlotTracker](auto Op) {
1588 O << "[ ";
1589 Op.value()->printAsOperand(O, SlotTracker);
1590 O << ", ";
1591 getIncomingBlock(Op.index())->printAsOperand(O);
1592 O << " ]";
1593 });
1594}
1595#endif
1596
1597#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1598void VPIRPhi::print(raw_ostream &O, const Twine &Indent,
1599 VPSlotTracker &SlotTracker) const {
1601
1602 if (getNumOperands() != 0) {
1603 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1605 [&O, &SlotTracker](auto Op) {
1606 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1607 O << " from ";
1608 std::get<1>(Op)->printAsOperand(O);
1609 });
1610 O << ")";
1611 }
1612}
1613#endif
1614
1616 : VPIRMetadata(I) {
1617 if (!LVer || !isa<LoadInst, StoreInst>(&I))
1618 return;
1619 const auto &[AliasScopeMD, NoAliasMD] = LVer->getNoAliasMetadataFor(&I);
1620 if (AliasScopeMD)
1621 Metadata.emplace_back(LLVMContext::MD_alias_scope, AliasScopeMD);
1622 if (NoAliasMD)
1623 Metadata.emplace_back(LLVMContext::MD_noalias, NoAliasMD);
1624}
1625
1627 for (const auto &[Kind, Node] : Metadata)
1628 I.setMetadata(Kind, Node);
1629}
1630
1632 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1633 for (const auto &[KindA, MDA] : Metadata) {
1634 for (const auto &[KindB, MDB] : Other.Metadata) {
1635 if (KindA == KindB && MDA == MDB) {
1636 MetadataIntersection.emplace_back(KindA, MDA);
1637 break;
1638 }
1639 }
1640 }
1641 Metadata = std::move(MetadataIntersection);
1642}
1643
1645 assert(State.VF.isVector() && "not widening");
1646 assert(Variant != nullptr && "Can't create vector function.");
1647
1648 FunctionType *VFTy = Variant->getFunctionType();
1649 // Add return type if intrinsic is overloaded on it.
1651 for (const auto &I : enumerate(args())) {
1652 Value *Arg;
1653 // Some vectorized function variants may also take a scalar argument,
1654 // e.g. linear parameters for pointers. This needs to be the scalar value
1655 // from the start of the respective part when interleaving.
1656 if (!VFTy->getParamType(I.index())->isVectorTy())
1657 Arg = State.get(I.value(), VPLane(0));
1658 else
1659 Arg = State.get(I.value(), onlyFirstLaneUsed(I.value()));
1660 Args.push_back(Arg);
1661 }
1662
1665 if (CI)
1666 CI->getOperandBundlesAsDefs(OpBundles);
1667
1668 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1669 applyFlags(*V);
1670 applyMetadata(*V);
1671 V->setCallingConv(Variant->getCallingConv());
1672
1673 if (!V->getType()->isVoidTy())
1674 State.set(this, V);
1675}
1676
1678 VPCostContext &Ctx) const {
1679 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1680 Variant->getFunctionType()->params(),
1681 Ctx.CostKind);
1682}
1683
1684#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1686 VPSlotTracker &SlotTracker) const {
1687 O << Indent << "WIDEN-CALL ";
1688
1689 Function *CalledFn = getCalledScalarFunction();
1690 if (CalledFn->getReturnType()->isVoidTy())
1691 O << "void ";
1692 else {
1694 O << " = ";
1695 }
1696
1697 O << "call";
1698 printFlags(O);
1699 O << " @" << CalledFn->getName() << "(";
1700 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1701 Op->printAsOperand(O, SlotTracker);
1702 });
1703 O << ")";
1704
1705 O << " (using library function";
1706 if (Variant->hasName())
1707 O << ": " << Variant->getName();
1708 O << ")";
1709}
1710#endif
1711
1713 assert(State.VF.isVector() && "not widening");
1714
1715 SmallVector<Type *, 2> TysForDecl;
1716 // Add return type if intrinsic is overloaded on it.
1717 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1, State.TTI))
1718 TysForDecl.push_back(VectorType::get(getResultType(), State.VF));
1720 for (const auto &I : enumerate(operands())) {
1721 // Some intrinsics have a scalar argument - don't replace it with a
1722 // vector.
1723 Value *Arg;
1724 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1725 State.TTI))
1726 Arg = State.get(I.value(), VPLane(0));
1727 else
1728 Arg = State.get(I.value(), onlyFirstLaneUsed(I.value()));
1729 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1730 State.TTI))
1731 TysForDecl.push_back(Arg->getType());
1732 Args.push_back(Arg);
1733 }
1734
1735 // Use vector version of the intrinsic.
1736 Module *M = State.Builder.GetInsertBlock()->getModule();
1737 Function *VectorF =
1738 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1739 assert(VectorF &&
1740 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1741
1744 if (CI)
1745 CI->getOperandBundlesAsDefs(OpBundles);
1746
1747 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1748
1749 applyFlags(*V);
1750 applyMetadata(*V);
1751
1752 if (!V->getType()->isVoidTy())
1753 State.set(this, V);
1754}
1755
1756/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1759 const VPRecipeWithIRFlags &R,
1760 ElementCount VF,
1761 VPCostContext &Ctx) {
1762 // Some backends analyze intrinsic arguments to determine cost. Use the
1763 // underlying value for the operand if it has one. Otherwise try to use the
1764 // operand of the underlying call instruction, if there is one. Otherwise
1765 // clear Arguments.
1766 // TODO: Rework TTI interface to be independent of concrete IR values.
1768 for (const auto &[Idx, Op] : enumerate(Operands)) {
1769 auto *V = Op->getUnderlyingValue();
1770 if (!V) {
1771 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1772 Arguments.push_back(UI->getArgOperand(Idx));
1773 continue;
1774 }
1775 Arguments.clear();
1776 break;
1777 }
1778 Arguments.push_back(V);
1779 }
1780
1781 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1782 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1783 SmallVector<Type *> ParamTys;
1784 for (const VPValue *Op : Operands) {
1785 ParamTys.push_back(VF.isVector()
1786 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1787 : Ctx.Types.inferScalarType(Op));
1788 }
1789
1790 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1791 FastMathFlags FMF =
1792 R.hasFastMathFlags() ? R.getFastMathFlags() : FastMathFlags();
1793 IntrinsicCostAttributes CostAttrs(
1794 ID, RetTy, Arguments, ParamTys, FMF,
1795 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1796 InstructionCost::getInvalid(), &Ctx.TLI);
1797 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1798}
1799
1801 VPCostContext &Ctx) const {
1803 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1804}
1805
1807 return Intrinsic::getBaseName(VectorIntrinsicID);
1808}
1809
1811 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1812 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1813 auto [Idx, V] = X;
1815 Idx, nullptr);
1816 });
1817}
1818
1819#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1821 VPSlotTracker &SlotTracker) const {
1822 O << Indent << "WIDEN-INTRINSIC ";
1823 if (ResultTy->isVoidTy()) {
1824 O << "void ";
1825 } else {
1827 O << " = ";
1828 }
1829
1830 O << "call";
1831 printFlags(O);
1832 O << getIntrinsicName() << "(";
1833
1835 Op->printAsOperand(O, SlotTracker);
1836 });
1837 O << ")";
1838}
1839#endif
1840
1842 IRBuilderBase &Builder = State.Builder;
1843
1844 Value *Address = State.get(getOperand(0));
1845 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
1846 VectorType *VTy = cast<VectorType>(Address->getType());
1847
1848 // The histogram intrinsic requires a mask even if the recipe doesn't;
1849 // if the mask operand was omitted then all lanes should be executed and
1850 // we just need to synthesize an all-true mask.
1851 Value *Mask = nullptr;
1852 if (VPValue *VPMask = getMask())
1853 Mask = State.get(VPMask);
1854 else
1855 Mask =
1856 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
1857
1858 // If this is a subtract, we want to invert the increment amount. We may
1859 // add a separate intrinsic in future, but for now we'll try this.
1860 if (Opcode == Instruction::Sub)
1861 IncAmt = Builder.CreateNeg(IncAmt);
1862 else
1863 assert(Opcode == Instruction::Add && "only add or sub supported for now");
1864
1865 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
1866 {VTy, IncAmt->getType()},
1867 {Address, IncAmt, Mask});
1868}
1869
1871 VPCostContext &Ctx) const {
1872 // FIXME: Take the gather and scatter into account as well. For now we're
1873 // generating the same cost as the fallback path, but we'll likely
1874 // need to create a new TTI method for determining the cost, including
1875 // whether we can use base + vec-of-smaller-indices or just
1876 // vec-of-pointers.
1877 assert(VF.isVector() && "Invalid VF for histogram cost");
1878 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
1879 VPValue *IncAmt = getOperand(1);
1880 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
1881 VectorType *VTy = VectorType::get(IncTy, VF);
1882
1883 // Assume that a non-constant update value (or a constant != 1) requires
1884 // a multiply, and add that into the cost.
1885 InstructionCost MulCost =
1886 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
1887 if (IncAmt->isLiveIn()) {
1889
1890 if (CI && CI->getZExtValue() == 1)
1891 MulCost = TTI::TCC_Free;
1892 }
1893
1894 // Find the cost of the histogram operation itself.
1895 Type *PtrTy = VectorType::get(AddressTy, VF);
1896 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1897 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
1898 Type::getVoidTy(Ctx.LLVMCtx),
1899 {PtrTy, IncTy, MaskTy});
1900
1901 // Add the costs together with the add/sub operation.
1902 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
1903 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
1904}
1905
1906#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1908 VPSlotTracker &SlotTracker) const {
1909 O << Indent << "WIDEN-HISTOGRAM buckets: ";
1911
1912 if (Opcode == Instruction::Sub)
1913 O << ", dec: ";
1914 else {
1915 assert(Opcode == Instruction::Add);
1916 O << ", inc: ";
1917 }
1919
1920 if (VPValue *Mask = getMask()) {
1921 O << ", mask: ";
1922 Mask->printAsOperand(O, SlotTracker);
1923 }
1924}
1925
1927 VPSlotTracker &SlotTracker) const {
1928 O << Indent << "WIDEN-SELECT ";
1930 O << " = select ";
1931 printFlags(O);
1933 O << ", ";
1935 O << ", ";
1937 O << (isInvariantCond() ? " (condition is loop invariant)" : "");
1938}
1939#endif
1940
1942 // The condition can be loop invariant but still defined inside the
1943 // loop. This means that we can't just use the original 'cond' value.
1944 // We have to take the 'vectorized' value and pick the first lane.
1945 // Instcombine will make this a no-op.
1946 Value *Cond = State.get(getCond(), isInvariantCond());
1947
1948 Value *Op0 = State.get(getOperand(1));
1949 Value *Op1 = State.get(getOperand(2));
1950 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
1951 State.set(this, Sel);
1952 if (auto *I = dyn_cast<Instruction>(Sel)) {
1954 applyFlags(*I);
1955 applyMetadata(*I);
1956 }
1957}
1958
1960 VPCostContext &Ctx) const {
1962 bool ScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1963 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1964 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1965
1966 VPValue *Op0, *Op1;
1967 if (!ScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1968 (match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1))) ||
1969 match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1))))) {
1970 // select x, y, false --> x & y
1971 // select x, true, y --> x | y
1972 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1973 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1974
1976 if (all_of(operands(),
1977 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1978 Operands.append(SI->op_begin(), SI->op_end());
1979 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1980 return Ctx.TTI.getArithmeticInstrCost(
1981 IsLogicalOr ? Instruction::Or : Instruction::And, VectorTy,
1982 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1983 }
1984
1985 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1986 if (!ScalarCond)
1987 CondTy = VectorType::get(CondTy, VF);
1988
1990 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
1991 Pred = Cmp->getPredicate();
1992 return Ctx.TTI.getCmpSelInstrCost(
1993 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1994 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1995}
1996
1997VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
1998 AllowReassoc = FMF.allowReassoc();
1999 NoNaNs = FMF.noNaNs();
2000 NoInfs = FMF.noInfs();
2001 NoSignedZeros = FMF.noSignedZeros();
2002 AllowReciprocal = FMF.allowReciprocal();
2003 AllowContract = FMF.allowContract();
2004 ApproxFunc = FMF.approxFunc();
2005}
2006
2007#if !defined(NDEBUG)
2008bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2009 switch (OpType) {
2010 case OperationType::OverflowingBinOp:
2011 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2012 Opcode == Instruction::Mul ||
2013 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2014 case OperationType::Trunc:
2015 return Opcode == Instruction::Trunc;
2016 case OperationType::DisjointOp:
2017 return Opcode == Instruction::Or;
2018 case OperationType::PossiblyExactOp:
2019 return Opcode == Instruction::AShr;
2020 case OperationType::GEPOp:
2021 return Opcode == Instruction::GetElementPtr ||
2022 Opcode == VPInstruction::PtrAdd ||
2023 Opcode == VPInstruction::WidePtrAdd;
2024 case OperationType::FPMathOp:
2025 return Opcode == Instruction::FAdd || Opcode == Instruction::FMul ||
2026 Opcode == Instruction::FSub || Opcode == Instruction::FNeg ||
2027 Opcode == Instruction::FDiv || Opcode == Instruction::FRem ||
2028 Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc ||
2029 Opcode == Instruction::FCmp || Opcode == Instruction::Select ||
2030 Opcode == VPInstruction::WideIVStep ||
2033 case OperationType::NonNegOp:
2034 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2035 case OperationType::Cmp:
2036 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2037 case OperationType::Other:
2038 return true;
2039 }
2040 llvm_unreachable("Unknown OperationType enum");
2041}
2042#endif
2043
2044#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2046 switch (OpType) {
2047 case OperationType::Cmp:
2049 break;
2050 case OperationType::DisjointOp:
2051 if (DisjointFlags.IsDisjoint)
2052 O << " disjoint";
2053 break;
2054 case OperationType::PossiblyExactOp:
2055 if (ExactFlags.IsExact)
2056 O << " exact";
2057 break;
2058 case OperationType::OverflowingBinOp:
2059 if (WrapFlags.HasNUW)
2060 O << " nuw";
2061 if (WrapFlags.HasNSW)
2062 O << " nsw";
2063 break;
2064 case OperationType::Trunc:
2065 if (TruncFlags.HasNUW)
2066 O << " nuw";
2067 if (TruncFlags.HasNSW)
2068 O << " nsw";
2069 break;
2070 case OperationType::FPMathOp:
2072 break;
2073 case OperationType::GEPOp:
2074 if (GEPFlags.isInBounds())
2075 O << " inbounds";
2076 else if (GEPFlags.hasNoUnsignedSignedWrap())
2077 O << " nusw";
2078 if (GEPFlags.hasNoUnsignedWrap())
2079 O << " nuw";
2080 break;
2081 case OperationType::NonNegOp:
2082 if (NonNegFlags.NonNeg)
2083 O << " nneg";
2084 break;
2085 case OperationType::Other:
2086 break;
2087 }
2088 O << " ";
2089}
2090#endif
2091
2093 auto &Builder = State.Builder;
2094 switch (Opcode) {
2095 case Instruction::Call:
2096 case Instruction::Br:
2097 case Instruction::PHI:
2098 case Instruction::GetElementPtr:
2099 case Instruction::Select:
2100 llvm_unreachable("This instruction is handled by a different recipe.");
2101 case Instruction::UDiv:
2102 case Instruction::SDiv:
2103 case Instruction::SRem:
2104 case Instruction::URem:
2105 case Instruction::Add:
2106 case Instruction::FAdd:
2107 case Instruction::Sub:
2108 case Instruction::FSub:
2109 case Instruction::FNeg:
2110 case Instruction::Mul:
2111 case Instruction::FMul:
2112 case Instruction::FDiv:
2113 case Instruction::FRem:
2114 case Instruction::Shl:
2115 case Instruction::LShr:
2116 case Instruction::AShr:
2117 case Instruction::And:
2118 case Instruction::Or:
2119 case Instruction::Xor: {
2120 // Just widen unops and binops.
2122 for (VPValue *VPOp : operands())
2123 Ops.push_back(State.get(VPOp));
2124
2125 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2126
2127 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2128 applyFlags(*VecOp);
2129 applyMetadata(*VecOp);
2130 }
2131
2132 // Use this vector value for all users of the original instruction.
2133 State.set(this, V);
2134 break;
2135 }
2136 case Instruction::ExtractValue: {
2137 assert(getNumOperands() == 2 && "expected single level extractvalue");
2138 Value *Op = State.get(getOperand(0));
2140 Value *Extract = Builder.CreateExtractValue(Op, CI->getZExtValue());
2141 State.set(this, Extract);
2142 break;
2143 }
2144 case Instruction::Freeze: {
2145 Value *Op = State.get(getOperand(0));
2146 Value *Freeze = Builder.CreateFreeze(Op);
2147 State.set(this, Freeze);
2148 break;
2149 }
2150 case Instruction::ICmp:
2151 case Instruction::FCmp: {
2152 // Widen compares. Generate vector compares.
2153 bool FCmp = Opcode == Instruction::FCmp;
2154 Value *A = State.get(getOperand(0));
2155 Value *B = State.get(getOperand(1));
2156 Value *C = nullptr;
2157 if (FCmp) {
2158 // Propagate fast math flags.
2159 C = Builder.CreateFCmpFMF(
2160 getPredicate(), A, B,
2162 } else {
2163 C = Builder.CreateICmp(getPredicate(), A, B);
2164 }
2165 if (auto *I = dyn_cast<Instruction>(C))
2166 applyMetadata(*I);
2167 State.set(this, C);
2168 break;
2169 }
2170 default:
2171 // This instruction is not vectorized by simple widening.
2172 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2173 << Instruction::getOpcodeName(Opcode));
2174 llvm_unreachable("Unhandled instruction!");
2175 } // end of switch.
2176
2177#if !defined(NDEBUG)
2178 // Verify that VPlan type inference results agree with the type of the
2179 // generated values.
2180 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2181 State.get(this)->getType() &&
2182 "inferred type and type from generated instructions do not match");
2183#endif
2184}
2185
2187 VPCostContext &Ctx) const {
2188 switch (Opcode) {
2189 case Instruction::UDiv:
2190 case Instruction::SDiv:
2191 case Instruction::SRem:
2192 case Instruction::URem:
2193 // If the div/rem operation isn't safe to speculate and requires
2194 // predication, then the only way we can even create a vplan is to insert
2195 // a select on the second input operand to ensure we use the value of 1
2196 // for the inactive lanes. The select will be costed separately.
2197 case Instruction::FNeg:
2198 case Instruction::Add:
2199 case Instruction::FAdd:
2200 case Instruction::Sub:
2201 case Instruction::FSub:
2202 case Instruction::Mul:
2203 case Instruction::FMul:
2204 case Instruction::FDiv:
2205 case Instruction::FRem:
2206 case Instruction::Shl:
2207 case Instruction::LShr:
2208 case Instruction::AShr:
2209 case Instruction::And:
2210 case Instruction::Or:
2211 case Instruction::Xor:
2212 case Instruction::Freeze:
2213 case Instruction::ExtractValue:
2214 case Instruction::ICmp:
2215 case Instruction::FCmp:
2216 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2217 default:
2218 llvm_unreachable("Unsupported opcode for instruction");
2219 }
2220}
2221
2222#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2224 VPSlotTracker &SlotTracker) const {
2225 O << Indent << "WIDEN ";
2227 O << " = " << Instruction::getOpcodeName(Opcode);
2228 printFlags(O);
2230}
2231#endif
2232
2234 auto &Builder = State.Builder;
2235 /// Vectorize casts.
2236 assert(State.VF.isVector() && "Not vectorizing?");
2237 Type *DestTy = VectorType::get(getResultType(), State.VF);
2238 VPValue *Op = getOperand(0);
2239 Value *A = State.get(Op);
2240 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2241 State.set(this, Cast);
2242 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2243 applyFlags(*CastOp);
2244 applyMetadata(*CastOp);
2245 }
2246}
2247
2249 VPCostContext &Ctx) const {
2250 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2251 // the legacy cost model, including truncates/extends when evaluating a
2252 // reduction in a smaller type.
2253 if (!getUnderlyingValue())
2254 return 0;
2255 // Computes the CastContextHint from a recipes that may access memory.
2256 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
2257 if (VF.isScalar())
2259 if (isa<VPInterleaveBase>(R))
2261 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R))
2262 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
2264 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
2265 if (WidenMemoryRecipe == nullptr)
2267 if (!WidenMemoryRecipe->isConsecutive())
2269 if (WidenMemoryRecipe->isReverse())
2271 if (WidenMemoryRecipe->isMasked())
2274 };
2275
2276 VPValue *Operand = getOperand(0);
2278 // For Trunc/FPTrunc, get the context from the only user.
2279 if ((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
2281 if (auto *StoreRecipe = dyn_cast<VPRecipeBase>(*user_begin()))
2282 CCH = ComputeCCH(StoreRecipe);
2283 }
2284 // For Z/Sext, get the context from the operand.
2285 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
2286 Opcode == Instruction::FPExt) {
2287 if (Operand->isLiveIn())
2289 else if (Operand->getDefiningRecipe())
2290 CCH = ComputeCCH(Operand->getDefiningRecipe());
2291 }
2292
2293 auto *SrcTy =
2294 cast<VectorType>(toVectorTy(Ctx.Types.inferScalarType(Operand), VF));
2295 auto *DestTy = cast<VectorType>(toVectorTy(getResultType(), VF));
2296 // Arm TTI will use the underlying instruction to determine the cost.
2297 return Ctx.TTI.getCastInstrCost(
2298 Opcode, DestTy, SrcTy, CCH, Ctx.CostKind,
2300}
2301
2302#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2304 VPSlotTracker &SlotTracker) const {
2305 O << Indent << "WIDEN-CAST ";
2307 O << " = " << Instruction::getOpcodeName(Opcode);
2308 printFlags(O);
2310 O << " to " << *getResultType();
2311}
2312#endif
2313
2315 VPCostContext &Ctx) const {
2316 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2317}
2318
2319/// A helper function that returns an integer or floating-point constant with
2320/// value C.
2322 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
2323 : ConstantFP::get(Ty, C);
2324}
2325
2326#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2328 VPSlotTracker &SlotTracker) const {
2329 O << Indent;
2331 O << " = WIDEN-INDUCTION ";
2333
2334 if (auto *TI = getTruncInst())
2335 O << " (truncated to " << *TI->getType() << ")";
2336}
2337#endif
2338
2340 // The step may be defined by a recipe in the preheader (e.g. if it requires
2341 // SCEV expansion), but for the canonical induction the step is required to be
2342 // 1, which is represented as live-in.
2344 return false;
2347 auto *CanIV = cast<VPCanonicalIVPHIRecipe>(&*getParent()->begin());
2348 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2349 getScalarType() == CanIV->getScalarType();
2350}
2351
2352#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2354 VPSlotTracker &SlotTracker) const {
2355 O << Indent;
2357 O << " = DERIVED-IV ";
2358 getStartValue()->printAsOperand(O, SlotTracker);
2359 O << " + ";
2360 getOperand(1)->printAsOperand(O, SlotTracker);
2361 O << " * ";
2362 getStepValue()->printAsOperand(O, SlotTracker);
2363}
2364#endif
2365
2367 // Fast-math-flags propagate from the original induction instruction.
2368 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2369 if (hasFastMathFlags())
2370 State.Builder.setFastMathFlags(getFastMathFlags());
2371
2372 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2373 /// variable on which to base the steps, \p Step is the size of the step.
2374
2375 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2376 Value *Step = State.get(getStepValue(), VPLane(0));
2377 IRBuilderBase &Builder = State.Builder;
2378
2379 // Ensure step has the same type as that of scalar IV.
2380 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2381 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2382
2383 // We build scalar steps for both integer and floating-point induction
2384 // variables. Here, we determine the kind of arithmetic we will perform.
2387 if (BaseIVTy->isIntegerTy()) {
2388 AddOp = Instruction::Add;
2389 MulOp = Instruction::Mul;
2390 } else {
2391 AddOp = InductionOpcode;
2392 MulOp = Instruction::FMul;
2393 }
2394
2395 // Determine the number of scalars we need to generate for each unroll
2396 // iteration.
2397 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2398 // Compute the scalar steps and save the results in State.
2399 Type *IntStepTy =
2400 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
2401 Type *VecIVTy = nullptr;
2402 Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2403 if (!FirstLaneOnly && State.VF.isScalable()) {
2404 VecIVTy = VectorType::get(BaseIVTy, State.VF);
2405 UnitStepVec =
2406 Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2407 SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2408 SplatIV = Builder.CreateVectorSplat(State.VF, BaseIV);
2409 }
2410
2411 unsigned StartLane = 0;
2412 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2413 if (State.Lane) {
2414 StartLane = State.Lane->getKnownLane();
2415 EndLane = StartLane + 1;
2416 }
2417 Value *StartIdx0;
2418 if (getUnrollPart(*this) == 0)
2419 StartIdx0 = ConstantInt::get(IntStepTy, 0);
2420 else {
2421 StartIdx0 = State.get(getOperand(2), true);
2422 if (getUnrollPart(*this) != 1) {
2423 StartIdx0 =
2424 Builder.CreateMul(StartIdx0, ConstantInt::get(StartIdx0->getType(),
2425 getUnrollPart(*this)));
2426 }
2427 StartIdx0 = Builder.CreateSExtOrTrunc(StartIdx0, IntStepTy);
2428 }
2429
2430 if (!FirstLaneOnly && State.VF.isScalable()) {
2431 auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2432 auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2433 if (BaseIVTy->isFloatingPointTy())
2434 InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2435 auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2436 auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2437 State.set(this, Add);
2438 // It's useful to record the lane values too for the known minimum number
2439 // of elements so we do those below. This improves the code quality when
2440 // trying to extract the first element, for example.
2441 }
2442
2443 if (BaseIVTy->isFloatingPointTy())
2444 StartIdx0 = Builder.CreateSIToFP(StartIdx0, BaseIVTy);
2445
2446 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2447 Value *StartIdx = Builder.CreateBinOp(
2448 AddOp, StartIdx0, getSignedIntOrFpConstant(BaseIVTy, Lane));
2449 // The step returned by `createStepForVF` is a runtime-evaluated value
2450 // when VF is scalable. Otherwise, it should be folded into a Constant.
2451 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2452 "Expected StartIdx to be folded to a constant when VF is not "
2453 "scalable");
2454 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2455 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2456 State.set(this, Add, VPLane(Lane));
2457 }
2458}
2459
2460#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2462 VPSlotTracker &SlotTracker) const {
2463 O << Indent;
2465 O << " = SCALAR-STEPS ";
2467}
2468#endif
2469
2471 assert(State.VF.isVector() && "not widening");
2472 // Construct a vector GEP by widening the operands of the scalar GEP as
2473 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2474 // results in a vector of pointers when at least one operand of the GEP
2475 // is vector-typed. Thus, to keep the representation compact, we only use
2476 // vector-typed operands for loop-varying values.
2477
2478 if (areAllOperandsInvariant()) {
2479 // If we are vectorizing, but the GEP has only loop-invariant operands,
2480 // the GEP we build (by only using vector-typed operands for
2481 // loop-varying values) would be a scalar pointer. Thus, to ensure we
2482 // produce a vector of pointers, we need to either arbitrarily pick an
2483 // operand to broadcast, or broadcast a clone of the original GEP.
2484 // Here, we broadcast a clone of the original.
2485 //
2486 // TODO: If at some point we decide to scalarize instructions having
2487 // loop-invariant operands, this special case will no longer be
2488 // required. We would add the scalarization decision to
2489 // collectLoopScalars() and teach getVectorValue() to broadcast
2490 // the lane-zero scalar value.
2492 for (unsigned I = 0, E = getNumOperands(); I != E; I++)
2493 Ops.push_back(State.get(getOperand(I), VPLane(0)));
2494
2495 auto *NewGEP =
2496 State.Builder.CreateGEP(getSourceElementType(), Ops[0], drop_begin(Ops),
2497 "", getGEPNoWrapFlags());
2498 Value *Splat = State.Builder.CreateVectorSplat(State.VF, NewGEP);
2499 State.set(this, Splat);
2500 } else {
2501 // If the GEP has at least one loop-varying operand, we are sure to
2502 // produce a vector of pointers unless VF is scalar.
2503 // The pointer operand of the new GEP. If it's loop-invariant, we
2504 // won't broadcast it.
2505 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2506
2507 // Collect all the indices for the new GEP. If any index is
2508 // loop-invariant, we won't broadcast it.
2510 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2511 VPValue *Operand = getOperand(I);
2512 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2513 }
2514
2515 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2516 // but it should be a vector, otherwise.
2517 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2518 "", getGEPNoWrapFlags());
2519 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2520 "NewGEP is not a pointer vector");
2521 State.set(this, NewGEP);
2522 }
2523}
2524
2525#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2527 VPSlotTracker &SlotTracker) const {
2528 O << Indent << "WIDEN-GEP ";
2529 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2530 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2531 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2532
2533 O << " ";
2535 O << " = getelementptr";
2536 printFlags(O);
2538}
2539#endif
2540
2541static Type *getGEPIndexTy(bool IsScalable, bool IsReverse, bool IsUnitStride,
2542 unsigned CurrentPart, IRBuilderBase &Builder) {
2543 // Use i32 for the gep index type when the value is constant,
2544 // or query DataLayout for a more suitable index type otherwise.
2545 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2546 return !IsUnitStride || (IsScalable && (IsReverse || CurrentPart > 0))
2547 ? DL.getIndexType(Builder.getPtrTy(0))
2548 : Builder.getInt32Ty();
2549}
2550
2552 auto &Builder = State.Builder;
2553 unsigned CurrentPart = getUnrollPart(*this);
2554 bool IsUnitStride = Stride == 1 || Stride == -1;
2555 Type *IndexTy = getGEPIndexTy(State.VF.isScalable(), /*IsReverse*/ true,
2556 IsUnitStride, CurrentPart, Builder);
2557
2558 // The wide store needs to start at the last vector element.
2559 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2560 if (IndexTy != RunTimeVF->getType())
2561 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2562 // NumElt = Stride * CurrentPart * RunTimeVF
2563 Value *NumElt = Builder.CreateMul(
2564 ConstantInt::get(IndexTy, Stride * (int64_t)CurrentPart), RunTimeVF);
2565 // LastLane = Stride * (RunTimeVF - 1)
2566 Value *LastLane = Builder.CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2567 if (Stride != 1)
2568 LastLane = Builder.CreateMul(ConstantInt::get(IndexTy, Stride), LastLane);
2569 Value *Ptr = State.get(getOperand(0), VPLane(0));
2570 Value *ResultPtr =
2571 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2572 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2574
2575 State.set(this, ResultPtr, /*IsScalar*/ true);
2576}
2577
2578#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2580 VPSlotTracker &SlotTracker) const {
2581 O << Indent;
2583 O << " = vector-end-pointer";
2584 printFlags(O);
2586}
2587#endif
2588
2590 auto &Builder = State.Builder;
2591 unsigned CurrentPart = getUnrollPart(*this);
2592 Type *IndexTy = getGEPIndexTy(State.VF.isScalable(), /*IsReverse*/ false,
2593 /*IsUnitStride*/ true, CurrentPart, Builder);
2594 Value *Ptr = State.get(getOperand(0), VPLane(0));
2595
2596 Value *Increment = createStepForVF(Builder, IndexTy, State.VF, CurrentPart);
2597 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Increment,
2598 "", getGEPNoWrapFlags());
2599
2600 State.set(this, ResultPtr, /*IsScalar*/ true);
2601}
2602
2603#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2605 VPSlotTracker &SlotTracker) const {
2606 O << Indent;
2608 O << " = vector-pointer ";
2609
2611}
2612#endif
2613
2615 VPCostContext &Ctx) const {
2616 // Handle cases where only the first lane is used the same way as the legacy
2617 // cost model.
2619 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2620
2621 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2622 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2623 return (getNumIncomingValues() - 1) *
2624 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2625 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2626}
2627
2628#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2630 VPSlotTracker &SlotTracker) const {
2631 O << Indent << "BLEND ";
2633 O << " =";
2634 if (getNumIncomingValues() == 1) {
2635 // Not a User of any mask: not really blending, this is a
2636 // single-predecessor phi.
2637 O << " ";
2638 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2639 } else {
2640 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2641 O << " ";
2642 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2643 if (I == 0)
2644 continue;
2645 O << "/";
2646 getMask(I)->printAsOperand(O, SlotTracker);
2647 }
2648 }
2649}
2650#endif
2651
2653 assert(!State.Lane && "Reduction being replicated.");
2654 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2657 "In-loop AnyOf reductions aren't currently supported");
2658 // Propagate the fast-math flags carried by the underlying instruction.
2659 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2660 State.Builder.setFastMathFlags(getFastMathFlags());
2661 Value *NewVecOp = State.get(getVecOp());
2662 if (VPValue *Cond = getCondOp()) {
2663 Value *NewCond = State.get(Cond, State.VF.isScalar());
2664 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2665 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2666
2667 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2668 if (State.VF.isVector())
2669 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2670
2671 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2672 NewVecOp = Select;
2673 }
2674 Value *NewRed;
2675 Value *NextInChain;
2676 if (IsOrdered) {
2677 if (State.VF.isVector())
2678 NewRed =
2679 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2680 else
2681 NewRed = State.Builder.CreateBinOp(
2683 PrevInChain, NewVecOp);
2684 PrevInChain = NewRed;
2685 NextInChain = NewRed;
2686 } else {
2687 PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2688 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2690 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2691 else
2692 NextInChain = State.Builder.CreateBinOp(
2694 PrevInChain, NewRed);
2695 }
2696 State.set(this, NextInChain, /*IsScalar*/ true);
2697}
2698
2700 assert(!State.Lane && "Reduction being replicated.");
2701
2702 auto &Builder = State.Builder;
2703 // Propagate the fast-math flags carried by the underlying instruction.
2704 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2705 Builder.setFastMathFlags(getFastMathFlags());
2706
2708 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2709 Value *VecOp = State.get(getVecOp());
2710 Value *EVL = State.get(getEVL(), VPLane(0));
2711
2712 Value *Mask;
2713 if (VPValue *CondOp = getCondOp())
2714 Mask = State.get(CondOp);
2715 else
2716 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2717
2718 Value *NewRed;
2719 if (isOrdered()) {
2720 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2721 } else {
2722 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2724 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2725 else
2726 NewRed = Builder.CreateBinOp(
2728 Prev);
2729 }
2730 State.set(this, NewRed, /*IsScalar*/ true);
2731}
2732
2734 VPCostContext &Ctx) const {
2735 RecurKind RdxKind = getRecurrenceKind();
2736 Type *ElementTy = Ctx.Types.inferScalarType(this);
2737 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2738 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2740 std::optional<FastMathFlags> OptionalFMF =
2741 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2742
2743 // TODO: Support any-of reductions.
2744 assert(
2746 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2747 "Any-of reduction not implemented in VPlan-based cost model currently.");
2748
2749 // Note that TTI should model the cost of moving result to the scalar register
2750 // and the BinOp cost in the getMinMaxReductionCost().
2753 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2754 }
2755
2756 // Note that TTI should model the cost of moving result to the scalar register
2757 // and the BinOp cost in the getArithmeticReductionCost().
2758 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2759 Ctx.CostKind);
2760}
2761
2763 ExpressionTypes ExpressionType,
2764 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2765 : VPSingleDefRecipe(VPDef::VPExpressionSC, {}, {}),
2766 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2767 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2768 assert(
2769 none_of(ExpressionRecipes,
2770 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2771 "expression cannot contain recipes with side-effects");
2772
2773 // Maintain a copy of the expression recipes as a set of users.
2774 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2775 for (auto *R : ExpressionRecipes)
2776 ExpressionRecipesAsSetOfUsers.insert(R);
2777
2778 // Recipes in the expression, except the last one, must only be used by
2779 // (other) recipes inside the expression. If there are other users, external
2780 // to the expression, use a clone of the recipe for external users.
2781 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2782 if (R != ExpressionRecipes.back() &&
2783 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2784 return !ExpressionRecipesAsSetOfUsers.contains(U);
2785 })) {
2786 // There are users outside of the expression. Clone the recipe and use the
2787 // clone those external users.
2788 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2789 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2790 VPUser &U, unsigned) {
2791 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2792 });
2793 CopyForExtUsers->insertBefore(R);
2794 }
2795 if (R->getParent())
2796 R->removeFromParent();
2797 }
2798
2799 // Internalize all external operands to the expression recipes. To do so,
2800 // create new temporary VPValues for all operands defined by a recipe outside
2801 // the expression. The original operands are added as operands of the
2802 // VPExpressionRecipe itself.
2803 for (auto *R : ExpressionRecipes) {
2804 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2805 auto *Def = Op->getDefiningRecipe();
2806 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2807 continue;
2808 addOperand(Op);
2809 LiveInPlaceholders.push_back(new VPValue());
2810 }
2811 }
2812
2813 // Replace each external operand with the first one created for it in
2814 // LiveInPlaceholders.
2815 for (auto *R : ExpressionRecipes)
2816 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2817 R->replaceUsesOfWith(LiveIn, Tmp);
2818}
2819
2821 for (auto *R : ExpressionRecipes)
2822 // Since the list could contain duplicates, make sure the recipe hasn't
2823 // already been inserted.
2824 if (!R->getParent())
2825 R->insertBefore(this);
2826
2827 for (const auto &[Idx, Op] : enumerate(operands()))
2828 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
2829
2830 replaceAllUsesWith(ExpressionRecipes.back());
2831 ExpressionRecipes.clear();
2832}
2833
2835 VPCostContext &Ctx) const {
2836 Type *RedTy = Ctx.Types.inferScalarType(this);
2837 auto *SrcVecTy = cast<VectorType>(
2838 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
2839 assert(RedTy->isIntegerTy() &&
2840 "VPExpressionRecipe only supports integer types currently.");
2841 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2842 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
2843 switch (ExpressionType) {
2844 case ExpressionTypes::ExtendedReduction: {
2845 return Ctx.TTI.getExtendedReductionCost(
2846 Opcode,
2847 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2848 Instruction::ZExt,
2849 RedTy, SrcVecTy, std::nullopt, Ctx.CostKind);
2850 }
2851 case ExpressionTypes::MulAccReduction:
2852 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
2853 Ctx.CostKind);
2854
2855 case ExpressionTypes::ExtNegatedMulAccReduction:
2856 assert(Opcode == Instruction::Add && "Unexpected opcode");
2857 Opcode = Instruction::Sub;
2859 case ExpressionTypes::ExtMulAccReduction: {
2860 return Ctx.TTI.getMulAccReductionCost(
2861 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2862 Instruction::ZExt,
2863 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
2864 }
2865 }
2866 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
2867}
2868
2870 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
2871 return R->mayReadFromMemory() || R->mayWriteToMemory();
2872 });
2873}
2874
2876 assert(
2877 none_of(ExpressionRecipes,
2878 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2879 "expression cannot contain recipes with side-effects");
2880 return false;
2881}
2882
2883#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2884
2886 VPSlotTracker &SlotTracker) const {
2887 O << Indent << "EXPRESSION ";
2889 O << " = ";
2890 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
2891 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
2892
2893 switch (ExpressionType) {
2894 case ExpressionTypes::ExtendedReduction: {
2896 O << " +";
2897 O << " reduce." << Instruction::getOpcodeName(Opcode) << " (";
2899 Red->printFlags(O);
2900
2901 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2902 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2903 << *Ext0->getResultType();
2904 if (Red->isConditional()) {
2905 O << ", ";
2906 Red->getCondOp()->printAsOperand(O, SlotTracker);
2907 }
2908 O << ")";
2909 break;
2910 }
2911 case ExpressionTypes::ExtNegatedMulAccReduction: {
2913 O << " + reduce."
2915 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
2916 << " (sub (0, mul";
2917 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2918 Mul->printFlags(O);
2919 O << "(";
2921 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2922 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2923 << *Ext0->getResultType() << "), (";
2925 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2926 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
2927 << *Ext1->getResultType() << ")";
2928 if (Red->isConditional()) {
2929 O << ", ";
2930 Red->getCondOp()->printAsOperand(O, SlotTracker);
2931 }
2932 O << "))";
2933 break;
2934 }
2935 case ExpressionTypes::MulAccReduction:
2936 case ExpressionTypes::ExtMulAccReduction: {
2938 O << " + ";
2939 O << "reduce."
2941 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
2942 << " (";
2943 O << "mul";
2944 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
2945 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
2946 : ExpressionRecipes[0]);
2947 Mul->printFlags(O);
2948 if (IsExtended)
2949 O << "(";
2951 if (IsExtended) {
2952 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2953 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2954 << *Ext0->getResultType() << "), (";
2955 } else {
2956 O << ", ";
2957 }
2959 if (IsExtended) {
2960 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2961 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
2962 << *Ext1->getResultType() << ")";
2963 }
2964 if (Red->isConditional()) {
2965 O << ", ";
2966 Red->getCondOp()->printAsOperand(O, SlotTracker);
2967 }
2968 O << ")";
2969 break;
2970 }
2971 }
2972}
2973
2975 VPSlotTracker &SlotTracker) const {
2976 O << Indent << "REDUCE ";
2978 O << " = ";
2980 O << " +";
2981 printFlags(O);
2982 O << " reduce."
2985 << " (";
2987 if (isConditional()) {
2988 O << ", ";
2990 }
2991 O << ")";
2992}
2993
2995 VPSlotTracker &SlotTracker) const {
2996 O << Indent << "REDUCE ";
2998 O << " = ";
3000 O << " +";
3001 printFlags(O);
3002 O << " vp.reduce."
3005 << " (";
3007 O << ", ";
3009 if (isConditional()) {
3010 O << ", ";
3012 }
3013 O << ")";
3014}
3015
3016#endif
3017
3018/// A helper function to scalarize a single Instruction in the innermost loop.
3019/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3020/// operands from \p RepRecipe instead of \p Instr's operands.
3021static void scalarizeInstruction(const Instruction *Instr,
3022 VPReplicateRecipe *RepRecipe,
3023 const VPLane &Lane, VPTransformState &State) {
3024 assert((!Instr->getType()->isAggregateType() ||
3025 canVectorizeTy(Instr->getType())) &&
3026 "Expected vectorizable or non-aggregate type.");
3027
3028 // Does this instruction return a value ?
3029 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3030
3031 Instruction *Cloned = Instr->clone();
3032 if (!IsVoidRetTy) {
3033 Cloned->setName(Instr->getName() + ".cloned");
3034 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3035 // The operands of the replicate recipe may have been narrowed, resulting in
3036 // a narrower result type. Update the type of the cloned instruction to the
3037 // correct type.
3038 if (ResultTy != Cloned->getType())
3039 Cloned->mutateType(ResultTy);
3040 }
3041
3042 RepRecipe->applyFlags(*Cloned);
3043 RepRecipe->applyMetadata(*Cloned);
3044
3045 if (RepRecipe->hasPredicate())
3046 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3047
3048 if (auto DL = RepRecipe->getDebugLoc())
3049 State.setDebugLocFrom(DL);
3050
3051 // Replace the operands of the cloned instructions with their scalar
3052 // equivalents in the new loop.
3053 for (const auto &I : enumerate(RepRecipe->operands())) {
3054 auto InputLane = Lane;
3055 VPValue *Operand = I.value();
3056 if (vputils::isSingleScalar(Operand))
3057 InputLane = VPLane::getFirstLane();
3058 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3059 }
3060
3061 // Place the cloned scalar in the new loop.
3062 State.Builder.Insert(Cloned);
3063
3064 State.set(RepRecipe, Cloned, Lane);
3065
3066 // If we just cloned a new assumption, add it the assumption cache.
3067 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3068 State.AC->registerAssumption(II);
3069
3070 assert(
3071 (RepRecipe->getParent()->getParent() ||
3072 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3073 all_of(RepRecipe->operands(),
3074 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3075 "Expected a recipe is either within a region or all of its operands "
3076 "are defined outside the vectorized region.");
3077}
3078
3081
3082 if (!State.Lane) {
3083 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3084 "must have already been unrolled");
3085 scalarizeInstruction(UI, this, VPLane(0), State);
3086 return;
3087 }
3088
3089 assert((State.VF.isScalar() || !isSingleScalar()) &&
3090 "uniform recipe shouldn't be predicated");
3091 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3092 scalarizeInstruction(UI, this, *State.Lane, State);
3093 // Insert scalar instance packing it into a vector.
3094 if (State.VF.isVector() && shouldPack()) {
3095 Value *WideValue =
3096 State.Lane->isFirstLane()
3097 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3098 : State.get(this);
3099 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3100 *State.Lane));
3101 }
3102}
3103
3105 // Find if the recipe is used by a widened recipe via an intervening
3106 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3107 return any_of(users(), [](const VPUser *U) {
3108 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3109 return !vputils::onlyScalarValuesUsed(PredR);
3110 return false;
3111 });
3112}
3113
3114/// Returns true if \p Ptr is a pointer computation for which the legacy cost
3115/// model computes a SCEV expression when computing the address cost.
3117 auto *PtrR = Ptr->getDefiningRecipe();
3118 if (!PtrR || !((isa<VPReplicateRecipe>(PtrR) &&
3120 Instruction::GetElementPtr) ||
3121 isa<VPWidenGEPRecipe>(PtrR) ||
3123 return false;
3124
3125 // We are looking for a GEP where all indices are either loop invariant or
3126 // inductions.
3127 for (VPValue *Opd : drop_begin(PtrR->operands())) {
3128 if (!Opd->isDefinedOutsideLoopRegions() &&
3130 return false;
3131 }
3132
3133 return true;
3134}
3135
3136/// Returns true if \p V is used as part of the address of another load or
3137/// store.
3138static bool isUsedByLoadStoreAddress(const VPUser *V) {
3140 SmallVector<const VPUser *> WorkList = {V};
3141
3142 while (!WorkList.empty()) {
3143 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3144 if (!Cur || !Seen.insert(Cur).second || isa<VPBlendRecipe>(Cur))
3145 continue;
3146
3147 for (VPUser *U : Cur->users()) {
3148 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3149 if (InterleaveR->getAddr() == Cur)
3150 return true;
3151 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3152 if (RepR->getOpcode() == Instruction::Load &&
3153 RepR->getOperand(0) == Cur)
3154 return true;
3155 if (RepR->getOpcode() == Instruction::Store &&
3156 RepR->getOperand(1) == Cur)
3157 return true;
3158 }
3159 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3160 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3161 return true;
3162 }
3163 }
3164
3165 append_range(WorkList, cast<VPSingleDefRecipe>(Cur)->users());
3166 }
3167 return false;
3168}
3169
3171 VPCostContext &Ctx) const {
3173 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3174 // transform, avoid computing their cost multiple times for now.
3175 Ctx.SkipCostComputation.insert(UI);
3176
3177 switch (UI->getOpcode()) {
3178 case Instruction::GetElementPtr:
3179 // We mark this instruction as zero-cost because the cost of GEPs in
3180 // vectorized code depends on whether the corresponding memory instruction
3181 // is scalarized or not. Therefore, we handle GEPs with the memory
3182 // instruction cost.
3183 return 0;
3184 case Instruction::Call: {
3185 auto *CalledFn =
3187
3190 for (const VPValue *ArgOp : ArgOps)
3191 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3192
3193 if (CalledFn->isIntrinsic())
3194 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3195 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3196 switch (CalledFn->getIntrinsicID()) {
3197 case Intrinsic::assume:
3198 case Intrinsic::lifetime_end:
3199 case Intrinsic::lifetime_start:
3200 case Intrinsic::sideeffect:
3201 case Intrinsic::pseudoprobe:
3202 case Intrinsic::experimental_noalias_scope_decl: {
3203 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3204 ElementCount::getFixed(1), Ctx) == 0 &&
3205 "scalarizing intrinsic should be free");
3206 return InstructionCost(0);
3207 }
3208 default:
3209 break;
3210 }
3211
3212 Type *ResultTy = Ctx.Types.inferScalarType(this);
3213 InstructionCost ScalarCallCost =
3214 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3215 if (isSingleScalar()) {
3216 if (CalledFn->isIntrinsic())
3217 ScalarCallCost = std::min(
3218 ScalarCallCost,
3219 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3220 ElementCount::getFixed(1), Ctx));
3221 return ScalarCallCost;
3222 }
3223
3224 if (VF.isScalable())
3226
3227 return ScalarCallCost * VF.getFixedValue() +
3228 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3229 }
3230 case Instruction::Add:
3231 case Instruction::Sub:
3232 case Instruction::FAdd:
3233 case Instruction::FSub:
3234 case Instruction::Mul:
3235 case Instruction::FMul:
3236 case Instruction::FDiv:
3237 case Instruction::FRem:
3238 case Instruction::Shl:
3239 case Instruction::LShr:
3240 case Instruction::AShr:
3241 case Instruction::And:
3242 case Instruction::Or:
3243 case Instruction::Xor:
3244 case Instruction::ICmp:
3245 case Instruction::FCmp:
3247 Ctx) *
3248 (isSingleScalar() ? 1 : VF.getFixedValue());
3249 case Instruction::SDiv:
3250 case Instruction::UDiv:
3251 case Instruction::SRem:
3252 case Instruction::URem: {
3253 InstructionCost ScalarCost =
3255 if (isSingleScalar())
3256 return ScalarCost;
3257
3258 ScalarCost = ScalarCost * VF.getFixedValue() +
3259 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3260 to_vector(operands()), VF);
3261 // If the recipe is not predicated (i.e. not in a replicate region), return
3262 // the scalar cost. Otherwise handle predicated cost.
3263 if (!getParent()->getParent()->isReplicator())
3264 return ScalarCost;
3265
3266 // Account for the phi nodes that we will create.
3267 ScalarCost += VF.getFixedValue() *
3268 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3269 // Scale the cost by the probability of executing the predicated blocks.
3270 // This assumes the predicated block for each vector lane is equally
3271 // likely.
3272 ScalarCost /= getPredBlockCostDivisor(Ctx.CostKind);
3273 return ScalarCost;
3274 }
3275 case Instruction::Load:
3276 case Instruction::Store: {
3277 if (VF.isScalable() && !isSingleScalar())
3279
3280 // TODO: See getMemInstScalarizationCost for how to handle replicating and
3281 // predicated cases.
3282 const VPRegionBlock *ParentRegion = getParent()->getParent();
3283 if (ParentRegion && ParentRegion->isReplicator())
3284 break;
3285
3286 bool IsLoad = UI->getOpcode() == Instruction::Load;
3287 const VPValue *PtrOp = getOperand(!IsLoad);
3288 // TODO: Handle cases where we need to pass a SCEV to
3289 // getAddressComputationCost.
3290 if (shouldUseAddressAccessSCEV(PtrOp))
3291 break;
3292
3293 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3294 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3295 const Align Alignment = getLoadStoreAlignment(UI);
3296 unsigned AS = getLoadStoreAddressSpace(UI);
3298 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3299 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo);
3300
3301 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3302 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3303 bool UsedByLoadStoreAddress =
3304 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3305 InstructionCost ScalarCost =
3306 ScalarMemOpCost + Ctx.TTI.getAddressComputationCost(
3307 PtrTy, UsedByLoadStoreAddress ? nullptr : &Ctx.SE,
3308 nullptr, Ctx.CostKind);
3309 if (isSingleScalar())
3310 return ScalarCost;
3311
3312 SmallVector<const VPValue *> OpsToScalarize;
3313 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3314 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3315 // don't assign scalarization overhead in general, if the target prefers
3316 // vectorized addressing or the loaded value is used as part of an address
3317 // of another load or store.
3318 if (!UsedByLoadStoreAddress) {
3319 bool EfficientVectorLoadStore =
3320 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3321 if (!(IsLoad && !PreferVectorizedAddressing) &&
3322 !(!IsLoad && EfficientVectorLoadStore))
3323 append_range(OpsToScalarize, operands());
3324
3325 if (!EfficientVectorLoadStore)
3326 ResultTy = Ctx.Types.inferScalarType(this);
3327 }
3328
3329 return (ScalarCost * VF.getFixedValue()) +
3330 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, true);
3331 }
3332 }
3333
3334 return Ctx.getLegacyCost(UI, VF);
3335}
3336
3337#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3339 VPSlotTracker &SlotTracker) const {
3340 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3341
3342 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3344 O << " = ";
3345 }
3346 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3347 O << "call";
3348 printFlags(O);
3349 O << "@" << CB->getCalledFunction()->getName() << "(";
3351 O, [&O, &SlotTracker](VPValue *Op) {
3352 Op->printAsOperand(O, SlotTracker);
3353 });
3354 O << ")";
3355 } else {
3357 printFlags(O);
3359 }
3360
3361 if (shouldPack())
3362 O << " (S->V)";
3363}
3364#endif
3365
3367 assert(State.Lane && "Branch on Mask works only on single instance.");
3368
3369 VPValue *BlockInMask = getOperand(0);
3370 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3371
3372 // Replace the temporary unreachable terminator with a new conditional branch,
3373 // whose two destinations will be set later when they are created.
3374 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3375 assert(isa<UnreachableInst>(CurrentTerminator) &&
3376 "Expected to replace unreachable terminator with conditional branch.");
3377 auto CondBr =
3378 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3379 CondBr->setSuccessor(0, nullptr);
3380 CurrentTerminator->eraseFromParent();
3381}
3382
3384 VPCostContext &Ctx) const {
3385 // The legacy cost model doesn't assign costs to branches for individual
3386 // replicate regions. Match the current behavior in the VPlan cost model for
3387 // now.
3388 return 0;
3389}
3390
3392 assert(State.Lane && "Predicated instruction PHI works per instance.");
3393 Instruction *ScalarPredInst =
3394 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3395 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3396 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3397 assert(PredicatingBB && "Predicated block has no single predecessor.");
3399 "operand must be VPReplicateRecipe");
3400
3401 // By current pack/unpack logic we need to generate only a single phi node: if
3402 // a vector value for the predicated instruction exists at this point it means
3403 // the instruction has vector users only, and a phi for the vector value is
3404 // needed. In this case the recipe of the predicated instruction is marked to
3405 // also do that packing, thereby "hoisting" the insert-element sequence.
3406 // Otherwise, a phi node for the scalar value is needed.
3407 if (State.hasVectorValue(getOperand(0))) {
3408 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3410 "Packed operands must generate an insertelement or insertvalue");
3411
3412 // If VectorI is a struct, it will be a sequence like:
3413 // %1 = insertvalue %unmodified, %x, 0
3414 // %2 = insertvalue %1, %y, 1
3415 // %VectorI = insertvalue %2, %z, 2
3416 // To get the unmodified vector we need to look through the chain.
3417 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3418 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3419 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3420
3421 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3422 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3423 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3424 if (State.hasVectorValue(this))
3425 State.reset(this, VPhi);
3426 else
3427 State.set(this, VPhi);
3428 // NOTE: Currently we need to update the value of the operand, so the next
3429 // predicated iteration inserts its generated value in the correct vector.
3430 State.reset(getOperand(0), VPhi);
3431 } else {
3432 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3433 return;
3434
3435 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3436 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3437 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3438 PredicatingBB);
3439 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3440 if (State.hasScalarValue(this, *State.Lane))
3441 State.reset(this, Phi, *State.Lane);
3442 else
3443 State.set(this, Phi, *State.Lane);
3444 // NOTE: Currently we need to update the value of the operand, so the next
3445 // predicated iteration inserts its generated value in the correct vector.
3446 State.reset(getOperand(0), Phi, *State.Lane);
3447 }
3448}
3449
3450#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3452 VPSlotTracker &SlotTracker) const {
3453 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3455 O << " = ";
3457}
3458#endif
3459
3461 VPCostContext &Ctx) const {
3463 const Align Alignment = getLoadStoreAlignment(&Ingredient);
3464 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3465 ->getAddressSpace();
3466 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3467 ? Instruction::Load
3468 : Instruction::Store;
3469
3470 if (!Consecutive) {
3471 // TODO: Using the original IR may not be accurate.
3472 // Currently, ARM will use the underlying IR to calculate gather/scatter
3473 // instruction cost.
3474 assert(!Reverse &&
3475 "Inconsecutive memory access should not have the order.");
3476
3478 Type *PtrTy = Ptr->getType();
3479
3480 // If the address value is uniform across all lanes, then the address can be
3481 // calculated with scalar type and broadcast.
3483 PtrTy = toVectorTy(PtrTy, VF);
3484
3485 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3486 Ctx.CostKind) +
3487 Ctx.TTI.getGatherScatterOpCost(Opcode, Ty, Ptr, IsMasked, Alignment,
3488 Ctx.CostKind, &Ingredient);
3489 }
3490
3492 if (IsMasked) {
3493 Cost +=
3494 Ctx.TTI.getMaskedMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind);
3495 } else {
3496 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3498 : getOperand(1));
3499 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3500 OpInfo, &Ingredient);
3501 }
3502 if (!Reverse)
3503 return Cost;
3504
3505 return Cost += Ctx.TTI.getShuffleCost(
3507 cast<VectorType>(Ty), {}, Ctx.CostKind, 0);
3508}
3509
3511 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3512 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3513 const Align Alignment = getLoadStoreAlignment(&Ingredient);
3514 bool CreateGather = !isConsecutive();
3515
3516 auto &Builder = State.Builder;
3517 Value *Mask = nullptr;
3518 if (auto *VPMask = getMask()) {
3519 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3520 // of a null all-one mask is a null mask.
3521 Mask = State.get(VPMask);
3522 if (isReverse())
3523 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3524 }
3525
3526 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3527 Value *NewLI;
3528 if (CreateGather) {
3529 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3530 "wide.masked.gather");
3531 } else if (Mask) {
3532 NewLI =
3533 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3534 PoisonValue::get(DataTy), "wide.masked.load");
3535 } else {
3536 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3537 }
3539 if (Reverse)
3540 NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
3541 State.set(this, NewLI);
3542}
3543
3544#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3546 VPSlotTracker &SlotTracker) const {
3547 O << Indent << "WIDEN ";
3549 O << " = load ";
3551}
3552#endif
3553
3554/// Use all-true mask for reverse rather than actual mask, as it avoids a
3555/// dependence w/o affecting the result.
3557 Value *EVL, const Twine &Name) {
3558 VectorType *ValTy = cast<VectorType>(Operand->getType());
3559 Value *AllTrueMask =
3560 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3561 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3562 {Operand, AllTrueMask, EVL}, nullptr, Name);
3563}
3564
3566 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3567 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3568 const Align Alignment = getLoadStoreAlignment(&Ingredient);
3569 bool CreateGather = !isConsecutive();
3570
3571 auto &Builder = State.Builder;
3572 CallInst *NewLI;
3573 Value *EVL = State.get(getEVL(), VPLane(0));
3574 Value *Addr = State.get(getAddr(), !CreateGather);
3575 Value *Mask = nullptr;
3576 if (VPValue *VPMask = getMask()) {
3577 Mask = State.get(VPMask);
3578 if (isReverse())
3579 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3580 } else {
3581 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3582 }
3583
3584 if (CreateGather) {
3585 NewLI =
3586 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3587 nullptr, "wide.masked.gather");
3588 } else {
3589 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3590 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3591 }
3592 NewLI->addParamAttr(
3593 0, Attribute::getWithAlignment(NewLI->getContext(), Alignment));
3594 applyMetadata(*NewLI);
3595 Instruction *Res = NewLI;
3596 if (isReverse())
3597 Res = createReverseEVL(Builder, Res, EVL, "vp.reverse");
3598 State.set(this, Res);
3599}
3600
3602 VPCostContext &Ctx) const {
3603 if (!Consecutive || IsMasked)
3604 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3605
3606 // We need to use the getMaskedMemoryOpCost() instead of getMemoryOpCost()
3607 // here because the EVL recipes using EVL to replace the tail mask. But in the
3608 // legacy model, it will always calculate the cost of mask.
3609 // TODO: Using getMemoryOpCost() instead of getMaskedMemoryOpCost when we
3610 // don't need to compare to the legacy cost model.
3612 const Align Alignment = getLoadStoreAlignment(&Ingredient);
3613 unsigned AS = getLoadStoreAddressSpace(&Ingredient);
3614 InstructionCost Cost = Ctx.TTI.getMaskedMemoryOpCost(
3615 Instruction::Load, Ty, Alignment, AS, Ctx.CostKind);
3616 if (!Reverse)
3617 return Cost;
3618
3619 return Cost + Ctx.TTI.getShuffleCost(
3621 cast<VectorType>(Ty), {}, Ctx.CostKind, 0);
3622}
3623
3624#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3626 VPSlotTracker &SlotTracker) const {
3627 O << Indent << "WIDEN ";
3629 O << " = vp.load ";
3631}
3632#endif
3633
3635 VPValue *StoredVPValue = getStoredValue();
3636 bool CreateScatter = !isConsecutive();
3637 const Align Alignment = getLoadStoreAlignment(&Ingredient);
3638
3639 auto &Builder = State.Builder;
3640
3641 Value *Mask = nullptr;
3642 if (auto *VPMask = getMask()) {
3643 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3644 // of a null all-one mask is a null mask.
3645 Mask = State.get(VPMask);
3646 if (isReverse())
3647 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3648 }
3649
3650 Value *StoredVal = State.get(StoredVPValue);
3651 if (isReverse()) {
3652 // If we store to reverse consecutive memory locations, then we need
3653 // to reverse the order of elements in the stored value.
3654 StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
3655 // We don't want to update the value in the map as it might be used in
3656 // another expression. So don't call resetVectorValue(StoredVal).
3657 }
3658 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3659 Instruction *NewSI = nullptr;
3660 if (CreateScatter)
3661 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3662 else if (Mask)
3663 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3664 else
3665 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3666 applyMetadata(*NewSI);
3667}
3668
3669#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3671 VPSlotTracker &SlotTracker) const {
3672 O << Indent << "WIDEN store ";
3674}
3675#endif
3676
3678 VPValue *StoredValue = getStoredValue();
3679 bool CreateScatter = !isConsecutive();
3680 const Align Alignment = getLoadStoreAlignment(&Ingredient);
3681
3682 auto &Builder = State.Builder;
3683
3684 CallInst *NewSI = nullptr;
3685 Value *StoredVal = State.get(StoredValue);
3686 Value *EVL = State.get(getEVL(), VPLane(0));
3687 if (isReverse())
3688 StoredVal = createReverseEVL(Builder, StoredVal, EVL, "vp.reverse");
3689 Value *Mask = nullptr;
3690 if (VPValue *VPMask = getMask()) {
3691 Mask = State.get(VPMask);
3692 if (isReverse())
3693 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3694 } else {
3695 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3696 }
3697 Value *Addr = State.get(getAddr(), !CreateScatter);
3698 if (CreateScatter) {
3699 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3700 Intrinsic::vp_scatter,
3701 {StoredVal, Addr, Mask, EVL});
3702 } else {
3703 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3704 Intrinsic::vp_store,
3705 {StoredVal, Addr, Mask, EVL});
3706 }
3707 NewSI->addParamAttr(
3708 1, Attribute::getWithAlignment(NewSI->getContext(), Alignment));
3709 applyMetadata(*NewSI);
3710}
3711
3713 VPCostContext &Ctx) const {
3714 if (!Consecutive || IsMasked)
3715 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3716
3717 // We need to use the getMaskedMemoryOpCost() instead of getMemoryOpCost()
3718 // here because the EVL recipes using EVL to replace the tail mask. But in the
3719 // legacy model, it will always calculate the cost of mask.
3720 // TODO: Using getMemoryOpCost() instead of getMaskedMemoryOpCost when we
3721 // don't need to compare to the legacy cost model.
3723 const Align Alignment = getLoadStoreAlignment(&Ingredient);
3724 unsigned AS = getLoadStoreAddressSpace(&Ingredient);
3725 InstructionCost Cost = Ctx.TTI.getMaskedMemoryOpCost(
3726 Instruction::Store, Ty, Alignment, AS, Ctx.CostKind);
3727 if (!Reverse)
3728 return Cost;
3729
3730 return Cost + Ctx.TTI.getShuffleCost(
3732 cast<VectorType>(Ty), {}, Ctx.CostKind, 0);
3733}
3734
3735#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3737 VPSlotTracker &SlotTracker) const {
3738 O << Indent << "WIDEN vp.store ";
3740}
3741#endif
3742
3744 VectorType *DstVTy, const DataLayout &DL) {
3745 // Verify that V is a vector type with same number of elements as DstVTy.
3746 auto VF = DstVTy->getElementCount();
3747 auto *SrcVecTy = cast<VectorType>(V->getType());
3748 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3749 Type *SrcElemTy = SrcVecTy->getElementType();
3750 Type *DstElemTy = DstVTy->getElementType();
3751 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3752 "Vector elements must have same size");
3753
3754 // Do a direct cast if element types are castable.
3755 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3756 return Builder.CreateBitOrPointerCast(V, DstVTy);
3757 }
3758 // V cannot be directly casted to desired vector type.
3759 // May happen when V is a floating point vector but DstVTy is a vector of
3760 // pointers or vice-versa. Handle this using a two-step bitcast using an
3761 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3762 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3763 "Only one type should be a pointer type");
3764 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3765 "Only one type should be a floating point type");
3766 Type *IntTy =
3767 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3768 auto *VecIntTy = VectorType::get(IntTy, VF);
3769 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3770 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3771}
3772
3773/// Return a vector containing interleaved elements from multiple
3774/// smaller input vectors.
3776 const Twine &Name) {
3777 unsigned Factor = Vals.size();
3778 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
3779
3780 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
3781#ifndef NDEBUG
3782 for (Value *Val : Vals)
3783 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
3784#endif
3785
3786 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
3787 // must use intrinsics to interleave.
3788 if (VecTy->isScalableTy()) {
3789 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
3790 return Builder.CreateVectorInterleave(Vals, Name);
3791 }
3792
3793 // Fixed length. Start by concatenating all vectors into a wide vector.
3794 Value *WideVec = concatenateVectors(Builder, Vals);
3795
3796 // Interleave the elements into the wide vector.
3797 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3798 return Builder.CreateShuffleVector(
3799 WideVec, createInterleaveMask(NumElts, Factor), Name);
3800}
3801
3802// Try to vectorize the interleave group that \p Instr belongs to.
3803//
3804// E.g. Translate following interleaved load group (factor = 3):
3805// for (i = 0; i < N; i+=3) {
3806// R = Pic[i]; // Member of index 0
3807// G = Pic[i+1]; // Member of index 1
3808// B = Pic[i+2]; // Member of index 2
3809// ... // do something to R, G, B
3810// }
3811// To:
3812// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
3813// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
3814// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
3815// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
3816//
3817// Or translate following interleaved store group (factor = 3):
3818// for (i = 0; i < N; i+=3) {
3819// ... do something to R, G, B
3820// Pic[i] = R; // Member of index 0
3821// Pic[i+1] = G; // Member of index 1
3822// Pic[i+2] = B; // Member of index 2
3823// }
3824// To:
3825// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
3826// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
3827// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
3828// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
3829// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
3831 assert(!State.Lane && "Interleave group being replicated.");
3832 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
3833 "Masking gaps for scalable vectors is not yet supported.");
3835 Instruction *Instr = Group->getInsertPos();
3836
3837 // Prepare for the vector type of the interleaved load/store.
3838 Type *ScalarTy = getLoadStoreType(Instr);
3839 unsigned InterleaveFactor = Group->getFactor();
3840 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
3841
3842 VPValue *BlockInMask = getMask();
3843 VPValue *Addr = getAddr();
3844 Value *ResAddr = State.get(Addr, VPLane(0));
3845
3846 auto CreateGroupMask = [&BlockInMask, &State,
3847 &InterleaveFactor](Value *MaskForGaps) -> Value * {
3848 if (State.VF.isScalable()) {
3849 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
3850 assert(InterleaveFactor <= 8 &&
3851 "Unsupported deinterleave factor for scalable vectors");
3852 auto *ResBlockInMask = State.get(BlockInMask);
3853 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
3854 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
3855 }
3856
3857 if (!BlockInMask)
3858 return MaskForGaps;
3859
3860 Value *ResBlockInMask = State.get(BlockInMask);
3861 Value *ShuffledMask = State.Builder.CreateShuffleVector(
3862 ResBlockInMask,
3863 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
3864 "interleaved.mask");
3865 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
3866 ShuffledMask, MaskForGaps)
3867 : ShuffledMask;
3868 };
3869
3870 const DataLayout &DL = Instr->getDataLayout();
3871 // Vectorize the interleaved load group.
3872 if (isa<LoadInst>(Instr)) {
3873 Value *MaskForGaps = nullptr;
3874 if (needsMaskForGaps()) {
3875 MaskForGaps =
3876 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
3877 assert(MaskForGaps && "Mask for Gaps is required but it is null");
3878 }
3879
3880 Instruction *NewLoad;
3881 if (BlockInMask || MaskForGaps) {
3882 Value *GroupMask = CreateGroupMask(MaskForGaps);
3883 Value *PoisonVec = PoisonValue::get(VecTy);
3884 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
3885 Group->getAlign(), GroupMask,
3886 PoisonVec, "wide.masked.vec");
3887 } else
3888 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
3889 Group->getAlign(), "wide.vec");
3890 applyMetadata(*NewLoad);
3891 // TODO: Also manage existing metadata using VPIRMetadata.
3892 Group->addMetadata(NewLoad);
3893
3895 if (VecTy->isScalableTy()) {
3896 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
3897 // so must use intrinsics to deinterleave.
3898 assert(InterleaveFactor <= 8 &&
3899 "Unsupported deinterleave factor for scalable vectors");
3900 NewLoad = State.Builder.CreateIntrinsic(
3901 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
3902 NewLoad->getType(), NewLoad,
3903 /*FMFSource=*/nullptr, "strided.vec");
3904 }
3905
3906 auto CreateStridedVector = [&InterleaveFactor, &State,
3907 &NewLoad](unsigned Index) -> Value * {
3908 assert(Index < InterleaveFactor && "Illegal group index");
3909 if (State.VF.isScalable())
3910 return State.Builder.CreateExtractValue(NewLoad, Index);
3911
3912 // For fixed length VF, use shuffle to extract the sub-vectors from the
3913 // wide load.
3914 auto StrideMask =
3915 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
3916 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
3917 "strided.vec");
3918 };
3919
3920 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
3921 Instruction *Member = Group->getMember(I);
3922
3923 // Skip the gaps in the group.
3924 if (!Member)
3925 continue;
3926
3927 Value *StridedVec = CreateStridedVector(I);
3928
3929 // If this member has different type, cast the result type.
3930 if (Member->getType() != ScalarTy) {
3931 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
3932 StridedVec =
3933 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
3934 }
3935
3936 if (Group->isReverse())
3937 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
3938
3939 State.set(VPDefs[J], StridedVec);
3940 ++J;
3941 }
3942 return;
3943 }
3944
3945 // The sub vector type for current instruction.
3946 auto *SubVT = VectorType::get(ScalarTy, State.VF);
3947
3948 // Vectorize the interleaved store group.
3949 Value *MaskForGaps =
3950 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
3951 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
3952 "Mismatch between NeedsMaskForGaps and MaskForGaps");
3953 ArrayRef<VPValue *> StoredValues = getStoredValues();
3954 // Collect the stored vector from each member.
3955 SmallVector<Value *, 4> StoredVecs;
3956 unsigned StoredIdx = 0;
3957 for (unsigned i = 0; i < InterleaveFactor; i++) {
3958 assert((Group->getMember(i) || MaskForGaps) &&
3959 "Fail to get a member from an interleaved store group");
3960 Instruction *Member = Group->getMember(i);
3961
3962 // Skip the gaps in the group.
3963 if (!Member) {
3964 Value *Undef = PoisonValue::get(SubVT);
3965 StoredVecs.push_back(Undef);
3966 continue;
3967 }
3968
3969 Value *StoredVec = State.get(StoredValues[StoredIdx]);
3970 ++StoredIdx;
3971
3972 if (Group->isReverse())
3973 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
3974
3975 // If this member has different type, cast it to a unified type.
3976
3977 if (StoredVec->getType() != SubVT)
3978 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
3979
3980 StoredVecs.push_back(StoredVec);
3981 }
3982
3983 // Interleave all the smaller vectors into one wider vector.
3984 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
3985 Instruction *NewStoreInstr;
3986 if (BlockInMask || MaskForGaps) {
3987 Value *GroupMask = CreateGroupMask(MaskForGaps);
3988 NewStoreInstr = State.Builder.CreateMaskedStore(
3989 IVec, ResAddr, Group->getAlign(), GroupMask);
3990 } else
3991 NewStoreInstr =
3992 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
3993
3994 applyMetadata(*NewStoreInstr);
3995 // TODO: Also manage existing metadata using VPIRMetadata.
3996 Group->addMetadata(NewStoreInstr);
3997}
3998
3999#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4001 VPSlotTracker &SlotTracker) const {
4003 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4004 IG->getInsertPos()->printAsOperand(O, false);
4005 O << ", ";
4007 VPValue *Mask = getMask();
4008 if (Mask) {
4009 O << ", ";
4010 Mask->printAsOperand(O, SlotTracker);
4011 }
4012
4013 unsigned OpIdx = 0;
4014 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4015 if (!IG->getMember(i))
4016 continue;
4017 if (getNumStoreOperands() > 0) {
4018 O << "\n" << Indent << " store ";
4020 O << " to index " << i;
4021 } else {
4022 O << "\n" << Indent << " ";
4024 O << " = load from index " << i;
4025 }
4026 ++OpIdx;
4027 }
4028}
4029#endif
4030
4032 assert(!State.Lane && "Interleave group being replicated.");
4033 assert(State.VF.isScalable() &&
4034 "Only support scalable VF for EVL tail-folding.");
4036 "Masking gaps for scalable vectors is not yet supported.");
4038 Instruction *Instr = Group->getInsertPos();
4039
4040 // Prepare for the vector type of the interleaved load/store.
4041 Type *ScalarTy = getLoadStoreType(Instr);
4042 unsigned InterleaveFactor = Group->getFactor();
4043 assert(InterleaveFactor <= 8 &&
4044 "Unsupported deinterleave/interleave factor for scalable vectors");
4045 ElementCount WideVF = State.VF * InterleaveFactor;
4046 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4047
4048 VPValue *Addr = getAddr();
4049 Value *ResAddr = State.get(Addr, VPLane(0));
4050 Value *EVL = State.get(getEVL(), VPLane(0));
4051 Value *InterleaveEVL = State.Builder.CreateMul(
4052 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4053 /* NUW= */ true, /* NSW= */ true);
4054 LLVMContext &Ctx = State.Builder.getContext();
4055
4056 Value *GroupMask = nullptr;
4057 if (VPValue *BlockInMask = getMask()) {
4058 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4059 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4060 } else {
4061 GroupMask =
4062 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4063 }
4064
4065 // Vectorize the interleaved load group.
4066 if (isa<LoadInst>(Instr)) {
4067 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4068 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4069 "wide.vp.load");
4070 NewLoad->addParamAttr(0,
4071 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4072
4073 applyMetadata(*NewLoad);
4074 // TODO: Also manage existing metadata using VPIRMetadata.
4075 Group->addMetadata(NewLoad);
4076
4077 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4078 // so must use intrinsics to deinterleave.
4079 NewLoad = State.Builder.CreateIntrinsic(
4080 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4081 NewLoad->getType(), NewLoad,
4082 /*FMFSource=*/nullptr, "strided.vec");
4083
4084 const DataLayout &DL = Instr->getDataLayout();
4085 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4086 Instruction *Member = Group->getMember(I);
4087 // Skip the gaps in the group.
4088 if (!Member)
4089 continue;
4090
4091 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4092 // If this member has different type, cast the result type.
4093 if (Member->getType() != ScalarTy) {
4094 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4095 StridedVec =
4096 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4097 }
4098
4099 State.set(getVPValue(J), StridedVec);
4100 ++J;
4101 }
4102 return;
4103 } // End for interleaved load.
4104
4105 // The sub vector type for current instruction.
4106 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4107 // Vectorize the interleaved store group.
4108 ArrayRef<VPValue *> StoredValues = getStoredValues();
4109 // Collect the stored vector from each member.
4110 SmallVector<Value *, 4> StoredVecs;
4111 const DataLayout &DL = Instr->getDataLayout();
4112 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4113 Instruction *Member = Group->getMember(I);
4114 // Skip the gaps in the group.
4115 if (!Member) {
4116 StoredVecs.push_back(PoisonValue::get(SubVT));
4117 continue;
4118 }
4119
4120 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4121 // If this member has different type, cast it to a unified type.
4122 if (StoredVec->getType() != SubVT)
4123 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4124
4125 StoredVecs.push_back(StoredVec);
4126 ++StoredIdx;
4127 }
4128
4129 // Interleave all the smaller vectors into one wider vector.
4130 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4131 CallInst *NewStore =
4132 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4133 {IVec, ResAddr, GroupMask, InterleaveEVL});
4134 NewStore->addParamAttr(1,
4135 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4136
4137 applyMetadata(*NewStore);
4138 // TODO: Also manage existing metadata using VPIRMetadata.
4139 Group->addMetadata(NewStore);
4140}
4141
4142#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4144 VPSlotTracker &SlotTracker) const {
4146 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4147 IG->getInsertPos()->printAsOperand(O, false);
4148 O << ", ";
4150 O << ", ";
4152 if (VPValue *Mask = getMask()) {
4153 O << ", ";
4154 Mask->printAsOperand(O, SlotTracker);
4155 }
4156
4157 unsigned OpIdx = 0;
4158 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4159 if (!IG->getMember(i))
4160 continue;
4161 if (getNumStoreOperands() > 0) {
4162 O << "\n" << Indent << " vp.store ";
4164 O << " to index " << i;
4165 } else {
4166 O << "\n" << Indent << " ";
4168 O << " = vp.load from index " << i;
4169 }
4170 ++OpIdx;
4171 }
4172}
4173#endif
4174
4176 VPCostContext &Ctx) const {
4177 Instruction *InsertPos = getInsertPos();
4178 // Find the VPValue index of the interleave group. We need to skip gaps.
4179 unsigned InsertPosIdx = 0;
4180 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4181 if (auto *Member = IG->getMember(Idx)) {
4182 if (Member == InsertPos)
4183 break;
4184 InsertPosIdx++;
4185 }
4186 Type *ValTy = Ctx.Types.inferScalarType(
4187 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4188 : getStoredValues()[InsertPosIdx]);
4189 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4190 unsigned AS = getLoadStoreAddressSpace(InsertPos);
4191
4192 unsigned InterleaveFactor = IG->getFactor();
4193 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4194
4195 // Holds the indices of existing members in the interleaved group.
4197 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4198 if (IG->getMember(IF))
4199 Indices.push_back(IF);
4200
4201 // Calculate the cost of the whole interleaved group.
4202 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4203 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4204 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4205
4206 if (!IG->isReverse())
4207 return Cost;
4208
4209 return Cost + IG->getNumMembers() *
4210 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4211 VectorTy, VectorTy, {}, Ctx.CostKind,
4212 0);
4213}
4214
4215#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4217 VPSlotTracker &SlotTracker) const {
4218 O << Indent << "EMIT ";
4220 O << " = CANONICAL-INDUCTION ";
4222}
4223#endif
4224
4226 return IsScalarAfterVectorization &&
4227 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4228}
4229
4230#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4232 VPSlotTracker &SlotTracker) const {
4233 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4234 "unexpected number of operands");
4235 O << Indent << "EMIT ";
4237 O << " = WIDEN-POINTER-INDUCTION ";
4239 O << ", ";
4241 O << ", ";
4243 if (getNumOperands() == 5) {
4244 O << ", ";
4246 O << ", ";
4248 }
4249}
4250
4252 VPSlotTracker &SlotTracker) const {
4253 O << Indent << "EMIT ";
4255 O << " = EXPAND SCEV " << *Expr;
4256}
4257#endif
4258
4260 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4261 Type *STy = CanonicalIV->getType();
4262 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4263 ElementCount VF = State.VF;
4264 Value *VStart = VF.isScalar()
4265 ? CanonicalIV
4266 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4267 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4268 if (VF.isVector()) {
4269 VStep = Builder.CreateVectorSplat(VF, VStep);
4270 VStep =
4271 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4272 }
4273 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4274 State.set(this, CanonicalVectorIV);
4275}
4276
4277#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4279 VPSlotTracker &SlotTracker) const {
4280 O << Indent << "EMIT ";
4282 O << " = WIDEN-CANONICAL-INDUCTION ";
4284}
4285#endif
4286
4288 auto &Builder = State.Builder;
4289 // Create a vector from the initial value.
4290 auto *VectorInit = getStartValue()->getLiveInIRValue();
4291
4292 Type *VecTy = State.VF.isScalar()
4293 ? VectorInit->getType()
4294 : VectorType::get(VectorInit->getType(), State.VF);
4295
4296 BasicBlock *VectorPH =
4297 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4298 if (State.VF.isVector()) {
4299 auto *IdxTy = Builder.getInt32Ty();
4300 auto *One = ConstantInt::get(IdxTy, 1);
4301 IRBuilder<>::InsertPointGuard Guard(Builder);
4302 Builder.SetInsertPoint(VectorPH->getTerminator());
4303 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4304 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4305 VectorInit = Builder.CreateInsertElement(
4306 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4307 }
4308
4309 // Create a phi node for the new recurrence.
4310 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4311 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4312 Phi->addIncoming(VectorInit, VectorPH);
4313 State.set(this, Phi);
4314}
4315
4318 VPCostContext &Ctx) const {
4319 if (VF.isScalar())
4320 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4321
4322 return 0;
4323}
4324
4325#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4327 VPSlotTracker &SlotTracker) const {
4328 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4330 O << " = phi ";
4332}
4333#endif
4334
4336 // Reductions do not have to start at zero. They can start with
4337 // any loop invariant values.
4338 VPValue *StartVPV = getStartValue();
4339
4340 // In order to support recurrences we need to be able to vectorize Phi nodes.
4341 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4342 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4343 // this value when we vectorize all of the instructions that use the PHI.
4344 BasicBlock *VectorPH =
4345 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4346 bool ScalarPHI = State.VF.isScalar() || IsInLoop;
4347 Value *StartV = State.get(StartVPV, ScalarPHI);
4348 Type *VecTy = StartV->getType();
4349
4350 BasicBlock *HeaderBB = State.CFG.PrevBB;
4351 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4352 "recipe must be in the vector loop header");
4353 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4354 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4355 State.set(this, Phi, IsInLoop);
4356
4357 Phi->addIncoming(StartV, VectorPH);
4358}
4359
4360#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4362 VPSlotTracker &SlotTracker) const {
4363 O << Indent << "WIDEN-REDUCTION-PHI ";
4364
4366 O << " = phi ";
4368 if (VFScaleFactor != 1)
4369 O << " (VF scaled by 1/" << VFScaleFactor << ")";
4370}
4371#endif
4372
4374 Value *Op0 = State.get(getOperand(0));
4375 Type *VecTy = Op0->getType();
4376 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4377 State.set(this, VecPhi);
4378}
4379
4380#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4382 VPSlotTracker &SlotTracker) const {
4383 O << Indent << "WIDEN-PHI ";
4384
4386 O << " = phi ";
4388}
4389#endif
4390
4391// TODO: It would be good to use the existing VPWidenPHIRecipe instead and
4392// remove VPActiveLaneMaskPHIRecipe.
4394 BasicBlock *VectorPH =
4395 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4396 Value *StartMask = State.get(getOperand(0));
4397 PHINode *Phi =
4398 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4399 Phi->addIncoming(StartMask, VectorPH);
4400 State.set(this, Phi);
4401}
4402
4403#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4405 VPSlotTracker &SlotTracker) const {
4406 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4407
4409 O << " = phi ";
4411}
4412#endif
4413
4414#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4416 VPSlotTracker &SlotTracker) const {
4417 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
4418
4420 O << " = phi ";
4422}
4423#endif
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition Compiler.h:404
iv users
Definition IVUsers.cpp:48
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
#define I(x, y, z)
Definition MD5.cpp:58
mir Rename Register Operands
static bool isOrdered(const Instruction *I)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
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)
static Type * getGEPIndexTy(bool IsScalable, bool IsReverse, bool IsUnitStride, unsigned CurrentPart, IRBuilderBase &Builder)
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 bool shouldUseAddressAccessSCEV(const VPValue *Ptr)
Returns true if Ptr is a pointer computation for which the legacy cost model computes a SCEV expressi...
static Constant * getSignedIntOrFpConstant(Type *Ty, int64_t C)
A helper function that returns an integer or floating-point constant with value C.
static BranchInst * createCondBranch(Value *Cond, VPBasicBlock *VPBB, VPTransformState &State)
Create a conditional branch using Cond branching to the successors of VPBB.
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
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
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
Conditional or Unconditional Branch instruction.
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)
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:131
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:163
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
A debug info location.
Definition DebugLoc.h:124
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:325
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:313
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:310
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:321
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
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
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:271
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:2574
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2628
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2562
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:2621
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:2640
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
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
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2085
LLVMContext & getContext() const
Definition IRBuilder.h:203
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 * 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:2783
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:319
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
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
std::pair< MDNode *, MDNode * > getNoAliasMetadataFor(const Instruction *OrigInst) const
Returns a pair containing the alias_scope and noalias metadata nodes for OrigInst,...
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 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 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:298
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:297
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:281
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:231
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:294
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:301
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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:3785
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:3838
iterator end()
Definition VPlan.h:3822
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:3851
void print(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 VPWidenMemoryRecipe.
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:2432
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2427
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:82
VPRegionBlock * getParent()
Definition VPlan.h:174
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:205
VPlan * getPlan()
Definition VPlan.cpp:165
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:357
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:199
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.
void print(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:302
void dump() const
Dump the VPDef to stderr (for debugging).
Definition VPlan.cpp:126
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:424
ArrayRef< VPValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:419
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:397
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:409
friend class VPValue
Definition VPlanValue.h:303
unsigned getVPDefID() const
Definition VPlanValue.h:429
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
Definition VPlan.h:3662
VPValue * getStartValue() const
Definition VPlan.h:3661
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(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.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
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.
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:2015
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
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:1711
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Class to record and manage LLVM IR flags.
Definition VPlan.h:601
FastMathFlagsTy FMFs
Definition VPlan.h:665
bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:659
CmpInst::Predicate CmpPredicate
Definition VPlan.h:658
void printFlags(raw_ostream &O) const
GEPNoWrapFlags GEPFlags
Definition VPlan.h:663
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:823
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
TruncFlagsTy TruncFlags
Definition VPlan.h:660
CmpInst::Predicate getPredicate() const
Definition VPlan.h:805
ExactFlagsTy ExactFlags
Definition VPlan.h:662
bool hasNoSignedWrap() const
Definition VPlan.h:847
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:817
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:820
DisjointFlagsTy DisjointFlags
Definition VPlan.h:661
unsigned AllFlags
Definition VPlan.h:666
bool hasNoUnsignedWrap() const
Definition VPlan.h:836
NonNegFlagsTy NonNegFlags
Definition VPlan.h:664
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:768
Instruction & getInstruction() const
Definition VPlan.h:1376
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void extractLastLaneOfFirstOperand(VPBuilder &Builder)
Update the recipes first operand to the last lane of the operand using Builder.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1351
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetada object with MD, keeping only metadata nodes that are common to both.
void applyMetadata(Instruction &I) const
Add all metadata to I.
void print(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.
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Definition VPlan.h:1101
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:1061
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1017
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1051
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1064
@ FirstOrderRecurrenceSplice
Definition VPlan.h:990
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1055
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1014
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1011
@ VScale
Returns the value for vscale.
Definition VPlan.h:1066
@ CanonicalIVIncrementForPart
Definition VPlan.h:1004
bool hasResult() const
Definition VPlan.h:1140
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).
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1180
unsigned getOpcode() const
Definition VPlan.h:1120
bool onlyFirstPartUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
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 needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:2542
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2546
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2544
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2536
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2565
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2530
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2639
void print(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:2658
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:2609
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
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()
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void print(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 VPPartialReductionRecipe.
unsigned getOpcode() const
Get the binary op's opcode.
Definition VPlan.h:2796
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:1266
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:3929
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:1291
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1258
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 print(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:395
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
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:416
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:483
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:406
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2841
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(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:2738
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:2742
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:2744
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:2734
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:2740
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:3973
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4041
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:2856
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:2901
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPReplicateRecipe.
unsigned getOpcode() const
Definition VPlan.h:2930
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
Definition VPlan.h:3727
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:522
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:587
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:524
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:931
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:199
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1458
operand_range operands()
Definition VPlanValue.h:267
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:243
unsigned getNumOperands() const
Definition VPlanValue.h:237
operand_iterator op_begin()
Definition VPlanValue.h:263
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:238
virtual bool onlyFirstLaneUsed(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:282
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1412
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:135
friend class VPExpressionRecipe
Definition VPlanValue.h:53
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1454
bool hasMoreThanOneUniqueUser() const
Returns true if the value has more than one unique user.
Definition VPlanValue.h:140
Value * getLiveInIRValue() const
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition VPlanValue.h:176
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:85
VPValue(const unsigned char SC, Value *UV=nullptr, VPDef *Def=nullptr)
Definition VPlan.cpp:98
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1415
user_iterator user_begin()
Definition VPlanValue.h:130
unsigned getNumUsers() const
Definition VPlanValue.h:113
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the VPlan.
Definition VPlanValue.h:171
user_range users()
Definition VPlanValue.h:134
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getSourceElementType() const
Definition VPlan.h:1915
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
operand_range args()
Definition VPlan.h:1668
Function * getCalledScalarFunction() const
Definition VPlan.h:1664
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 execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void print(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:1537
void execute(VPTransformState &State) override
Produce widened copies of the cast.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:1812
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2071
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2182
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2191
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:1602
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Return the scalar return type of the intrinsic.
Definition VPlan.h:1605
void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
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:3165
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3162
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3202
Instruction & Ingredient
Definition VPlan.h:3156
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:3159
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3216
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3209
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3206
void print(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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1440
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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getUF() const
Definition VPlan.h:4305
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1049
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:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
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:253
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
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
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.
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...
Definition VPlanUtils.h:44
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.
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:318
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:477
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:831
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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.
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:1727
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2474
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:644
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:733
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:2138
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2233
auto cast_or_null(const Y &Val)
Definition Casting.h:715
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.
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:754
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:1734
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1741
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:548
bool canConstantBeExtended(const ConstantInt *CI, Type *NarrowType, TTI::PartialReductionExtendKind ExtKind)
Check if a constant CI can be safely treated as having been extended from a narrower type with the gi...
Definition VPlan.cpp:1756
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:325
@ 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.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ 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
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:560
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1899
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.
unsigned getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind)
A helper function that returns how much we should divide the cost of a predicated block by.
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 print(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:1413
PHINode & getIRPhi()
Definition VPlan.h:1421
void print(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 print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the instruction.
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:876
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, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:877
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
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:293
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.
void execute(VPTransformState &State) override
Generate the wide load or gather.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3289
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a wide load or gather.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool isInvariantCond() const
Definition VPlan.h:1757
VPValue * getCond() const
Definition VPlan.h:1753
void print(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 VPWidenSelectRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the select instruction.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3370
void execute(VPTransformState &State) override
Generate the wide store or scatter.
void print(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 VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3373
void execute(VPTransformState &State) override
Generate a wide store or scatter.
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3334
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.