LLVM 24.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 "VPlanHelpers.h"
17#include "VPlanPatternMatch.h"
18#include "VPlanUtils.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Twine.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/Format.h"
42#include <cassert>
43
44using namespace llvm;
45using namespace llvm::VPlanPatternMatch;
46
47#define LV_NAME "loop-vectorize"
48#define DEBUG_TYPE LV_NAME
49
50#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
51// It is sometimes necessary to disable printing of metadata in tests in order
52// to avoid non-deterministic behaviour due to metadata introduced by VPlan
53// that wasn't present in the original scalar IR.
55 "vplan-print-metadata", cl::init(true), cl::Hidden,
56 cl::desc("Controls the printing of recipe metadata when debugging."));
57#endif
58
59namespace llvm {
61} // namespace llvm
62
64 switch (getVPRecipeID()) {
65 case VPExpressionSC:
66 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
67 case VPInstructionSC: {
68 auto *VPI = cast<VPInstruction>(this);
69 // Loads read from memory but don't write to memory.
70 if (VPI->getOpcode() == Instruction::Load)
71 return false;
72 return VPI->opcodeMayReadOrWriteFromMemory();
73 }
74 case VPInterleaveEVLSC:
75 case VPInterleaveSC:
76 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
77 case VPWidenStoreEVLSC:
78 case VPWidenStoreSC:
79 return true;
80 case VPReplicateSC:
81 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
82 ->mayWriteToMemory();
83 case VPWidenCallSC:
84 return !cast<VPWidenCallRecipe>(this)
85 ->getCalledScalarFunction()
86 ->onlyReadsMemory();
87 case VPWidenMemIntrinsicSC:
88 case VPWidenIntrinsicSC:
89 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
90 case VPActiveLaneMaskPHISC:
91 case VPCurrentIterationPHISC:
92 case VPBranchOnMaskSC:
93 case VPDerivedIVSC:
94 case VPFirstOrderRecurrencePHISC:
95 case VPReductionPHISC:
96 case VPScalarIVStepsSC:
97 case VPPredInstPHISC:
98 case VPExpandSCEVSC:
99 return false;
100 case VPBlendSC:
101 case VPReductionEVLSC:
102 case VPReductionSC:
103 case VPVectorPointerSC:
104 case VPWidenCanonicalIVSC:
105 case VPWidenCastSC:
106 case VPWidenGEPSC:
107 case VPWidenIntOrFpInductionSC:
108 case VPWidenLoadEVLSC:
109 case VPWidenLoadSC:
110 case VPWidenPHISC:
111 case VPWidenPointerInductionSC:
112 case VPWidenSC: {
113 const Instruction *I =
114 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
115 (void)I;
116 assert((!I || !I->mayWriteToMemory()) &&
117 "underlying instruction may write to memory");
118 return false;
119 }
120 default:
121 return true;
122 }
123}
124
126 switch (getVPRecipeID()) {
127 case VPExpressionSC:
128 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
129 case VPInstructionSC:
130 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
131 case VPWidenLoadEVLSC:
132 case VPWidenLoadSC:
133 return true;
134 case VPReplicateSC:
135 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
136 ->mayReadFromMemory();
137 case VPWidenCallSC:
138 return !cast<VPWidenCallRecipe>(this)
139 ->getCalledScalarFunction()
140 ->onlyWritesMemory();
141 case VPWidenMemIntrinsicSC:
142 case VPWidenIntrinsicSC:
143 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
144 case VPBranchOnMaskSC:
145 case VPDerivedIVSC:
146 case VPCurrentIterationPHISC:
147 case VPFirstOrderRecurrencePHISC:
148 case VPReductionPHISC:
149 case VPPredInstPHISC:
150 case VPScalarIVStepsSC:
151 case VPWidenStoreEVLSC:
152 case VPWidenStoreSC:
153 case VPExpandSCEVSC:
154 return false;
155 case VPBlendSC:
156 case VPReductionEVLSC:
157 case VPReductionSC:
158 case VPVectorPointerSC:
159 case VPWidenCanonicalIVSC:
160 case VPWidenCastSC:
161 case VPWidenGEPSC:
162 case VPWidenIntOrFpInductionSC:
163 case VPWidenPHISC:
164 case VPWidenPointerInductionSC:
165 case VPWidenSC: {
166 const Instruction *I =
167 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
168 (void)I;
169 assert((!I || !I->mayReadFromMemory()) &&
170 "underlying instruction may read from memory");
171 return false;
172 }
173 default:
174 // FIXME: Return false if the recipe represents an interleaved store.
175 return true;
176 }
177}
178
180 switch (getVPRecipeID()) {
181 case VPExpressionSC:
182 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
183 case VPActiveLaneMaskPHISC:
184 case VPDerivedIVSC:
185 case VPCurrentIterationPHISC:
186 case VPFirstOrderRecurrencePHISC:
187 case VPReductionPHISC:
188 case VPPredInstPHISC:
189 case VPVectorEndPointerSC:
190 case VPExpandSCEVSC:
191 return false;
192 case VPInstructionSC: {
193 auto *VPI = cast<VPInstruction>(this);
194 return mayWriteToMemory() ||
195 VPI->getOpcode() == VPInstruction::BranchOnCount ||
196 VPI->getOpcode() == VPInstruction::BranchOnCond ||
197 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
198 }
199 case VPWidenCallSC: {
200 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
201 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
202 }
203 case VPWidenMemIntrinsicSC:
204 case VPWidenIntrinsicSC:
205 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
206 case VPBlendSC:
207 case VPReductionEVLSC:
208 case VPReductionSC:
209 case VPScalarIVStepsSC:
210 case VPVectorPointerSC:
211 case VPWidenCanonicalIVSC:
212 case VPWidenCastSC:
213 case VPWidenGEPSC:
214 case VPWidenIntOrFpInductionSC:
215 case VPWidenPHISC:
216 case VPWidenPointerInductionSC:
217 case VPWidenSC: {
218 const Instruction *I =
219 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
220 (void)I;
221 assert((!I || !I->mayHaveSideEffects()) &&
222 "underlying instruction has side-effects");
223 return false;
224 }
225 case VPInterleaveEVLSC:
226 case VPInterleaveSC:
227 return mayWriteToMemory();
228 case VPWidenLoadEVLSC:
229 case VPWidenLoadSC:
230 case VPWidenStoreEVLSC:
231 case VPWidenStoreSC:
232 assert(
233 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
235 "mayHaveSideffects result for ingredient differs from this "
236 "implementation");
237 return mayWriteToMemory();
238 case VPReplicateSC: {
239 auto *R = cast<VPReplicateRecipe>(this);
240 return R->getUnderlyingInstr()->mayHaveSideEffects();
241 }
242 default:
243 return true;
244 }
245}
246
248 switch (getVPRecipeID()) {
249 default:
250 return false;
251 case VPInstructionSC: {
252 unsigned Opcode = cast<VPInstruction>(this)->getOpcode();
253 if (Instruction::isCast(Opcode))
254 return true;
255
256 switch (Opcode) {
257 default:
258 return false;
259 case Instruction::Add:
260 case Instruction::Sub:
261 case Instruction::Mul:
262 case Instruction::GetElementPtr:
263 return true;
264 }
265 }
266 }
267}
268
270 assert(!Parent && "Recipe already in some VPBasicBlock");
271 assert(InsertPos->getParent() &&
272 "Insertion position not in any VPBasicBlock");
273 InsertPos->getParent()->insert(this, InsertPos->getIterator());
274}
275
276void VPRecipeBase::insertBefore(VPBasicBlock &BB,
278 assert(!Parent && "Recipe already in some VPBasicBlock");
279 assert(I == BB.end() || I->getParent() == &BB);
280 BB.insert(this, I);
281}
282
284 assert(!Parent && "Recipe already in some VPBasicBlock");
285 assert(InsertPos->getParent() &&
286 "Insertion position not in any VPBasicBlock");
287 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
288}
289
291 assert(getParent() && "Recipe not in any VPBasicBlock");
293 Parent = nullptr;
294}
295
297 assert(getParent() && "Recipe not in any VPBasicBlock");
299}
300
303 insertAfter(InsertPos);
304}
305
311
313 // Get the underlying instruction for the recipe, if there is one. It is used
314 // to
315 // * decide if cost computation should be skipped for this recipe,
316 // * apply forced target instruction cost.
317 Instruction *UI = nullptr;
318 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
319 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
320 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
321 UI = IG->getInsertPos();
322 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
323 UI = &WidenMem->getIngredient();
324
325 InstructionCost RecipeCost;
326 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
327 RecipeCost = 0;
328 } else {
329 RecipeCost = computeCost(VF, Ctx);
330 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
331 RecipeCost.isValid()) {
332 // VPDerivedIVRecipe and VPScalarIVStepsRecipe never have underlying
333 // instructions.
336 else
337 RecipeCost = InstructionCost(0);
338 }
339 }
340
341 LLVM_DEBUG({
342 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
343 if (VPSlotTracker *SlotTracker = Ctx.getSlotTracker()) {
344 print(dbgs(), "", *SlotTracker);
345 dbgs() << "\n";
346 } else {
347 dump();
348 }
349 });
350 return RecipeCost;
351}
352
354 VPCostContext &Ctx) const {
355 llvm_unreachable("subclasses should implement computeCost");
356}
357
359 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
361}
362
364 assert(OpType == Other.OpType && "OpType must match");
365 switch (OpType) {
366 case OperationType::OverflowingBinOp:
367 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
368 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
369 break;
370 case OperationType::Trunc:
371 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
372 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
373 break;
374 case OperationType::DisjointOp:
375 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
376 break;
377 case OperationType::PossiblyExactOp:
378 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
379 break;
380 case OperationType::GEPOp:
381 GEPFlagsStorage &= Other.GEPFlagsStorage;
382 break;
383 case OperationType::FPMathOp:
384 case OperationType::FCmp:
385 assert((OpType != OperationType::FCmp ||
386 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
387 "Cannot drop CmpPredicate");
388 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
389 break;
390 case OperationType::NonNegOp:
391 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
392 break;
393 case OperationType::Cmp:
394 assert(CmpPredStorage == Other.CmpPredStorage &&
395 "Cannot drop CmpPredicate");
396 break;
397 case OperationType::ReductionOp:
398 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
399 "Cannot change RecurKind");
400 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
401 "Cannot change IsOrdered");
402 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
403 "Cannot change IsInLoop");
404 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
405 break;
406 case OperationType::Other:
407 break;
408 }
409}
410
412 if (!hasFastMathFlags())
413 return {};
414 const FastMathFlagsTy &F = getFMFsRef();
415 FastMathFlags Res;
416 Res.setAllowReassoc(F.AllowReassoc);
417 Res.setNoNaNs(F.NoNaNs);
418 Res.setNoInfs(F.NoInfs);
419 Res.setNoSignedZeros(F.NoSignedZeros);
420 Res.setAllowReciprocal(F.AllowReciprocal);
421 Res.setAllowContract(F.AllowContract);
422 Res.setApproxFunc(F.ApproxFunc);
423 return Res;
424}
425
426#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
428
429void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
430 VPSlotTracker &SlotTracker) const {
431 printRecipe(O, Indent, SlotTracker);
432 if (auto DL = getDebugLoc()) {
433 O << ", !dbg ";
434 DL.print(O);
435 }
436
437 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
439}
440#endif
441
443 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
444 Expr(Expr) {}
445
446/// For call VPInstruction operands, return the operand index of the called
447/// function. The function is either the last operand (for unmasked calls) or
448/// the second-to-last operand (for masked calls).
450 unsigned NumOps = Operands.size();
451 auto *LastOp = dyn_cast<VPIRValue>(Operands[NumOps - 1]);
452 if (LastOp && isa<Function>(LastOp->getValue()))
453 return NumOps - 1;
455 "expected function operand");
456 return NumOps - 2;
457}
458
459/// For call VPInstruction operands, return the called function.
464
467 assert(!Operands.empty() &&
468 "zero-operand VPInstruction opcodes must pass explicit ResultTy");
469 // Assert operand \p Idx (if present and typed) has type \p ExpectedTy.
470 [[maybe_unused]] auto AssertOperandType = [&Operands](unsigned Idx,
471 Type *ExpectedTy) {
472 if (!ExpectedTy || Operands.size() <= Idx)
473 return;
474 [[maybe_unused]] Type *OpTy = Operands[Idx]->getScalarType();
475 assert((!OpTy || OpTy == ExpectedTy) &&
476 "different types inferred for different operands");
477 };
478
479 Type *Op0Ty = Operands[0]->getScalarType();
480 LLVMContext &Ctx = Op0Ty->getContext();
481 switch (Opcode) {
483 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
484 return Type::getVoidTy(Ctx);
486 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
487 AssertOperandType(1, IntegerType::get(Ctx, 1));
488 return Type::getVoidTy(Ctx);
490 assert(Op0Ty->isIntegerTy() && "expected integer operand");
491 AssertOperandType(1, Op0Ty);
492 return Type::getVoidTy(Ctx);
494 assert(Op0Ty->isIntegerTy() && "expected integer operand");
495 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
496 AssertOperandType(Idx, Op0Ty);
497 return Op0Ty;
498 case Instruction::Switch:
499 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
500 AssertOperandType(Idx, Op0Ty);
501 return Type::getVoidTy(Ctx);
502 case Instruction::Store:
503 return Type::getVoidTy(Ctx);
504 case Instruction::ICmp:
505 assert(Op0Ty->isIntOrPtrTy() && "expected integer or pointer operand");
506 AssertOperandType(1, Op0Ty);
507 return IntegerType::get(Ctx, 1);
508 case Instruction::FCmp:
509 assert(Op0Ty->isFloatingPointTy() && "expected floating-point operand");
510 AssertOperandType(1, Op0Ty);
511 return IntegerType::get(Ctx, 1);
514 assert(Op0Ty->isIntegerTy() && "expected integer operand");
515 AssertOperandType(1, Op0Ty);
516 return IntegerType::get(Ctx, 1);
518 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
519 return IntegerType::get(Ctx, 1);
522 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
523 AssertOperandType(1, Op0Ty);
524 return IntegerType::get(Ctx, 1);
526 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
527 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
528 AssertOperandType(Idx, Op0Ty);
529 return IntegerType::get(Ctx, 1);
531 assert(Op0Ty->isIntegerTy() && "expected integer operand");
532 return IntegerType::get(Ctx, 32);
533 case Instruction::Select: {
534 assert((!Op0Ty || Op0Ty->isIntegerTy(1)) &&
535 "select condition must be bool");
536 Type *Op1Ty = Operands[1]->getScalarType();
537 AssertOperandType(2, Op1Ty);
538 return Op1Ty;
539 }
540 case Instruction::InsertElement:
541 // The inserted scalar (operand 1) must match the vector element type;
542 // operand 2 must be an integer.
543 AssertOperandType(1, Op0Ty);
544 assert(Operands[2]->getScalarType()->isIntegerTy() &&
545 "expected integer operand");
546 return Op0Ty;
548 // The start value and the identity value (operands 0 and 1) fill the same
549 // vector and must match in type; operand 2 is the scaling factor.
550 AssertOperandType(1, Op0Ty);
551 return Op0Ty;
553 assert(Operands.size() >= 2 && "ExtractLane requires a lane operand and "
554 "at least one source vector operand");
555 // Operand 0 is the lane index, used for integer arithmetic.
556 assert(Op0Ty->isIntegerTy() && "expected integer operand");
557 Type *Op1Ty = Operands[1]->getScalarType();
558 for (unsigned Idx = 2; Idx != Operands.size(); ++Idx)
559 AssertOperandType(Idx, Op1Ty);
560 return Op1Ty;
561 }
564 assert(Operands[0]->getScalarType()->isPointerTy() &&
565 "expected pointer operand");
566 assert(Operands[1]->getScalarType()->isIntegerTy() &&
567 "expected integer operand");
568 return Op0Ty;
569 case Instruction::ExtractValue: {
570 assert(Operands.size() == 2 && "expected single level extractvalue");
571 auto *StructTy = cast<StructType>(Op0Ty);
572 return StructTy->getTypeAtIndex(
573 cast<VPConstantInt>(Operands[1])->getZExtValue());
574 }
579 case Instruction::Load:
580 case Instruction::Alloca:
581 llvm_unreachable("type must be passed explicitly");
582 case Instruction::Call:
584 default:
585 if (Instruction::isCast(Opcode))
586 llvm_unreachable("type must be passed explicitly");
587 break;
588 }
589
590 // Opcodes that require all operands to share the same scalar type as the
591 // result.
592 bool AllOperandsSameType =
593 Instruction::isBinaryOp(Opcode) ||
597 Opcode);
598 if (AllOperandsSameType)
599 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
600 AssertOperandType(Idx, Op0Ty);
601
602 return Op0Ty;
603}
604
607 unsigned Opcode = I->getOpcode();
608 if (Instruction::isCast(Opcode) ||
609 is_contained(ArrayRef<unsigned>({Instruction::ExtractValue,
610 Instruction::Load, Instruction::Alloca}),
611 Opcode))
612 return I->getType();
614}
615
617 const VPIRFlags &Flags, const VPIRMetadata &MD,
618 DebugLoc DL, const Twine &Name, Type *ResultTy)
620 VPRecipeBase::VPInstructionSC, Operands,
621 ResultTy ? ResultTy
623 Flags, DL),
624 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
626 "Set flags not supported for the provided opcode");
628 "Opcode requires specific flags to be set");
632 "number of operands does not match opcode");
633}
634
636 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
637 return 1;
638
639 if (Instruction::isBinaryOp(Opcode))
640 return 2;
641
642 switch (Opcode) {
645 return 0;
646 case Instruction::Alloca:
647 case Instruction::ExtractValue:
648 case Instruction::Freeze:
649 case Instruction::Load:
662 return 1;
663 case Instruction::ICmp:
664 case Instruction::FCmp:
665 case Instruction::ExtractElement:
666 case Instruction::Store:
678 return 2;
679 case Instruction::InsertElement:
680 case Instruction::Select:
683 return 3;
684 case Instruction::Call:
685 return getCalledFnOperandIndex(operands()) + 1;
686 case Instruction::GetElementPtr:
687 case Instruction::PHI:
688 case Instruction::Switch:
689 case Instruction::AtomicRMW:
690 case Instruction::AtomicCmpXchg:
691 case Instruction::Fence:
702 // Cannot determine the number of operands from the opcode.
703 return -1u;
704 }
705 llvm_unreachable("all cases should be handled above");
706}
707
709 return Opcode == VPInstruction::Unpack ||
711}
712
713bool VPInstruction::canGenerateScalarForFirstLane() const {
715 return true;
717 return true;
718 switch (Opcode) {
719 case Instruction::Freeze:
720 case Instruction::ICmp:
721 case Instruction::PHI:
722 case Instruction::Select:
731 return true;
732 default:
733 return false;
734 }
735}
736
738 if (Kind == RecurKind::Sub)
739 return Instruction::Add;
740 if (Kind == RecurKind::FSub)
741 return Instruction::FAdd;
742 llvm_unreachable("RecurKind should be Sub/FSub.");
743}
744
745Value *VPInstruction::generate(VPTransformState &State) {
746 IRBuilderBase &Builder = State.Builder;
747
749 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
750 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
751 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
752 auto *Res =
753 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
754 if (auto *I = dyn_cast<Instruction>(Res))
755 applyFlags(*I);
756 return Res;
757 }
759 Value *Op = State.get(getOperand(0), VPLane(0));
761 getScalarType());
762 if (auto *CastOp = dyn_cast<Instruction>(Res)) {
763 applyFlags(*CastOp);
764 applyMetadata(*CastOp);
765 }
766 return Res;
767 }
768
769 switch (getOpcode()) {
770 case VPInstruction::Not: {
771 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
772 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
773 return Builder.CreateNot(A, Name);
774 }
775 case Instruction::ExtractElement: {
776 assert(State.VF.isVector() && "Only extract elements from vectors");
777 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
778 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
779 Value *Vec = State.get(getOperand(0));
780 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
781 return Builder.CreateExtractElement(Vec, Idx, Name);
782 }
783 case Instruction::InsertElement: {
784 assert(State.VF.isVector() && "Can only insert elements into vectors");
785 Value *Vec = State.get(getOperand(0), /*IsScalar=*/false);
786 Value *Elt = State.get(getOperand(1), /*IsScalar=*/true);
787 Value *Idx = State.get(getOperand(2), /*IsScalar=*/true);
788 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
789 }
790 case Instruction::Freeze: {
792 return Builder.CreateFreeze(Op, Name);
793 }
794 case Instruction::FCmp:
795 case Instruction::ICmp: {
796 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
797 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
798 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
799 return Builder.CreateCmp(getPredicate(), A, B, Name);
800 }
801 case Instruction::PHI: {
802 llvm_unreachable("should be handled by VPPhi::execute");
803 }
804 case Instruction::Select: {
805 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
806 Value *Cond =
807 State.get(getOperand(0),
808 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
809 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
810 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
811 return Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(),
812 Name);
813 }
816 // Get first lane of vector induction variable.
817 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
818 // Get the original loop tripcount.
819 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
820
821 uint64_t Multiplier =
823 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
824 : 1;
825
826 // If this part of the active lane mask is scalar, generate the CMP directly
827 // to avoid unnecessary extracts.
828 if (State.VF.isScalar() && Multiplier == 1)
829 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
830 Name);
831
832 auto *PredTy = VectorType::get(Builder.getInt1Ty(), State.VF * Multiplier);
833 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
834 {PredTy, ScalarTC->getType()},
835 {VIVElem0, ScalarTC}, nullptr, Name);
836 }
838 Value *Op = State.get(getOperand(0));
839 auto *VecTy = cast<VectorType>(Op->getType());
840 assert(VecTy->getScalarSizeInBits() == 1 &&
841 "NumActiveLanes only implemented for i1 vectors");
842
843 Type *Ty = getScalarType();
844 Value *ZExt = Builder.CreateCast(
845 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
846 Value *NumActive =
847 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
848 return NumActive;
849 }
851 // Generate code to combine the previous and current values in vector v3.
852 //
853 // vector.ph:
854 // v_init = vector(..., ..., ..., a[-1])
855 // br vector.body
856 //
857 // vector.body
858 // i = phi [0, vector.ph], [i+4, vector.body]
859 // v1 = phi [v_init, vector.ph], [v2, vector.body]
860 // v2 = a[i, i+1, i+2, i+3];
861 // v3 = vector(v1(3), v2(0, 1, 2))
862
863 auto *V1 = State.get(getOperand(0));
864 if (!V1->getType()->isVectorTy())
865 return V1;
866 Value *V2 = State.get(getOperand(1));
867 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
868 }
870 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
871 // be outside of the main loop.
872 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
873 // Compute EVL
874 assert(AVL->getType()->isIntegerTy() &&
875 "Requested vector length should be an integer.");
876
877 assert(State.VF.isScalable() && "Expected scalable vector factor.");
878 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
879
880 Value *EVL = Builder.CreateIntrinsic(
881 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
882 {AVL, VFArg, Builder.getTrue()});
883 return EVL;
884 }
886 Value *Cond = State.get(getOperand(0), VPLane(0));
887 // Replace the temporary unreachable terminator with a new conditional
888 // branch, hooking it up to backward destination for latch blocks now, and
889 // to forward destination(s) later when they are created.
890 // Second successor may be backwards - iff it is already in VPBB2IRBB.
891 VPBasicBlock *SecondVPSucc =
892 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
893 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
894 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
895 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
896 // First successor is always forward, reset it to nullptr.
897 Br->setSuccessor(0, nullptr);
899 applyMetadata(*Br);
900 return Br;
901 }
903 return Builder.CreateVectorSplat(
904 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
905 }
907 // For struct types, we need to build a new 'wide' struct type, where each
908 // element is widened, i.e., we create a struct of vectors.
909 auto *StructTy = cast<StructType>(getOperand(0)->getScalarType());
910 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
911 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
912 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
913 FieldIndex++) {
914 Value *ScalarValue =
915 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
916 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
917 VectorValue =
918 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
919 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
920 }
921 }
922 return Res;
923 }
925 auto *ScalarTy = getOperand(0)->getScalarType();
926 auto NumOfElements = ElementCount::getFixed(getNumOperands());
927 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
928 for (const auto &[Idx, Op] : enumerate(operands()))
929 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
930 Builder.getInt64(Idx));
931 return Res;
932 }
934 if (State.VF.isScalar())
935 return State.get(getOperand(0), true);
936 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
938 // If this start vector is scaled then it should produce a vector with fewer
939 // elements than the VF.
940 ElementCount VF = State.VF.divideCoefficientBy(
941 cast<VPConstantInt>(getOperand(2))->getZExtValue());
942 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
943 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
944 Builder.getInt64(0));
945 }
947 RecurKind RK = getRecurKind();
948 bool IsOrdered = isReductionOrdered();
949 bool IsInLoop = isReductionInLoop();
951 "FindIV should use min/max reduction kinds");
952
953 // The recipe may have multiple operands to be reduced together.
954 unsigned NumOperandsToReduce = getNumOperands();
955 SmallVector<Value *, 2> RdxParts(NumOperandsToReduce);
956 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
957 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
958
959 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
961
962 // Reduce multiple operands into one.
963 Value *ReducedPartRdx = RdxParts[0];
964 if (IsOrdered) {
965 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
966 } else {
967 // Floating-point operations should have some FMF to enable the reduction.
968 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
969 Value *RdxPart = RdxParts[Part];
971 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
972 else {
973 // For sub-recurrences, each part's reduction variable is already
974 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
978 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
979 ReducedPartRdx =
980 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
981 }
982 }
983 }
984
985 // Create the reduction after the loop. Note that inloop reductions create
986 // the target reduction in the loop using a Reduction recipe.
987 if (State.VF.isVector() && !IsInLoop) {
988 // TODO: Support in-order reductions based on the recurrence descriptor.
989 // All ops in the reduction inherit fast-math-flags from the recurrence
990 // descriptor.
991 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
992 }
993
994 return ReducedPartRdx;
995 }
998 unsigned Offset =
1000 Value *Res;
1001 if (State.VF.isVector()) {
1002 assert(Offset <= State.VF.getKnownMinValue() &&
1003 "invalid offset to extract from");
1004 // Extract lane VF - Offset from the operand.
1005 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
1006 } else {
1007 // TODO: Remove ExtractLastLane for scalar VFs.
1008 assert(Offset <= 1 && "invalid offset to extract from");
1009 Res = State.get(getOperand(0));
1010 }
1011 if (isa<ExtractElementInst>(Res))
1012 Res->setName(Name);
1013 return Res;
1014 }
1016 Value *A = State.get(getOperand(0));
1017 Value *B = State.get(getOperand(1));
1018 return Builder.CreateLogicalAnd(A, B, Name);
1019 }
1021 Value *A = State.get(getOperand(0));
1022 Value *B = State.get(getOperand(1));
1023 return Builder.CreateLogicalOr(A, B, Name);
1024 }
1025 case VPInstruction::PtrAdd: {
1026 assert((State.VF.isScalar() || vputils::onlyFirstLaneUsed(this)) &&
1027 "can only generate first lane for PtrAdd");
1028 Value *Ptr = State.get(getOperand(0), VPLane(0));
1029 Value *Addend = State.get(getOperand(1), VPLane(0));
1030 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1031 }
1033 Value *Ptr =
1035 Value *Addend = State.get(getOperand(1));
1036 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1037 }
1038 case VPInstruction::AnyOf: {
1039 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
1040 for (VPValue *Op : drop_begin(operands()))
1041 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
1042 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1043 }
1045 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1046 "simplified to ExtractElement.");
1047 Value *LaneToExtract = State.get(getOperand(0), true);
1048 Type *IdxTy = getOperand(0)->getScalarType();
1049 Value *Res = nullptr;
1050 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1051
1052 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1053 Value *VectorStart =
1054 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1055 Value *VectorIdx = Idx == 1
1056 ? LaneToExtract
1057 : Builder.CreateSub(LaneToExtract, VectorStart);
1058 Value *Ext = State.VF.isScalar()
1059 ? State.get(getOperand(Idx))
1060 : Builder.CreateExtractElement(
1061 State.get(getOperand(Idx)), VectorIdx);
1062 if (Res) {
1063 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1064 Res = Builder.CreateSelect(Cmp, Ext, Res);
1065 } else {
1066 Res = Ext;
1067 }
1068 }
1069 return Res;
1070 }
1072 Type *Ty = this->getScalarType();
1073 if (getNumOperands() == 1) {
1074 Value *Mask = State.get(getOperand(0));
1075 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1076 /*ZeroIsPoison=*/false, Name);
1077 }
1078 // If there are multiple operands, create a chain of selects to pick the
1079 // first operand with an active lane and add the number of lanes of the
1080 // preceding operands.
1081 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
1082 unsigned LastOpIdx = getNumOperands() - 1;
1083 Value *Res = nullptr;
1084 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1085 Value *TrailingZeros =
1086 State.VF.isScalar()
1087 ? Builder.CreateZExt(
1088 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1089 Builder.getFalse()),
1090 Ty)
1092 Ty, State.get(getOperand(Idx)),
1093 /*ZeroIsPoison=*/false, Name);
1094 Value *Current = Builder.CreateAdd(
1095 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1096 TrailingZeros);
1097 if (Res) {
1098 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1099 Res = Builder.CreateSelect(Cmp, Current, Res);
1100 } else {
1101 Res = Current;
1102 }
1103 }
1104
1105 return Res;
1106 }
1108 return State.get(getOperand(0), true);
1110 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1112 Value *Result = State.get(getOperand(0), /*IsScalar=*/true);
1113 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1114 Value *Data = State.get(getOperand(Idx));
1115 Value *Mask = State.get(getOperand(Idx + 1));
1116 Type *VTy = Data->getType();
1117
1118 if (State.VF.isScalar())
1119 Result = Builder.CreateSelect(Mask, Data, Result);
1120 else
1121 Result = Builder.CreateIntrinsic(
1122 Intrinsic::experimental_vector_extract_last_active, {VTy},
1123 {Data, Mask, Result});
1124 }
1125
1126 return Result;
1127 }
1129 Value *Src = State.get(getOperand(0));
1130 Type *DstTy = VectorType::get(getScalarType(), State.VF);
1131 uint64_t Part = cast<VPConstantInt>(getOperand(1))->getZExtValue();
1132
1133 if (Src->getType() == DstTy)
1134 return Src;
1135
1136 return Builder.CreateExtractVector(
1137 DstTy, Src, Builder.getInt64(State.VF.getKnownMinValue() * Part), Name);
1138 }
1140 return State.Builder.CreateStepVector(
1141 VectorType::get(getScalarType(), State.VF));
1143 SmallVector<Value *, 2> Args;
1144 for (VPValue *Op : drop_end(operands()))
1145 Args.push_back(State.get(Op, /*IsSingleScalar=*/true));
1146 return State.Builder.CreateIntrinsic(getScalarType(),
1147 vputils::getIntrinsicID(this), Args,
1148 /*FMFSource=*/nullptr, getName());
1149 }
1150 default:
1151 llvm_unreachable("Unsupported opcode for instruction");
1152 }
1153}
1154
1156 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1157 Type *ScalarTy = this->getScalarType();
1158 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1159 switch (Opcode) {
1160 case Instruction::FNeg:
1161 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1162 case Instruction::UDiv:
1163 case Instruction::SDiv:
1164 case Instruction::SRem:
1165 case Instruction::URem:
1166 case Instruction::Add:
1167 case Instruction::FAdd:
1168 case Instruction::Sub:
1169 case Instruction::FSub:
1170 case Instruction::Mul:
1171 case Instruction::FMul:
1172 case Instruction::FDiv:
1173 case Instruction::FRem:
1174 case Instruction::Shl:
1175 case Instruction::LShr:
1176 case Instruction::AShr:
1177 case Instruction::And:
1178 case Instruction::Or:
1179 case Instruction::Xor: {
1180 // Certain instructions can be cheaper if they have a constant second
1181 // operand. One example of this are shifts on x86.
1182 VPValue *RHS = getOperand(1);
1183 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1184
1185 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1188
1191 if (CtxI)
1192 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1193 return Ctx.TTI.getArithmeticInstrCost(
1194 Opcode, ResultTy, Ctx.CostKind,
1195 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1196 RHSInfo, Operands, CtxI, &Ctx.TLI);
1197 }
1198 case Instruction::Freeze:
1199 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1200 // requires the actual vector instruction. Instead, both here and in the
1201 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1202 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1203 // them in sync.
1204 return TTI::TCC_Free;
1205 case Instruction::ExtractValue:
1206 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1207 Ctx.CostKind);
1208 case Instruction::ICmp:
1209 case Instruction::FCmp: {
1210 Type *ScalarOpTy = getOperand(0)->getScalarType();
1211 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1213 return Ctx.TTI.getCmpSelInstrCost(
1215 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1216 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1217 }
1218 case Instruction::BitCast: {
1219 Type *ScalarTy = this->getScalarType();
1220 if (ScalarTy->isPointerTy())
1221 return 0;
1222 [[fallthrough]];
1223 }
1224 case Instruction::SExt:
1225 case Instruction::ZExt:
1226 case Instruction::FPToUI:
1227 case Instruction::FPToSI:
1228 case Instruction::FPExt:
1229 case Instruction::PtrToInt:
1230 case Instruction::PtrToAddr:
1231 case Instruction::IntToPtr:
1232 case Instruction::SIToFP:
1233 case Instruction::UIToFP:
1234 case Instruction::Trunc:
1235 case Instruction::FPTrunc:
1236 case Instruction::AddrSpaceCast: {
1237 // Computes the CastContextHint from a recipe that may access memory.
1238 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1239 if (isa<VPInterleaveBase>(R))
1241 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1242 // Only compute CCH for memory operations, matching the legacy model
1243 // which only considers loads/stores for cast context hints.
1244 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1245 if (!isa<LoadInst, StoreInst>(UI))
1247 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1249 }
1250 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1251 if (WidenMemoryRecipe == nullptr)
1253 if (VF.isScalar())
1255 if (!WidenMemoryRecipe->isConsecutive())
1257 if (WidenMemoryRecipe->isMasked())
1260 };
1261
1262 VPValue *Operand = getOperand(0);
1264 bool IsReverse = false;
1265 // For Trunc/FPTrunc, get the context from the only user.
1266 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1267 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1268 if (match(Recipe,
1272 IsReverse = true;
1274 Recipe->getVPSingleValue()->getSingleUser());
1275 }
1276 if (Recipe)
1277 CCH = ComputeCCH(Recipe);
1278 }
1279 }
1280 // For Z/Sext, get the context from the operand.
1281 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1282 Opcode == Instruction::FPExt) {
1283 if (auto *Recipe = Operand->getDefiningRecipe()) {
1284 VPValue *ReverseOp;
1285 if (match(Recipe,
1286 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1288 m_VPValue(ReverseOp))))) {
1289 Recipe = ReverseOp->getDefiningRecipe();
1290 IsReverse = true;
1291 }
1292 if (Recipe)
1293 CCH = ComputeCCH(Recipe);
1294 }
1295 }
1296 if (IsReverse && CCH != TTI::CastContextHint::None)
1298
1299 auto *ScalarSrcTy = Operand->getScalarType();
1300 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1301 // Arm TTI will use the underlying instruction to determine the cost.
1302 return Ctx.TTI.getCastInstrCost(
1303 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1305 }
1306 case Instruction::Select: {
1308 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1309 Type *ScalarTy = this->getScalarType();
1310
1311 VPValue *Op0, *Op1;
1312 bool IsLogicalAnd =
1313 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1314 bool IsLogicalOr =
1315 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1316 // Also match the inverted forms:
1317 // select x, false, y --> !x & y (still AND)
1318 // select x, y, true --> !x | y (still OR)
1319 IsLogicalAnd |=
1320 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1321 IsLogicalOr |=
1322 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1323
1324 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1325 (IsLogicalAnd || IsLogicalOr)) {
1326 // select x, y, false --> x & y
1327 // select x, true, y --> x | y
1328 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1329 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1330
1332 if (SI && all_of(operands(),
1333 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1334 append_range(Operands, SI->operands());
1335 return Ctx.TTI.getArithmeticInstrCost(
1336 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1337 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1338 }
1339
1340 Type *CondTy = getOperand(0)->getScalarType();
1341 if (!IsScalarCond && VF.isVector())
1342 CondTy = VectorType::get(CondTy, VF);
1343
1344 llvm::CmpPredicate Pred;
1345 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1346 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1347 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1348 Pred = Cmp->getPredicate();
1349 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1350 return Ctx.TTI.getCmpSelInstrCost(
1351 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1352 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1353 }
1354 }
1355 llvm_unreachable("called for unsupported opcode");
1356}
1357
1359 VPCostContext &Ctx) const {
1360 // NOTE: At the moment it seems only possible to expose this path for
1361 // the trunc, zext and sext opcodes.
1362 // TODO: Update VF arg to use onlyFirstLaneUsed once WidenCast is unified.
1365 Ctx);
1366
1368 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1369 // TODO: Compute cost for VPInstructions without underlying values once
1370 // the legacy cost model has been retired.
1371 return 0;
1372 }
1373
1375 "Should only generate a vector value or single scalar, not scalars "
1376 "for all lanes.");
1378 getOpcode(),
1380 }
1381
1382 switch (getOpcode()) {
1383 case Instruction::Select: {
1385 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1386 auto *CondTy = getOperand(0)->getScalarType();
1387 auto *VecTy = getOperand(1)->getScalarType();
1388 if (!vputils::onlyFirstLaneUsed(this)) {
1389 CondTy = toVectorTy(CondTy, VF);
1390 VecTy = toVectorTy(VecTy, VF);
1391 }
1392 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1393 Ctx.CostKind);
1394 }
1395 case Instruction::ExtractElement:
1397 if (VF.isScalar()) {
1398 // ExtractLane with VF=1 takes care of handling extracting across multiple
1399 // parts.
1400 return 0;
1401 }
1402
1403 // Add on the cost of extracting the element.
1404 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1405 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1406 Ctx.CostKind);
1407 }
1408 case VPInstruction::AnyOf: {
1409 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1410 return Ctx.TTI.getArithmeticReductionCost(
1411 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1412 }
1414 Type *Ty = this->getScalarType();
1415 Type *ScalarTy = getOperand(0)->getScalarType();
1416 if (VF.isScalar())
1417 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1419 CmpInst::ICMP_EQ, Ctx.CostKind);
1420 // Calculate the cost of determining the lane index.
1421 auto *PredTy = toVectorTy(ScalarTy, VF);
1422 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1423 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1424 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1425 }
1427 Type *Ty = this->getScalarType();
1428 Type *ScalarTy = getOperand(0)->getScalarType();
1429 if (VF.isScalar())
1430 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1432 CmpInst::ICMP_EQ, Ctx.CostKind);
1433 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1434 auto *PredTy = toVectorTy(ScalarTy, VF);
1435 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1436 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1437 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1438 // Add cost of NOT operation on the predicate.
1439 Cost += Ctx.TTI.getArithmeticInstrCost(
1440 Instruction::Xor, PredTy, Ctx.CostKind,
1441 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1442 {TargetTransformInfo::OK_UniformConstantValue,
1443 TargetTransformInfo::OP_None});
1444 // Add cost of SUB operation on the index.
1445 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1446 return Cost;
1447 }
1449 Type *ScalarTy = this->getScalarType();
1450 Type *VecTy = toVectorTy(ScalarTy, VF);
1451 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1453 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1454 {VecTy, MaskTy, ScalarTy});
1455 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1456 }
1458 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1459 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1460 return Ctx.TTI.getShuffleCost(
1462 cast<VectorType>(VectorTy), Ctx.CostKind, {}, -1);
1463 }
1466 Type *ArgTy = getOperand(0)->getScalarType();
1467 uint64_t Multiplier =
1469 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
1470 : 1;
1471 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1472 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1473 {ArgTy, ArgTy});
1474 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1475 }
1477 Type *Arg0Ty = getOperand(0)->getScalarType();
1478 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1479 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1480 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1481 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1482 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1483 }
1485 assert(VF.isVector() && "Reverse operation must be vector type");
1486 Type *EltTy = this->getScalarType();
1487 // Skip the reverse operation cost for the mask.
1488 // FIXME: Remove this once redundant mask reverse operations can be
1489 // eliminated by VPlanTransforms::cse before cost computation.
1490 if (EltTy->isIntegerTy(1))
1491 return 0;
1492 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1493 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1494 VectorTy, Ctx.CostKind, /*Mask=*/{},
1495 /*Index=*/0);
1496 }
1498 // Add on the cost of extracting the element.
1499 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1500 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1501 VecTy, Ctx.CostKind, 0);
1502 }
1503 case VPInstruction::Not: {
1504 Type *ValTy = this->getScalarType();
1505 // InstCombine will fold `xor` to the conditional branch.
1506 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1507 if (match(U, m_BranchOnCond(m_VPValue())))
1508 return 0;
1509 if (!vputils::onlyFirstLaneUsed(this))
1510 ValTy = toVectorTy(ValTy, VF);
1511 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1512 Ctx.CostKind);
1513 }
1515 // If TC <= VF then this is just a branch.
1516 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1517 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1518 // some cases we get a cost that's too high due to counting a cmp that
1519 // later gets removed.
1520 // FIXME: The compare could also be removed if TC = M * vscale,
1521 // VF = N * vscale, and M <= N. Detecting that would require having the
1522 // trip count as a SCEV though.
1523 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
1524 return 0;
1525 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1526 Type *ValTy = getOperand(0)->getScalarType();
1527 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1529 CmpInst::ICMP_EQ, Ctx.CostKind);
1530 }
1532 Type *Ty = getScalarType();
1534 for (const VPValue *Op : drop_end(operands()))
1535 ArgTys.push_back(Op->getScalarType());
1536 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1537 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1538 }
1540 // TODO: This isn't quite right since even if the step-vector is hoisted
1541 // out of the loop it has a non-zero cost in the middle block, etc.
1542 // Once the stepvector is correctly hoisted out of the vector loop by the
1543 // licm transform we can add the cost here so that it doesn't incorrectly
1544 // affect the choice of VF.
1545 return 0;
1547 // It isn't currently possible to expose cases where WideIVStep's cost is
1548 // queried.
1549 llvm_unreachable("Unhandled opcode");
1550 case Instruction::FCmp:
1551 case Instruction::ICmp:
1553 getOpcode(),
1556 if (VF == ElementCount::getScalable(1))
1558 [[fallthrough]];
1559 default:
1560 // TODO: Compute cost other VPInstructions once the legacy cost model has
1561 // been retired.
1563 "unexpected VPInstruction witht underlying value");
1564 return 0;
1565 }
1566}
1567
1580
1582 switch (getOpcode()) {
1583 case Instruction::Load:
1584 case Instruction::PHI:
1588 return true;
1589 default:
1591 }
1592}
1593
1595#ifndef NDEBUG
1596 Type *Ty = Op->getScalarType();
1597 switch (getOpcode()) {
1601 assert(Ty == getOperand(0)->getScalarType() &&
1602 "types of operand 0 and new operand must match");
1603 break;
1607 assert(Ty == getOperand(0)->getScalarType() &&
1608 "appended operand must match operand 0's scalar type");
1609 break;
1611 assert(Ty == getOperand(1)->getScalarType() &&
1612 "appended operand must match operand 1's scalar type");
1613 break;
1615 // The recipe is constructed with 3 operands (result, data, mask). Extra
1616 // operands beyond that are appended in (data, mask) pairs.
1617 constexpr unsigned NumInitialOperands = 3;
1618 assert(getNumOperands() >= NumInitialOperands &&
1619 "ExtractLastActive must have at least the initial 3 operands");
1620 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1621 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1622 : Ty == getOperand(1)->getScalarType()) &&
1623 "ExtractLastActive expects alternating data/mask operands "
1624 "matching operand 1's type and i1, respectively");
1625 break;
1626 }
1627 default:
1628 llvm_unreachable("opcode does not support growing the operand list "
1629 "outside of construction");
1630 }
1631#endif
1633}
1634
1636 assert(!isMasked() && "cannot execute masked VPInstruction");
1637 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1639 "Set flags not supported for the provided opcode");
1641 "Opcode requires specific flags to be set");
1642 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1643 Value *GeneratedValue = generate(State);
1644 if (!hasResult())
1645 return;
1646 assert(GeneratedValue && "generate must produce a value");
1647 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1650 assert((((GeneratedValue->getType()->isVectorTy() ||
1651 GeneratedValue->getType()->isStructTy()) ==
1652 !GeneratesPerFirstLaneOnly) ||
1653 State.VF.isScalar()) &&
1654 "scalar value but not only first lane defined");
1655 State.set(this, GeneratedValue,
1656 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1658 getOpcode() == Instruction::Freeze) {
1659 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1660 // resume phis, and to let epilogue vectorization recover the frozen
1661 // reduction start from the main plan. Must be removed once epilogue
1662 // vectorization explicitly connects VPlans.
1663 setUnderlyingValue(GeneratedValue);
1664 }
1665}
1666
1670 return false;
1671 switch (getOpcode()) {
1672 case Instruction::ExtractValue:
1673 case Instruction::InsertValue:
1674 case Instruction::GetElementPtr:
1675 case Instruction::ExtractElement:
1676 case Instruction::InsertElement:
1677 case Instruction::Freeze:
1678 case Instruction::FCmp:
1679 case Instruction::ICmp:
1680 case Instruction::Select:
1681 case Instruction::PHI:
1708 case VPInstruction::Not:
1716 return false;
1719 AttributeSet Attrs =
1721 return !Attrs.getMemoryEffects().doesNotAccessMemory();
1722 }
1723 case Instruction::Call:
1725 default:
1726 return true;
1727 }
1728}
1729
1731 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1733 return vputils::onlyFirstLaneUsed(this);
1734
1735 switch (getOpcode()) {
1736 default:
1737 return false;
1738 case Instruction::ExtractElement:
1739 return Op == getOperand(1);
1740 case Instruction::InsertElement:
1741 return Op == getOperand(1) || Op == getOperand(2);
1742 case Instruction::PHI:
1743 return true;
1744 case Instruction::FCmp:
1745 case Instruction::ICmp:
1746 case Instruction::Select:
1747 case Instruction::Or:
1748 case Instruction::Freeze:
1749 case VPInstruction::Not:
1750 // TODO: Cover additional opcodes.
1751 return vputils::onlyFirstLaneUsed(this);
1752 case Instruction::Load:
1764 return true;
1767 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1768 // operand, after replicating its operands only the first lane is used.
1769 // Before replicating, it will have only a single operand.
1770 return getNumOperands() > 1;
1772 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1774 // WidePtrAdd supports scalar and vector base addresses.
1775 return false;
1778 return Op == getOperand(0);
1779 };
1780 llvm_unreachable("switch should return");
1781}
1782
1784 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1786 return vputils::onlyFirstPartUsed(this);
1787
1788 switch (getOpcode()) {
1789 default:
1790 return false;
1791 case Instruction::FCmp:
1792 case Instruction::ICmp:
1793 case Instruction::Select:
1794 return vputils::onlyFirstPartUsed(this);
1799 return true;
1800 };
1801 llvm_unreachable("switch should return");
1802}
1803
1804#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1806 VPSlotTracker SlotTracker(getParent()->getPlan());
1808}
1809
1811 VPSlotTracker &SlotTracker) const {
1812 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1813
1814 if (hasResult()) {
1816 O << " = ";
1817 }
1818
1819 switch (getOpcode()) {
1820 case VPInstruction::Not:
1821 O << "not";
1822 break;
1824 O << "active lane mask";
1825 break;
1827 O << "wide active lane mask";
1828 break;
1830 O << "incoming-alias-mask";
1831 break;
1833 O << "EXPLICIT-VECTOR-LENGTH";
1834 break;
1836 O << "first-order splice";
1837 break;
1839 O << "branch-on-cond";
1840 break;
1842 O << "branch-on-two-conds";
1843 break;
1845 O << "VF * Part +";
1846 break;
1848 O << "branch-on-count";
1849 break;
1851 O << "broadcast";
1852 break;
1854 O << "buildstructvector";
1855 break;
1857 O << "buildvector";
1858 break;
1860 O << "exiting-iv-value";
1861 break;
1863 O << "masked-cond";
1864 break;
1866 O << "extract-lane";
1867 break;
1869 O << "extract-last-lane";
1870 break;
1872 O << "extract-last-part";
1873 break;
1875 O << "extract-penultimate-element";
1876 break;
1878 O << "extract-vector-for-part";
1879 break;
1881 O << "compute-reduction-result";
1882 break;
1884 O << "logical-and";
1885 break;
1887 O << "logical-or";
1888 break;
1890 O << "ptradd";
1891 break;
1893 O << "wide-ptradd";
1894 break;
1896 O << "any-of";
1897 break;
1899 O << "first-active-lane";
1900 break;
1902 O << "last-active-lane";
1903 break;
1905 O << "reduction-start-vector";
1906 break;
1908 O << "resume-for-epilogue";
1909 break;
1911 O << "reverse";
1912 break;
1914 O << "unpack";
1915 break;
1917 O << "extract-last-active";
1918 break;
1920 O << "num-active-lanes";
1921 break;
1923 O << "wide-iv-step";
1924 break;
1926 O << "step-vector " << *getScalarType();
1927 break;
1929 O << "call " << *getScalarType() << " @"
1932 Op->printAsOperand(O, SlotTracker);
1933 });
1934 O << ")";
1935 return;
1936 }
1937 case Instruction::Load:
1938 O << "load";
1939 break;
1940 default:
1942 }
1943
1944 if (!operands_empty()) {
1945 printFlags(O);
1947 }
1949 O << " to " << *getScalarType();
1950}
1951#endif
1952
1953/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
1954/// adds incoming values, and stores the result in State. For header phis, only
1955/// the preheader incoming value is added; the backedge is fixed up later by
1956/// VPlan::execute().
1958 VPTransformState &State, bool IsScalar,
1959 const Twine &Name) {
1960 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
1961 ? 1
1962 : Phi.getNumIncoming();
1963 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
1964 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
1965 NewPhi->addIncoming(FirstInc,
1966 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
1967 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
1968 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
1969 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
1970 State.set(R, NewPhi, IsScalar);
1971}
1972
1974 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
1975}
1976
1977#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1978void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1979 VPSlotTracker &SlotTracker) const {
1980 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1982 O << " = phi";
1983 printFlags(O);
1985}
1986#endif
1987
1988VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1989 if (auto *Phi = dyn_cast<PHINode>(&I))
1990 return new VPIRPhi(*Phi);
1991 return new VPIRInstruction(I);
1992}
1993
1995 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1996 "PHINodes must be handled by VPIRPhi");
1997 // Advance the insert point after the wrapped IR instruction. This allows
1998 // interleaving VPIRInstructions and other recipes.
1999 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
2000}
2001
2003 VPCostContext &Ctx) const {
2004 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2005 // hence it does not contribute to the cost-modeling for the VPlan.
2006 return 0;
2007}
2008
2009#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2011 VPSlotTracker &SlotTracker) const {
2012 O << Indent << "IR " << I;
2013}
2014#endif
2015
2017 PHINode *Phi = &getIRPhi();
2018 for (const auto &[Idx, Op] : enumerate(operands())) {
2019 VPValue *ExitValue = Op;
2020 auto Lane = vputils::isSingleScalar(ExitValue)
2022 : VPLane::getLastLaneForVF(State.VF);
2023 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2024 auto *PredVPBB = Pred->getExitingBasicBlock();
2025 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2026 // Set insertion point in PredBB in case an extract needs to be generated.
2027 // TODO: Model extracts explicitly.
2028 State.Builder.SetInsertPoint(PredBB->getTerminator());
2029 Value *V = State.get(ExitValue, VPLane(Lane));
2030 // If there is no existing block for PredBB in the phi, add a new incoming
2031 // value. Otherwise update the existing incoming value for PredBB.
2032 if (Phi->getBasicBlockIndex(PredBB) == -1)
2033 Phi->addIncoming(V, PredBB);
2034 else
2035 Phi->setIncomingValueForBlock(PredBB, V);
2036 }
2037
2038 // Advance the insert point after the wrapped IR instruction. This allows
2039 // interleaving VPIRInstructions and other recipes.
2040 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
2041}
2042
2044 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2045 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2046 "Number of phi operands must match number of predecessors");
2047 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2048 R->removeOperand(Position);
2049}
2050
2051VPValue *
2053 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2054 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2055}
2056
2058 VPValue *V) const {
2059 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2060 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2061}
2062
2063#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2065 VPSlotTracker &SlotTracker) const {
2067 O << "[ ";
2068 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2069 O << ", ";
2070 std::get<1>(Op)->printAsOperand(O);
2071 O << " ]";
2072 });
2073}
2074#endif
2075
2076#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2078 VPSlotTracker &SlotTracker) const {
2080
2081 if (getNumOperands() != 0) {
2082 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2084 [&O, &SlotTracker](auto Op) {
2085 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2086 O << " from ";
2087 std::get<1>(Op)->printAsOperand(O);
2088 });
2089 O << ")";
2090 }
2091}
2092#endif
2093
2095 if (Metadata.empty())
2096 return;
2097 // Frequencies and estimated branch weights are VPlan-internal and must not
2098 // reach IR.
2099 unsigned ExecFreqKind = getMDKindID(ExecutionFrequencyMDName);
2100 unsigned EstProfKind = getMDKindID(EstimatedProfileMDName);
2101 for (const auto &[Kind, Node] : Metadata)
2102 if (Kind != ExecFreqKind && Kind != EstProfKind)
2103 I.setMetadata(Kind, Node);
2104}
2105
2106/// Returns the execution frequency recorded in \p Node.
2108 assert(Node->getNumOperands() <= 2 && "unexpected frequency node shape");
2109 uint64_t Freq =
2110 mdconst::extract<ConstantInt>(Node->getOperand(0))->getZExtValue();
2112 "frequency cannot exceed the one of an always executing block");
2113 return {BlockFrequency(Freq), Node->getNumOperands() == 2};
2114}
2115
2117 std::optional<VPExecutionFrequency> Freq, LLVMContext &Ctx) {
2118 // A recipe that never or always executes needs no annotation.
2119 if (!Freq || Freq->Freq.getFrequency() == 0 ||
2120 Freq->Freq.getFrequency() == vputils::AlwaysExecutesFreq)
2121 return;
2123 ConstantInt::get(Type::getInt64Ty(Ctx), Freq->Freq.getFrequency()))};
2124 if (Freq->IsEstimated)
2126 setMetadata(Ctx.getMDKindID(ExecutionFrequencyMDName), MDNode::get(Ctx, Ops));
2127}
2128
2129std::optional<VPExecutionFrequency>
2131 if (MDNode *Node = getInternalMetadata(ExecutionFrequencyMDName))
2133 return std::nullopt;
2134}
2135
2137 if (Metadata.empty())
2138 return;
2139 unsigned ID = getMDKindID(ExecutionFrequencyMDName);
2140 erase_if(Metadata, [ID](const auto &P) { return P.first == ID; });
2141}
2142
2144 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
2145 for (const auto &[KindA, MDA] : Metadata) {
2146 for (const auto &[KindB, MDB] : Other.Metadata) {
2147 if (KindA == KindB && MDA == MDB) {
2148 MetadataIntersection.emplace_back(KindA, MDA);
2149 break;
2150 }
2151 }
2152 }
2153 Metadata = std::move(MetadataIntersection);
2154}
2155
2156#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2158 const Module *M = SlotTracker.getModule();
2159 if (Metadata.empty() || !M || !VPlanPrintMetadata)
2160 return;
2161
2162 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2163 O << " (";
2164 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2165 auto [Kind, Node] = KindNodePair;
2166 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2167 "Unexpected unnamed metadata kind");
2168 O << "!" << MDNames[Kind] << " ";
2169 // Print the values of branch weights, which are more informative than the
2170 // ID of the metadata node holding them.
2171 SmallVector<uint32_t> Weights;
2172 bool IsEstimatedProfile = MDNames[Kind] == EstimatedProfileMDName;
2173 if ((Kind == LLVMContext::MD_prof || IsEstimatedProfile) &&
2174 extractBranchWeights(Node, Weights)) {
2175 if (IsEstimatedProfile)
2176 O << "estimated ";
2177 O << "{";
2178 interleaveComma(Weights, O);
2179 O << "}";
2180 } else if (MDNames[Kind] == ExecutionFrequencyMDName) {
2181 // Print the frequency together with the probability it corresponds to.
2182 auto [Freq, IsEstimated] = getExecutionFrequencyFromMD(Node);
2183 O << Freq.getFrequency()
2184 << format(" (%.4g%%%s)",
2185 100.0 * Freq.getFrequency() / vputils::AlwaysExecutesFreq,
2186 IsEstimated ? ", estimated" : "");
2187 } else {
2188 Node->printAsOperand(O, M);
2189 }
2190 });
2191 O << ")";
2192}
2193#endif
2194
2196 assert(State.VF.isVector() && "not widening");
2197 assert(Variant != nullptr && "Can't create vector function.");
2198
2199 FunctionType *VFTy = Variant->getFunctionType();
2200 // Add return type if intrinsic is overloaded on it.
2202 for (const auto &I : enumerate(args())) {
2203 Value *Arg;
2204 // Some vectorized function variants may also take a scalar argument,
2205 // e.g. linear parameters for pointers. This needs to be the scalar value
2206 // from the start of the respective part when interleaving.
2207 if (!VFTy->getParamType(I.index())->isVectorTy())
2208 Arg = State.get(I.value(), VPLane(0));
2209 else
2210 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2211 Args.push_back(Arg);
2212 }
2213
2216 if (CI)
2217 CI->getOperandBundlesAsDefs(OpBundles);
2218
2219 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
2220 applyFlags(*V);
2221 applyMetadata(*V);
2222 V->setCallingConv(Variant->getCallingConv());
2223
2224 if (!V->getType()->isVoidTy())
2225 State.set(this, V);
2226}
2227
2229 VPCostContext &Ctx) const {
2230 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2231 "Variant return type must match VF");
2232 return computeCallCost(Variant, Ctx);
2233}
2234
2236 VPCostContext &Ctx) {
2237 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2238 Variant->getFunctionType()->params(),
2239 Ctx.CostKind);
2240}
2241
2243 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2244 assert(Variant && "Variant not set");
2245 FunctionType *VFTy = Variant->getFunctionType();
2246 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2247 auto [Idx, V] = Arg;
2248 Type *ArgTy = VFTy->getParamType(Idx);
2249 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2250 ArgTy->isPointerTy() || ArgTy->isByteTy();
2251 });
2252}
2253
2254#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2256 VPSlotTracker &SlotTracker) const {
2257 O << Indent << "WIDEN-CALL ";
2258
2259 Function *CalledFn = getCalledScalarFunction();
2260 if (CalledFn->getReturnType()->isVoidTy())
2261 O << "void ";
2262 else {
2264 O << " = ";
2265 }
2266
2267 O << "call";
2268 printFlags(O);
2269 O << "@" << CalledFn->getName() << "(";
2270 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
2271 Op->printAsOperand(O, SlotTracker);
2272 });
2273 O << ")";
2274
2275 O << " (using library function";
2276 if (Variant->hasName())
2277 O << ": " << Variant->getName();
2278 O << ")";
2279}
2280#endif
2281
2283 assert(State.VF.isVector() && "not widening");
2284
2285 SmallVector<Type *, 2> TysForDecl;
2286 // Add return type if intrinsic is overloaded on it.
2287 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2288 State.TTI)) {
2289 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2290 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2291 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2293 Idx, State.TTI))
2294 TysForDecl.push_back(Ty);
2295 }
2296 }
2298 for (const auto &I : enumerate(operands())) {
2299 // Some intrinsics have a scalar argument - don't replace it with a
2300 // vector.
2301 Value *Arg;
2302 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2303 State.TTI))
2304 Arg = State.get(I.value(), VPLane(0));
2305 else
2306 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2307 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2308 State.TTI))
2309 TysForDecl.push_back(Arg->getType());
2310 Args.push_back(Arg);
2311 }
2312
2313 // Use vector version of the intrinsic.
2314 Module *M = State.Builder.GetInsertBlock()->getModule();
2315 Function *VectorF =
2316 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2317 assert(VectorF &&
2318 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2319
2322 if (CI)
2323 CI->getOperandBundlesAsDefs(OpBundles);
2324
2325 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
2326
2327 applyFlags(*V);
2328 applyMetadata(*V);
2329
2330 return V;
2331}
2332
2334 CallInst *V = createVectorCall(State);
2335 if (!V->getType()->isVoidTy())
2336 State.set(this, V);
2337}
2338
2341 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2342 Type *ScalarRetTy = R.getScalarType();
2343 // Skip the reverse operation cost for the mask.
2344 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2345 // by VPlanTransforms::cse before cost computation.
2346 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2347 return InstructionCost(0);
2348
2349 // Some backends analyze intrinsic arguments to determine cost. Use the
2350 // underlying value for the operand if it has one. Otherwise try to use the
2351 // operand of the underlying call instruction, if there is one. Otherwise
2352 // clear Arguments.
2353 // TODO: Rework TTI interface to be independent of concrete IR values.
2355 for (const auto &[Idx, Op] : enumerate(Operands)) {
2356 auto *V = Op->getUnderlyingValue();
2357 if (!V) {
2358 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2359 Arguments.push_back(UI->getArgOperand(Idx));
2360 continue;
2361 }
2362 Arguments.clear();
2363 break;
2364 }
2365 Arguments.push_back(V);
2366 }
2367
2368 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2369 SmallVector<Type *> ParamTys =
2370 map_to_vector(Operands, [&](const VPValue *Op) {
2371 return toVectorTy(Op->getScalarType(), VF);
2372 });
2373
2375 for (const VPValue *Op : Operands)
2376 if (isa<VPWidenRecipe>(Op) &&
2379 break;
2380 }
2381
2382 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2383 IntrinsicCostAttributes CostAttrs(
2384 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2385 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2387 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2388}
2389
2391 VPCostContext &Ctx) const {
2392 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2393}
2394
2396 return Intrinsic::getBaseName(VectorIntrinsicID);
2397}
2398
2400 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2401 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2402 auto [Idx, V] = X;
2404 Idx, nullptr);
2405 });
2406}
2407
2408#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2410 VPSlotTracker &SlotTracker) const {
2411 O << Indent << "WIDEN-INTRINSIC ";
2412 if (getScalarType()->isVoidTy()) {
2413 O << "void ";
2414 } else {
2416 O << " = ";
2417 }
2418
2419 O << "call";
2420 printFlags(O);
2421 O << getIntrinsicName() << "(";
2423 O << ")";
2424}
2425#endif
2426
2428 CallInst *MemI = createVectorCall(State);
2430 assert(PtrPos && "Expected a memory intrinsic with a valid pointer position");
2431 MemI->addParamAttr(
2432 *PtrPos, Attribute::getWithAlignment(MemI->getContext(), Alignment));
2433 if (!MemI->getType()->isVoidTy())
2434 State.set(this, MemI);
2435}
2436
2438 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2439 VPCostContext &Ctx) {
2440 return Ctx.TTI.getMemIntrinsicInstrCost(
2441 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2442 Ctx.CostKind);
2443}
2444
2447 VPCostContext &Ctx) const {
2448 Type *DataTy;
2450 DataTy = getOperand(*DataPos)->getScalarType();
2451 else
2452 DataTy = getScalarType();
2453 assert(!DataTy->isVoidTy() && "Expected a non-void data type");
2454 Type *Ty = toVectorTy(DataTy, VF);
2456 assert(MaskPos && "Expected a memory intrinsic with a valid mask position");
2458 !match(getOperand(*MaskPos), m_True()),
2459 Alignment, Ctx);
2460}
2461
2463 IRBuilderBase &Builder = State.Builder;
2464
2465 Value *Address = State.get(getOperand(0));
2466 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2467 VectorType *VTy = cast<VectorType>(Address->getType());
2468
2469 // The histogram intrinsic requires a mask even if the recipe doesn't;
2470 // if the mask operand was omitted then all lanes should be executed and
2471 // we just need to synthesize an all-true mask.
2472 Value *Mask = nullptr;
2473 if (VPValue *VPMask = getMask())
2474 Mask = State.get(VPMask);
2475 else
2476 Mask =
2477 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2478
2479 // If this is a subtract, we want to invert the increment amount. We may
2480 // add a separate intrinsic in future, but for now we'll try this.
2481 if (Opcode == Instruction::Sub)
2482 IncAmt = Builder.CreateNeg(IncAmt);
2483 else
2484 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2485
2486 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2487 Intrinsic::experimental_vector_histogram_add, {VTy, IncAmt->getType()},
2488 {Address, IncAmt, Mask});
2489 applyMetadata(*HistogramInst);
2490}
2491
2493 VPCostContext &Ctx) const {
2494 // FIXME: Take the gather and scatter into account as well. For now we're
2495 // generating the same cost as the fallback path, but we'll likely
2496 // need to create a new TTI method for determining the cost, including
2497 // whether we can use base + vec-of-smaller-indices or just
2498 // vec-of-pointers.
2499 assert(VF.isVector() && "Invalid VF for histogram cost");
2500 Type *AddressTy = getOperand(0)->getScalarType();
2501 VPValue *IncAmt = getOperand(1);
2502 Type *IncTy = IncAmt->getScalarType();
2503 VectorType *VTy = VectorType::get(IncTy, VF);
2504
2505 // Assume that a non-constant update value (or a constant != 1) requires
2506 // a multiply, and add that into the cost.
2507 InstructionCost MulCost =
2508 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2509 if (match(IncAmt, m_One()))
2510 MulCost = TTI::TCC_Free;
2511
2512 // Find the cost of the histogram operation itself.
2513 Type *PtrTy = VectorType::get(AddressTy, VF);
2514 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2515 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2516 Type::getVoidTy(Ctx.LLVMCtx),
2517 {PtrTy, IncTy, MaskTy});
2518
2519 // Add the costs together with the add/sub operation.
2520 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2521 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2522}
2523
2524#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2526 VPSlotTracker &SlotTracker) const {
2527 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2529
2530 if (Opcode == Instruction::Sub)
2531 O << ", dec: ";
2532 else {
2533 assert(Opcode == Instruction::Add);
2534 O << ", inc: ";
2535 }
2537
2538 if (VPValue *Mask = getMask()) {
2539 O << ", mask: ";
2540 Mask->printAsOperand(O, SlotTracker);
2541 }
2542}
2543#endif
2544
2545VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2546 AllowReassoc = FMF.allowReassoc();
2547 NoNaNs = FMF.noNaNs();
2548 NoInfs = FMF.noInfs();
2549 NoSignedZeros = FMF.noSignedZeros();
2550 AllowReciprocal = FMF.allowReciprocal();
2551 AllowContract = FMF.allowContract();
2552 ApproxFunc = FMF.approxFunc();
2553}
2554
2555VPIRFlags VPIRFlags::getDefaultFlags(unsigned Opcode, Type *ResultTy) {
2556 switch (Opcode) {
2557 case Instruction::Add:
2558 case Instruction::Sub:
2559 case Instruction::Mul:
2560 case Instruction::Shl:
2562 return WrapFlagsTy(false, false);
2563 case Instruction::Trunc:
2564 return TruncFlagsTy(false, false);
2565 case Instruction::Or:
2566 return DisjointFlagsTy(false);
2567 case Instruction::AShr:
2568 case Instruction::LShr:
2569 case Instruction::UDiv:
2570 case Instruction::SDiv:
2571 return ExactFlagsTy(false);
2572 case Instruction::GetElementPtr:
2575 return GEPNoWrapFlags::none();
2576 case Instruction::ZExt:
2577 case Instruction::UIToFP:
2578 return NonNegFlagsTy(false);
2579 case Instruction::FAdd:
2580 case Instruction::FSub:
2581 case Instruction::FMul:
2582 case Instruction::FDiv:
2583 case Instruction::FRem:
2584 case Instruction::FNeg:
2585 case Instruction::FPExt:
2586 case Instruction::FPTrunc:
2587 return FastMathFlags();
2588 case Instruction::Select:
2589 case Instruction::PHI:
2590 case Instruction::Call:
2591 // Selects, phis and calls only have fast-math flags if they have a
2592 // supported floating-point result type.
2594 return FastMathFlags();
2595 return VPIRFlags();
2596 case Instruction::ICmp:
2597 case Instruction::FCmp:
2599 llvm_unreachable("opcode requires explicit flags");
2600 default:
2601 return VPIRFlags();
2602 }
2603}
2604
2605#if !defined(NDEBUG)
2606bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2607 switch (OpType) {
2608 case OperationType::OverflowingBinOp:
2609 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2610 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2611 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2612 case OperationType::Trunc:
2613 return Opcode == Instruction::Trunc;
2614 case OperationType::DisjointOp:
2615 return Opcode == Instruction::Or;
2616 case OperationType::PossiblyExactOp:
2617 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2618 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2619 case OperationType::GEPOp:
2620 return Opcode == Instruction::GetElementPtr ||
2621 Opcode == VPInstruction::PtrAdd ||
2622 Opcode == VPInstruction::WidePtrAdd;
2623 case OperationType::FPMathOp:
2624 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2625 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2626 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2627 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2628 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2629 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2630 Opcode == Instruction::UIToFP ||
2631 Opcode == VPInstruction::WideIVStep ||
2633 case OperationType::FCmp:
2634 return Opcode == Instruction::FCmp;
2635 case OperationType::NonNegOp:
2636 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2637 case OperationType::Cmp:
2638 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2639 case OperationType::ReductionOp:
2641 case OperationType::Other:
2642 return true;
2643 }
2644 llvm_unreachable("Unknown OperationType enum");
2645}
2646
2648 Type *ResultTy) const {
2649 // Handle opcodes without default flags.
2650 if (Opcode == Instruction::ICmp)
2651 return OpType == OperationType::Cmp;
2652 if (Opcode == Instruction::FCmp)
2653 return OpType == OperationType::FCmp;
2655 return OpType == OperationType::ReductionOp;
2656
2657 OperationType Required = getDefaultFlags(Opcode, ResultTy).OpType;
2658 return Required == OperationType::Other || Required == OpType;
2659}
2660#endif
2661
2662#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2663static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2664 switch (Kind) {
2665 case RecurKind::None:
2666 OS << "none";
2667 break;
2668 case RecurKind::Add:
2669 OS << "add";
2670 break;
2671 case RecurKind::Sub:
2672 OS << "sub";
2673 break;
2675 OS << "add-chain-with-subs";
2676 break;
2677 case RecurKind::Mul:
2678 OS << "mul";
2679 break;
2680 case RecurKind::Or:
2681 OS << "or";
2682 break;
2683 case RecurKind::And:
2684 OS << "and";
2685 break;
2686 case RecurKind::Xor:
2687 OS << "xor";
2688 break;
2689 case RecurKind::SMin:
2690 OS << "smin";
2691 break;
2692 case RecurKind::SMax:
2693 OS << "smax";
2694 break;
2695 case RecurKind::UMin:
2696 OS << "umin";
2697 break;
2698 case RecurKind::UMax:
2699 OS << "umax";
2700 break;
2701 case RecurKind::FAdd:
2702 OS << "fadd";
2703 break;
2705 OS << "fadd-chain-with-subs";
2706 break;
2707 case RecurKind::FSub:
2708 OS << "fsub";
2709 break;
2710 case RecurKind::FMul:
2711 OS << "fmul";
2712 break;
2713 case RecurKind::FMin:
2714 OS << "fmin";
2715 break;
2716 case RecurKind::FMax:
2717 OS << "fmax";
2718 break;
2719 case RecurKind::FMinNum:
2720 OS << "fminnum";
2721 break;
2722 case RecurKind::FMaxNum:
2723 OS << "fmaxnum";
2724 break;
2726 OS << "fminimum";
2727 break;
2729 OS << "fmaximum";
2730 break;
2732 OS << "fminimumnum";
2733 break;
2735 OS << "fmaximumnum";
2736 break;
2737 case RecurKind::FMulAdd:
2738 OS << "fmuladd";
2739 break;
2740 case RecurKind::AnyOf:
2741 OS << "any-of";
2742 break;
2743 case RecurKind::FindIV:
2744 OS << "find-iv";
2745 break;
2747 OS << "find-last";
2748 break;
2749 }
2750}
2751
2753 switch (OpType) {
2754 case OperationType::Cmp:
2756 break;
2757 case OperationType::FCmp:
2760 break;
2761 case OperationType::DisjointOp:
2762 if (DisjointFlags.IsDisjoint)
2763 O << " disjoint";
2764 break;
2765 case OperationType::PossiblyExactOp:
2766 if (ExactFlags.IsExact)
2767 O << " exact";
2768 break;
2769 case OperationType::OverflowingBinOp:
2770 if (WrapFlags.HasNUW)
2771 O << " nuw";
2772 if (WrapFlags.HasNSW)
2773 O << " nsw";
2774 break;
2775 case OperationType::Trunc:
2776 if (TruncFlags.HasNUW)
2777 O << " nuw";
2778 if (TruncFlags.HasNSW)
2779 O << " nsw";
2780 break;
2781 case OperationType::FPMathOp:
2783 break;
2784 case OperationType::GEPOp: {
2786 if (Flags.isInBounds())
2787 O << " inbounds";
2788 else if (Flags.hasNoUnsignedSignedWrap())
2789 O << " nusw";
2790 if (Flags.hasNoUnsignedWrap())
2791 O << " nuw";
2792 break;
2793 }
2794 case OperationType::NonNegOp:
2795 if (NonNegFlags.NonNeg)
2796 O << " nneg";
2797 break;
2798 case OperationType::ReductionOp: {
2799 O << " (";
2801 if (isReductionInLoop())
2802 O << ", in-loop";
2803 if (isReductionOrdered())
2804 O << ", ordered";
2805 O << ")";
2807 break;
2808 }
2809 case OperationType::Other:
2810 break;
2811 }
2812 O << " ";
2813}
2814#endif
2815
2817 auto &Builder = State.Builder;
2818 switch (Opcode) {
2819 case Instruction::Call:
2820 case Instruction::UncondBr:
2821 case Instruction::CondBr:
2822 case Instruction::PHI:
2823 case Instruction::GetElementPtr:
2824 llvm_unreachable("This instruction is handled by a different recipe.");
2825 case Instruction::UDiv:
2826 case Instruction::SDiv:
2827 case Instruction::SRem:
2828 case Instruction::URem:
2829 case Instruction::Add:
2830 case Instruction::FAdd:
2831 case Instruction::Sub:
2832 case Instruction::FSub:
2833 case Instruction::FNeg:
2834 case Instruction::Mul:
2835 case Instruction::FMul:
2836 case Instruction::FDiv:
2837 case Instruction::FRem:
2838 case Instruction::Shl:
2839 case Instruction::LShr:
2840 case Instruction::AShr:
2841 case Instruction::And:
2842 case Instruction::Or:
2843 case Instruction::Xor: {
2844 // Just widen unops and binops.
2846 for (VPValue *VPOp : operands())
2847 Ops.push_back(State.get(VPOp));
2848
2849 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2850
2851 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2852 applyFlags(*VecOp);
2853 applyMetadata(*VecOp);
2854 }
2855
2856 // Use this vector value for all users of the original instruction.
2857 State.set(this, V);
2858 break;
2859 }
2860 case Instruction::ExtractValue: {
2861 assert(getNumOperands() == 2 && "expected single level extractvalue");
2862 Value *Op = State.get(getOperand(0));
2863 Value *Extract = Builder.CreateExtractValue(
2864 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2865 State.set(this, Extract);
2866 break;
2867 }
2868 case Instruction::Freeze: {
2869 Value *Op = State.get(getOperand(0));
2870 Value *Freeze = Builder.CreateFreeze(Op);
2871 State.set(this, Freeze);
2872 break;
2873 }
2874 case Instruction::ICmp:
2875 case Instruction::FCmp: {
2876 // Widen compares. Generate vector compares.
2877 bool FCmp = Opcode == Instruction::FCmp;
2878 Value *A = State.get(getOperand(0));
2879 Value *B = State.get(getOperand(1));
2880 Value *C = nullptr;
2881 if (FCmp) {
2882 C = Builder.CreateFCmp(getPredicate(), A, B);
2883 } else {
2884 C = Builder.CreateICmp(getPredicate(), A, B);
2885 }
2886 if (auto *I = dyn_cast<Instruction>(C)) {
2887 applyFlags(*I);
2888 applyMetadata(*I);
2889 }
2890 State.set(this, C);
2891 break;
2892 }
2893 case Instruction::Select: {
2894 VPValue *CondOp = getOperand(0);
2895 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2896 Value *Op0 = State.get(getOperand(1));
2897 Value *Op1 = State.get(getOperand(2));
2898 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2899 State.set(this, Sel);
2900 if (auto *I = dyn_cast<Instruction>(Sel)) {
2902 applyFlags(*I);
2903 applyMetadata(*I);
2904 }
2905 break;
2906 }
2907 default:
2908 // This instruction is not vectorized by simple widening.
2909 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2910 << Instruction::getOpcodeName(Opcode));
2911 llvm_unreachable("Unhandled instruction!");
2912 } // end of switch.
2913
2914#if !defined(NDEBUG)
2915 // Verify that VPlan type inference results agree with the type of the
2916 // generated values.
2917 assert(VectorType::get(this->getScalarType(), State.VF) ==
2918 State.get(this)->getType() &&
2919 "inferred type and type from generated instructions do not match");
2920#endif
2921}
2922
2924 VPCostContext &Ctx) const {
2925 switch (Opcode) {
2926 case Instruction::UDiv:
2927 case Instruction::SDiv:
2928 case Instruction::SRem:
2929 case Instruction::URem:
2930 // If the div/rem operation isn't safe to speculate and requires
2931 // predication, then the only way we can even create a vplan is to insert
2932 // a select on the second input operand to ensure we use the value of 1
2933 // for the inactive lanes. The select will be costed separately.
2934 case Instruction::FNeg:
2935 case Instruction::Add:
2936 case Instruction::FAdd:
2937 case Instruction::Sub:
2938 case Instruction::FSub:
2939 case Instruction::Mul:
2940 case Instruction::FMul:
2941 case Instruction::FDiv:
2942 case Instruction::FRem:
2943 case Instruction::Shl:
2944 case Instruction::LShr:
2945 case Instruction::AShr:
2946 case Instruction::And:
2947 case Instruction::Or:
2948 case Instruction::Xor:
2949 case Instruction::Freeze:
2950 case Instruction::ExtractValue:
2951 case Instruction::ICmp:
2952 case Instruction::FCmp:
2953 case Instruction::Select:
2954 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2955 default:
2956 llvm_unreachable("Unsupported opcode for instruction");
2957 }
2958}
2959
2960#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2962 VPSlotTracker &SlotTracker) const {
2963 O << Indent << "WIDEN ";
2965 O << " = " << Instruction::getOpcodeName(Opcode);
2966 printFlags(O);
2968}
2969#endif
2970
2972 auto &Builder = State.Builder;
2973 /// Vectorize casts.
2974 assert(State.VF.isVector() && "Not vectorizing?");
2975 Type *DestTy = VectorType::get(getScalarType(), State.VF);
2976 VPValue *Op = getOperand(0);
2977 Value *A = State.get(Op);
2978 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2979 State.set(this, Cast);
2980 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2981 applyFlags(*CastOp);
2982 applyMetadata(*CastOp);
2983 }
2984}
2985
2990
2991#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2993 VPSlotTracker &SlotTracker) const {
2994 O << Indent << "WIDEN-CAST ";
2996 O << " = " << Instruction::getOpcodeName(Opcode);
2997 printFlags(O);
2999 O << " to " << *getScalarType();
3000}
3001#endif
3002
3004 VPCostContext &Ctx) const {
3005 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3006}
3007
3008#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3010 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
3011 O << Indent;
3013 O << " = WIDEN-INDUCTION";
3014 printFlags(O);
3016
3017 if (auto *TI = getTruncInst())
3018 O << " (truncated to " << *TI->getType() << ")";
3019}
3020#endif
3021
3023 // The step may be defined by a recipe in the preheader (e.g. if it requires
3024 // SCEV expansion), but for the canonical induction the step is required to be
3025 // 1, which is represented as live-in.
3026 return match(getStartValue(), m_ZeroInt()) &&
3027 match(getStepValue(), m_One()) &&
3028 getScalarType() == getRegion()->getCanonicalIVType();
3029}
3030
3033 VPCostContext &Ctx) const {
3034 // A widened induction generates a vector phi and increments it by the
3035 // splatted step each iteration.
3037 InstructionCost Cost = Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3038 Type *StepTy = getScalarType();
3039 unsigned IncOpc = ID.getKind() == InductionDescriptor::IK_IntInduction
3040 ? Instruction::Add
3041 : ID.getInductionOpcode();
3042 assert(IncOpc != Instruction::BinaryOpsEnd &&
3043 "induction must have a valid increment opcode");
3044 return Cost + Ctx.TTI.getArithmeticInstrCost(IncOpc, toVectorTy(StepTy, VF),
3045 Ctx.CostKind);
3046}
3047
3048/// Returns the ConstantFP \p V wraps, or nullptr if it does not wrap one.
3049static const ConstantFP *getConstantFP(const VPValue *V) {
3050 auto *C = dyn_cast<VPConstant>(V);
3051 return C ? dyn_cast<ConstantFP>(C->getConstant()) : nullptr;
3052}
3053
3055 VPCostContext &Ctx) const {
3056 // The cost model for this is modelled on expandVPDerivedIV in
3057 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
3058 // negatively affect vectorization it takes into account any expected
3059 // simplifications that happen in simplifyRecipe.
3060 switch (getInductionKind()) {
3061 default:
3062 // TODO: Compute cost for remaining kinds.
3063 break;
3065 // There are currently no tests that expose a path where all lanes are
3066 // used, so it's better to bail out for now.
3067 if (!vputils::onlyFirstLaneUsed(this))
3068 break;
3069
3070 // Start off by assuming we need both mul and add, then refine this.
3071 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
3072
3073 // If the start value is zero the add gets folded away.
3074 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
3075 NeedsAdd = !StartC->isZero();
3076
3077 // For some values of step the arithmetic changes:
3078 // 1. A step of 1 requires no operation.
3079 // 2. A step of -1 requires a negate.
3080 // 3. A power-of-2 step will use a shl, instead of a mul.
3081 Type *StepTy = getStepValue()->getScalarType();
3083 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
3084 if (StepC->isOne())
3085 NeedsMul = false;
3086 else if (StepC->getAPInt().isAllOnes()) {
3087 // This will most likely end up as a negate in simplifyRecipe, and
3088 // the negate will be combined with the add to make a sub.
3089 // NOTE: This is perhaps an invalid assumption that the cost of an
3090 // 'add' is the same as a 'sub'.
3091 NeedsMul = false;
3092 NeedsAdd = true;
3093 } else if (StepC->getAPInt().isPowerOf2()) {
3094 // This will most likely end up as a shift-left in simplifyRecipe
3095 NeedsMul = false;
3096 NeedsShl = true;
3097 }
3098 }
3099
3100 // Add the cost of the conversion from index to step type if the index
3101 // will be used.
3102 Type *IndexTy = getIndex()->getScalarType();
3103 unsigned StepTySize = StepTy->getScalarSizeInBits();
3104 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3105 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3106 unsigned CastOpc =
3107 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::ZExt;
3108 Cost += Ctx.TTI.getCastInstrCost(
3109 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3110 }
3111
3112 if (NeedsMul)
3113 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3114 Ctx.CostKind);
3115 if (NeedsShl)
3116 Cost += Ctx.TTI.getArithmeticInstrCost(
3117 Instruction::Shl, StepTy, Ctx.CostKind,
3118 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3119 {TargetTransformInfo::OK_UniformConstantValue,
3120 TargetTransformInfo::OP_None});
3121 if (NeedsAdd)
3122 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3123 Ctx.CostKind);
3124 return Cost;
3125 }
3127 // There are currently no tests that expose a path where all lanes are
3128 // used, so it's better to bail out for now.
3129 if (!vputils::onlyFirstLaneUsed(this))
3130 break;
3131
3132 // Unlike the integer case, converting the index to the FP step type is
3133 // unavoidable: the index is always the integer canonical IV, so this
3134 // cast is never folded away.
3135 Type *StepTy = getStepValue()->getScalarType();
3136 Type *IndexTy = getIndex()->getScalarType();
3138 Ctx.TTI.getCastInstrCost(Instruction::SIToFP, StepTy, IndexTy,
3139 TTI::CastContextHint::None, Ctx.CostKind);
3140
3141 // If the step is 1.0, the multiply is an exact identity and gets folded
3142 // away, independent of fast-math flags.
3143 const ConstantFP *StepC = getConstantFP(getStepValue());
3144 bool NeedsMul = !StepC || !StepC->isOne();
3145
3146 // "fadd -0.0, X" folds to X unconditionally, but "fadd 0.0, X" only folds
3147 // to X without nsz if X can be proven to never be -0.0, which we cannot, as
3148 // Step may be -0.0.
3149 // TODO: Consider fast-math flags when they are available in
3150 // VPDerivedIVRecipe.
3151 const ConstantFP *StartC = getConstantFP(getStartValue());
3152 bool AddFolds = getFPBinOp()->getOpcode() == Instruction::FAdd && StartC &&
3153 StartC->isZero() && (StartC->isNegZero() || !NeedsMul);
3154
3155 if (NeedsMul)
3156 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::FMul, StepTy,
3157 Ctx.CostKind);
3158 if (!AddFolds)
3159 Cost += Ctx.TTI.getArithmeticInstrCost(getFPBinOp()->getOpcode(), StepTy,
3160 Ctx.CostKind);
3161 return Cost;
3162 }
3163 }
3164
3165 return 0;
3166}
3167
3168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3170 VPSlotTracker &SlotTracker) const {
3171 O << Indent;
3173 O << " = DERIVED-IV";
3174 printFlags(O);
3175 getStartValue()->printAsOperand(O, SlotTracker);
3176 O << " + ";
3177 getOperand(1)->printAsOperand(O, SlotTracker);
3178 O << " * ";
3179 getStepValue()->printAsOperand(O, SlotTracker);
3180}
3181#endif
3182
3186
3188 VPCostContext &Ctx) const {
3189 Type *BaseIVTy = getOperand(0)->getScalarType();
3190 assert((BaseIVTy->isIntegerTy() || BaseIVTy->isFloatingPointTy()) &&
3191 "VPScalarIVStepsRecipe is only created for integer and FP inductions");
3192
3193 // If only the first lane is used, then there won't be any code that remains
3194 // in the loop for the first unrolled part.
3196 return 0;
3197
3198 // If the vector body executes at most once, the canonical IV is a constant
3199 // and every lane's step folds away with it.
3200 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
3201 return 0;
3202
3203 // Typically the operations are:
3204 // 1. Add the start index to each lane value.
3205 // 2. Multiply the start index by the step.
3206 // 3. Add the scaled start index to base IV.
3207 // Any code generated for 1 and 2 should be loop invariant and therefore
3208 // hoisted out of the loop. We only need to add on the cost of 3.
3210 if (BaseIVTy->isFloatingPointTy()) {
3211 // Unlike the integer case, the users of an FP induction cannot be re-based
3212 // on a common value, so each lane needs its own FAdd/FSub.
3213 assert(!VF.isScalable() &&
3214 "FP scalar steps for all lanes are only created for fixed VFs");
3215 Cost = Ctx.TTI.getArithmeticInstrCost(InductionOpcode, BaseIVTy,
3216 Ctx.CostKind) *
3217 (VF.getFixedValue() - 1);
3218 } else {
3219 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3220 // %add1 = add i32 %iv, 0
3221 // %add2 = add i32 %iv, 1
3222 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3223 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3224 // it's very likely that these GEPs will all be rewritten to have a common
3225 // base such that what's left is just
3226 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3227 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3228 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3229 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3230 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3231 Cost = Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3232 Ctx.CostKind);
3233 }
3234
3235 // If the steps are generated inside a replicate region, scale by execution
3236 // probability.
3237 const VPRegionBlock *Region = getRegion();
3238 if (Region && Region->isReplicator())
3239 Cost /= Ctx.getReplicateRegionCostDivisor(Region);
3240 return Cost;
3241}
3242
3244 // Fast-math-flags propagate from the original induction instruction.
3245 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3246 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3247
3248 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3249 /// variable on which to base the steps, \p Step is the size of the step.
3250
3251 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3252 Value *Step = State.get(getStepValue(), VPLane(0));
3253 IRBuilderBase &Builder = State.Builder;
3254
3255 // Ensure step has the same type as that of scalar IV.
3256 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3257 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3258
3259 // We build scalar steps for both integer and floating-point induction
3260 // variables. Here, we determine the kind of arithmetic we will perform.
3263 if (BaseIVTy->isIntegerTy()) {
3264 AddOp = Instruction::Add;
3265 MulOp = Instruction::Mul;
3266 } else {
3267 AddOp = InductionOpcode;
3268 MulOp = Instruction::FMul;
3269 }
3270
3271 // Determine the number of scalars we need to generate.
3272 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
3273 // Compute the scalar steps and save the results in State.
3274
3275 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
3276 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
3277 : Constant::getNullValue(BaseIVTy);
3278
3279 for (unsigned Lane = 0; Lane < EndLane; ++Lane) {
3280 // It is okay if the induction variable type cannot hold the lane number,
3281 // we expect truncation in this case.
3282 Constant *LaneValue =
3283 BaseIVTy->isIntegerTy()
3284 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
3285 /*ImplicitTrunc=*/true)
3286 : ConstantFP::get(BaseIVTy, Lane);
3287 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
3288 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
3289 "Expected StartIdx to be folded to a constant when VF is not "
3290 "scalable");
3291 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3292 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3293 State.set(this, Add, VPLane(Lane));
3294 }
3295}
3296
3297#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3299 VPSlotTracker &SlotTracker) const {
3300 O << Indent;
3302 O << " = SCALAR-STEPS ";
3304}
3305#endif
3306
3308 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3310}
3311
3313 assert(State.VF.isVector() && "not widening");
3314 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3315 return State.get(Op, vputils::isSingleScalar(Op));
3316 });
3317 auto *GEP =
3318 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3319 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3320 State.set(this, GEP, vputils::isSingleScalar(this));
3321}
3322
3323#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3325 VPSlotTracker &SlotTracker) const {
3326 O << Indent << "WIDEN-GEP ";
3328 O << " = getelementptr";
3329 printFlags(O);
3331}
3332#endif
3333
3335 assert(!getOffset() && "Unexpected offset operand");
3336 VPBuilder Builder(this);
3337 VPlan &Plan = *getParent()->getPlan();
3338 VPValue *VFVal = getVFValue();
3339 const DataLayout &DL = Plan.getDataLayout();
3340 Type *IndexTy = DL.getIndexType(this->getScalarType());
3341 VPValue *Stride =
3342 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3343 VPValue *VF =
3344 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3345
3346 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3347 VPInstruction *VFMinusOne =
3348 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3349 DebugLoc::getUnknown(), "", {true, true});
3350 VPInstruction *Offset0 =
3351 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3352
3353 // Offset for PartN = Offset0 + Part * Stride * VF.
3354 VPValue *PartxStride =
3355 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3356 VPValue *Offset = Builder.createAdd(
3357 Offset0,
3358 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3360}
3361
3363 auto &Builder = State.Builder;
3364 assert(getOffset() && "Expected prior materialization of offset");
3365 Value *Ptr = State.get(getPointer(), true);
3366 Value *Offset = State.get(getOffset(), true);
3367 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3369 State.set(this, ResultPtr, /*IsScalar*/ true);
3370}
3371
3372#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3374 VPSlotTracker &SlotTracker) const {
3375 O << Indent;
3377 O << " = vector-end-pointer";
3378 printFlags(O);
3379 getSourceElementType()->print(O);
3380 O << ", ";
3382}
3383#endif
3384
3386 assert(getVFxPart() &&
3387 "Expected prior simplification of recipe without VFxPart");
3388
3389 auto &Builder = State.Builder;
3390 Value *Ptr = State.get(getOperand(0), VPLane(0));
3391 Value *Offset = State.get(getVFxPart(), true);
3392 // TODO: Expand to VPInstruction to support constant folding.
3393 if (!match(getStride(), m_One())) {
3394 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3395 Offset->getType());
3396 Offset = Builder.CreateMul(Offset, Stride);
3397 }
3398 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3400 State.set(this, ResultPtr, /*IsScalar*/ true);
3401}
3402
3403#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3405 VPSlotTracker &SlotTracker) const {
3406 O << Indent;
3408 O << " = vector-pointer";
3409 printFlags(O);
3410 getSourceElementType()->print(O);
3411 O << ", ";
3413}
3414#endif
3415
3417 VPCostContext &Ctx) const {
3418 // A blend will be expanded to a select VPInstruction, which will generate a
3419 // scalar select if only the first lane is used.
3421 VF = ElementCount::getFixed(1);
3422
3423 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3424 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3425
3427 for (unsigned I = 1, E = getNumIncomingValues(); I != E; ++I) {
3428 CmpPredicate Pred;
3429 if (!match(getMask(I), m_Cmp(Pred, m_VPValue(), m_VPValue())))
3430 Pred = getScalarType()->isFloatingPointTy() ? CmpInst::BAD_FCMP_PREDICATE
3432 Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3433 Pred, Ctx.CostKind);
3434 }
3435 return Cost;
3436}
3437
3438#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3440 VPSlotTracker &SlotTracker) const {
3441 O << Indent << "BLEND ";
3443 O << " =";
3444 printFlags(O);
3445 if (getNumIncomingValues() == 1) {
3446 // Not a User of any mask: not really blending, this is a
3447 // single-predecessor phi.
3448 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3449 } else {
3450 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3451 if (I != 0)
3452 O << " ";
3453 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3454 if (I == 0 && isNormalized())
3455 continue;
3456 O << "/";
3457 getMask(I)->printAsOperand(O, SlotTracker);
3458 }
3459 }
3460}
3461#endif
3462
3466 "In-loop AnyOf reductions aren't currently supported");
3467 // Propagate the fast-math flags carried by the underlying instruction.
3468 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3469 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3470 Value *NewVecOp = State.get(getVecOp());
3471 if (VPValue *Cond = getCondOp()) {
3472 Value *NewCond = State.get(Cond, State.VF.isScalar());
3473 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3474 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3475
3476 Value *Start =
3478 if (State.VF.isVector())
3479 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3480
3481 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3482 NewVecOp = Select;
3483 }
3484 Value *NewRed;
3485 Value *NextInChain;
3486 if (isOrdered()) {
3487 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3488 if (State.VF.isVector())
3489 NewRed =
3490 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3491 else
3492 NewRed = State.Builder.CreateBinOp(
3494 PrevInChain, NewVecOp);
3495 PrevInChain = NewRed;
3496 NextInChain = NewRed;
3497 } else if (isPartialReduction()) {
3498 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3499 "Unexpected partial reduction kind");
3500 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
3501 NewRed = State.Builder.CreateIntrinsic(
3502 PrevInChain->getType(),
3503 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3504 : Intrinsic::vector_partial_reduce_fadd,
3505 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3506 "partial.reduce");
3507 PrevInChain = NewRed;
3508 NextInChain = NewRed;
3509 } else {
3510 assert(isInLoop() &&
3511 "The reduction must either be ordered, partial or in-loop");
3512 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3513 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3515 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3516 else
3517 NextInChain = State.Builder.CreateBinOp(
3519 PrevInChain, NewRed);
3520 }
3521 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3522}
3523
3525
3526 assert(State.VF.isVector() &&
3527 "Shouldn't generate VPReductionEVLRecipe with scalar VF");
3528 auto &Builder = State.Builder;
3529 // Propagate the fast-math flags carried by the underlying instruction.
3530 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3531 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3532
3534 Value *Prev = State.get(getChainOp(), /*IsScalar*/ !isPartialReduction());
3535 Value *VecOp = State.get(getVecOp());
3536 Value *EVL = State.get(getEVL(), VPLane(0));
3537
3538 Value *Mask;
3539 if (VPValue *CondOp = getCondOp())
3540 Mask = State.get(CondOp);
3541 else
3542 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3543
3544 Value *NewRed;
3545 if (isPartialReduction()) {
3546 // For partial reductions, we need to generate a predicated select
3547 // (vp.merge) since `@llvm.vector.partial.reduce()` doesn't have a vector
3548 // predicated version.
3549 VectorType *VecTy = cast<VectorType>(VecOp->getType());
3550 Value *Identity = getRecurrenceIdentity(Kind, VecTy->getElementType(),
3552 Identity =
3553 State.Builder.CreateVectorSplat(VecTy->getElementCount(), Identity);
3554
3555 // TODO: Calculate the predicate cost for the partial reduction.
3556 Value *NewVecOp = State.Builder.CreateIntrinsic(
3557 VecTy, Intrinsic::vp_merge, {Mask, VecOp, Identity, EVL});
3558 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3559 "Unexpected partial reduction kind");
3560 NewRed = State.Builder.CreateIntrinsic(
3561 Prev->getType(),
3562 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3563 : Intrinsic::vector_partial_reduce_fadd,
3564 {Prev, NewVecOp}, State.Builder.getFastMathFlags(), "partial.reduce");
3565 } else if (isOrdered()) {
3566 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3567 } else {
3568 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3570 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3571 else
3572 NewRed = Builder.CreateBinOp(
3574 Prev);
3575 }
3576 State.set(this, NewRed, !isPartialReduction());
3577}
3578
3580 VPCostContext &Ctx) const {
3581 RecurKind RdxKind = getRecurrenceKind();
3582 Type *ElementTy = this->getScalarType();
3583 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3584 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3586 std::optional<FastMathFlags> OptionalFMF =
3587 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3588
3589 if (isPartialReduction()) {
3590 InstructionCost CondCost = 0;
3591 if (isConditional()) {
3593 auto *CondTy =
3595 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3596 CondTy, Pred, Ctx.CostKind);
3597 }
3598 return CondCost + Ctx.TTI.getPartialReductionCost(
3599 Opcode, ElementTy, nullptr, ElementTy, VF,
3600 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3601 OptionalFMF);
3602 }
3603
3604 // TODO: Support any-of reductions.
3605 assert(
3607 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
3608 "Any-of reduction not implemented in VPlan-based cost model currently.");
3609
3610 // Note that TTI should model the cost of moving result to the scalar register
3611 // and the BinOp cost in the getMinMaxReductionCost().
3614 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3615 }
3616
3617 // Note that TTI should model the cost of moving result to the scalar register
3618 // and the BinOp cost in the getArithmeticReductionCost().
3619 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3620 Ctx.CostKind);
3621}
3622
3624 ExpressionTypes ExpressionType,
3625 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3626 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3627 cast<VPReductionRecipe>(ExpressionRecipes.back())
3628 ->getChainOp()
3629 ->getScalarType()),
3630 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3631 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3632 assert(
3633 none_of(ExpressionRecipes,
3634 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3635 "expression cannot contain recipes with side-effects");
3636
3637 // Maintain a copy of the expression recipes as a set of users.
3638 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3639 for (auto *R : ExpressionRecipes)
3640 ExpressionRecipesAsSetOfUsers.insert(R);
3641
3642 // Recipes in the expression, except the last one, must only be used by
3643 // (other) recipes inside the expression. If there are other users, external
3644 // to the expression, use a clone of the recipe for external users.
3645 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3646 if (R != ExpressionRecipes.back() &&
3647 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3648 return !ExpressionRecipesAsSetOfUsers.contains(U);
3649 })) {
3650 // There are users outside of the expression. Clone the recipe and use the
3651 // clone those external users.
3652 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3653 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
3654 VPUser &U, unsigned) {
3655 return !ExpressionRecipesAsSetOfUsers.contains(&U);
3656 });
3657 CopyForExtUsers->insertBefore(R);
3658 }
3659 if (R->getParent())
3660 R->removeFromParent();
3661 }
3662
3663 // Internalize all external operands to the expression recipes. To do so,
3664 // create new temporary VPValues for all operands defined by a recipe outside
3665 // the expression. The original operands are added as operands of the
3666 // VPExpressionRecipe itself.
3667 for (auto *R : ExpressionRecipes) {
3668 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3669 auto *Def = Op->getDefiningRecipe();
3670 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3671 continue;
3672 addOperand(Op);
3673 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3674 }
3675 }
3676
3677 // Replace each external operand with the first one created for it in
3678 // LiveInPlaceholders.
3679 for (auto *R : ExpressionRecipes)
3680 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3681 R->replaceUsesOfWith(LiveIn, Tmp);
3682}
3683
3685 for (auto *R : ExpressionRecipes)
3686 // Since the list could contain duplicates, make sure the recipe hasn't
3687 // already been inserted.
3688 if (!R->getParent())
3689 R->insertBefore(this);
3690
3691 for (const auto &[Idx, Op] : enumerate(operands()))
3692 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3693
3694 replaceAllUsesWith(ExpressionRecipes.back());
3695 SmallVector<VPSingleDefRecipe *> DecomposedRecipes(ExpressionRecipes);
3696 ExpressionRecipes.clear();
3697 return DecomposedRecipes;
3698}
3699
3701 VPCostContext &Ctx) const {
3702 Type *RedTy = this->getScalarType();
3703 auto *SrcVecTy =
3705 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3706 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3707 switch (ExpressionType) {
3708 case ExpressionTypes::NegatedExtendedReduction:
3709 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3710 "Unexpected opcode");
3711 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3712 [[fallthrough]];
3713 case ExpressionTypes::ExtendedReduction: {
3714 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3715 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3716
3717 if (RedR->isPartialReduction())
3718 return Ctx.TTI.getPartialReductionCost(
3719 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3721 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3722 RedTy->isFloatingPointTy()
3723 ? std::optional{RedR->getFastMathFlagsOrNone()}
3724 : std::nullopt);
3725 else if (!RedTy->isFloatingPointTy())
3726 // TTI::getExtendedReductionCost only supports integer types.
3727 return Ctx.TTI.getExtendedReductionCost(
3728 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3729 std::nullopt, Ctx.CostKind);
3730 else
3732 }
3733 case ExpressionTypes::MulAccReduction:
3734 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3735 Ctx.CostKind);
3736
3737 case ExpressionTypes::ExtNegatedMulAccReduction:
3738 switch (Opcode) {
3739 case Instruction::Add:
3740 Opcode = Instruction::Sub;
3741 break;
3742 case Instruction::FAdd:
3743 Opcode = Instruction::FSub;
3744 break;
3745 default:
3746 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3747 }
3748 [[fallthrough]];
3749 case ExpressionTypes::ExtMulAccReduction: {
3750 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3751 if (RedR->isPartialReduction()) {
3752 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3753 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3754 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3755 return Ctx.TTI.getPartialReductionCost(
3756 Opcode, getOperand(0)->getScalarType(),
3757 getOperand(1)->getScalarType(), RedTy, VF,
3759 Ext0R->getOpcode()),
3761 Ext1R->getOpcode()),
3762 Mul->getOpcode(), Ctx.CostKind,
3763 RedTy->isFloatingPointTy()
3764 ? std::optional{RedR->getFastMathFlagsOrNone()}
3765 : std::nullopt);
3766 }
3767 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3768 return Ctx.TTI.getMulAccReductionCost(
3769 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3770 Instruction::ZExt,
3771 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3772 }
3773 }
3774 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3775}
3776
3778 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3779 return R->mayReadFromMemory() || R->mayWriteToMemory();
3780 });
3781}
3782
3784 assert(
3785 none_of(ExpressionRecipes,
3786 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3787 "expression cannot contain recipes with side-effects");
3788 return false;
3789}
3790
3792 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3793 return RR && !RR->isPartialReduction();
3794}
3795
3796#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3797
3799 VPSlotTracker &SlotTracker) const {
3800 O << Indent << "EXPRESSION ";
3802 O << " = ";
3803 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3804 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3805 VPValue *Mask = getOperand(getNumOperands() - 1);
3806 VPValue *EVL =
3808 ? getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1))
3809 : nullptr;
3810 VPValue *RdxStart = getOperand(
3811 getNumOperands() - (Red->isConditional() ? 2 : 1) - (EVL ? 1 : 0));
3812 auto PrintEVLAndMask = [&]() {
3813 if (EVL) {
3814 O << ", ";
3815 EVL->printAsOperand(O, SlotTracker);
3816 }
3817 if (Red->isConditional()) {
3818 O << ", ";
3819 Mask->printAsOperand(O, SlotTracker);
3820 }
3821 };
3822
3823 switch (ExpressionType) {
3824 case ExpressionTypes::NegatedExtendedReduction:
3825 case ExpressionTypes::ExtendedReduction: {
3826 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
3828 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3829 O << Instruction::getOpcodeName(Opcode) << " (";
3830 if (Negated)
3831 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
3833 if (Negated)
3834 O << ")";
3835 Red->printFlags(O);
3836
3837 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3838 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3839 << *Ext0->getScalarType();
3840 PrintEVLAndMask();
3841 O << ")";
3842 break;
3843 }
3844 case ExpressionTypes::ExtNegatedMulAccReduction: {
3845 RdxStart->printAsOperand(O, SlotTracker);
3846 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3848 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3849 << " (sub (0, mul";
3850 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3851 Mul->printFlags(O);
3852 O << "(";
3854 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3855 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3856 << *Ext0->getScalarType() << "), (";
3858 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3859 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3860 << *Ext1->getScalarType() << ")";
3861 PrintEVLAndMask();
3862 O << "))";
3863 break;
3864 }
3865 case ExpressionTypes::MulAccReduction:
3866 case ExpressionTypes::ExtMulAccReduction: {
3867 RdxStart->printAsOperand(O, SlotTracker);
3868 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3870 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3871 << " (";
3872 O << "mul";
3873 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3874 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3875 : ExpressionRecipes[0]);
3876 Mul->printFlags(O);
3877 if (IsExtended)
3878 O << "(";
3880 if (IsExtended) {
3881 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3882 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3883 << *Ext0->getScalarType() << "), (";
3884 } else {
3885 O << ", ";
3886 }
3888 if (IsExtended) {
3889 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3890 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3891 << *Ext1->getScalarType() << ")";
3892 }
3893 PrintEVLAndMask();
3894 O << ")";
3895 break;
3896 }
3897 }
3898}
3899
3901 VPSlotTracker &SlotTracker) const {
3902 if (isPartialReduction())
3903 O << Indent << "PARTIAL-REDUCE ";
3904 else
3905 O << Indent << "REDUCE ";
3907 O << " = ";
3909 O << " +";
3910 printFlags(O);
3911 O << " reduce.";
3913 O << " (";
3915 if (isConditional()) {
3916 O << ", ";
3918 }
3919 O << ")";
3920}
3921
3923 VPSlotTracker &SlotTracker) const {
3924 if (isPartialReduction())
3925 O << Indent << "PARTIAL-REDUCE ";
3926 else
3927 O << Indent << "REDUCE ";
3929 O << " = ";
3931 O << " +";
3932 printFlags(O);
3933 O << " vp.reduce."
3936 << " (";
3938 O << ", ";
3940 if (isConditional()) {
3941 O << ", ";
3943 }
3944 O << ")";
3945}
3946
3947#endif
3948
3950 assert(IsSingleScalar &&
3951 "VPReplicateRecipes must be unrolled before ::execute");
3952 auto *Instr = getUnderlyingInstr();
3953 Instruction *Cloned = Instr->clone();
3954 Type *ResultTy = getScalarType();
3955 if (!ResultTy->isVoidTy()) {
3956 Cloned->setName(Instr->getName() + ".cloned");
3957 // The operands of the replicate recipe may have been narrowed, resulting in
3958 // a narrower result type. Update the type of the cloned instruction to the
3959 // correct type.
3960 if (ResultTy != Cloned->getType())
3961 Cloned->mutateType(ResultTy);
3962 }
3963
3964 applyFlags(*Cloned);
3965 applyMetadata(*Cloned);
3966
3967 if (hasPredicate())
3968 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
3969
3970 // Replace the operands of the cloned instructions with their scalar
3971 // equivalents in the new loop.
3972 for (const auto &[Idx, V] : enumerate(operands()))
3973 Cloned->setOperand(Idx, State.get(V, true));
3974
3975 // Place the cloned scalar in the new loop.
3976 State.Builder.Insert(Cloned);
3977
3978 State.set(this, Cloned, true);
3979
3980 // If we just cloned a new assumption, add it the assumption cache.
3981 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3982 State.AC->registerAssumption(II);
3983}
3984
3985/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3986/// which the legacy cost model computes a SCEV expression when computing the
3987/// address cost. Computing SCEVs for VPValues is incomplete and returns
3988/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3989/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3990static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3992 const Loop *L) {
3993 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3994 if (isa<SCEVCouldNotCompute>(Addr))
3995 return Addr;
3996
3997 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3998}
3999
4001 VPCostContext &Ctx) const {
4003 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
4004 // transform, avoid computing their cost multiple times for now.
4005 Ctx.SkipCostComputation.insert(UI);
4006
4007 if (VF.isScalable() && !isSingleScalar())
4009
4010 switch (UI->getOpcode()) {
4011 case Instruction::Alloca:
4012 if (VF.isScalable())
4014 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4015 this->getScalarType(), Ctx.CostKind);
4016 case Instruction::GetElementPtr:
4017 // We mark this instruction as zero-cost because the cost of GEPs in
4018 // vectorized code depends on whether the corresponding memory instruction
4019 // is scalarized or not. Therefore, we handle GEPs with the memory
4020 // instruction cost.
4021 return 0;
4022 case Instruction::Call: {
4023 auto *CalledFn =
4025 Type *ResultTy = this->getScalarType();
4026 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
4027 isSingleScalar(), VF, Ctx);
4028 }
4029 case Instruction::Add:
4030 case Instruction::Sub:
4031 case Instruction::FAdd:
4032 case Instruction::FSub:
4033 case Instruction::Mul:
4034 case Instruction::FMul:
4035 case Instruction::FDiv:
4036 case Instruction::FRem:
4037 case Instruction::Shl:
4038 case Instruction::LShr:
4039 case Instruction::AShr:
4040 case Instruction::And:
4041 case Instruction::Or:
4042 case Instruction::Xor:
4043 case Instruction::ICmp:
4044 case Instruction::FCmp:
4046 Ctx) *
4047 (isSingleScalar() ? 1 : VF.getFixedValue());
4048 case Instruction::SDiv:
4049 case Instruction::UDiv:
4050 case Instruction::SRem:
4051 case Instruction::URem: {
4052 InstructionCost ScalarCost =
4054 if (isSingleScalar())
4055 return ScalarCost;
4056
4057 // If any of the operands is from a different replicate region and has its
4058 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
4059 // model to avoid cost mis-match.
4060 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
4061 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
4062 if (!PredR)
4063 return false;
4064 return Ctx.skipCostComputation(
4066 PredR->getOperand(0)->getUnderlyingValue()),
4067 VF.isVector());
4068 }))
4069 break;
4070
4071 ScalarCost = ScalarCost * VF.getFixedValue() +
4072 Ctx.getScalarizationOverhead(this->getScalarType(),
4073 to_vector(operands()), VF);
4074 // If the recipe is not predicated (i.e. not in a replicate region), return
4075 // the scalar cost. Otherwise handle predicated cost.
4076 if (!getRegion()->isReplicator())
4077 return ScalarCost;
4078
4079 // Account for the phi nodes that we will create.
4080 ScalarCost += VF.getFixedValue() *
4081 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4082 // Scale the cost by the probability of executing the predicated blocks.
4083 // This assumes the predicated block for each vector lane is equally
4084 // likely.
4085 ScalarCost /= Ctx.getReplicateRegionCostDivisor(getRegion());
4086 return ScalarCost;
4087 }
4088 case Instruction::Load:
4089 case Instruction::Store: {
4090 bool IsLoad = UI->getOpcode() == Instruction::Load;
4091 const VPValue *PtrOp = getOperand(!IsLoad);
4092 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
4094 break;
4095
4096 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
4097 Type *ScalarPtrTy = PtrOp->getScalarType();
4098 const Align Alignment = getLoadStoreAlignment(UI);
4099 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
4101 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
4102 bool UsedByLoadStoreAddress =
4103 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
4104 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
4105 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
4106 UsedByLoadStoreAddress ? UI : nullptr);
4107
4108 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
4109 InstructionCost ScalarCost =
4110 ScalarMemOpCost +
4111 Ctx.TTI.getAddressComputationCost(
4112 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
4113 Ctx.CostKind);
4114 if (isSingleScalar())
4115 return ScalarCost;
4116
4117 SmallVector<const VPValue *> OpsToScalarize;
4118 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
4119 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
4120 // don't assign scalarization overhead in general, if the target prefers
4121 // vectorized addressing or the loaded value is used as part of an address
4122 // of another load or store.
4123 if (!UsedByLoadStoreAddress) {
4124 bool EfficientVectorLoadStore =
4125 Ctx.TTI.supportsEfficientVectorElementLoadStore();
4126 if (!(IsLoad && !PreferVectorizedAddressing) &&
4127 !(!IsLoad && EfficientVectorLoadStore))
4128 append_range(OpsToScalarize, operands());
4129
4130 if (!EfficientVectorLoadStore)
4131 ResultTy = this->getScalarType();
4132 }
4133
4135 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
4137 (ScalarCost * VF.getFixedValue()) +
4138 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
4139
4140 const VPRegionBlock *ParentRegion = getRegion();
4141 if (ParentRegion && ParentRegion->isReplicator()) {
4142 if (!PtrSCEV)
4143 break;
4144 Cost /= Ctx.getReplicateRegionCostDivisor(ParentRegion);
4145 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
4146
4147 auto *VecI1Ty = VectorType::get(
4148 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
4149 Cost += Ctx.TTI.getScalarizationOverhead(
4150 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4151 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
4152
4153 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
4154 // Artificially setting to a high enough value to practically disable
4155 // vectorization with such operations.
4156 return 3000000;
4157 }
4158 }
4159 return Cost;
4160 }
4161 case Instruction::SExt:
4162 case Instruction::ZExt:
4163 case Instruction::FPToUI:
4164 case Instruction::FPToSI:
4165 case Instruction::FPExt:
4166 case Instruction::PtrToInt:
4167 case Instruction::PtrToAddr:
4168 case Instruction::IntToPtr:
4169 case Instruction::SIToFP:
4170 case Instruction::UIToFP:
4171 case Instruction::Trunc:
4172 case Instruction::FPTrunc:
4173 case Instruction::Select:
4174 case Instruction::AddrSpaceCast: {
4176 Ctx) *
4177 (isSingleScalar() ? 1 : VF.getFixedValue());
4178 }
4179 case Instruction::ExtractValue:
4180 case Instruction::InsertValue:
4181 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
4182 }
4183
4184 return Ctx.getLegacyCost(UI, VF);
4185}
4186
4188 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
4189 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
4191 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
4192
4193 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
4194 auto GetIntrinsicCost = [&] {
4195 if (!IntrinID)
4197 return Ctx.TTI.getIntrinsicInstrCost(
4198 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4199 };
4200
4201 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4202 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4203 return 0;
4204 }
4205
4206 InstructionCost ScalarCallCost =
4207 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4208 if (IsSingleScalar) {
4209 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4210 return ScalarCallCost;
4211 }
4212
4213 // Scalarization overhead is undefined for scalable VFs.
4214 if (VF.isScalable())
4216
4217 return ScalarCallCost * VF.getFixedValue() +
4218 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4219}
4220
4221#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4223 VPSlotTracker &SlotTracker) const {
4224 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4225
4226 if (!getScalarType()->isVoidTy()) {
4228 O << " = ";
4229 }
4230 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4231 O << "call";
4232 printFlags(O);
4233 O << "@" << CB->getCalledFunction()->getName() << "(";
4235 Op->printAsOperand(O, SlotTracker);
4236 });
4237 O << ")";
4238 } else {
4240 printFlags(O);
4242 }
4243
4244 // Find if the recipe is used by a widened recipe via an intervening
4245 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4246 if (any_of(users(), [](const VPUser *U) {
4247 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4248 return !vputils::onlyScalarValuesUsed(PredR);
4249 return false;
4250 }))
4251 O << " (S->V)";
4252}
4253#endif
4254
4256 llvm_unreachable("recipe must be removed when dissolving replicate region");
4257}
4258
4260 VPCostContext &Ctx) const {
4261 // The legacy cost model doesn't assign costs to branches for individual
4262 // replicate regions. Match the current behavior in the VPlan cost model for
4263 // now.
4264 return 0;
4265}
4266
4268 llvm_unreachable("recipe must be removed when dissolving replicate region");
4269}
4270
4271#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4273 VPSlotTracker &SlotTracker) const {
4274 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4276 O << " = ";
4278}
4279#endif
4280
4282const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4283
4286
4288const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4289
4292
4294 VPCostContext &Ctx) const {
4295 const VPRecipeBase *R = getAsRecipe();
4297 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4298 : R->getOperand(1)->getScalarType();
4299 Type *Ty = toVectorTy(ScalarTy, VF);
4300 unsigned AS =
4301 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4302 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4303
4304 if (!Consecutive) {
4305 // TODO: Using the original IR may not be accurate.
4306 // Currently, ARM will use the underlying IR to calculate gather/scatter
4307 // instruction cost.
4308 Type *PtrTy = getAddr()->getScalarType();
4309 const Value *Ptr = getAddr()->getUnderlyingValue();
4310
4311 // If the address value is uniform across all lanes, then the address can be
4312 // calculated with scalar type and broadcast.
4314 PtrTy = toVectorTy(PtrTy, VF);
4315
4316 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4317 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4318 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4319 : Intrinsic::vp_scatter;
4320 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4321 Ctx.CostKind) +
4322 Ctx.TTI.getMemIntrinsicInstrCost(
4324 &Ingredient),
4325 Ctx.CostKind);
4326 }
4327
4329 if (IsMasked) {
4330 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4331 : Intrinsic::masked_store;
4332 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4333 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4334 } else {
4335 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4337 : R->getOperand(1));
4338 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4339 OpInfo, &Ingredient);
4340 }
4341 return Cost;
4342}
4343
4345 Type *ScalarDataTy = getScalarType();
4346 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4347 bool CreateGather = !isConsecutive();
4348
4349 auto &Builder = State.Builder;
4350 Value *Mask = nullptr;
4351 if (auto *VPMask = getMask())
4352 Mask = State.get(VPMask);
4353
4354 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
4355 Value *NewLI;
4356 if (CreateGather) {
4357 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4358 "wide.masked.gather");
4359 } else if (Mask) {
4360 NewLI =
4361 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4362 PoisonValue::get(DataTy), "wide.masked.load");
4363 } else {
4364 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4365 }
4367 State.set(this, NewLI);
4368}
4369
4370#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4372 VPSlotTracker &SlotTracker) const {
4373 O << Indent << "WIDEN ";
4375 O << " = load ";
4377}
4378#endif
4379
4381 Type *ScalarDataTy = getScalarType();
4382 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4383 bool CreateGather = !isConsecutive();
4384
4385 auto &Builder = State.Builder;
4386 CallInst *NewLI;
4387 Value *EVL = State.get(getEVL(), VPLane(0));
4388 Value *Addr = State.get(getAddr(), !CreateGather);
4389 Value *Mask = nullptr;
4390 if (VPValue *VPMask = getMask())
4391 Mask = State.get(VPMask);
4392 else
4393 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4394
4395 if (CreateGather) {
4396 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4397 {Addr, Mask, EVL}, nullptr,
4398 "wide.masked.gather");
4399 } else {
4400 NewLI = Builder.CreateIntrinsicWithoutFolding(
4401 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4402 }
4403 NewLI->addParamAttr(
4405 applyMetadata(*NewLI);
4406 State.set(this, NewLI);
4407}
4408
4410 VPCostContext &Ctx) const {
4411 if (!Consecutive || IsMasked)
4412 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4413
4414 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4415 // here because the EVL recipes using EVL to replace the tail mask. But in the
4416 // legacy model, it will always calculate the cost of mask.
4417 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4418 // don't need to compare to the legacy cost model.
4419 Type *Ty = toVectorTy(getScalarType(), VF);
4420 unsigned AS =
4421 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4422 return Ctx.TTI.getMemIntrinsicInstrCost(
4423 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4424 Ctx.CostKind);
4425}
4426
4427#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4429 VPSlotTracker &SlotTracker) const {
4430 O << Indent << "WIDEN ";
4432 O << " = vp.load ";
4434}
4435#endif
4436
4438 VPValue *StoredVPValue = getStoredValue();
4439 bool CreateScatter = !isConsecutive();
4440
4441 auto &Builder = State.Builder;
4442
4443 Value *Mask = nullptr;
4444 if (auto *VPMask = getMask())
4445 Mask = State.get(VPMask);
4446
4447 Value *StoredVal = State.get(StoredVPValue);
4448 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
4449 Instruction *NewSI = nullptr;
4450 if (CreateScatter)
4451 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4452 else if (Mask)
4453 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4454 else
4455 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4456 applyMetadata(*NewSI);
4457}
4458
4459#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4461 VPSlotTracker &SlotTracker) const {
4462 O << Indent << "WIDEN store ";
4464}
4465#endif
4466
4468 VPValue *StoredValue = getStoredValue();
4469 bool CreateScatter = !isConsecutive();
4470
4471 auto &Builder = State.Builder;
4472
4473 CallInst *NewSI = nullptr;
4474 Value *StoredVal = State.get(StoredValue);
4475 Value *EVL = State.get(getEVL(), VPLane(0));
4476 Value *Mask = nullptr;
4477 if (VPValue *VPMask = getMask())
4478 Mask = State.get(VPMask);
4479 else
4480 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4481
4482 Value *Addr = State.get(getAddr(), !CreateScatter);
4483 if (CreateScatter) {
4484 NewSI = Builder.CreateIntrinsicWithoutFolding(
4485 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4486 {StoredVal, Addr, Mask, EVL});
4487 } else {
4488 NewSI = Builder.CreateIntrinsicWithoutFolding(
4489 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4490 {StoredVal, Addr, Mask, EVL});
4491 }
4492 NewSI->addParamAttr(
4494 applyMetadata(*NewSI);
4495}
4496
4498 VPCostContext &Ctx) const {
4499 if (!Consecutive || IsMasked)
4500 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4501
4502 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4503 // here because the EVL recipes using EVL to replace the tail mask. But in the
4504 // legacy model, it will always calculate the cost of mask.
4505 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4506 // don't need to compare to the legacy cost model.
4507 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4508 unsigned AS =
4509 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4510 return Ctx.TTI.getMemIntrinsicInstrCost(
4511 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4512 Ctx.CostKind);
4513}
4514
4515#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4517 VPSlotTracker &SlotTracker) const {
4518 O << Indent << "WIDEN vp.store ";
4520}
4521#endif
4522
4524 VectorType *DstVTy, const DataLayout &DL) {
4525 // Verify that V is a vector type with same number of elements as DstVTy.
4526 auto VF = DstVTy->getElementCount();
4527 auto *SrcVecTy = cast<VectorType>(V->getType());
4528 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4529 Type *SrcElemTy = SrcVecTy->getElementType();
4530 Type *DstElemTy = DstVTy->getElementType();
4531 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4532 "Vector elements must have same size");
4533
4534 // Do a direct cast if element types are castable.
4535 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4536 return Builder.CreateBitOrPointerCast(V, DstVTy);
4537 }
4538 // V cannot be directly casted to desired vector type.
4539 // May happen when V is a floating point vector but DstVTy is a vector of
4540 // pointers or vice-versa. Handle this using a two-step bitcast using an
4541 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4542 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4543 "Only one type should be a pointer type");
4544 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4545 "Only one type should be a floating point type");
4546 Type *IntTy =
4547 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4548 auto *VecIntTy = VectorType::get(IntTy, VF);
4549 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4550 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4551}
4552
4553/// Return a vector containing interleaved elements from multiple
4554/// smaller input vectors.
4556 const Twine &Name) {
4557 unsigned Factor = Vals.size();
4558 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4559
4560 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4561#ifndef NDEBUG
4562 for (Value *Val : Vals)
4563 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4564#endif
4565
4566 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4567 // must use intrinsics to interleave.
4568 if (VecTy->isScalableTy()) {
4569 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4570 return Builder.CreateVectorInterleave(Vals, Name);
4571 }
4572
4573 // Fixed length. Start by concatenating all vectors into a wide vector.
4574 Value *WideVec = concatenateVectors(Builder, Vals);
4575
4576 // Interleave the elements into the wide vector.
4577 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4578 return Builder.CreateShuffleVector(
4579 WideVec, createInterleaveMask(NumElts, Factor), Name);
4580}
4581
4582// Try to vectorize the interleave group that \p Instr belongs to.
4583//
4584// E.g. Translate following interleaved load group (factor = 3):
4585// for (i = 0; i < N; i+=3) {
4586// R = Pic[i]; // Member of index 0
4587// G = Pic[i+1]; // Member of index 1
4588// B = Pic[i+2]; // Member of index 2
4589// ... // do something to R, G, B
4590// }
4591// To:
4592// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4593// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4594// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4595// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4596//
4597// Or translate following interleaved store group (factor = 3):
4598// for (i = 0; i < N; i+=3) {
4599// ... do something to R, G, B
4600// Pic[i] = R; // Member of index 0
4601// Pic[i+1] = G; // Member of index 1
4602// Pic[i+2] = B; // Member of index 2
4603// }
4604// To:
4605// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4606// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4607// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4608// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4609// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4611 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4612 "Masking gaps for scalable vectors is not yet supported.");
4614 Instruction *Instr = Group->getInsertPos();
4615
4616 // Prepare for the vector type of the interleaved load/store.
4617 Type *ScalarTy = getLoadStoreType(Instr);
4618 unsigned InterleaveFactor = Group->getFactor();
4619 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4620
4621 VPValue *BlockInMask = getMask();
4622 VPValue *Addr = getAddr();
4623 Value *ResAddr = State.get(Addr, VPLane(0));
4624
4625 auto CreateGroupMask = [&BlockInMask, &State,
4626 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4627 if (State.VF.isScalable()) {
4628 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4629 assert(InterleaveFactor <= 8 &&
4630 "Unsupported deinterleave factor for scalable vectors");
4631 auto *ResBlockInMask = State.get(BlockInMask);
4632 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4633 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4634 }
4635
4636 if (!BlockInMask)
4637 return MaskForGaps;
4638
4639 Value *ResBlockInMask = State.get(BlockInMask);
4640 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4641 ResBlockInMask,
4642 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4643 "interleaved.mask");
4644 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4645 ShuffledMask, MaskForGaps)
4646 : ShuffledMask;
4647 };
4648
4649 const DataLayout &DL = Instr->getDataLayout();
4650 // Vectorize the interleaved load group.
4651 if (isa<LoadInst>(Instr)) {
4652 Value *MaskForGaps = nullptr;
4653 if (needsMaskForGaps()) {
4654 MaskForGaps =
4655 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4656 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4657 }
4658
4659 Instruction *NewLoad;
4660 if (BlockInMask || MaskForGaps) {
4661 Value *GroupMask = CreateGroupMask(MaskForGaps);
4662 Value *PoisonVec = PoisonValue::get(VecTy);
4663 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4664 Group->getAlign(), GroupMask,
4665 PoisonVec, "wide.masked.vec");
4666 } else
4667 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4668 Group->getAlign(), "wide.vec");
4669 applyMetadata(*NewLoad);
4670 // TODO: Also manage existing metadata using VPIRMetadata.
4671 Group->addMetadata(NewLoad);
4672
4674 if (VecTy->isScalableTy()) {
4675 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4676 // so must use intrinsics to deinterleave.
4677 assert(InterleaveFactor <= 8 &&
4678 "Unsupported deinterleave factor for scalable vectors");
4679 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4680 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4681 NewLoad->getType(), NewLoad,
4682 /*FMFSource=*/nullptr, "strided.vec");
4683 }
4684
4685 auto CreateStridedVector = [&InterleaveFactor, &State,
4686 &NewLoad](unsigned Index) -> Value * {
4687 assert(Index < InterleaveFactor && "Illegal group index");
4688 if (State.VF.isScalable())
4689 return State.Builder.CreateExtractValue(NewLoad, Index);
4690
4691 // For fixed length VF, use shuffle to extract the sub-vectors from the
4692 // wide load.
4693 auto StrideMask =
4694 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4695 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4696 "strided.vec");
4697 };
4698
4699 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4700 Instruction *Member = Group->getMember(I);
4701
4702 // Skip the gaps in the group.
4703 if (!Member)
4704 continue;
4705
4706 Value *StridedVec = CreateStridedVector(I);
4707
4708 // If this member has different type, cast the result type.
4709 if (Member->getType() != ScalarTy) {
4710 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4711 StridedVec =
4712 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4713 }
4714
4715 if (Group->isReverse())
4716 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4717
4718 State.set(VPDefs[J], StridedVec);
4719 ++J;
4720 }
4721 return;
4722 }
4723
4724 // The sub vector type for current instruction.
4725 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4726
4727 // Vectorize the interleaved store group.
4728 Value *MaskForGaps =
4729 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4730 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4731 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4732 ArrayRef<VPValue *> StoredValues = getStoredValues();
4733 // Collect the stored vector from each member.
4734 SmallVector<Value *, 4> StoredVecs;
4735 unsigned StoredIdx = 0;
4736 for (unsigned i = 0; i < InterleaveFactor; i++) {
4737 assert((Group->getMember(i) || MaskForGaps) &&
4738 "Fail to get a member from an interleaved store group");
4739 Instruction *Member = Group->getMember(i);
4740
4741 // Skip the gaps in the group.
4742 if (!Member) {
4743 Value *Undef = PoisonValue::get(SubVT);
4744 StoredVecs.push_back(Undef);
4745 continue;
4746 }
4747
4748 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4749 ++StoredIdx;
4750
4751 if (Group->isReverse())
4752 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4753
4754 // If this member has different type, cast it to a unified type.
4755
4756 if (StoredVec->getType() != SubVT)
4757 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4758
4759 StoredVecs.push_back(StoredVec);
4760 }
4761
4762 // Interleave all the smaller vectors into one wider vector.
4763 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4764 Instruction *NewStoreInstr;
4765 if (BlockInMask || MaskForGaps) {
4766 Value *GroupMask = CreateGroupMask(MaskForGaps);
4767 NewStoreInstr = State.Builder.CreateMaskedStore(
4768 IVec, ResAddr, Group->getAlign(), GroupMask);
4769 } else
4770 NewStoreInstr =
4771 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4772
4773 applyMetadata(*NewStoreInstr);
4774 // TODO: Also manage existing metadata using VPIRMetadata.
4775 Group->addMetadata(NewStoreInstr);
4776}
4777
4778#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4780 VPSlotTracker &SlotTracker) const {
4782 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4784 VPValue *Mask = getMask();
4785 if (Mask) {
4786 O << ", ";
4787 Mask->printAsOperand(O, SlotTracker);
4788 }
4789
4790 unsigned OpIdx = 0;
4791 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4792 if (!IG->getMember(i))
4793 continue;
4794 if (getNumStoreOperands() > 0) {
4795 O << "\n" << Indent << " store ";
4796 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
4797 O << " to index " << i;
4798 } else {
4799 O << "\n" << Indent << " ";
4801 O << " = load from index " << i;
4802 }
4803 ++OpIdx;
4804 }
4805}
4806#endif
4807
4809 assert(State.VF.isScalable() &&
4810 "Only support scalable VF for EVL tail-folding.");
4812 "Masking gaps for scalable vectors is not yet supported.");
4814 Instruction *Instr = Group->getInsertPos();
4815
4816 // Prepare for the vector type of the interleaved load/store.
4817 Type *ScalarTy = getLoadStoreType(Instr);
4818 unsigned InterleaveFactor = Group->getFactor();
4819 assert(InterleaveFactor <= 8 &&
4820 "Unsupported deinterleave/interleave factor for scalable vectors");
4821 ElementCount WideVF = State.VF * InterleaveFactor;
4822 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4823
4824 VPValue *Addr = getAddr();
4825 Value *ResAddr = State.get(Addr, VPLane(0));
4826 Value *EVL = State.get(getEVL(), VPLane(0));
4827 Value *InterleaveEVL = State.Builder.CreateMul(
4828 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4829 /* NUW= */ true, /* NSW= */ true);
4830 LLVMContext &Ctx = State.Builder.getContext();
4831
4832 Value *GroupMask = nullptr;
4833 if (VPValue *BlockInMask = getMask()) {
4834 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4835 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4836 } else {
4837 GroupMask =
4838 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4839 }
4840
4841 // Vectorize the interleaved load group.
4842 if (isa<LoadInst>(Instr)) {
4843 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4844 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4845 "wide.vp.load");
4846 NewLoad->addParamAttr(0,
4847 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4848
4849 applyMetadata(*NewLoad);
4850 // TODO: Also manage existing metadata using VPIRMetadata.
4851 Group->addMetadata(NewLoad);
4852
4853 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4854 // so must use intrinsics to deinterleave.
4855 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4856 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4857 NewLoad->getType(), NewLoad,
4858 /*FMFSource=*/nullptr, "strided.vec");
4859
4860 const DataLayout &DL = Instr->getDataLayout();
4861 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4862 Instruction *Member = Group->getMember(I);
4863 // Skip the gaps in the group.
4864 if (!Member)
4865 continue;
4866
4867 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4868 // If this member has different type, cast the result type.
4869 if (Member->getType() != ScalarTy) {
4870 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4871 StridedVec =
4872 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4873 }
4874
4875 State.set(getVPValue(J), StridedVec);
4876 ++J;
4877 }
4878 return;
4879 } // End for interleaved load.
4880
4881 // The sub vector type for current instruction.
4882 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4883 // Vectorize the interleaved store group.
4884 ArrayRef<VPValue *> StoredValues = getStoredValues();
4885 // Collect the stored vector from each member.
4886 SmallVector<Value *, 4> StoredVecs;
4887 const DataLayout &DL = Instr->getDataLayout();
4888 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4889 Instruction *Member = Group->getMember(I);
4890 // Skip the gaps in the group.
4891 if (!Member) {
4892 StoredVecs.push_back(PoisonValue::get(SubVT));
4893 continue;
4894 }
4895
4896 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4897 // If this member has different type, cast it to a unified type.
4898 if (StoredVec->getType() != SubVT)
4899 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4900
4901 StoredVecs.push_back(StoredVec);
4902 ++StoredIdx;
4903 }
4904
4905 // Interleave all the smaller vectors into one wider vector.
4906 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4907 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
4908 Type::getVoidTy(Ctx), Intrinsic::vp_store,
4909 {IVec, ResAddr, GroupMask, InterleaveEVL});
4910
4911 NewStore->addParamAttr(1,
4912 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4913
4914 applyMetadata(*NewStore);
4915 // TODO: Also manage existing metadata using VPIRMetadata.
4916 Group->addMetadata(NewStore);
4917}
4918
4919#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4921 VPSlotTracker &SlotTracker) const {
4923 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4925 O << ", ";
4927 if (VPValue *Mask = getMask()) {
4928 O << ", ";
4929 Mask->printAsOperand(O, SlotTracker);
4930 }
4931
4932 unsigned OpIdx = 0;
4933 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4934 if (!IG->getMember(i))
4935 continue;
4936 if (getNumStoreOperands() > 0) {
4937 O << "\n" << Indent << " vp.store ";
4938 getOperand(2 + OpIdx)->printAsOperand(O, SlotTracker);
4939 O << " to index " << i;
4940 } else {
4941 O << "\n" << Indent << " ";
4943 O << " = vp.load from index " << i;
4944 }
4945 ++OpIdx;
4946 }
4947}
4948#endif
4949
4951 VPCostContext &Ctx) const {
4952 Instruction *InsertPos = getInsertPos();
4953 // Find the VPValue index of the interleave group. We need to skip gaps.
4954 unsigned InsertPosIdx = 0;
4955 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4956 if (auto *Member = IG->getMember(Idx)) {
4957 if (Member == InsertPos)
4958 break;
4959 InsertPosIdx++;
4960 }
4961 const VPValue *ValV = getNumDefinedValues() > 0
4962 ? getVPValue(InsertPosIdx)
4963 : getStoredValues()[InsertPosIdx];
4964 Type *ValTy = ValV->getScalarType();
4965 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4966 unsigned AS =
4967 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4968
4969 unsigned InterleaveFactor = IG->getFactor();
4970 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4971
4972 // Holds the indices of existing members in the interleaved group.
4974 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4975 if (IG->getMember(IF))
4976 Indices.push_back(IF);
4977
4978 // Calculate the cost of the whole interleaved group.
4979 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4980 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4981 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4982
4983 if (!IG->isReverse())
4984 return Cost;
4985
4986 return Cost + IG->getNumMembers() *
4987 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4988 VectorTy, VectorTy, Ctx.CostKind, {},
4989 0);
4990}
4991
4993 return vputils::onlyScalarValuesUsed(this) &&
4994 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4995}
4996
4997#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4999 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5000 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
5001 "unexpected number of operands");
5002 O << Indent << "EMIT ";
5004 O << " = WIDEN-POINTER-INDUCTION ";
5006 O << ", ";
5008 O << ", ";
5010 if (getNumOperands() == 5) {
5011 O << ", ";
5013 O << ", ";
5015 }
5016}
5017
5019 VPSlotTracker &SlotTracker) const {
5020 O << Indent << "EMIT ";
5022 O << " = EXPAND SCEV " << *Expr;
5023}
5024#endif
5025
5026#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5028 VPSlotTracker &SlotTracker) const {
5029 O << Indent << "EMIT ";
5031 O << " = WIDEN-CANONICAL-INDUCTION";
5032 printFlags(O);
5034}
5035#endif
5036
5038 auto &Builder = State.Builder;
5039 // Create a vector from the initial value.
5040 auto *VectorInit = getStartValue()->getLiveInIRValue();
5041
5042 Type *VecTy = State.VF.isScalar()
5043 ? VectorInit->getType()
5044 : VectorType::get(VectorInit->getType(), State.VF);
5045
5046 BasicBlock *VectorPH =
5047 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5048 if (State.VF.isVector()) {
5049 auto *IdxTy = Builder.getInt32Ty();
5050 auto *One = ConstantInt::get(IdxTy, 1);
5051 IRBuilder<>::InsertPointGuard Guard(Builder);
5052 Builder.SetInsertPoint(VectorPH->getTerminator());
5053 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
5054 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
5055 VectorInit = Builder.CreateInsertElement(
5056 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
5057 }
5058
5059 // Create a phi node for the new recurrence.
5060 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
5061 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
5062 Phi->addIncoming(VectorInit, VectorPH);
5063 State.set(this, Phi);
5064}
5065
5068 VPCostContext &Ctx) const {
5069 if (VF.isScalar())
5070 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5071
5072 return 0;
5073}
5074
5075#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5077 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5078 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
5080 O << " = phi ";
5082}
5083#endif
5084
5086 // Reductions do not have to start at zero. They can start with
5087 // any loop invariant values.
5088 VPValue *StartVPV = getStartValue();
5089
5090 // In order to support recurrences we need to be able to vectorize Phi nodes.
5091 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
5092 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
5093 // this value when we vectorize all of the instructions that use the PHI.
5094 BasicBlock *VectorPH =
5095 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5096 bool ScalarPHI = State.VF.isScalar() || isInLoop();
5097 Value *StartV = State.get(StartVPV, ScalarPHI);
5098 Type *VecTy = StartV->getType();
5099
5100 BasicBlock *HeaderBB = State.CFG.PrevBB;
5101 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
5102 "recipe must be in the vector loop header");
5103 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
5104 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
5105 State.set(this, Phi, isInLoop());
5106
5107 Phi->addIncoming(StartV, VectorPH);
5108}
5109
5110#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5112 VPSlotTracker &SlotTracker) const {
5113 O << Indent << "WIDEN-REDUCTION-PHI ";
5114
5116 O << " = phi (";
5117 printRecurrenceKind(O, Kind);
5118 O << ")";
5119 printFlags(O);
5121 if (getVFScaleFactor() > 1)
5122 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
5123}
5124#endif
5125
5127 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
5128 return vputils::onlyFirstLaneUsed(this);
5129}
5130
5132 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
5133}
5134
5136 VPCostContext &Ctx) const {
5137 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5138}
5139
5140#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5142 VPSlotTracker &SlotTracker) const {
5143 O << Indent << "WIDEN-PHI ";
5144
5146 O << " = phi ";
5148}
5149#endif
5150
5152 BasicBlock *VectorPH =
5153 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5154 Value *StartMask = State.get(getOperand(0));
5155 PHINode *Phi =
5156 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
5157 Phi->addIncoming(StartMask, VectorPH);
5158 State.set(this, Phi);
5159}
5160
5161#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5163 VPSlotTracker &SlotTracker) const {
5164 O << Indent << "ACTIVE-LANE-MASK-PHI ";
5165
5167 O << " = phi ";
5169}
5170#endif
5171
5172#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5174 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5175 O << Indent << "CURRENT-ITERATION-PHI ";
5176
5178 O << " = phi ";
5180}
5181#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
Hexagon Common GEP
Value * getPointer(Value *Ptr)
iv users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const Value *V)
static bool isOrdered(const Instruction *I)
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
SI Fold Operands
static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, EVT VT, SDValue A, SDValue B, SDValue GlueChain, SDNodeFlags Flags)
This file contains some templates that are useful if you are working with the STL at all.
This file defines less commonly used SmallVector utilities.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static const ConstantFP * getConstantFP(const VPValue *V)
Returns the ConstantFP V wraps, or nullptr if it does not wrap one.
static void executePhiRecipe(VPSingleDefRecipe *R, VPPhiAccessors &Phi, VPTransformState &State, bool IsScalar, const Twine &Name)
Shared execute logic for VPPhi and VPWidenPHIRecipe.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
static Instruction::BinaryOps getSubRecurOpcode(RecurKind Kind)
static cl::opt< bool > VPlanPrintMetadata("vplan-print-metadata", cl::init(true), cl::Hidden, cl::desc("Controls the printing of recipe metadata when debugging."))
static VPExecutionFrequency getExecutionFrequencyFromMD(const MDNode *Node)
Returns the execution frequency recorded in Node.
static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind)
static unsigned getCalledFnOperandIndex(ArrayRef< VPValue * > Operands)
For call VPInstruction operands, return the operand index of the called function.
This file contains the declarations of the Vectorization Plan base classes:
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
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...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
bool isNegZero() const
Return true if the value is negative zero.
Definition Constants.h:473
bool isOne() const
Returns true if this value is exactly +1.0.
Definition Constants.h:485
bool isZero() const
Return true if the value is positive or negative zero.
Definition Constants.h:467
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:320
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:308
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
Definition Operator.h:302
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:290
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:647
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:577
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:869
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2677
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:519
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2731
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2665
LLVM_ABI Value * CreateVectorSpliceRight(Value *V1, Value *V2, Value *Offset, const Twine &Name="")
Create a vector.splice.right intrinsic call, or a shufflevector that produces the same result if the ...
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1224
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2724
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:2743
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:534
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1120
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2100
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2292
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:300
LLVM_ABI Value * CreateVectorReverse(Value *V, const Twine &Name="")
Return a vector value that contains the vector V reversed.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2394
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:482
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1778
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:477
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2524
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1862
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2390
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1162
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1447
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2129
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1430
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:462
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1739
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2402
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1786
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1600
LLVM_ABI Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1464
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
A struct for saving information about induction variables.
@ IK_FpInduction
Floating point induction variable.
@ IK_IntInduction
Integer induction variable. Step = C.
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:338
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isReverse() const
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
Information for memory intrinsic cost model.
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
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.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
llvm::VectorInstrContext VectorInstrContext
@ 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:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
value_op_iterator value_op_end()
Definition User.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4415
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4468
iterator end()
Definition VPlan.h:4452
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4481
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:3001
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2996
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition VPlan.h:2992
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:95
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:229
static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop header, based on regions or VPDT in their absence.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPBranchOnMaskRecipe.
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
VPlan-based builder utility analogous to IRBuilder.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:579
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:552
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:564
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:574
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4233
VPValue * getIndex() const
Definition VPlan.h:4230
VPValue * getStepValue() const
Definition VPlan.h:4231
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPDerivedIVRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStartValue() const
Definition VPlan.h:4229
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPExpandSCEVRecipe(const SCEV *Expr)
bool isVectorToScalar() const
Returns true if this VPExpressionRecipe produces a single scalar.
SmallVector< VPSingleDefRecipe * > decompose()
Return and insert the recipes of the expression back into the VPlan, directly before the current reci...
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.
VPExpressionRecipe(ExpressionTypes ExpressionType, ArrayRef< VPSingleDefRecipe * > ExpressionRecipes)
Construct a new VPExpressionRecipe by internalizing recipes in ExpressionRecipes.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2483
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
Definition VPlan.h:2204
Class to record and manage LLVM IR flags.
Definition VPlan.h:705
FastMathFlagsTy FMFs
Definition VPlan.h:794
ReductionFlagsTy ReductionFlags
Definition VPlan.h:796
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:788
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:1011
static VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
bool isReductionOrdered() const
Definition VPlan.h:1072
TruncFlagsTy TruncFlags
Definition VPlan.h:789
CmpInst::Predicate getPredicate() const
Definition VPlan.h:983
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:791
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:792
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:1001
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:1006
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode, Type *ResultTy) const
Returns true if Opcode with scalar result type ResultTy has its required flags set.
DisjointFlagsTy DisjointFlags
Definition VPlan.h:790
FCmpFlagsTy FCmpFlags
Definition VPlan.h:795
NonNegFlagsTy NonNegFlags
Definition VPlan.h:793
bool isReductionInLoop() const
Definition VPlan.h:1078
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:940
uint8_t CmpPredStorage
Definition VPlan.h:787
RecurKind getRecurKind() const
Definition VPlan.h:1066
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1734
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
std::optional< VPExecutionFrequency > getExecutionFrequency() const
Returns the frequency recorded by setExecutionFrequency, if any.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
void clearExecutionFrequency()
Drop the frequency recorded by setExecutionFrequency, if any.
VPIRMetadata()=default
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print metadata with node IDs.
void applyMetadata(Instruction &I) const
Add all metadata to I.
void setMetadata(unsigned Kind, MDNode *Node)
Set metadata with kind Kind to Node.
Definition VPlan.h:1241
void setExecutionFrequency(std::optional< VPExecutionFrequency > Freq, LLVMContext &Ctx)
Record that the recipe executes with frequency Freq, relative to the entry of the loop region.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1306
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr)
bool doesGeneratePerAllLanes() const
Returns true if this recipe produces scalar values for all VF lanes.
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1416
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1428
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1407
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1420
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1424
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1410
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1357
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1403
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1352
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1349
@ CanonicalIVIncrementForPart
Definition VPlan.h:1333
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1360
bool hasResult() const
Definition VPlan.h:1513
bool opcodeMayReadOrWriteFromMemory() const
Returns true if the underlying opcode may read from or write to memory.
LLVM_DUMP_METHOD void dump() const
Print the VPInstruction to dbgs() (for debugging).
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1599
unsigned getOpcode() const
Definition VPlan.h:1492
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
void addOperand(VPValue *Op)
Add Op as operand of this VPInstruction.
bool isVectorToScalar() const
Returns true if this VPInstruction produces a scalar value from a vector, e.g.
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1538
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:3105
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3109
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3107
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3099
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3128
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3093
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3202
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3215
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3165
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
static LLVM_ABI std::optional< unsigned > getMaskParamPos(Intrinsic::ID IntrinsicID)
static LLVM_ABI std::optional< unsigned > getMemoryDataParamPos(Intrinsic::ID)
static LLVM_ABI std::optional< unsigned > getMemoryPointerParamPos(Intrinsic::ID)
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()
Helper type to provide functions to access incoming values and blocks for phi-like recipes.
Definition VPlan.h:1614
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
VPValue * getIncomingValueForBlock(const VPBasicBlock *VPBB) const
Returns the incoming value for VPBB. VPBB must be an incoming block.
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
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:1663
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1623
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const
Sets the incoming value for VPBB to V.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:412
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
virtual void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPRecipe prints itself, without printing common information, like debug info or metadat...
VPRegionBlock * getRegion()
Definition VPlan.h:4814
LLVM_ABI_FOR_TEST void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:115
bool isPhi() const
Returns true for PHI-like recipes.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
VPRecipeTy getVPRecipeID() const
Definition VPlan.h:530
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:484
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:562
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
bool isSafeToSpeculativelyExecute() const
Return true if we can safely execute this recipe unconditionally even if it is masked originally.
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.
VPRecipeBase(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:474
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const
Print the recipe, delegating to printRecipe().
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:354
friend class VPValue
Definition VPlanValue.h:333
void execute(VPTransformState &State) override
Generate the reduction in the loop.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3376
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2905
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2924
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3315
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:3328
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3330
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3311
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3317
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3326
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3321
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4640
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4716
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:3457
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPReplicateRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
static Type * computeScalarType(const Instruction *I, ArrayRef< VPValue * > Operands)
Compute the scalar result type for a VPReplicateRecipe wrapping I with Operands (excluding any predic...
static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy, ArrayRef< const VPValue * > ArgOps, bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx)
Return the cost of scalarizing a call to CalledFn with argument operands ArgOps for a given VF.
unsigned getOpcode() const
Definition VPlan.h:3495
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPScalarIVStepsRecipe.
bool doesGeneratePerAllLanes() const
Returns true if this recipe produces scalar values for all VF lanes.
VPValue * getStepValue() const
Definition VPlan.h:4288
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4296
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:620
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:690
LLVM_ABI_FOR_TEST LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:622
This class can be used to assign names to VPValues.
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:217
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:401
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1545
operand_range operands()
Definition VPlanValue.h:474
unsigned getNumOperands() const
Definition VPlanValue.h:441
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:442
bool operands_empty() const
Definition VPlanValue.h:478
void addOperand(VPValue *Operand)
Definition VPlanValue.h:427
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:147
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:141
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1496
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:128
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1541
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:209
VPUser * getSingleUser()
Return the single user of this value, or nullptr if there is not exactly one user.
Definition VPlanValue.h:179
VPValue * getVFValue() const
Definition VPlan.h:2298
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2295
int64_t getStride() const
Definition VPlan.h:2296
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2372
Type * getSourceElementType() const
Definition VPlan.h:2387
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPValue * getVFxPart() const
Definition VPlan.h:2374
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
operand_range args()
Definition VPlan.h:2155
Function * getCalledScalarFunction() const
Definition VPlan.h:2151
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.
static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx)
Return the cost of widening a call using the vector function Variant.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Instruction::CastOps getOpcode() const
Definition VPlan.h:1926
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce widened copies of the cast.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:2252
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2567
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2587
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2675
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
CallInst * createVectorCall(VPTransformState &State)
Helper function to produce the widened intrinsic call.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:2040
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
StringRef getIntrinsicName() const
Return to name of the intrinsic as string.
static InstructionCost computeCallCost(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost of a vector intrinsic with ID and Operands.
LLVM_ABI_FOR_TEST bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment, VPCostContext &Ctx)
Helper function for computing the cost of vector memory intrinsic.
void execute(VPTransformState &State) override
Produce a widened version of the vector memory intrinsic.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector memory intrinsic.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3762
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3787
Instruction & Ingredient
Definition VPlan.h:3753
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3759
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3797
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3756
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3790
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPHIRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenRecipe.
void execute(VPTransformState &State) override
Produce a widened instruction using the opcode and operands of the recipe, processing State....
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getOpcode() const
Definition VPlan.h:1869
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4827
const DataLayout & getDataLayout() const
Definition VPlan.h:5041
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5143
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
self_iterator getIterator()
Definition ilist_node.h:123
iterator erase(iterator where)
Definition ilist.h:204
pointer remove(iterator &IT)
Definition ilist.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI AttributeSet getFnAttributes(LLVMContext &C, ID id)
Return the function attributes for an intrinsic.
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.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
bool match(Val *V, const Pattern &P)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
int_pred_ty< is_zero_int, 1 > m_False()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
int_pred_ty< is_one, 1 > m_True()
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
Intrinsic::ID getIntrinsicID(const Ty *R)
Return the intrinsic ID underlying a call.
Definition VPlanUtils.h:87
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
constexpr uint64_t AlwaysExecutesFreq
Denominator of the frequencies computed by computeExecutionFrequencies, i.e.
Definition VPlanUtils.h:238
bool onlyScalarValuesUsed(const VPValue *Def)
Returns true if only scalar values of Def are used by all users.
bool isUsedByLoadStoreAddress(const VPValue *V)
Returns true if V is used as part of the address of another load or store.
const SCEV * getSCEVExprForVPValue(const VPValue *V, PredicatedScalarEvolution &PSE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:577
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:830
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
InstructionCost Cost
@ Undef
Value of the register doesn't matter.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
VectorInstrContext
Represents a hint about the context in which a vector instruction or intrinsic is used.
@ None
The instruction is not folded.
@ BinaryOp
One of the operands is a binary op.
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
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
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2313
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
cl::opt< unsigned > ForceTargetInstructionCost("force-target-instruction-cost", cl::init(0), cl::Hidden, cl::desc("A flag that overrides the target's expected cost for " "an instruction to a single constant value. Mostly " "useful for getting consistent testing."))
Definition VPlan.cpp:58
ElementCount getVectorizedTypeVF(Type *Ty)
Returns the number of vector elements for a vectorized type.
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:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
LLVM_ABI Type * computeScalarTypeForInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands)
Compute the scalar result type for an IR Opcode given Operands.
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
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:322
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
@ Other
Any other memory.
Definition ModRef.h:68
static const MachineInstrBuilder & addOffset(const MachineInstrBuilder &MIB, int Offset)
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
RecurKind
These are the kinds of recurrences that we support.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ FMinimumNum
FP min with llvm.minimumnum semantics.
@ FindIV
FindIV reduction with select(icmp(),x,y) where one of (x,y) is a loop induction variable (increasing ...
@ Or
Bitwise or logical OR of integers.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ None
Not a recurrence.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
DWARFExpression::Operation Op
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI Value * createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence kind RdxKind.
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Struct to hold various analysis needed for cost computations.
static bool isFreeScalarIntrinsic(Intrinsic::ID ID)
Returns true if ID is a pseudo intrinsic that is dropped via scalarization rather than widened.
Definition VPlan.cpp:1994
static bool executesAtMostOnce(const VPlan &Plan, ElementCount VF)
Returns true if the vector loop body of Plan is known to execute at most once at VF,...
TargetTransformInfo::TargetCostKind CostKind
The frequency with which a recipe executes, relative to the entry of the loop region.
Definition VPlan.h:1183
void execute(VPTransformState &State) override
Generate the phi nodes.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1792
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
PHINode & getIRPhi() const
Definition VPlan.h:1805
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void execute(VPTransformState &State) override
Generate the instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1128
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
SmallDenseMap< const VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
struct llvm::VPTransformState::CFGState CFG
Value * get(const VPValue *Def, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def if IsScalar is false, otherwise return the gen...
Definition VPlan.cpp:313
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.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3888
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3990
void execute(VPTransformState &State) override
Generate the wide store or scatter.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3993
void execute(VPTransformState &State) override
Generate a wide store or scatter.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3938