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