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 "VectorizeOptions.h"
20#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/Twine.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
40#include "llvm/Support/Debug.h"
44#include <cassert>
45
46using namespace llvm;
47using namespace llvm::VPlanPatternMatch;
48
49#define LV_NAME "loop-vectorize"
50#define DEBUG_TYPE LV_NAME
51
52/// For call VPInstruction operands, return the operand index of the called
53/// function. The function is either the last operand (for unmasked calls) or
54/// the second-to-last operand (for masked calls).
56 unsigned NumOps = Operands.size();
57 auto *LastOp = dyn_cast<VPIRValue>(Operands[NumOps - 1]);
58 if (LastOp && isa<Function>(LastOp->getValue()))
59 return NumOps - 1;
61 "expected function operand");
62 return NumOps - 2;
63}
64
65/// For call VPInstruction operands, return the called function.
70
71/// Return the function attributes of the callee of \p VPI, which must be a
72/// call or intrinsic VPInstruction.
79
81 switch (getVPRecipeID()) {
82 case VPExpressionSC:
83 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
84 case VPInstructionSC: {
85 auto *VPI = cast<VPInstruction>(this);
86 // Loads read from memory but don't write to memory.
87 if (VPI->getOpcode() == Instruction::Load ||
88 VPI->getOpcode() == VPInstruction::WideVectorLoad)
89 return false;
90 return VPI->opcodeMayReadOrWriteFromMemory();
91 }
92 case VPInterleaveEVLSC:
93 case VPInterleaveSC:
94 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
95 case VPWidenStoreEVLSC:
96 case VPWidenStoreSC:
97 return true;
98 case VPReplicateSC:
99 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
100 ->mayWriteToMemory();
101 case VPWidenCallSC:
102 return !cast<VPWidenCallRecipe>(this)
103 ->getCalledScalarFunction()
104 ->onlyReadsMemory();
105 case VPWidenMemIntrinsicSC:
106 case VPWidenIntrinsicSC:
107 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
108 case VPActiveLaneMaskPHISC:
109 case VPCurrentIterationPHISC:
110 case VPBranchOnMaskSC:
111 case VPDerivedIVSC:
112 case VPFirstOrderRecurrencePHISC:
113 case VPReductionPHISC:
114 case VPScalarIVStepsSC:
115 case VPPredInstPHISC:
116 case VPExpandSCEVSC:
117 case VPConditionalInductionPHISC:
118 return false;
119 case VPBlendSC:
120 case VPReductionEVLSC:
121 case VPReductionSC:
122 case VPVectorPointerSC:
123 case VPVectorEndPointerSC:
124 case VPWidenCanonicalIVSC:
125 case VPWidenCastSC:
126 case VPWidenGEPSC:
127 case VPWidenIntOrFpInductionSC:
128 case VPWidenLoadEVLSC:
129 case VPWidenLoadSC:
130 case VPWidenPHISC:
131 case VPWidenPointerInductionSC:
132 case VPWidenSC: {
133 const Instruction *I =
134 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
135 (void)I;
136 assert((!I || !I->mayWriteToMemory()) &&
137 "underlying instruction may write to memory");
138 return false;
139 }
140 default:
141 return true;
142 }
143}
144
146 switch (getVPRecipeID()) {
147 case VPExpressionSC:
148 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
149 case VPInstructionSC: {
150 auto *VPI = cast<VPInstruction>(this);
151 // Stores write to memory but don't read from memory.
152 if (VPI->getOpcode() == VPInstruction::WideVectorStore)
153 return false;
154 return VPI->opcodeMayReadOrWriteFromMemory();
155 }
156 case VPWidenLoadEVLSC:
157 case VPWidenLoadSC:
158 return true;
159 case VPReplicateSC:
160 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
161 ->mayReadFromMemory();
162 case VPWidenCallSC:
163 return !cast<VPWidenCallRecipe>(this)
164 ->getCalledScalarFunction()
165 ->onlyWritesMemory();
166 case VPWidenMemIntrinsicSC:
167 case VPWidenIntrinsicSC:
168 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
169 case VPActiveLaneMaskPHISC:
170 case VPBranchOnMaskSC:
171 case VPDerivedIVSC:
172 case VPCurrentIterationPHISC:
173 case VPFirstOrderRecurrencePHISC:
174 case VPReductionPHISC:
175 case VPPredInstPHISC:
176 case VPScalarIVStepsSC:
177 case VPWidenStoreEVLSC:
178 case VPWidenStoreSC:
179 case VPExpandSCEVSC:
180 case VPConditionalInductionPHISC:
181 return false;
182 case VPBlendSC:
183 case VPReductionEVLSC:
184 case VPReductionSC:
185 case VPVectorPointerSC:
186 case VPVectorEndPointerSC:
187 case VPWidenCanonicalIVSC:
188 case VPWidenCastSC:
189 case VPWidenGEPSC:
190 case VPWidenIntOrFpInductionSC:
191 case VPWidenPHISC:
192 case VPWidenPointerInductionSC:
193 case VPWidenSC: {
194 const Instruction *I =
195 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
196 (void)I;
197 assert((!I || !I->mayReadFromMemory()) &&
198 "underlying instruction may read from memory");
199 return false;
200 }
201 default:
202 // FIXME: Return false if the recipe represents an interleaved store.
203 return true;
204 }
205}
206
208 switch (getVPRecipeID()) {
209 case VPExpressionSC:
210 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
211 case VPActiveLaneMaskPHISC:
212 case VPDerivedIVSC:
213 case VPCurrentIterationPHISC:
214 case VPFirstOrderRecurrencePHISC:
215 case VPReductionPHISC:
216 case VPPredInstPHISC:
217 case VPVectorEndPointerSC:
218 case VPExpandSCEVSC:
219 case VPConditionalInductionPHISC:
220 return false;
221 case VPInstructionSC: {
222 auto *VPI = cast<VPInstruction>(this);
223 if (VPI->getOpcode() == Instruction::Call ||
224 VPI->getOpcode() == VPInstruction::Intrinsic) {
225 AttributeSet CalleeFnAttrs = getCalleeFnAttrs(*VPI);
226 return mayWriteToMemory() ||
227 !VPI->hasFnAttr(Attribute::NoUnwind, CalleeFnAttrs) ||
228 !VPI->hasFnAttr(Attribute::WillReturn, CalleeFnAttrs);
229 }
230 return mayWriteToMemory() ||
231 VPI->getOpcode() == VPInstruction::BranchOnCount ||
232 VPI->getOpcode() == VPInstruction::BranchOnCond ||
233 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
234 }
235 case VPWidenCallSC: {
236 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
237 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
238 }
239 case VPWidenMemIntrinsicSC:
240 case VPWidenIntrinsicSC:
241 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
242 case VPBlendSC:
243 case VPReductionEVLSC:
244 case VPReductionSC:
245 case VPScalarIVStepsSC:
246 case VPVectorPointerSC:
247 case VPWidenCanonicalIVSC:
248 case VPWidenCastSC:
249 case VPWidenGEPSC:
250 case VPWidenIntOrFpInductionSC:
251 case VPWidenPHISC:
252 case VPWidenPointerInductionSC:
253 case VPWidenSC: {
254 const Instruction *I =
255 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
256 (void)I;
257 assert((!I || !I->mayHaveSideEffects()) &&
258 "underlying instruction has side-effects");
259 return false;
260 }
261 case VPInterleaveEVLSC:
262 case VPInterleaveSC:
263 return mayWriteToMemory();
264 case VPWidenLoadEVLSC:
265 case VPWidenLoadSC:
266 case VPWidenStoreEVLSC:
267 case VPWidenStoreSC:
268 assert(
269 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
271 "mayHaveSideffects result for ingredient differs from this "
272 "implementation");
273 return mayWriteToMemory();
274 case VPReplicateSC: {
275 auto *R = cast<VPReplicateRecipe>(this);
276 return R->getUnderlyingInstr()->mayHaveSideEffects();
277 }
278 default:
279 return true;
280 }
281}
282
284 switch (getVPRecipeID()) {
285 default:
286 return false;
287 case VPInstructionSC: {
288 unsigned Opcode = cast<VPInstruction>(this)->getOpcode();
289 if (Instruction::isCast(Opcode))
290 return true;
291
292 switch (Opcode) {
293 default:
294 return false;
295 case Instruction::Add:
296 case Instruction::Sub:
297 case Instruction::Mul:
298 case Instruction::GetElementPtr:
299 return true;
300 case Instruction::Call:
303 .hasAttribute(Attribute::Speculatable);
304 }
305 }
306 }
307}
308
310 insertBefore(InsertPos->getIterator());
311}
312
314 assert(!getParent() && "Recipe already in some VPBasicBlock");
315 assert(I.getNodeParent() && "Insertion position not in any VPBasicBlock");
316 I.getNodeParent()->insert(this, I);
317}
318
320 assert(InsertPos->getParent() &&
321 "Insertion position not in any VPBasicBlock");
322 insertBefore(std::next(InsertPos->getIterator()));
323}
324
326 assert(getParent() && "Recipe not in any VPBasicBlock");
327 getParent()->getRecipeList().remove(getIterator());
328 setParent(nullptr);
329}
330
332 assert(getParent() && "Recipe not in any VPBasicBlock");
333 return getParent()->getRecipeList().erase(getIterator());
334}
335
338 insertAfter(InsertPos);
339}
340
345
347 // Get the underlying instruction for the recipe, if there is one. It is used
348 // to
349 // * decide if cost computation should be skipped for this recipe,
350 // * apply forced target instruction cost.
351 Instruction *UI = nullptr;
352 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
353 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
354 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
355 UI = IG->getInsertPos();
356 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
357 UI = &WidenMem->getIngredient();
358
359 // Replicating per lane is invalid for scalable VFs. Don't skip such recipes
360 // even if the legacy cost model ignores UI, e.g. as an address of an
361 // interleave group member, assuming the group is widened.
362 auto *RepR = dyn_cast<VPReplicateRecipe>(this);
363 bool ReplicatesScalable =
364 RepR && VF.isScalable() && RepR->doesGeneratePerAllLanes();
365 InstructionCost RecipeCost;
366 if (UI && Ctx.skipCostComputation(UI, VF.isVector()) && !ReplicatesScalable) {
367 RecipeCost = 0;
368 } else {
369 RecipeCost = computeCost(VF, Ctx);
370 if (Ctx.Opts.force_target_instruction_cost && RecipeCost.isValid()) {
371 // VPDerivedIVRecipe, VPScalarIVStepsRecipe and VPBranchOnMaskRecipe never
372 // have underlying instructions.
373 if (UI ||
375 this))
376 RecipeCost = InstructionCost(*Ctx.Opts.force_target_instruction_cost);
377 else
378 RecipeCost = InstructionCost(0);
379 }
380 }
381
382 LLVM_DEBUG({
383 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
384 if (VPSlotTracker *SlotTracker = Ctx.getSlotTracker()) {
385 print(dbgs(), "", *SlotTracker);
386 dbgs() << "\n";
387 } else {
388 dump();
389 }
390 });
391 return RecipeCost;
392}
393
395 VPCostContext &Ctx) const {
396 llvm_unreachable("subclasses should implement computeCost");
397}
398
400 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
402}
403
405 assert(OpType == Other.OpType && "OpType must match");
406 switch (OpType) {
407 case OperationType::OverflowingBinOp:
408 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
409 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
410 break;
411 case OperationType::Trunc:
412 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
413 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
414 break;
415 case OperationType::DisjointOp:
416 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
417 break;
418 case OperationType::PossiblyExactOp:
419 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
420 break;
421 case OperationType::GEPOp:
422 GEPFlagsStorage &= Other.GEPFlagsStorage;
423 break;
424 case OperationType::FPMathOp:
425 case OperationType::FCmp:
426 assert((OpType != OperationType::FCmp ||
427 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
428 "Cannot drop CmpPredicate");
429 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
430 break;
431 case OperationType::NonNegOp:
432 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
433 break;
434 case OperationType::Cmp:
435 assert(CmpPredStorage == Other.CmpPredStorage &&
436 "Cannot drop CmpPredicate");
437 break;
438 case OperationType::ReductionOp:
439 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
440 "Cannot change RecurKind");
441 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
442 "Cannot change IsOrdered");
443 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
444 "Cannot change IsInLoop");
445 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
446 break;
447 case OperationType::Other:
448 break;
449 }
450}
451
453 if (!hasFastMathFlags())
454 return {};
455 const FastMathFlagsTy &F = getFMFsRef();
456 FastMathFlags Res;
457 Res.setAllowReassoc(F.AllowReassoc);
458 Res.setNoNaNs(F.NoNaNs);
459 Res.setNoInfs(F.NoInfs);
460 Res.setNoSignedZeros(F.NoSignedZeros);
461 Res.setAllowReciprocal(F.AllowReciprocal);
462 Res.setAllowContract(F.AllowContract);
463 Res.setApproxFunc(F.ApproxFunc);
464 return Res;
465}
466
467#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
469
470void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
471 VPSlotTracker &SlotTracker) const {
472 printRecipe(O, Indent, SlotTracker);
473 if (auto DL = getDebugLoc()) {
474 O << ", !dbg ";
475 DL.print(O);
476 }
477
478 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
480}
481#endif
482
483VPExpandSCEVRecipe::VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR)
484 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
485 Expr(Expr), ExpandInIR(ExpandInIR) {}
486
492
495 assert(!Operands.empty() &&
496 "zero-operand VPInstruction opcodes must pass explicit ResultTy");
497 // Assert operand \p Idx (if present and typed) has type \p ExpectedTy.
498 [[maybe_unused]] auto AssertOperandType = [&Operands](unsigned Idx,
499 Type *ExpectedTy) {
500 if (!ExpectedTy || Operands.size() <= Idx)
501 return;
502 [[maybe_unused]] Type *OpTy = Operands[Idx]->getScalarType();
503 assert((!OpTy || OpTy == ExpectedTy) &&
504 "different types inferred for different operands");
505 };
506
507 Type *Op0Ty = Operands[0]->getScalarType();
508 LLVMContext &Ctx = Op0Ty->getContext();
509 switch (Opcode) {
511 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
512 return Type::getVoidTy(Ctx);
514 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
515 AssertOperandType(1, IntegerType::get(Ctx, 1));
516 return Type::getVoidTy(Ctx);
518 assert(Op0Ty->isIntegerTy() && "expected integer operand");
519 AssertOperandType(1, Op0Ty);
520 return Type::getVoidTy(Ctx);
522 assert(Op0Ty->isIntegerTy() && "expected integer operand");
523 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
524 AssertOperandType(Idx, Op0Ty);
525 return Op0Ty;
526 case Instruction::Switch:
527 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
528 AssertOperandType(Idx, Op0Ty);
529 return Type::getVoidTy(Ctx);
531 case Instruction::Store:
532 return Type::getVoidTy(Ctx);
533 case Instruction::ICmp:
534 assert(Op0Ty->isIntOrPtrTy() && "expected integer or pointer operand");
535 AssertOperandType(1, Op0Ty);
536 return IntegerType::get(Ctx, 1);
537 case Instruction::FCmp:
538 assert(Op0Ty->isFloatingPointTy() && "expected floating-point operand");
539 AssertOperandType(1, Op0Ty);
540 return IntegerType::get(Ctx, 1);
543 assert(Op0Ty->isIntegerTy() && "expected integer operand");
544 AssertOperandType(1, Op0Ty);
545 return IntegerType::get(Ctx, 1);
547 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
548 return IntegerType::get(Ctx, 1);
551 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
552 AssertOperandType(1, Op0Ty);
553 return IntegerType::get(Ctx, 1);
555 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
556 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
557 AssertOperandType(Idx, Op0Ty);
558 return IntegerType::get(Ctx, 1);
560 assert(Op0Ty->isIntegerTy() && "expected integer operand");
561 return IntegerType::get(Ctx, 32);
562 case Instruction::Select: {
563 assert((!Op0Ty || Op0Ty->isIntegerTy(1)) &&
564 "select condition must be bool");
565 Type *Op1Ty = Operands[1]->getScalarType();
566 AssertOperandType(2, Op1Ty);
567 return Op1Ty;
568 }
569 case Instruction::InsertElement:
570 // The inserted scalar (operand 1) must match the vector element type;
571 // operand 2 must be an integer.
572 AssertOperandType(1, Op0Ty);
573 assert(Operands[2]->getScalarType()->isIntegerTy() &&
574 "expected integer operand");
575 return Op0Ty;
577 // The start value and the identity value (operands 0 and 1) fill the same
578 // vector and must match in type; operand 2 is the scaling factor.
579 AssertOperandType(1, Op0Ty);
580 return Op0Ty;
582 assert(Operands.size() >= 2 && "ExtractLane requires a lane operand and "
583 "at least one source vector operand");
584 // Operand 0 is the lane index, used for integer arithmetic.
585 assert(Op0Ty->isIntegerTy() && "expected integer operand");
586 Type *Op1Ty = Operands[1]->getScalarType();
587 for (unsigned Idx = 2; Idx != Operands.size(); ++Idx)
588 AssertOperandType(Idx, Op1Ty);
589 return Op1Ty;
590 }
593 assert(Operands[0]->getScalarType()->isPointerTy() &&
594 "expected pointer operand");
595 assert(Operands[1]->getScalarType()->isIntegerTy() &&
596 "expected integer operand");
597 return Op0Ty;
598 case Instruction::ExtractValue:
606 case Instruction::Load:
607 case Instruction::Alloca:
608 llvm_unreachable("type must be passed explicitly");
609 case Instruction::Call:
613 "BuildVector operands must be valid vector elements");
614 break;
615 default:
616 if (Instruction::isCast(Opcode))
617 llvm_unreachable("type must be passed explicitly");
618 break;
619 }
620
621 // Opcodes that require all operands to share the same scalar type as the
622 // result.
623 bool AllOperandsSameType =
624 Instruction::isBinaryOp(Opcode) ||
628 Opcode);
629 if (AllOperandsSameType)
630 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
631 AssertOperandType(Idx, Op0Ty);
632
633 return Op0Ty;
634}
635
638 unsigned Opcode = I->getOpcode();
639 if (Instruction::isCast(Opcode) ||
640 is_contained(ArrayRef<unsigned>({Instruction::Load, Instruction::Alloca}),
641 Opcode))
642 return I->getType();
644}
645
646/// Returns true if VPInstructions with \p Opcode always generate a single
647/// scalar.
648static bool alwaysGeneratesSingleScalar(unsigned Opcode) {
649 switch (Opcode) {
650 case Instruction::Load:
651 case Instruction::PHI:
655 return true;
656 default:
657 return false;
658 }
659}
660
662 const VPIRFlags &Flags, const VPIRMetadata &MD,
663 DebugLoc DL, const Twine &Name, Type *ResultTy,
664 const VPIRAttributes &Attrs,
665 std::optional<bool> GeneratesSingleScalar)
667 VPRecipeBase::VPInstructionSC, Operands,
668 ResultTy ? ResultTy
670 Flags, DL),
671 VPIRMetadata(MD), VPIRAttributes(Attrs), Opcode(Opcode), Name(Name.str()),
672 GeneratesSingleScalar(
673 GeneratesSingleScalar.value_or(alwaysGeneratesSingleScalar(Opcode))) {
674 assert(
675 (!alwaysGeneratesSingleScalar(Opcode) || this->GeneratesSingleScalar) &&
676 "GeneratesSingleScalar must be set for opcodes that always generate "
677 "a single scalar");
679 "Set flags not supported for the provided opcode");
681 "Opcode requires specific flags to be set");
685 "number of operands does not match opcode");
686}
687
689 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
690 return 1;
691
692 if (Instruction::isBinaryOp(Opcode))
693 return 2;
694
695 switch (Opcode) {
698 return 0;
699 case Instruction::Alloca:
700 case Instruction::Freeze:
701 case Instruction::Load:
714 return 1;
715 case Instruction::ICmp:
716 case Instruction::FCmp:
717 case Instruction::ExtractElement:
718 case Instruction::Store:
730 return 2;
731 case Instruction::InsertElement:
732 case Instruction::Select:
736 return 3;
738 return 4;
739 case Instruction::Call:
740 return getCalledFnOperandIndex(operands()) + 1;
741 case Instruction::GetElementPtr:
742 case Instruction::PHI:
743 case Instruction::Switch:
744 case Instruction::AtomicRMW:
745 case Instruction::AtomicCmpXchg:
746 case Instruction::ExtractValue:
747 case Instruction::Fence:
758 // Cannot determine the number of operands from the opcode.
759 return -1u;
760 }
761 llvm_unreachable("all cases should be handled above");
762}
763
765 return Opcode == VPInstruction::Unpack ||
767}
768
769bool VPInstruction::inferGeneratesSingleScalar() const {
771 return true;
772 switch (Opcode) {
773 case Instruction::Freeze:
774 case Instruction::ICmp:
775 case Instruction::Select:
782 return vputils::onlyFirstLaneUsed(this);
783 default:
784 return (Instruction::isBinaryOp(Opcode) || Instruction::isCast(Opcode)) &&
786 }
787}
788
790 if (Kind == RecurKind::Sub)
791 return Instruction::Add;
792 if (Kind == RecurKind::FSub)
793 return Instruction::FAdd;
794 llvm_unreachable("RecurKind should be Sub/FSub.");
795}
796
797Value *VPInstruction::generate(VPTransformState &State,
798 bool GenerateSingleScalar) {
799 IRBuilderBase &Builder = State.Builder;
800
802 Value *A = State.get(getOperand(0), GenerateSingleScalar);
803 Value *B = State.get(getOperand(1), GenerateSingleScalar);
804 auto *Res =
805 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
806 if (auto *I = dyn_cast<Instruction>(Res))
807 applyFlags(*I);
808 return Res;
809 }
811 Value *Op = State.get(getOperand(0), VPLane(0));
813 getScalarType());
814 if (auto *CastOp = dyn_cast<Instruction>(Res)) {
815 applyFlags(*CastOp);
816 applyMetadata(*CastOp);
817 }
818 return Res;
819 }
820
821 switch (getOpcode()) {
822 case VPInstruction::Not: {
823 Value *A = State.get(getOperand(0), GenerateSingleScalar);
824 return Builder.CreateNot(A, Name);
825 }
827 // TODO: Use GeneratesSingleScalar to produce a scalar value.
828 Value *A = State.get(getOperand(0));
829 Value *B = State.get(getOperand(1));
830 return Builder.CreateLogicalAnd(A, B, Name);
831 }
833 // TODO: Use GeneratesSingleScalar to produce a scalar value.
834 Value *A = State.get(getOperand(0));
835 Value *B = State.get(getOperand(1));
836 return Builder.CreateLogicalOr(A, B, Name);
837 }
838 case Instruction::ExtractElement: {
839 assert(GenerateSingleScalar &&
840 "Can only generate first lane for ExtractElement");
841 assert(State.VF.isVector() && "Only extract elements from vectors");
842 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
843 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
844 Value *Vec = State.get(getOperand(0));
845 Value *Idx = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
846 return Builder.CreateExtractElement(Vec, Idx, Name);
847 }
848 case Instruction::InsertElement: {
849 assert(!GenerateSingleScalar &&
850 "Cannot generate scalar value for InsertElement");
851 assert(State.VF.isVector() && "Can only insert elements into vectors");
852 Value *Vec = State.get(getOperand(0), /*NeedsSingleScalar=*/false);
853 Value *Elt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
854 Value *Idx = State.get(getOperand(2), /*NeedsSingleScalar=*/true);
855 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
856 }
857 case Instruction::Freeze: {
858 Value *Op = State.get(getOperand(0), GenerateSingleScalar);
859 return Builder.CreateFreeze(Op, Name);
860 }
861 case Instruction::FCmp:
862 case Instruction::ICmp: {
863 Value *A = State.get(getOperand(0), GenerateSingleScalar);
864 Value *B = State.get(getOperand(1), GenerateSingleScalar);
865 return Builder.CreateCmp(getPredicate(), A, B, Name);
866 }
867 case Instruction::PHI: {
868 llvm_unreachable("should be handled by VPPhi::execute");
869 }
870 case Instruction::Select: {
871 Value *Cond =
872 State.get(getOperand(0), GenerateSingleScalar ||
874 Value *Op1 = State.get(getOperand(1), GenerateSingleScalar);
875 Value *Op2 = State.get(getOperand(2), GenerateSingleScalar);
876 Value *Sel =
877 Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(), Name);
878 if (auto *I = dyn_cast<Instruction>(Sel))
880 return Sel;
881 }
884 // Can produce either a scalar value as a icmp of a phi, or a vector value,
885 // as a get.active.lane.mask intrinsic.
886 // Get first lane of vector induction variable.
887 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
888 // Get the original loop tripcount.
889 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
890
891 uint64_t Multiplier =
893 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
894 : 1;
895
896 // If this part of the active lane mask is scalar, generate the CMP directly
897 // to avoid unnecessary extracts.
898 if (State.VF.isScalar() && Multiplier == 1)
899 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
900 Name);
901
902 auto *PredTy = VectorType::get(Builder.getInt1Ty(), State.VF * Multiplier);
903 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
904 {PredTy, ScalarTC->getType()},
905 {VIVElem0, ScalarTC}, nullptr, Name);
906 }
908 assert(GenerateSingleScalar &&
909 "Can only generate first lane for NumActiveLanes");
910 Value *Op = State.get(getOperand(0));
911 auto *VecTy = cast<VectorType>(Op->getType());
912 assert(VecTy->getScalarSizeInBits() == 1 &&
913 "NumActiveLanes only implemented for i1 vectors");
914
915 Type *Ty = getScalarType();
916 Value *ZExt = Builder.CreateCast(
917 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
918 Value *NumActive =
919 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
920 return NumActive;
921 }
923 // Generate code to combine the previous and current values in vector v3.
924 //
925 // vector.ph:
926 // v_init = vector(..., ..., ..., a[-1])
927 // br vector.body
928 //
929 // vector.body
930 // i = phi [0, vector.ph], [i+4, vector.body]
931 // v1 = phi [v_init, vector.ph], [v2, vector.body]
932 // v2 = a[i, i+1, i+2, i+3];
933 // v3 = vector(v1(3), v2(0, 1, 2))
934
935 auto *V1 = State.get(getOperand(0));
936 if (!V1->getType()->isVectorTy())
937 return V1;
938 Value *V2 = State.get(getOperand(1));
939 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
940 }
942 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
943 // be outside of the main loop.
944 assert(GenerateSingleScalar &&
945 "Can only generate first lane for ExplicitVectorLength");
946 Value *AVL = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
947 // Compute EVL
948 assert(AVL->getType()->isIntegerTy() &&
949 "Requested vector length should be an integer.");
950
951 assert(State.VF.isScalable() && "Expected scalable vector factor.");
952 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
953
954 Value *EVL = Builder.CreateIntrinsic(
955 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
956 {AVL, VFArg, Builder.getTrue()});
957 return EVL;
958 }
960 assert(GenerateSingleScalar &&
961 "Can only generate first lane for BranchOnCond");
962 Value *Cond = State.get(getOperand(0), VPLane(0));
963 // Replace the temporary unreachable terminator with a new conditional
964 // branch, hooking it up to backward destination for latch blocks now, and
965 // to forward destination(s) later when they are created.
966 // Second successor may be backwards - iff it is already in VPBB2IRBB.
967 VPBasicBlock *SecondVPSucc =
968 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
969 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
970 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
971 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
972 // First successor is always forward, reset it to nullptr.
973 Br->setSuccessor(0, nullptr);
975 applyMetadata(*Br);
976 return Br;
977 }
979 assert(!GenerateSingleScalar &&
980 "Cannot generate scalar value for Broadcast");
981 return Builder.CreateVectorSplat(
982 State.VF, State.get(getOperand(0), /*NeedsSingleScalar=*/true),
983 "broadcast");
984 }
986 assert(!GenerateSingleScalar &&
987 "Cannot generate scalar value for BuildVector");
988 Value *Res = PoisonValue::get(
990 for (const auto &[Idx, Op] : enumerate(operands()))
991 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
992 Builder.getInt64(Idx));
993 return Res;
994 }
996 Type *ScalarTy = getScalarType();
997 auto *WideTy = VectorType::get(ScalarTy, State.VF * getNumOperands());
998 Value *Res = PoisonValue::get(WideTy);
999 for (const auto &[Idx, Op] : enumerate(operands()))
1000 Res = Builder.CreateInsertVector(WideTy, Res, State.get(Op),
1001 Idx * State.VF.getKnownMinValue());
1002 return Res;
1003 }
1005 if (State.VF.isScalar())
1006 return State.get(getOperand(0), true);
1007 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
1009 // If this start vector is scaled then it should produce a vector with fewer
1010 // elements than the VF.
1011 ElementCount VF = State.VF.divideCoefficientBy(
1012 cast<VPConstantInt>(getOperand(2))->getZExtValue());
1013 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
1014 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
1015 Builder.getInt64(0));
1016 }
1018 assert(GenerateSingleScalar &&
1019 "Can only generate first lane for ComputeReductionResult");
1020 RecurKind RK = getRecurKind();
1021 bool IsOrdered = isReductionOrdered();
1022 bool IsInLoop = isReductionInLoop();
1024 "FindIV should use min/max reduction kinds");
1025
1026 // The recipe may have multiple operands to be reduced together.
1027 unsigned NumOperandsToReduce = getNumOperands();
1028 SmallVector<Value *, 2> RdxParts(NumOperandsToReduce);
1029 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
1030 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
1031
1032 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
1034
1035 // Reduce multiple operands into one.
1036 Value *ReducedPartRdx = RdxParts[0];
1037 if (IsOrdered) {
1038 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
1039 } else {
1040 // Floating-point operations should have some FMF to enable the reduction.
1041 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
1042 Value *RdxPart = RdxParts[Part];
1044 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
1045 else {
1046 // For sub-recurrences, each part's reduction variable is already
1047 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
1048 Instruction::BinaryOps Opcode =
1050 ? getSubRecurOpcode(RK)
1051 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
1052 ReducedPartRdx =
1053 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
1054 }
1055 }
1056 }
1057
1058 // Create the reduction after the loop. Note that inloop reductions create
1059 // the target reduction in the loop using a Reduction recipe.
1060 if (State.VF.isVector() && !IsInLoop) {
1061 // TODO: Support in-order reductions based on the recurrence descriptor.
1062 // All ops in the reduction inherit fast-math-flags from the recurrence
1063 // descriptor.
1064 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
1065 }
1066
1067 return ReducedPartRdx;
1068 }
1071 assert(GenerateSingleScalar &&
1072 "Can only generate first lane for ExtractLane and "
1073 "ExtractPenultimateElement");
1074 unsigned Offset =
1076 Value *Res;
1077 if (State.VF.isVector()) {
1078 assert(Offset <= State.VF.getKnownMinValue() &&
1079 "invalid offset to extract from");
1080 // Extract lane VF - Offset from the operand.
1081 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
1082 } else {
1083 // TODO: Remove ExtractLastLane for scalar VFs.
1084 assert(Offset <= 1 && "invalid offset to extract from");
1085 Res = State.get(getOperand(0));
1086 }
1087 if (isa<ExtractElementInst>(Res))
1088 Res->setName(Name);
1089 return Res;
1090 }
1091 case VPInstruction::PtrAdd: {
1092 assert(GenerateSingleScalar && "Can only generate first lane for PtrAdd");
1093 Value *Ptr = State.get(getOperand(0), VPLane(0));
1094 Value *Addend = State.get(getOperand(1), VPLane(0));
1095 // TODO: Require that offset matches index type in VPlan.
1096 Addend = Builder.CreateSExtOrTrunc(
1097 Addend, Builder.getDataLayout().getIndexType(Ptr->getType()));
1098 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1099 }
1101 assert(!GenerateSingleScalar &&
1102 "Cannot generate scalar value for WidePtrAdd");
1103 Value *Ptr =
1105 Value *Addend = State.get(getOperand(1));
1106 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1107 }
1108 case VPInstruction::AnyOf: {
1109 assert(GenerateSingleScalar && "Can only generate first lane for AnyOf");
1110 Value *Res = State.get(getOperand(0));
1111 for (VPValue *Op : drop_begin(operands()))
1112 Res = Builder.CreateOr(Res, State.get(Op));
1113 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1114 }
1116 assert(GenerateSingleScalar &&
1117 "Can only generate first lane for ExtractLane");
1118 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1119 "simplified to ExtractElement.");
1120 Value *LaneToExtract = State.get(getOperand(0), true);
1121 Type *IdxTy = getOperand(0)->getScalarType();
1122 Value *Res = nullptr;
1123 Value *RuntimeVF = Builder.CreateElementCount(IdxTy, State.VF);
1124
1125 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1126 Value *VectorStart =
1127 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1128 Value *VectorIdx = Idx == 1
1129 ? LaneToExtract
1130 : Builder.CreateSub(LaneToExtract, VectorStart);
1131 Value *Ext = State.VF.isScalar()
1132 ? State.get(getOperand(Idx))
1133 : Builder.CreateExtractElement(
1134 State.get(getOperand(Idx)), VectorIdx);
1135 if (Res) {
1136 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1137 Res = Builder.CreateSelect(Cmp, Ext, Res);
1138 } else {
1139 Res = Ext;
1140 }
1141 }
1142 return Res;
1143 }
1145 assert(GenerateSingleScalar &&
1146 "Can only generate first lane for FirstActiveLane");
1147 Type *Ty = this->getScalarType();
1148 if (getNumOperands() == 1) {
1149 Value *Mask = State.get(getOperand(0));
1150 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1151 /*ZeroIsPoison=*/false, Name);
1152 }
1153 // If there are multiple operands, create a chain of selects to pick the
1154 // first operand with an active lane and add the number of lanes of the
1155 // preceding operands.
1156 Value *RuntimeVF = Builder.CreateElementCount(Ty, State.VF);
1157 unsigned LastOpIdx = getNumOperands() - 1;
1158 Value *Res = nullptr;
1159 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1160 Value *TrailingZeros =
1161 State.VF.isScalar()
1162 ? Builder.CreateZExt(
1163 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1164 Builder.getFalse()),
1165 Ty)
1167 Ty, State.get(getOperand(Idx)),
1168 /*ZeroIsPoison=*/false, Name);
1169 Value *Current = Builder.CreateAdd(
1170 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1171 TrailingZeros);
1172 if (Res) {
1173 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1174 Res = Builder.CreateSelect(Cmp, Current, Res);
1175 } else {
1176 Res = Current;
1177 }
1178 }
1179
1180 return Res;
1181 }
1183 assert(GenerateSingleScalar &&
1184 "Can only generate first lane for ResumeForEpilogue");
1185 return State.get(getOperand(0), true);
1187 assert(!GenerateSingleScalar && "Cannot generate scalar value for Reverse");
1188 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1190 assert(GenerateSingleScalar &&
1191 "Can only generate first lane for ExtractLastActive");
1192 Value *Result = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
1193 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1194 Value *Data = State.get(getOperand(Idx));
1195 Value *Mask = State.get(getOperand(Idx + 1));
1196 Type *VTy = Data->getType();
1197
1198 if (State.VF.isScalar())
1199 Result = Builder.CreateSelect(Mask, Data, Result);
1200 else
1201 Result = Builder.CreateIntrinsic(
1202 Intrinsic::experimental_vector_extract_last_active, {VTy},
1203 {Data, Mask, Result});
1204 }
1205
1206 return Result;
1207 }
1209 assert(!GenerateSingleScalar &&
1210 "Cannot generate scalar value for ExtractVectorForPart");
1211 Value *Src = State.get(getOperand(0));
1212 Type *DstTy = VectorType::get(getScalarType(), State.VF);
1213 uint64_t Part = cast<VPConstantInt>(getOperand(1))->getZExtValue();
1214
1215 if (Src->getType() == DstTy)
1216 return Src;
1217
1218 return Builder.CreateExtractVector(
1219 DstTy, Src, Builder.getInt64(State.VF.getKnownMinValue() * Part), Name);
1220 }
1222 assert(!GenerateSingleScalar &&
1223 "Cannot generate scalar value for StepVector");
1224 return State.Builder.CreateStepVector(
1225 VectorType::get(getScalarType(), State.VF));
1227 assert(GenerateSingleScalar &&
1228 "Can only generate first lane for Intrinsic");
1229 SmallVector<Value *, 2> Args;
1230 for (VPValue *Op : drop_end(operands()))
1231 Args.push_back(State.get(Op, /*NeedsSingleScalar=*/true));
1232 return State.Builder.CreateIntrinsic(getScalarType(),
1233 vputils::getIntrinsicID(this), Args,
1234 /*FMFSource=*/nullptr, getName());
1235 }
1237 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1238 auto *WideDataTy = VectorType::get(getScalarType(), State.VF * Multiplier);
1239
1240 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1241 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1242 Instruction *WideLI;
1243 if (isMasked()) {
1244 Value *Mask = State.get(getMask());
1245 WideLI = Builder.CreateMaskedLoad(WideDataTy, Addr, Alignment, Mask);
1246 } else {
1247 WideLI = Builder.CreateAlignedLoad(WideDataTy, Addr, Alignment);
1248 }
1249 applyMetadata(*WideLI);
1250 return WideLI;
1251 }
1253 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1254 Value *WideData = State.get(getOperand(3));
1255 assert(cast<VectorType>(WideData->getType())->getElementCount() ==
1256 State.VF * Multiplier &&
1257 "stored value does not match wide element count");
1258 (void)Multiplier;
1259
1260 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1261 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1262 Instruction *WideSI;
1263 if (isMasked()) {
1264 Value *Mask = State.get(getMask());
1265 WideSI = Builder.CreateMaskedStore(WideData, Addr, Alignment, Mask);
1266 } else {
1267 WideSI = Builder.CreateAlignedStore(WideData, Addr, Alignment);
1268 }
1269 applyMetadata(*WideSI);
1270 return WideSI;
1271 }
1273 llvm_unreachable("Should have been lowered in VPlanPredicator");
1274 default:
1275 llvm_unreachable("Unsupported opcode for instruction");
1276 }
1277}
1278
1280 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1281 Type *ScalarTy = this->getScalarType();
1282 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1283 switch (Opcode) {
1284 case Instruction::FNeg:
1285 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1286 case Instruction::UDiv:
1287 case Instruction::SDiv:
1288 case Instruction::SRem:
1289 case Instruction::URem:
1290 case Instruction::Add:
1291 case Instruction::FAdd:
1292 case Instruction::Sub:
1293 case Instruction::FSub:
1294 case Instruction::Mul:
1295 case Instruction::FMul:
1296 case Instruction::FDiv:
1297 case Instruction::FRem:
1298 case Instruction::Shl:
1299 case Instruction::LShr:
1300 case Instruction::AShr:
1301 case Instruction::And:
1302 case Instruction::Or:
1303 case Instruction::Xor: {
1304 // Certain instructions can be cheaper if they have a constant second
1305 // operand. One example of this are shifts on x86.
1306 VPValue *RHS = getOperand(1);
1307 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1308
1309 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1312
1315 if (CtxI)
1316 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1317 return Ctx.TTI.getArithmeticInstrCost(
1318 Opcode, ResultTy, Ctx.CostKind,
1319 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1320 RHSInfo, Operands, CtxI, &Ctx.TLI);
1321 }
1322 case Instruction::Freeze:
1323 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1324 // requires the actual vector instruction. Instead, both here and in the
1325 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1326 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1327 // them in sync.
1328 return TTI::TCC_Free;
1329 case Instruction::ExtractValue:
1330 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1331 Ctx.CostKind);
1332 case Instruction::ICmp:
1333 case Instruction::FCmp: {
1334 Type *ScalarOpTy = getOperand(0)->getScalarType();
1335 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1337 return Ctx.TTI.getCmpSelInstrCost(
1339 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1340 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1341 }
1342 case Instruction::BitCast: {
1343 Type *ScalarTy = this->getScalarType();
1344 if (ScalarTy->isPointerTy())
1345 return 0;
1346 [[fallthrough]];
1347 }
1348 case Instruction::SExt:
1349 case Instruction::ZExt:
1350 case Instruction::FPToUI:
1351 case Instruction::FPToSI:
1352 case Instruction::FPExt:
1353 case Instruction::PtrToInt:
1354 case Instruction::PtrToAddr:
1355 case Instruction::IntToPtr:
1356 case Instruction::SIToFP:
1357 case Instruction::UIToFP:
1358 case Instruction::Trunc:
1359 case Instruction::FPTrunc:
1360 case Instruction::AddrSpaceCast: {
1361 // Computes the CastContextHint from a recipe that may access memory.
1362 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1363 if (isa<VPInterleaveBase>(R))
1365 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1366 // Only compute CCH for memory operations, matching the legacy model
1367 // which only considers loads/stores for cast context hints.
1368 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1369 if (!isa<LoadInst, StoreInst>(UI))
1371 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1373 }
1374 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1375 if (WidenMemoryRecipe == nullptr)
1377 if (VF.isScalar())
1379 if (!WidenMemoryRecipe->isConsecutive())
1381 if (WidenMemoryRecipe->isMasked())
1384 };
1385
1386 VPValue *Operand = getOperand(0);
1388 bool IsReverse = false;
1389 // For Trunc/FPTrunc, get the context from the only user.
1390 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1391 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1392 if (match(Recipe,
1396 IsReverse = true;
1398 Recipe->getVPSingleValue()->getSingleUser());
1399 }
1400 if (Recipe)
1401 CCH = ComputeCCH(Recipe);
1402 }
1403 }
1404 // For Z/Sext, get the context from the operand.
1405 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1406 Opcode == Instruction::FPExt) {
1407 if (auto *Recipe = Operand->getDefiningRecipe()) {
1408 VPValue *ReverseOp;
1409 if (match(Recipe,
1410 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1412 m_VPValue(ReverseOp))))) {
1413 Recipe = ReverseOp->getDefiningRecipe();
1414 IsReverse = true;
1415 }
1416 if (Recipe)
1417 CCH = ComputeCCH(Recipe);
1418 }
1419 }
1420 if (IsReverse && CCH != TTI::CastContextHint::None)
1422
1423 auto *ScalarSrcTy = Operand->getScalarType();
1424 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1425 // Arm TTI will use the underlying instruction to determine the cost.
1426 return Ctx.TTI.getCastInstrCost(
1427 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1429 }
1430 case Instruction::Select: {
1432 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1433 Type *ScalarTy = this->getScalarType();
1434
1435 VPValue *Op0, *Op1;
1436 bool IsLogicalAnd =
1437 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1438 bool IsLogicalOr =
1439 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1440 // Also match the inverted forms:
1441 // select x, false, y --> !x & y (still AND)
1442 // select x, y, true --> !x | y (still OR)
1443 IsLogicalAnd |=
1444 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1445 IsLogicalOr |=
1446 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1447
1448 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1449 (IsLogicalAnd || IsLogicalOr)) {
1450 // select x, y, false --> x & y
1451 // select x, true, y --> x | y
1452 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1453 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1454
1456 if (SI && all_of(operands(),
1457 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1458 append_range(Operands, SI->operands());
1459 return Ctx.TTI.getArithmeticInstrCost(
1460 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1461 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1462 }
1463
1464 Type *CondTy = getOperand(0)->getScalarType();
1465 if (!IsScalarCond && VF.isVector())
1466 CondTy = VectorType::get(CondTy, VF);
1467
1468 llvm::CmpPredicate Pred;
1469 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1470 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1471 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1472 Pred = Cmp->getPredicate();
1473 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1474 return Ctx.TTI.getCmpSelInstrCost(
1475 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1476 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1477 }
1478 }
1479 llvm_unreachable("called for unsupported opcode");
1480}
1481
1483 VPCostContext &Ctx) const {
1484 // NOTE: At the moment it seems only possible to expose this path for
1485 // the trunc, zext and sext opcodes.
1486 // TODO: Update VF arg to use onlyFirstLaneUsed once WidenCast is unified.
1488 // A scalar zext/trunc that only adjusts the width of an
1489 // ExplicitVectorLength to the canonical IV type is free: it feeds only
1490 // the IV increment and AVL decrement, which are modeled as free below.
1491 if (match(this, m_ZExtOrTrunc(m_EVL(m_VPValue()))))
1492 return 0;
1494 Ctx);
1495 }
1496
1498 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1499 // TODO: Compute cost for VPInstructions without underlying values once
1500 // the legacy cost model has been retired.
1501 return 0;
1502 }
1503
1505 "Should only generate a vector value or single scalar, not scalars "
1506 "for all lanes.");
1508 getOpcode(),
1510 }
1511
1512 switch (getOpcode()) {
1513 case Instruction::Select: {
1515 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1516 auto *CondTy = getOperand(0)->getScalarType();
1517 auto *VecTy = getOperand(1)->getScalarType();
1518 if (!vputils::onlyFirstLaneUsed(this)) {
1519 CondTy = toVectorTy(CondTy, VF);
1520 VecTy = toVectorTy(VecTy, VF);
1521 }
1522 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1523 Ctx.CostKind);
1524 }
1525 case Instruction::ExtractElement:
1527 if (VF.isScalar()) {
1528 // ExtractLane with VF=1 takes care of handling extracting across multiple
1529 // parts.
1530 return 0;
1531 }
1532
1533 // Add on the cost of extracting the element.
1534 auto *VecTy = toVectorTy(getScalarType(), VF);
1535 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1536 Ctx.CostKind);
1537 }
1538 case VPInstruction::AnyOf: {
1539 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1540 return Ctx.TTI.getArithmeticReductionCost(
1541 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1542 }
1544 Type *Ty = this->getScalarType();
1545 Type *ScalarTy = getOperand(0)->getScalarType();
1546 if (VF.isScalar())
1547 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1549 CmpInst::ICMP_EQ, Ctx.CostKind);
1550 // Calculate the cost of determining the lane index.
1551 auto *PredTy = toVectorTy(ScalarTy, VF);
1552 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1553 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1554 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1555 }
1557 Type *Ty = this->getScalarType();
1558 Type *ScalarTy = getOperand(0)->getScalarType();
1559 if (VF.isScalar())
1560 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1562 CmpInst::ICMP_EQ, Ctx.CostKind);
1563 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1564 auto *PredTy = toVectorTy(ScalarTy, VF);
1565 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1566 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1567 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1568 // Add cost of NOT operation on the predicate.
1569 Cost += Ctx.TTI.getArithmeticInstrCost(
1570 Instruction::Xor, PredTy, Ctx.CostKind,
1571 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1572 {TargetTransformInfo::OK_UniformConstantValue,
1573 TargetTransformInfo::OP_None});
1574 // Add cost of SUB operation on the index.
1575 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1576 return Cost;
1577 }
1579 Type *ScalarTy = this->getScalarType();
1580 Type *VecTy = toVectorTy(ScalarTy, VF);
1581 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1583 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1584 {VecTy, MaskTy, ScalarTy});
1585 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1586 }
1588 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1589 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1590 return Ctx.TTI.getShuffleCost(
1592 cast<VectorType>(VectorTy), Ctx.CostKind, {}, -1);
1593 }
1596 Type *ArgTy = getOperand(0)->getScalarType();
1597 uint64_t Multiplier =
1599 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
1600 : 1;
1601 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1602 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1603 {ArgTy, ArgTy});
1604 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1605 }
1607 Type *Arg0Ty = getOperand(0)->getScalarType();
1608 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1609 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1610 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1611 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1612 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1613 }
1615 assert(VF.isVector() && "Reverse operation must be vector type");
1616 Type *EltTy = this->getScalarType();
1617 // Skip the reverse operation cost for the mask.
1618 // FIXME: Remove this once redundant mask reverse operations can be
1619 // eliminated by VPlanTransforms::cse before cost computation.
1620 if (EltTy->isIntegerTy(1))
1621 return 0;
1622 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1623 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1624 VectorTy, Ctx.CostKind, /*Mask=*/{},
1625 /*Index=*/0);
1626 }
1628 // Add on the cost of extracting the element.
1629 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1630 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1631 VecTy, Ctx.CostKind, 0);
1632 }
1633 case VPInstruction::Not: {
1634 Type *ValTy = this->getScalarType();
1635 // InstCombine will fold `xor` to the conditional branch.
1636 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1637 if (match(U, m_BranchOnCond(m_VPValue())))
1638 return 0;
1639 if (!vputils::onlyFirstLaneUsed(this))
1640 ValTy = toVectorTy(ValTy, VF);
1641 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1642 Ctx.CostKind);
1643 }
1645 Type *ElementTy = getOperand(0)->getScalarType();
1646 auto *MaskTy = cast<VectorType>(toVectorTy(ElementTy, VF));
1647 return Ctx.TTI.getExtendedReductionCost(
1648 Instruction::Add, /*IsUnsigned=*/true, getScalarType(), MaskTy,
1649 /*FMF=*/{}, Ctx.CostKind);
1650 }
1652 // If TC <= VF then this is just a branch.
1653 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1654 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1655 // some cases we get a cost that's too high due to counting a cmp that
1656 // later gets removed.
1657 // FIXME: The compare could also be removed if TC = M * vscale,
1658 // VF = N * vscale, and M <= N. Detecting that would require having the
1659 // trip count as a SCEV though.
1660 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
1661 return 0;
1662 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1663 Type *ValTy = getOperand(0)->getScalarType();
1664 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1666 CmpInst::ICMP_EQ, Ctx.CostKind);
1667 }
1669 Type *Ty = getScalarType();
1671 for (const VPValue *Op : drop_end(operands()))
1672 ArgTys.push_back(Op->getScalarType());
1673 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1674 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1675 }
1677 // TODO: This isn't quite right since even if the step-vector is hoisted
1678 // out of the loop it has a non-zero cost in the middle block, etc.
1679 // Once the stepvector is correctly hoisted out of the vector loop by the
1680 // licm transform we can add the cost here so that it doesn't incorrectly
1681 // affect the choice of VF.
1682 return 0;
1684 // It isn't currently possible to expose cases where WideIVStep's cost is
1685 // queried.
1686 llvm_unreachable("Unhandled opcode");
1687 case Instruction::FCmp:
1688 case Instruction::ICmp:
1690 getOpcode(),
1693 if (VF == ElementCount::getScalable(1))
1695 [[fallthrough]];
1696 default:
1697 // TODO: Compute cost other VPInstructions once the legacy cost model has
1698 // been retired.
1700 "unexpected VPInstruction witht underlying value");
1701 return 0;
1702 }
1703}
1704
1717
1719#ifndef NDEBUG
1720 Type *Ty = Op->getScalarType();
1721 switch (getOpcode()) {
1725 assert(Ty == getOperand(0)->getScalarType() &&
1726 "types of operand 0 and new operand must match");
1727 break;
1731 assert(Ty == getOperand(0)->getScalarType() &&
1732 "appended operand must match operand 0's scalar type");
1733 break;
1735 assert(Ty == getOperand(1)->getScalarType() &&
1736 "appended operand must match operand 1's scalar type");
1737 break;
1739 // The recipe is constructed with 3 operands (result, data, mask). Extra
1740 // operands beyond that are appended in (data, mask) pairs.
1741 constexpr unsigned NumInitialOperands = 3;
1742 assert(getNumOperands() >= NumInitialOperands &&
1743 "ExtractLastActive must have at least the initial 3 operands");
1744 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1745 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1746 : Ty == getOperand(1)->getScalarType()) &&
1747 "ExtractLastActive expects alternating data/mask operands "
1748 "matching operand 1's type and i1, respectively");
1749 break;
1750 }
1751 default:
1752 llvm_unreachable("opcode does not support growing the operand list "
1753 "outside of construction");
1754 }
1755#endif
1757}
1758
1760 assert(!isAbstract() && "cannot execute this VPInstruction");
1761 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1763 "Set flags not supported for the provided opcode");
1765 "Opcode requires specific flags to be set");
1766 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1767 bool GenerateSingleScalar =
1768 State.VF.isScalar() || inferGeneratesSingleScalar();
1769 Value *GeneratedValue = generate(State, GenerateSingleScalar);
1770 if (!hasResult())
1771 return;
1772 assert(GeneratedValue && "generate must produce a value");
1773 assert(GeneratedValue->getType()->isVectorTy() == !GenerateSingleScalar &&
1774 "scalar value but not only first lane defined");
1775 State.set(this, GeneratedValue, GenerateSingleScalar);
1777 getOpcode() == Instruction::Freeze) {
1778 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1779 // resume phis, and to let epilogue vectorization recover the frozen
1780 // reduction start from the main plan. Must be removed once epilogue
1781 // vectorization explicitly connects VPlans.
1782 setUnderlyingValue(GeneratedValue);
1783 }
1784}
1785
1789 return false;
1790 switch (getOpcode()) {
1791 case Instruction::ExtractValue:
1792 case Instruction::GetElementPtr:
1793 case Instruction::ExtractElement:
1794 case Instruction::InsertElement:
1795 case Instruction::Freeze:
1796 case Instruction::FCmp:
1797 case Instruction::ICmp:
1798 case Instruction::Select:
1799 case Instruction::PHI:
1826 case VPInstruction::Not:
1835 return false;
1837 case Instruction::Call:
1839 default:
1840 return true;
1841 }
1842}
1843
1845 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1847 return vputils::onlyFirstLaneUsed(this);
1848
1849 switch (getOpcode()) {
1850 default:
1851 return false;
1852 case Instruction::ExtractElement:
1853 return Op == getOperand(1);
1854 case Instruction::InsertElement:
1855 return Op == getOperand(1) || Op == getOperand(2);
1857 return Op == getOperand(0);
1858 case Instruction::PHI:
1859 case Instruction::Load:
1872 return true;
1875 return Op == getOperand(0) || Op == getOperand(1) || Op == getOperand(2);
1879 return Op == getOperand(0);
1880 }
1881}
1882
1884 switch (getOpcode()) {
1885 default:
1886 return false;
1891 return true;
1892 };
1893}
1894
1895#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1897 VPSlotTracker SlotTracker(getParent()->getPlan());
1899}
1900
1902 VPSlotTracker &SlotTracker) const {
1903 O << Indent << "EMIT" << (doesGenerateSingleScalar() ? "-SCALAR" : "") << " ";
1904
1905 if (hasResult()) {
1907 O << " = ";
1908 }
1909
1910 switch (getOpcode()) {
1911 case VPInstruction::Not:
1912 O << "not";
1913 break;
1915 O << "active lane mask";
1916 break;
1918 O << "wide active lane mask";
1919 break;
1921 O << "wide vector load";
1922 break;
1924 O << "wide vector store";
1925 break;
1927 O << "concat-vectors";
1928 break;
1930 O << "incoming-alias-mask";
1931 break;
1933 O << "EXPLICIT-VECTOR-LENGTH";
1934 break;
1936 O << "first-order splice";
1937 break;
1939 O << "branch-on-cond";
1940 break;
1942 O << "branch-on-two-conds";
1943 break;
1945 O << "VF * Part +";
1946 break;
1948 O << "branch-on-count";
1949 break;
1951 O << "broadcast";
1952 break;
1954 O << "buildvector";
1955 break;
1957 O << "exiting-iv-value";
1958 break;
1960 O << "masked-cond";
1961 break;
1963 O << "extract-lane";
1964 break;
1966 O << "extract-last-lane";
1967 break;
1969 O << "extract-last-part";
1970 break;
1972 O << "extract-penultimate-element";
1973 break;
1975 O << "extract-vector-for-part";
1976 break;
1978 O << "compute-reduction-result";
1979 break;
1981 O << "logical-and";
1982 break;
1984 O << "logical-or";
1985 break;
1987 O << "ptradd";
1988 break;
1990 O << "wide-ptradd";
1991 break;
1993 O << "any-of";
1994 break;
1996 O << "first-active-lane";
1997 break;
1999 O << "last-active-lane";
2000 break;
2002 O << "reduction-start-vector";
2003 break;
2005 O << "resume-for-epilogue";
2006 break;
2008 O << "reverse";
2009 break;
2011 O << "unpack";
2012 break;
2014 O << "extract-last-active";
2015 break;
2017 O << "num-active-lanes";
2018 break;
2020 O << "wide-iv-step";
2021 break;
2023 O << "step-vector " << *getScalarType();
2024 break;
2026 case Instruction::Call: {
2027 O << "call";
2028 printFlags(O);
2029 printRetAttrs(O);
2030 O << *getScalarType() << " ";
2031 unsigned NumArgs;
2034 NumArgs = getNumOperands() - 1;
2035 } else {
2036 getCalledFunction(operands())->printAsOperand(O, /*PrintType=*/false);
2037 NumArgs = getCalledFnOperandIndex(operands());
2038 }
2039 O << "(";
2041 O, [&O, &SlotTracker, this](const auto &IndexedOp) {
2042 auto [Idx, Op] = IndexedOp;
2043 printParamAttrs(O, Idx);
2044 Op->printAsOperand(O, SlotTracker);
2045 });
2046 O << ")";
2047 printFnAttrs(O);
2048 if (VPValue *Mask = getMask()) {
2049 O << ", ";
2050 Mask->printAsOperand(O, SlotTracker);
2051 }
2052 return;
2053 }
2054 case Instruction::Load:
2055 O << "load";
2056 break;
2057 default:
2059 }
2060
2061 if (!operands_empty()) {
2062 printFlags(O);
2064 }
2066 O << " to " << *getScalarType();
2067}
2068#endif
2069
2070/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
2071/// adds incoming values, and stores the result in State. For header phis, only
2072/// the preheader incoming value is added; the backedge is fixed up later by
2073/// VPlan::execute().
2075 VPTransformState &State, bool IsScalar,
2076 const Twine &Name) {
2077 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
2078 ? 1
2079 : Phi.getNumIncoming();
2080 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
2081 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
2082 NewPhi->addIncoming(FirstInc,
2083 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
2084 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
2085 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
2086 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
2087 State.set(R, NewPhi, IsScalar);
2088}
2089
2091 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
2092}
2093
2094#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2095void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
2096 VPSlotTracker &SlotTracker) const {
2097 O << Indent << "EMIT" << (doesGenerateSingleScalar() ? "-SCALAR" : "") << " ";
2099 O << " = phi";
2100 printFlags(O);
2102}
2103#endif
2104
2105VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
2106 if (auto *Phi = dyn_cast<PHINode>(&I))
2107 return new VPIRPhi(*Phi);
2108 return new VPIRInstruction(I);
2109}
2110
2112 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
2113 "PHINodes must be handled by VPIRPhi");
2114 // Advance the insert point after the wrapped IR instruction. This allows
2115 // interleaving VPIRInstructions and other recipes.
2116 State.Builder.SetInsertPoint(std::next(I.getIterator()));
2117}
2118
2120 VPCostContext &Ctx) const {
2121 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2122 // hence it does not contribute to the cost-modeling for the VPlan.
2123 return 0;
2124}
2125
2126#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2128 VPSlotTracker &SlotTracker) const {
2129 O << Indent << "IR " << I;
2130}
2131#endif
2132
2134 PHINode *Phi = &getIRPhi();
2135 for (const auto &[Idx, Op] : enumerate(operands())) {
2136 VPValue *ExitValue = Op;
2137 auto Lane = vputils::isSingleScalar(ExitValue)
2139 : VPLane::getLastLaneForVF(State.VF);
2140 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2141 auto *PredVPBB = Pred->getExitingBasicBlock();
2142 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2143 // Set insertion point in PredBB in case an extract needs to be generated.
2144 // TODO: Model extracts explicitly.
2145 State.Builder.SetInsertPoint(PredBB->getTerminator());
2146 Value *V = State.get(ExitValue, VPLane(Lane));
2147 // If there is no existing block for PredBB in the phi, add a new incoming
2148 // value. Otherwise update the existing incoming value for PredBB.
2149 if (Phi->getBasicBlockIndex(PredBB) == -1)
2150 Phi->addIncoming(V, PredBB);
2151 else
2152 Phi->setIncomingValueForBlock(PredBB, V);
2153 }
2154
2155 // Advance the insert point after the wrapped IR instruction. This allows
2156 // interleaving VPIRInstructions and other recipes.
2157 State.Builder.SetInsertPoint(std::next(Phi->getIterator()));
2158}
2159
2161 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2162 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2163 "Number of phi operands must match number of predecessors");
2164 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2165 R->removeOperand(Position);
2166}
2167
2168VPValue *
2170 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2171 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2172}
2173
2175 VPValue *V) const {
2176 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2177 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2178}
2179
2180#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2182 VPSlotTracker &SlotTracker) const {
2184 O << "[ ";
2185 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2186 O << ", ";
2187 std::get<1>(Op)->printAsOperand(O);
2188 O << " ]";
2189 });
2190}
2191#endif
2192
2193#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2195 VPSlotTracker &SlotTracker) const {
2197
2198 if (getNumOperands() != 0) {
2199 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2201 [&O, &SlotTracker](auto Op) {
2202 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2203 O << " from ";
2204 std::get<1>(Op)->printAsOperand(O);
2205 });
2206 O << ")";
2207 }
2208}
2209#endif
2210
2212 if (Metadata.empty())
2213 return;
2214 // Frequencies and estimated branch weights are VPlan-internal and must not
2215 // reach IR.
2216 unsigned ExecFreqKind = getMDKindID(ExecutionFrequencyMDName);
2217 unsigned EstProfKind = getMDKindID(EstimatedProfileMDName);
2218 for (const auto &[Kind, Node] : Metadata)
2219 if (Kind != ExecFreqKind && Kind != EstProfKind)
2220 I.setMetadata(Kind, Node);
2221}
2222
2223/// Returns the execution frequency recorded in \p Node.
2225 assert(Node->getNumOperands() <= 2 && "unexpected frequency node shape");
2226 uint64_t Freq =
2227 mdconst::extract<ConstantInt>(Node->getOperand(0))->getZExtValue();
2229 "frequency cannot exceed the one of an always executing block");
2230 return {BlockFrequency(Freq), Node->getNumOperands() == 2};
2231}
2232
2234 std::optional<VPExecutionFrequency> Freq, LLVMContext &Ctx) {
2235 // A recipe that always executes needs no annotation.
2236 if (!Freq || vputils::getExecutionProbability(Freq->Freq).isOne())
2237 return;
2239 ConstantInt::get(Type::getInt64Ty(Ctx), Freq->Freq.getFrequency()))};
2240 if (Freq->IsEstimated)
2242 setMetadata(Ctx.getMDKindID(ExecutionFrequencyMDName), MDNode::get(Ctx, Ops));
2243}
2244
2245std::optional<VPExecutionFrequency>
2247 if (MDNode *Node = getInternalMetadata(ExecutionFrequencyMDName))
2249 return std::nullopt;
2250}
2251
2253 if (Metadata.empty())
2254 return;
2255 unsigned ID = getMDKindID(ExecutionFrequencyMDName);
2256 erase_if(Metadata, [ID](const auto &P) { return P.first == ID; });
2257}
2258
2260 erase_if(Metadata,
2261 [&](const auto &MD) { return !is_contained(Other.Metadata, MD); });
2262}
2263
2264#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2266 const Module *M = SlotTracker.getModule();
2267 if (Metadata.empty() || !M)
2268 return;
2269
2270 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2271 O << " (";
2272 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2273 auto [Kind, Node] = KindNodePair;
2274 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2275 "Unexpected unnamed metadata kind");
2276 O << "!" << MDNames[Kind] << " ";
2277 // Print the values of branch weights, which are more informative than the
2278 // ID of the metadata node holding them.
2279 SmallVector<uint32_t> Weights;
2280 bool IsEstimatedProfile = MDNames[Kind] == EstimatedProfileMDName;
2281 if ((Kind == LLVMContext::MD_prof || IsEstimatedProfile) &&
2282 extractBranchWeights(Node, Weights)) {
2283 if (IsEstimatedProfile)
2284 O << "estimated ";
2285 O << "{";
2286 interleaveComma(Weights, O);
2287 O << "}";
2288 } else if (MDNames[Kind] == ExecutionFrequencyMDName) {
2289 // Print the frequency together with the probability it corresponds to.
2290 auto [Freq, IsEstimated] = getExecutionFrequencyFromMD(Node);
2291 const fltSemantics &Sem = APFloat::IEEEdouble();
2292 uint64_t Full =
2294 APFloat Percent = APFloat(Sem, Freq.getFrequency()) * APFloat(Sem, 100) /
2295 APFloat(Sem, Full);
2296 SmallString<16> PercentStr;
2297 Percent.toString(PercentStr, /*FormatPrecision=*/4);
2298 O << Freq.getFrequency() << " (" << PercentStr << "%"
2299 << (IsEstimated ? ", estimated" : "") << ")";
2300 } else {
2301 SlotTracker.printMetadataAsOperand(O, Node);
2302 }
2303 });
2304 O << ")";
2305}
2306#endif
2307
2309 FunctionType *WideTy) {
2310 assert(Call.getOpcode() == Instruction::Call && "expected call");
2311 unsigned NumArgs = getCalledFnOperandIndex(Call.operands());
2312 assert(NumArgs <= WideTy->getNumParams() &&
2313 "widened call must take all scalar arguments");
2314 LLVMContext &Ctx = WideTy->getContext();
2315 AttributeList ScalarAttrs = Call.CallAttrs;
2316
2317 // Limit initial supported set of attributes to subset of poison-generating
2318 // ones that can be transferred to the widened return value and arguments.
2319 // TODO: Support additional attributes.
2320 static constexpr Attribute::AttrKind PropagatableAttrKinds[] = {
2321 Attribute::Alignment, Attribute::NonNull, Attribute::NoFPClass,
2322 Attribute::Range};
2323
2324 // Only keep allowed attributes (which do not trigger UB) and ones that are
2325 // compatible with the widened type Ty.
2326 auto Filter = [&](Type *Ty, AttributeSet AS) {
2327 AttributeMask Incompatible = AttributeFuncs::typeIncompatible(Ty, AS);
2328 AttrBuilder AB(Ctx);
2329 for (Attribute::AttrKind K : PropagatableAttrKinds)
2330 if (AS.hasAttribute(K) && !Incompatible.contains(K))
2331 AB.addAttribute(AS.getAttribute(K));
2332 return AttributeSet::get(Ctx, AB);
2333 };
2334
2335 AttributeSet RetAttrs =
2336 Filter(WideTy->getReturnType(), ScalarAttrs.getRetAttrs());
2337
2338 // For masked calls, the widened call also executes for lanes the scalar call
2339 // did not execute for. Masked variants ignore the inactive lanes of widened
2340 // arguments, but scalar (uniform or linear) arguments are shared by all
2341 // lanes, e.g. linear arguments pass the value of the first lane, which may
2342 // be inactive. Unmasked variants process all lanes.
2343 bool IsMaskedVariant = WideTy->getNumParams() > NumArgs;
2344 SmallVector<AttributeSet> ArgAttrs(WideTy->getNumParams());
2345 for (unsigned I = 0; I != NumArgs; ++I) {
2346 Type *WideArgTy = WideTy->getParamType(I);
2347 bool IsWidenedArg = WideArgTy != Call.getOperand(I)->getScalarType();
2348 if (Call.isMasked() && (!IsMaskedVariant || !IsWidenedArg))
2349 continue;
2350 ArgAttrs[I] = Filter(WideArgTy, ScalarAttrs.getParamAttrs(I));
2351 }
2352
2353 CallAttrs = AttributeList::get(Ctx, AttributeSet(), RetAttrs, ArgAttrs);
2354}
2355
2357 LLVMContext &Ctx) {
2358 CallAttrs =
2359 CallAttrs.intersectWith(Ctx, Other.CallAttrs).value_or(AttributeList());
2360}
2361
2362#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2364 AttributeSet RetAttrs = CallAttrs.getRetAttrs();
2365 if (RetAttrs.hasAttributes())
2366 O << RetAttrs.getAsString() << " ";
2367}
2368
2369void VPIRAttributes::printParamAttrs(raw_ostream &O, unsigned ArgIdx) const {
2370 AttributeSet PA = CallAttrs.getParamAttrs(ArgIdx);
2371 if (PA.hasAttributes())
2372 O << PA.getAsString() << " ";
2373}
2374
2376 AttributeSet FnAttrs = CallAttrs.getFnAttrs();
2377 if (FnAttrs.hasAttributes())
2378 O << " " << FnAttrs.getAsString();
2379}
2380#endif
2381
2383 assert(State.VF.isVector() && "not widening");
2384 assert(Variant != nullptr && "Can't create vector function.");
2385
2386 FunctionType *VFTy = Variant->getFunctionType();
2387 // Add return type if intrinsic is overloaded on it.
2389 for (const auto &I : enumerate(args())) {
2390 Value *Arg;
2391 // Some vectorized function variants may also take a scalar argument,
2392 // e.g. linear parameters for pointers. This needs to be the scalar value
2393 // from the start of the respective part when interleaving.
2394 if (!VFTy->getParamType(I.index())->isVectorTy())
2395 Arg = State.get(I.value(), VPLane(0));
2396 else
2397 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2398 Args.push_back(Arg);
2399 }
2400
2401 CallInst *V = State.Builder.CreateCall(Variant, Args);
2402 applyFlags(*V);
2403 applyMetadata(*V);
2404 applyAttrs(*V);
2405 V->setCallingConv(Variant->getCallingConv());
2406
2407 if (!V->getType()->isVoidTy())
2408 State.set(this, V);
2409}
2410
2412 VPCostContext &Ctx) const {
2413 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2414 "Variant return type must match VF");
2415 return computeCallCost(Variant, Ctx);
2416}
2417
2419 VPCostContext &Ctx) {
2420 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2421 Variant->getFunctionType()->params(),
2422 Ctx.CostKind);
2423}
2424
2426 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2427 assert(Variant && "Variant not set");
2428 FunctionType *VFTy = Variant->getFunctionType();
2429 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2430 auto [Idx, V] = Arg;
2431 Type *ArgTy = VFTy->getParamType(Idx);
2432 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2433 ArgTy->isPointerTy() || ArgTy->isByteTy();
2434 });
2435}
2436
2437#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2439 VPSlotTracker &SlotTracker) const {
2440 O << Indent << "WIDEN-CALL ";
2441
2442 Function *CalledFn = getCalledScalarFunction();
2443 if (CalledFn->getReturnType()->isVoidTy())
2444 O << "void ";
2445 else {
2447 O << " = ";
2448 }
2449
2450 O << "call";
2451 printFlags(O);
2452 printRetAttrs(O);
2453 O << "@" << CalledFn->getName() << "(";
2455 [&O, &SlotTracker, this](const auto &IndexedOp) {
2456 auto [Idx, Op] = IndexedOp;
2457 printParamAttrs(O, Idx);
2458 Op->printAsOperand(O, SlotTracker);
2459 });
2460 O << ")";
2461
2462 O << " (using library function";
2463 if (Variant->hasName())
2464 O << ": " << Variant->getName();
2465 O << ")";
2466}
2467#endif
2468
2470 assert(State.VF.isVector() && "not widening");
2471
2472 SmallVector<Type *, 2> TysForDecl;
2473 // Add return type if intrinsic is overloaded on it.
2474 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2475 State.TTI)) {
2476 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2477 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2478 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2480 Idx, State.TTI))
2481 TysForDecl.push_back(Ty);
2482 }
2483 }
2485 for (const auto &I : enumerate(operands())) {
2486 // Some intrinsics have a scalar argument - don't replace it with a
2487 // vector.
2488 Value *Arg;
2489 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2490 State.TTI))
2491 Arg = State.get(I.value(), VPLane(0));
2492 else
2493 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2494 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2495 State.TTI))
2496 TysForDecl.push_back(Arg->getType());
2497 Args.push_back(Arg);
2498 }
2499
2500 // Use vector version of the intrinsic.
2501 Module *M = State.Builder.getModule();
2502 Function *VectorF =
2503 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2504 assert(VectorF &&
2505 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2506
2507 CallInst *V = State.Builder.CreateCall(VectorF, Args);
2508
2509 applyFlags(*V);
2510 applyMetadata(*V);
2511
2512 return V;
2513}
2514
2516 CallInst *V = createVectorCall(State);
2517 if (!V->getType()->isVoidTy())
2518 State.set(this, V);
2519}
2520
2523 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2524 Type *ScalarRetTy = R.getScalarType();
2525 // Skip the reverse operation cost for the mask.
2526 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2527 // by VPlanTransforms::cse before cost computation.
2528 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2529 return InstructionCost(0);
2530
2531 // Some backends analyze intrinsic arguments to determine cost. Use the
2532 // underlying value for the operand if it has one. Otherwise try to use the
2533 // operand of the underlying call instruction, if there is one. Otherwise
2534 // clear Arguments.
2535 // TODO: Rework TTI interface to be independent of concrete IR values.
2537 for (const auto &[Idx, Op] : enumerate(Operands)) {
2538 auto *V = Op->getUnderlyingValue();
2539 if (!V) {
2540 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2541 Arguments.push_back(UI->getArgOperand(Idx));
2542 continue;
2543 }
2544 Arguments.clear();
2545 break;
2546 }
2547 Arguments.push_back(V);
2548 }
2549
2550 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2551 SmallVector<Type *> ParamTys =
2552 map_to_vector(Operands, [&](const VPValue *Op) {
2553 return toVectorTy(Op->getScalarType(), VF);
2554 });
2555
2557 for (const VPValue *Op : Operands) {
2558 if (isa<VPWidenRecipe>(Op) &&
2561 break;
2562 }
2563 if (auto *WidenIntrinsic = dyn_cast<VPWidenIntrinsicRecipe>(Op)) {
2564 if (is_contained({Intrinsic::umin, Intrinsic::umax, Intrinsic::smin,
2565 Intrinsic::smax},
2566 WidenIntrinsic->getVectorIntrinsicID())) {
2568 break;
2569 }
2570 }
2571 }
2572
2573 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2574 IntrinsicCostAttributes CostAttrs(
2575 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2576 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2578 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2579}
2580
2582 VPCostContext &Ctx) const {
2583 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2584}
2585
2587 return Intrinsic::getBaseName(VectorIntrinsicID);
2588}
2589
2591 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2592 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2593 auto [Idx, V] = X;
2595 Idx, nullptr);
2596 });
2597}
2598
2599#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2601 VPSlotTracker &SlotTracker) const {
2602 O << Indent << "WIDEN-INTRINSIC ";
2603 if (getScalarType()->isVoidTy()) {
2604 O << "void ";
2605 } else {
2607 O << " = ";
2608 }
2609
2610 O << "call";
2611 printFlags(O);
2612 O << getIntrinsicName() << "(";
2614 O << ")";
2615}
2616#endif
2617
2619 CallInst *MemI = createVectorCall(State);
2621 MemI->getContext(), Alignment));
2622 if (!MemI->getType()->isVoidTy())
2623 State.set(this, MemI);
2624}
2625
2628 assert(MaskPos && "Expected a memory intrinsic with a valid mask position");
2629 return getOperand(*MaskPos);
2630}
2631
2634 assert(PtrPos && "Expected a memory intrinsic with a valid pointer position");
2635 return *PtrPos;
2636}
2637
2639 Type *DataTy;
2641 DataTy = getOperand(*DataPos)->getScalarType();
2642 else
2643 DataTy = getScalarType();
2644 assert(!DataTy->isVoidTy() && "Expected a non-void data type");
2645 return toVectorTy(DataTy, VF);
2646}
2647
2649 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2650 VPCostContext &Ctx) {
2651 return Ctx.TTI.getMemIntrinsicInstrCost(
2652 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2653 Ctx.CostKind);
2654}
2655
2662
2664 IRBuilderBase &Builder = State.Builder;
2665
2666 Value *Address = State.get(getOperand(0));
2667 Value *IncAmt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
2668 VectorType *VTy = cast<VectorType>(Address->getType());
2669
2670 // The histogram intrinsic requires a mask even if the recipe doesn't;
2671 // if the mask operand was omitted then all lanes should be executed and
2672 // we just need to synthesize an all-true mask.
2673 Value *Mask = nullptr;
2674 if (VPValue *VPMask = getMask())
2675 Mask = State.get(VPMask);
2676 else
2677 Mask =
2678 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2679
2680 // If this is a subtract, we want to invert the increment amount and use
2681 // the histogram_add intrinsic.
2682 if (mustNegateIncrement())
2683 IncAmt = Builder.CreateNeg(IncAmt);
2684
2685 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2686 getHistogramIntrinsicID(), {VTy, IncAmt->getType()},
2687 {Address, IncAmt, Mask});
2688 applyMetadata(*HistogramInst);
2689}
2690
2691Intrinsic::ID VPHistogramRecipe::getHistogramIntrinsicID() const {
2692 switch (UpdateKind) {
2695 return Intrinsic::experimental_vector_histogram_add;
2697 return Intrinsic::experimental_vector_histogram_uadd_sat;
2699 return Intrinsic::experimental_vector_histogram_umax;
2701 return Intrinsic::experimental_vector_histogram_umin;
2702 }
2703 llvm_unreachable("Unknown HistogramUpdateKind");
2704}
2705
2707 VPCostContext &Ctx) const {
2708 // FIXME: Improve the TTI method for determining the cost, including
2709 // whether we can use base + vec-of-smaller-indices or just
2710 // vec-of-pointers for the gather and scatter.
2711 assert(VF.isVector() && "Invalid VF for histogram cost");
2712 Type *AddressTy = getOperand(0)->getScalarType();
2713 VPValue *IncAmt = getOperand(1);
2714 Type *IncTy = IncAmt->getScalarType();
2715 VectorType *VTy = VectorType::get(IncTy, VF);
2716
2717 // For umin/umax, there's no multiplication — the increment value is compared
2718 // directly. For add/sub/uadd.sat, assume that a non-constant update value
2719 // (or a constant != 1) requires a multiply.
2721 if (!match(IncAmt, m_One()) && UpdateKind != HistogramUpdateKind::UMax &&
2722 UpdateKind != HistogramUpdateKind::UMin)
2723 MulCost =
2724 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2725
2726 // Find the cost of the histogram operation itself.
2727 Type *PtrTy = VectorType::get(AddressTy, VF);
2728 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2729 IntrinsicCostAttributes ICA(getHistogramIntrinsicID(),
2730 Type::getVoidTy(Ctx.LLVMCtx),
2731 {PtrTy, IncTy, MaskTy});
2732
2733 // The histogram intrinsic's TTI cost already includes the update operation
2734 // (load + update + store), so no separate UpdateCost is needed.
2735 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost;
2736}
2737
2738#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2740 VPSlotTracker &SlotTracker) const {
2741 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2743
2744 switch (UpdateKind) {
2746 O << ", inc: ";
2747 break;
2749 O << ", dec: ";
2750 break;
2752 O << ", saturated inc: ";
2753 break;
2755 O << ", max: ";
2756 break;
2758 O << ", min: ";
2759 break;
2760 }
2762
2763 if (VPValue *Mask = getMask()) {
2764 O << ", mask: ";
2765 Mask->printAsOperand(O, SlotTracker);
2766 }
2767}
2768#endif
2769
2770VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2771 AllowReassoc = FMF.allowReassoc();
2772 NoNaNs = FMF.noNaNs();
2773 NoInfs = FMF.noInfs();
2774 NoSignedZeros = FMF.noSignedZeros();
2775 AllowReciprocal = FMF.allowReciprocal();
2776 AllowContract = FMF.allowContract();
2777 ApproxFunc = FMF.approxFunc();
2778}
2779
2780VPIRFlags VPIRFlags::getDefaultFlags(unsigned Opcode, Type *ResultTy) {
2781 switch (Opcode) {
2782 case Instruction::Add:
2783 case Instruction::Sub:
2784 case Instruction::Mul:
2785 case Instruction::Shl:
2787 return WrapFlagsTy(false, false);
2788 case Instruction::Trunc:
2789 return TruncFlagsTy(false, false);
2790 case Instruction::Or:
2791 return DisjointFlagsTy(false);
2792 case Instruction::AShr:
2793 case Instruction::LShr:
2794 case Instruction::UDiv:
2795 case Instruction::SDiv:
2796 return ExactFlagsTy(false);
2797 case Instruction::GetElementPtr:
2800 return GEPNoWrapFlags::none();
2801 case Instruction::ZExt:
2802 case Instruction::UIToFP:
2803 return NonNegFlagsTy(false);
2804 case Instruction::FAdd:
2805 case Instruction::FSub:
2806 case Instruction::FMul:
2807 case Instruction::FDiv:
2808 case Instruction::FRem:
2809 case Instruction::FNeg:
2810 case Instruction::FPExt:
2811 case Instruction::FPTrunc:
2812 return FastMathFlags();
2813 case Instruction::Select:
2814 case Instruction::PHI:
2815 case Instruction::Call:
2816 // Selects, phis and calls only have fast-math flags if they have a
2817 // supported floating-point result type.
2819 return FastMathFlags();
2820 return VPIRFlags();
2821 case Instruction::ICmp:
2822 case Instruction::FCmp:
2824 llvm_unreachable("opcode requires explicit flags");
2825 default:
2826 return VPIRFlags();
2827 }
2828}
2829
2830#if !defined(NDEBUG)
2831bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2832 switch (OpType) {
2833 case OperationType::OverflowingBinOp:
2834 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2835 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2836 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2837 case OperationType::Trunc:
2838 return Opcode == Instruction::Trunc;
2839 case OperationType::DisjointOp:
2840 return Opcode == Instruction::Or;
2841 case OperationType::PossiblyExactOp:
2842 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2843 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2844 case OperationType::GEPOp:
2845 return Opcode == Instruction::GetElementPtr ||
2846 Opcode == VPInstruction::PtrAdd ||
2847 Opcode == VPInstruction::WidePtrAdd;
2848 case OperationType::FPMathOp:
2849 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2850 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2851 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2852 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2853 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2854 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2855 Opcode == Instruction::UIToFP ||
2856 Opcode == VPInstruction::WideIVStep ||
2858 case OperationType::FCmp:
2859 return Opcode == Instruction::FCmp;
2860 case OperationType::NonNegOp:
2861 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2862 case OperationType::Cmp:
2863 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2864 case OperationType::ReductionOp:
2866 case OperationType::Other:
2867 return true;
2868 }
2869 llvm_unreachable("Unknown OperationType enum");
2870}
2871
2873 Type *ResultTy) const {
2874 // Handle opcodes without default flags.
2875 if (Opcode == Instruction::ICmp)
2876 return OpType == OperationType::Cmp;
2877 if (Opcode == Instruction::FCmp)
2878 return OpType == OperationType::FCmp;
2880 return OpType == OperationType::ReductionOp;
2881
2882 OperationType Required = getDefaultFlags(Opcode, ResultTy).OpType;
2883 return Required == OperationType::Other || Required == OpType;
2884}
2885#endif
2886
2887#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2888static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2889 switch (Kind) {
2890 case RecurKind::None:
2891 OS << "none";
2892 break;
2893 case RecurKind::Add:
2894 OS << "add";
2895 break;
2896 case RecurKind::Sub:
2897 OS << "sub";
2898 break;
2900 OS << "add-chain-with-subs";
2901 break;
2902 case RecurKind::Mul:
2903 OS << "mul";
2904 break;
2905 case RecurKind::Or:
2906 OS << "or";
2907 break;
2908 case RecurKind::And:
2909 OS << "and";
2910 break;
2911 case RecurKind::Xor:
2912 OS << "xor";
2913 break;
2914 case RecurKind::SMin:
2915 OS << "smin";
2916 break;
2917 case RecurKind::SMax:
2918 OS << "smax";
2919 break;
2920 case RecurKind::UMin:
2921 OS << "umin";
2922 break;
2923 case RecurKind::UMax:
2924 OS << "umax";
2925 break;
2926 case RecurKind::FAdd:
2927 OS << "fadd";
2928 break;
2930 OS << "fadd-chain-with-subs";
2931 break;
2932 case RecurKind::FSub:
2933 OS << "fsub";
2934 break;
2935 case RecurKind::FMul:
2936 OS << "fmul";
2937 break;
2938 case RecurKind::FMin:
2939 OS << "fmin";
2940 break;
2941 case RecurKind::FMax:
2942 OS << "fmax";
2943 break;
2944 case RecurKind::FMinNum:
2945 OS << "fminnum";
2946 break;
2947 case RecurKind::FMaxNum:
2948 OS << "fmaxnum";
2949 break;
2951 OS << "fmin-select-nofmf";
2952 break;
2954 OS << "fmax-select-nofmf";
2955 break;
2957 OS << "fminimum";
2958 break;
2960 OS << "fmaximum";
2961 break;
2963 OS << "fminimumnum";
2964 break;
2966 OS << "fmaximumnum";
2967 break;
2968 case RecurKind::FMulAdd:
2969 OS << "fmuladd";
2970 break;
2971 case RecurKind::AnyOf:
2972 OS << "any-of";
2973 break;
2974 case RecurKind::FindIV:
2975 OS << "find-iv";
2976 break;
2978 OS << "find-last";
2979 break;
2980 }
2981}
2982
2984 switch (OpType) {
2985 case OperationType::Cmp:
2987 break;
2988 case OperationType::FCmp:
2991 break;
2992 case OperationType::DisjointOp:
2993 if (DisjointFlags.IsDisjoint)
2994 O << " disjoint";
2995 break;
2996 case OperationType::PossiblyExactOp:
2997 if (ExactFlags.IsExact)
2998 O << " exact";
2999 break;
3000 case OperationType::OverflowingBinOp:
3001 if (WrapFlags.HasNUW)
3002 O << " nuw";
3003 if (WrapFlags.HasNSW)
3004 O << " nsw";
3005 break;
3006 case OperationType::Trunc:
3007 if (TruncFlags.HasNUW)
3008 O << " nuw";
3009 if (TruncFlags.HasNSW)
3010 O << " nsw";
3011 break;
3012 case OperationType::FPMathOp:
3014 break;
3015 case OperationType::GEPOp: {
3017 if (Flags.isInBounds())
3018 O << " inbounds";
3019 else if (Flags.hasNoUnsignedSignedWrap())
3020 O << " nusw";
3021 if (Flags.hasNoUnsignedWrap())
3022 O << " nuw";
3023 break;
3024 }
3025 case OperationType::NonNegOp:
3026 if (NonNegFlags.NonNeg)
3027 O << " nneg";
3028 break;
3029 case OperationType::ReductionOp: {
3030 O << " (";
3032 if (isReductionInLoop())
3033 O << ", in-loop";
3034 if (isReductionOrdered())
3035 O << ", ordered";
3036 O << ")";
3038 break;
3039 }
3040 case OperationType::Other:
3041 break;
3042 }
3043 O << " ";
3044}
3045#endif
3046
3048 auto &Builder = State.Builder;
3049 switch (Opcode) {
3050 case Instruction::Call:
3051 case Instruction::UncondBr:
3052 case Instruction::CondBr:
3053 case Instruction::PHI:
3054 case Instruction::GetElementPtr:
3055 llvm_unreachable("This instruction is handled by a different recipe.");
3056 case Instruction::UDiv:
3057 case Instruction::SDiv:
3058 case Instruction::SRem:
3059 case Instruction::URem:
3060 case Instruction::Add:
3061 case Instruction::FAdd:
3062 case Instruction::Sub:
3063 case Instruction::FSub:
3064 case Instruction::FNeg:
3065 case Instruction::Mul:
3066 case Instruction::FMul:
3067 case Instruction::FDiv:
3068 case Instruction::FRem:
3069 case Instruction::Shl:
3070 case Instruction::LShr:
3071 case Instruction::AShr:
3072 case Instruction::And:
3073 case Instruction::Or:
3074 case Instruction::Xor: {
3075 // Just widen unops and binops.
3077 for (VPValue *VPOp : operands())
3078 Ops.push_back(State.get(VPOp));
3079
3080 Value *V = Builder.CreateNAryOp(Opcode, Ops);
3081
3082 if (auto *VecOp = dyn_cast<Instruction>(V)) {
3083 applyFlags(*VecOp);
3084 applyMetadata(*VecOp);
3085 }
3086
3087 // Use this vector value for all users of the original instruction.
3088 State.set(this, V);
3089 break;
3090 }
3091 case Instruction::ExtractValue: {
3092 Value *Op = State.get(getOperand(0));
3093 Value *Extract =
3094 Builder.CreateExtractValue(Op, getExtractValueIndices(operands()));
3095 State.set(this, Extract);
3096 break;
3097 }
3098 case Instruction::Freeze: {
3099 Value *Op = State.get(getOperand(0));
3100 Value *Freeze = Builder.CreateFreeze(Op);
3101 State.set(this, Freeze);
3102 break;
3103 }
3104 case Instruction::ICmp:
3105 case Instruction::FCmp: {
3106 // Widen compares. Generate vector compares.
3107 bool FCmp = Opcode == Instruction::FCmp;
3108 Value *A = State.get(getOperand(0));
3109 Value *B = State.get(getOperand(1));
3110 Value *C = nullptr;
3111 if (FCmp) {
3112 C = Builder.CreateFCmp(getPredicate(), A, B);
3113 } else {
3114 C = Builder.CreateICmp(getPredicate(), A, B);
3115 }
3116 if (auto *I = dyn_cast<Instruction>(C)) {
3117 applyFlags(*I);
3118 applyMetadata(*I);
3119 }
3120 State.set(this, C);
3121 break;
3122 }
3123 case Instruction::Select: {
3124 VPValue *CondOp = getOperand(0);
3125 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
3126 Value *Op0 = State.get(getOperand(1));
3127 Value *Op1 = State.get(getOperand(2));
3128 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
3129 State.set(this, Sel);
3130 if (auto *I = dyn_cast<Instruction>(Sel)) {
3132 applyFlags(*I);
3133 applyMetadata(*I);
3134 }
3135 break;
3136 }
3137 default:
3138 // This instruction is not vectorized by simple widening.
3139 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
3140 << Instruction::getOpcodeName(Opcode));
3141 llvm_unreachable("Unhandled instruction!");
3142 } // end of switch.
3143
3144#if !defined(NDEBUG)
3145 // Verify that VPlan type inference results agree with the type of the
3146 // generated values.
3147 assert(VectorType::get(this->getScalarType(), State.VF) ==
3148 State.get(this)->getType() &&
3149 "inferred type and type from generated instructions do not match");
3150#endif
3151}
3152
3154 VPCostContext &Ctx) const {
3155 switch (Opcode) {
3156 case Instruction::UDiv:
3157 case Instruction::SDiv:
3158 case Instruction::SRem:
3159 case Instruction::URem:
3160 // If the div/rem operation isn't safe to speculate and requires
3161 // predication, then the only way we can even create a vplan is to insert
3162 // a select on the second input operand to ensure we use the value of 1
3163 // for the inactive lanes. The select will be costed separately.
3164 case Instruction::FNeg:
3165 case Instruction::Add:
3166 case Instruction::FAdd:
3167 case Instruction::Sub:
3168 case Instruction::FSub:
3169 case Instruction::Mul:
3170 case Instruction::FMul:
3171 case Instruction::FDiv:
3172 case Instruction::FRem:
3173 case Instruction::Shl:
3174 case Instruction::LShr:
3175 case Instruction::AShr:
3176 case Instruction::And:
3177 case Instruction::Or:
3178 case Instruction::Xor:
3179 case Instruction::Freeze:
3180 case Instruction::ExtractValue:
3181 case Instruction::ICmp:
3182 case Instruction::FCmp:
3183 case Instruction::Select:
3184 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
3185 default:
3186 llvm_unreachable("Unsupported opcode for instruction");
3187 }
3188}
3189
3190#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3192 VPSlotTracker &SlotTracker) const {
3193 O << Indent << "WIDEN ";
3195 O << " = " << Instruction::getOpcodeName(Opcode);
3196 printFlags(O);
3198}
3199#endif
3200
3202 auto &Builder = State.Builder;
3203 /// Vectorize casts.
3204 assert(State.VF.isVector() && "Not vectorizing?");
3205 Type *DestTy = VectorType::get(getScalarType(), State.VF);
3206 VPValue *Op = getOperand(0);
3207 Value *A = State.get(Op);
3208 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
3209 State.set(this, Cast);
3210 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
3211 applyFlags(*CastOp);
3212 applyMetadata(*CastOp);
3213 }
3214}
3215
3220
3221#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3223 VPSlotTracker &SlotTracker) const {
3224 O << Indent << "WIDEN-CAST ";
3226 O << " = " << Instruction::getOpcodeName(Opcode);
3227 printFlags(O);
3229 O << " to " << *getScalarType();
3230}
3231#endif
3232
3234 VPCostContext &Ctx) const {
3235 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3236}
3237
3238#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3240 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
3241 O << Indent;
3243 O << " = WIDEN-INDUCTION";
3244 printFlags(O);
3246
3247 if (isTruncated())
3248 O << " (truncated to " << *getScalarType() << ")";
3249}
3250#endif
3251
3253 // The step may be defined by a recipe in the preheader (e.g. if it requires
3254 // SCEV expansion), but for the canonical induction the step is required to be
3255 // 1, which is represented as live-in.
3256 return match(getStartValue(), m_ZeroInt()) &&
3257 match(getStepValue(), m_One()) &&
3258 getScalarType() == getRegion()->getCanonicalIVType();
3259}
3260
3263 VPCostContext &Ctx) const {
3264 // A widened induction generates a vector phi and increments it by the
3265 // splatted step each iteration.
3267 InstructionCost Cost = Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3268 Type *StepTy = getScalarType();
3269 unsigned IncOpc = ID.getKind() == InductionDescriptor::IK_IntInduction
3270 ? Instruction::Add
3271 : ID.getInductionOpcode();
3272 assert(IncOpc != Instruction::BinaryOpsEnd &&
3273 "induction must have a valid increment opcode");
3274 return Cost + Ctx.TTI.getArithmeticInstrCost(IncOpc, toVectorTy(StepTy, VF),
3275 Ctx.CostKind);
3276}
3277
3278/// Returns the ConstantFP \p V wraps, or nullptr if it does not wrap one.
3279static const ConstantFP *getConstantFP(const VPValue *V) {
3280 auto *C = dyn_cast<VPConstant>(V);
3281 return C ? dyn_cast<ConstantFP>(C->getConstant()) : nullptr;
3282}
3283
3285 VPCostContext &Ctx) const {
3286 // The cost model for this is modelled on expandVPDerivedIV in
3287 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
3288 // negatively affect vectorization it takes into account any expected
3289 // simplifications that happen in simplifyRecipe.
3290 switch (getInductionKind()) {
3291 default:
3292 // TODO: Compute cost for remaining kinds.
3293 break;
3295 // There are currently no tests that expose a path where all lanes are
3296 // used, so it's better to bail out for now.
3297 if (!vputils::onlyFirstLaneUsed(this))
3298 break;
3299
3300 // Start off by assuming we need both mul and add, then refine this.
3301 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
3302
3303 // If the start value is zero the add gets folded away.
3304 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
3305 NeedsAdd = !StartC->isZero();
3306
3307 // For some values of step the arithmetic changes:
3308 // 1. A step of 1 requires no operation.
3309 // 2. A step of -1 requires a negate.
3310 // 3. A power-of-2 step will use a shl, instead of a mul.
3311 Type *StepTy = getStepValue()->getScalarType();
3313 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
3314 if (StepC->isOne())
3315 NeedsMul = false;
3316 else if (StepC->getAPInt().isAllOnes()) {
3317 // This will most likely end up as a negate in simplifyRecipe, and
3318 // the negate will be combined with the add to make a sub.
3319 // NOTE: This is perhaps an invalid assumption that the cost of an
3320 // 'add' is the same as a 'sub'.
3321 NeedsMul = false;
3322 NeedsAdd = true;
3323 } else if (StepC->getAPInt().isPowerOf2()) {
3324 // This will most likely end up as a shift-left in simplifyRecipe
3325 NeedsMul = false;
3326 NeedsShl = true;
3327 }
3328 }
3329
3330 // Add the cost of the conversion from index to step type if the index
3331 // will be used.
3332 Type *IndexTy = getIndex()->getScalarType();
3333 unsigned StepTySize = StepTy->getScalarSizeInBits();
3334 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3335 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3336 unsigned CastOpc =
3337 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::ZExt;
3338 Cost += Ctx.TTI.getCastInstrCost(
3339 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3340 }
3341
3342 if (NeedsMul)
3343 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3344 Ctx.CostKind);
3345 if (NeedsShl)
3346 Cost += Ctx.TTI.getArithmeticInstrCost(
3347 Instruction::Shl, StepTy, Ctx.CostKind,
3348 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3349 {TargetTransformInfo::OK_UniformConstantValue,
3350 TargetTransformInfo::OP_None});
3351 if (NeedsAdd)
3352 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3353 Ctx.CostKind);
3354 return Cost;
3355 }
3357 // There are currently no tests that expose a path where all lanes are
3358 // used, so it's better to bail out for now.
3359 if (!vputils::onlyFirstLaneUsed(this))
3360 break;
3361
3362 // Unlike the integer case, converting the index to the FP step type is
3363 // unavoidable: the index is always the integer canonical IV, so this
3364 // cast is never folded away.
3365 Type *StepTy = getStepValue()->getScalarType();
3366 Type *IndexTy = getIndex()->getScalarType();
3368 Ctx.TTI.getCastInstrCost(Instruction::UIToFP, StepTy, IndexTy,
3369 TTI::CastContextHint::None, Ctx.CostKind);
3370
3371 // If the step is 1.0, the multiply is an exact identity and gets folded
3372 // away, independent of fast-math flags.
3373 const ConstantFP *StepC = getConstantFP(getStepValue());
3374 bool NeedsMul = !StepC || !StepC->isOne();
3375
3376 // "fadd -0.0, X" folds to X unconditionally, but "fadd 0.0, X" only folds
3377 // to X without nsz if X can be proven to never be -0.0, which we cannot, as
3378 // Step may be -0.0.
3379 // TODO: Consider fast-math flags when they are available in
3380 // VPDerivedIVRecipe.
3381 const ConstantFP *StartC = getConstantFP(getStartValue());
3382 bool AddFolds = getFPBinOp()->getOpcode() == Instruction::FAdd && StartC &&
3383 StartC->isZero() && (StartC->isNegZero() || !NeedsMul);
3384
3385 if (NeedsMul)
3386 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::FMul, StepTy,
3387 Ctx.CostKind);
3388 if (!AddFolds)
3389 Cost += Ctx.TTI.getArithmeticInstrCost(getFPBinOp()->getOpcode(), StepTy,
3390 Ctx.CostKind);
3391 return Cost;
3392 }
3393 }
3394
3395 return 0;
3396}
3397
3398#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3400 VPSlotTracker &SlotTracker) const {
3401 O << Indent;
3403 O << " = DERIVED-IV";
3404 printFlags(O);
3405 getStartValue()->printAsOperand(O, SlotTracker);
3406 O << " + ";
3407 getOperand(1)->printAsOperand(O, SlotTracker);
3408 O << " * ";
3409 getStepValue()->printAsOperand(O, SlotTracker);
3410}
3411#endif
3412
3416
3418 VPCostContext &Ctx) const {
3419 Type *BaseIVTy = getOperand(0)->getScalarType();
3420 assert((BaseIVTy->isIntegerTy() || BaseIVTy->isFloatingPointTy()) &&
3421 "VPScalarIVStepsRecipe is only created for integer and FP inductions");
3422
3423 // If only the first lane is used, then there won't be any code that remains
3424 // in the loop for the first unrolled part.
3426 return 0;
3427
3428 // If the vector body executes at most once, the canonical IV is a constant
3429 // and every lane's step folds away with it.
3430 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
3431 return 0;
3432
3433 // Typically the operations are:
3434 // 1. Add the start index to each lane value.
3435 // 2. Multiply the start index by the step.
3436 // 3. Add the scaled start index to base IV.
3437 // Any code generated for 1 and 2 should be loop invariant and therefore
3438 // hoisted out of the loop. We only need to add on the cost of 3.
3440 if (BaseIVTy->isFloatingPointTy()) {
3441 // Unlike the integer case, the users of an FP induction cannot be re-based
3442 // on a common value, so each lane needs its own FAdd/FSub.
3443 assert(!VF.isScalable() &&
3444 "FP scalar steps for all lanes are only created for fixed VFs");
3445 Cost = Ctx.TTI.getArithmeticInstrCost(InductionOpcode, BaseIVTy,
3446 Ctx.CostKind) *
3447 (VF.getFixedValue() - 1);
3448 } else {
3449 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3450 // %add1 = add i32 %iv, 0
3451 // %add2 = add i32 %iv, 1
3452 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3453 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3454 // it's very likely that these GEPs will all be rewritten to have a common
3455 // base such that what's left is just
3456 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3457 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3458 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3459 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3460 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3461 Cost = Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3462 Ctx.CostKind);
3463 }
3464
3465 // If the steps are generated inside a replicate region, scale by execution
3466 // probability.
3467 const VPRegionBlock *Region = getRegion();
3468 if (Region && Region->isReplicator())
3469 Cost /= Ctx.getCostDivisor(
3470 Region->getEntryBranchOnMask()->getExecutionFrequency());
3471 return Cost;
3472}
3473
3475 // Fast-math-flags propagate from the original induction instruction.
3476 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3477 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3478
3479 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3480 /// variable on which to base the steps, \p Step is the size of the step.
3481
3482 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3483 Value *Step = State.get(getStepValue(), VPLane(0));
3484 IRBuilderBase &Builder = State.Builder;
3485
3486 // Ensure step has the same type as that of scalar IV.
3487 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3488 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3489
3490 // We build scalar steps for both integer and floating-point induction
3491 // variables. Here, we determine the kind of arithmetic we will perform.
3494 if (BaseIVTy->isIntegerTy()) {
3495 AddOp = Instruction::Add;
3496 MulOp = Instruction::Mul;
3497 } else {
3498 AddOp = InductionOpcode;
3499 MulOp = Instruction::FMul;
3500 }
3501
3502 // Lanes other than the first have been materialized as separate
3503 // single-scalar recipes by replicateByVF, each with its own start index.
3504 assert((vputils::onlyFirstLaneUsed(this) || State.VF.isScalar()) &&
3505 "must have been replicated by VF");
3506 Value *StartIdx = getStartIndex() ? State.get(getStartIndex(), true)
3507 : Constant::getNullValue(BaseIVTy);
3508 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3509 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3510 State.set(this, Add, VPLane(0));
3511}
3512
3513#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3515 VPSlotTracker &SlotTracker) const {
3516 O << Indent;
3518 O << " = SCALAR-STEPS ";
3520}
3521#endif
3522
3524 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3526}
3527
3529 assert(State.VF.isVector() && "not widening");
3530 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3531 return State.get(Op, vputils::isSingleScalar(Op));
3532 });
3533 auto *GEP =
3534 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3535 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3536 State.set(this, GEP, vputils::isSingleScalar(this));
3537}
3538
3539#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3541 VPSlotTracker &SlotTracker) const {
3542 O << Indent << "WIDEN-GEP ";
3544 O << " = getelementptr";
3545 printFlags(O);
3547}
3548#endif
3549
3551 assert(!getOffset() && "Unexpected offset operand");
3552 VPBuilder Builder(this);
3553 VPlan &Plan = *getParent()->getPlan();
3554 VPValue *VFVal = getVFValue();
3555 const DataLayout &DL = Plan.getDataLayout();
3556 Type *IndexTy = DL.getIndexType(this->getScalarType());
3557 VPValue *Stride =
3558 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3559 VPValue *VF =
3560 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3561
3562 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3563 VPInstruction *VFMinusOne =
3564 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3565 DebugLoc::getUnknown(), "", {true, true});
3566 VPInstruction *Offset0 =
3567 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3568
3569 // Offset for PartN = Offset0 + Part * Stride * VF.
3570 VPValue *PartxStride =
3571 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3572 VPValue *Offset = Builder.createAdd(
3573 Offset0,
3574 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3576}
3577
3579 auto &Builder = State.Builder;
3580 assert(getOffset() && "Expected prior materialization of offset");
3581 Value *Ptr = State.get(getPointer(), true);
3582 Value *Offset = State.get(getOffset(), true);
3583 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3585 State.set(this, ResultPtr, /*IsScalar*/ true);
3586}
3587
3588#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3590 VPSlotTracker &SlotTracker) const {
3591 O << Indent;
3593 O << " = vector-end-pointer";
3594 printFlags(O);
3595 getSourceElementType()->print(O);
3596 O << ", ";
3598}
3599#endif
3600
3602 assert(getVFxPart() &&
3603 "Expected prior simplification of recipe without VFxPart");
3604
3605 auto &Builder = State.Builder;
3606 Value *Ptr = State.get(getOperand(0), VPLane(0));
3607 Value *Offset = State.get(getVFxPart(), true);
3608 // TODO: Expand to VPInstruction to support constant folding.
3609 if (!match(getStride(), m_One())) {
3610 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3611 Offset->getType());
3612 Offset = Builder.CreateMul(Offset, Stride);
3613 }
3614 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3616 State.set(this, ResultPtr, /*IsScalar*/ true);
3617}
3618
3619#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3621 VPSlotTracker &SlotTracker) const {
3622 O << Indent;
3624 O << " = vector-pointer";
3625 printFlags(O);
3626 getSourceElementType()->print(O);
3627 O << ", ";
3629}
3630#endif
3631
3633 VPCostContext &Ctx) const {
3634 // A blend will be expanded to a select VPInstruction, which will generate a
3635 // scalar select if only the first lane is used.
3637 VF = ElementCount::getFixed(1);
3638
3639 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3640 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3641
3643 for (unsigned I = 1, E = getNumIncomingValues(); I != E; ++I) {
3644 CmpPredicate Pred;
3645 if (!match(getMask(I), m_Cmp(Pred, m_VPValue(), m_VPValue())))
3646 Pred = getScalarType()->isFloatingPointTy() ? CmpInst::BAD_FCMP_PREDICATE
3648 Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3649 Pred, Ctx.CostKind);
3650 }
3651 return Cost;
3652}
3653
3654#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3656 VPSlotTracker &SlotTracker) const {
3657 O << Indent << "BLEND ";
3659 O << " =";
3660 printFlags(O);
3661 if (getNumIncomingValues() == 1) {
3662 // Not a User of any mask: not really blending, this is a
3663 // single-predecessor phi.
3664 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3665 } else {
3666 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3667 if (I != 0)
3668 O << " ";
3669 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3670 if (I == 0 && isNormalized())
3671 continue;
3672 O << "/";
3673 getMask(I)->printAsOperand(O, SlotTracker);
3674 }
3675 }
3676}
3677#endif
3678
3682 "In-loop AnyOf reductions aren't currently supported");
3683 // Propagate the fast-math flags carried by the underlying instruction.
3684 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3685 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3686 Value *NewVecOp = State.get(getVecOp());
3687 if (VPValue *Cond = getCondOp()) {
3688 Value *NewCond = State.get(Cond, State.VF.isScalar());
3689 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3690 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3691
3692 Value *Start =
3694 if (State.VF.isVector())
3695 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3696
3697 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3698 NewVecOp = Select;
3699 }
3700 Value *NewRed;
3701 Value *NextInChain;
3702 if (isOrdered()) {
3703 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3704 if (State.VF.isVector())
3705 NewRed =
3706 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3707 else
3708 NewRed = State.Builder.CreateBinOp(
3710 PrevInChain, NewVecOp);
3711 PrevInChain = NewRed;
3712 NextInChain = NewRed;
3713 } else if (isPartialReduction()) {
3714 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3715 "Unexpected partial reduction kind");
3716 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/false);
3717 NewRed = State.Builder.CreateIntrinsic(
3718 PrevInChain->getType(),
3719 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3720 : Intrinsic::vector_partial_reduce_fadd,
3721 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3722 "partial.reduce");
3723 PrevInChain = NewRed;
3724 NextInChain = NewRed;
3725 } else {
3726 assert(isInLoop() &&
3727 "The reduction must either be ordered, partial or in-loop");
3728 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3729 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3731 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3732 else
3733 NextInChain = State.Builder.CreateBinOp(
3735 PrevInChain, NewRed);
3736 }
3737 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3738}
3739
3741
3742 assert(State.VF.isVector() &&
3743 "Shouldn't generate VPReductionEVLRecipe with scalar VF");
3744 auto &Builder = State.Builder;
3745 // Propagate the fast-math flags carried by the underlying instruction.
3746 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3747 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3748
3750 Value *Prev =
3751 State.get(getChainOp(), /*NeedsSingleScalar=*/!isPartialReduction());
3752 Value *VecOp = State.get(getVecOp());
3753 Value *EVL = State.get(getEVL(), VPLane(0));
3754
3755 Value *Mask;
3756 if (VPValue *CondOp = getCondOp())
3757 Mask = State.get(CondOp);
3758 else
3759 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3760
3761 Value *NewRed;
3762 if (isPartialReduction()) {
3763 // For partial reductions, we need to generate a predicated select
3764 // (vp.merge) since `@llvm.vector.partial.reduce()` doesn't have a vector
3765 // predicated version.
3766 VectorType *VecTy = cast<VectorType>(VecOp->getType());
3767 Value *Identity = getRecurrenceIdentity(Kind, VecTy->getElementType(),
3769 Identity =
3770 State.Builder.CreateVectorSplat(VecTy->getElementCount(), Identity);
3771
3772 // TODO: Calculate the predicate cost for the partial reduction.
3773 Value *NewVecOp = State.Builder.CreateIntrinsic(
3774 VecTy, Intrinsic::vp_merge, {Mask, VecOp, Identity, EVL});
3775 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3776 "Unexpected partial reduction kind");
3777 NewRed = State.Builder.CreateIntrinsic(
3778 Prev->getType(),
3779 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3780 : Intrinsic::vector_partial_reduce_fadd,
3781 {Prev, NewVecOp}, State.Builder.getFastMathFlags(), "partial.reduce");
3782 } else if (isOrdered()) {
3783 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3784 } else {
3785 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3787 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3788 else
3789 NewRed = Builder.CreateBinOp(
3791 Prev);
3792 }
3793 State.set(this, NewRed, !isPartialReduction());
3794}
3795
3797 VPCostContext &Ctx) const {
3798 RecurKind RdxKind = getRecurrenceKind();
3799 Type *ElementTy = this->getScalarType();
3800 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3801 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3803 std::optional<FastMathFlags> OptionalFMF =
3804 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3805
3806 if (isPartialReduction()) {
3807 InstructionCost CondCost = 0;
3808 if (isConditional()) {
3810 auto *CondTy =
3812 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3813 CondTy, Pred, Ctx.CostKind);
3814 }
3815 return CondCost + Ctx.TTI.getPartialReductionCost(
3816 Opcode, ElementTy, nullptr, ElementTy, VF,
3817 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3818 OptionalFMF);
3819 }
3820
3821 // TODO: Support any-of reductions.
3822 assert(
3824 Ctx.Opts.force_target_instruction_cost) &&
3825 "Any-of reduction not implemented in VPlan-based cost model currently.");
3826
3827 // Note that TTI should model the cost of moving result to the scalar register
3828 // and the BinOp cost in the getMinMaxReductionCost().
3831 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3832 }
3833
3834 // Note that TTI should model the cost of moving result to the scalar register
3835 // and the BinOp cost in the getArithmeticReductionCost().
3836 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3837 Ctx.CostKind);
3838}
3839
3841 ExpressionTypes ExpressionType,
3842 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3843 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3844 [&]() {
3845 if (ExpressionType == ExpressionTypes::FoldedVPMerge)
3846 return ExpressionRecipes.back()->getScalarType();
3848 ExpressionRecipes.back())
3849 ->getChainOp()
3850 ->getScalarType();
3851 }()),
3852 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3853 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3854 assert(
3855 none_of(ExpressionRecipes,
3856 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3857 "expression cannot contain recipes with side-effects");
3858
3859 // Maintain a copy of the expression recipes as a set of users.
3860 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3861 for (auto *R : ExpressionRecipes)
3862 ExpressionRecipesAsSetOfUsers.insert(R);
3863
3864 // Recipes in the expression, except the last one, must only be used by
3865 // (other) recipes inside the expression. If there are other users, external
3866 // to the expression, use a clone of the recipe for external users.
3867 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3868 if (R != ExpressionRecipes.back() &&
3869 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3870 return !ExpressionRecipesAsSetOfUsers.contains(U);
3871 })) {
3872 // There are users outside of the expression. Clone the recipe and use the
3873 // clone those external users.
3874 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3875 R->replaceUsesWithIf(CopyForExtUsers,
3876 [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3877 return !ExpressionRecipesAsSetOfUsers.contains(U);
3878 });
3879 CopyForExtUsers->insertBefore(R);
3880 }
3881 if (R->getParent())
3882 R->removeFromParent();
3883 }
3884
3885 // Internalize all external operands to the expression recipes. To do so,
3886 // create new temporary VPValues for all operands defined by a recipe outside
3887 // the expression. The original operands are added as operands of the
3888 // VPExpressionRecipe itself.
3889 for (auto *R : ExpressionRecipes) {
3890 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3891 auto *Def = Op->getDefiningRecipe();
3892 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3893 continue;
3894 addOperand(Op);
3895 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3896 }
3897 }
3898
3899 // Replace each external operand with the first one created for it in
3900 // LiveInPlaceholders.
3901 for (auto *R : ExpressionRecipes)
3902 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3903 R->replaceUsesOfWith(LiveIn, Tmp);
3904}
3905
3907 for (auto *R : ExpressionRecipes)
3908 // Since the list could contain duplicates, make sure the recipe hasn't
3909 // already been inserted.
3910 if (!R->getParent())
3911 R->insertBefore(this);
3912
3913 for (const auto &[Idx, Op] : enumerate(operands()))
3914 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3915
3916 replaceAllUsesWith(ExpressionRecipes.back());
3917 SmallVector<VPSingleDefRecipe *> DecomposedRecipes(ExpressionRecipes);
3918 ExpressionRecipes.clear();
3919 return DecomposedRecipes;
3920}
3921
3923 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3924 // The last operand of a folded operation is the vp.merge EVL.
3925 if (ExpressionType == ExpressionTypes::FoldedVPMerge &&
3926 Op == getLastOperand()) {
3927 assert(match(Op, m_EVL(m_VPValue())) &&
3928 "Expected an explicit vector length recipe");
3929 return true;
3930 }
3931
3932 return false;
3933}
3934
3936 VPCostContext &Ctx) const {
3937 // The last recipes in the chain will be optimized away, so igonre the cost.
3938 if (ExpressionType == ExpressionTypes::FoldedVPMerge) {
3940 for (auto *R : drop_end(ExpressionRecipes))
3941 Cost += R->cost(VF, Ctx);
3942 return Cost;
3943 }
3944
3945 Type *RedTy = this->getScalarType();
3946 auto *SrcVecTy =
3948 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3949 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3950 switch (ExpressionType) {
3951 case ExpressionTypes::NegatedExtendedReduction:
3952 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3953 "Unexpected opcode");
3954 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3955 [[fallthrough]];
3956 case ExpressionTypes::ExtendedReduction: {
3957 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3958 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3959
3960 if (RedR->isPartialReduction())
3961 return Ctx.TTI.getPartialReductionCost(
3962 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3964 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3965 RedTy->isFloatingPointTy()
3966 ? std::optional{RedR->getFastMathFlagsOrNone()}
3967 : std::nullopt);
3968 else if (!RedTy->isFloatingPointTy())
3969 // TTI::getExtendedReductionCost only supports integer types.
3970 return Ctx.TTI.getExtendedReductionCost(
3971 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3972 std::nullopt, Ctx.CostKind);
3973 else
3975 }
3976 case ExpressionTypes::MulAccReduction:
3977 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3978 Ctx.CostKind);
3979
3980 case ExpressionTypes::ExtNegatedMulAccReduction:
3981 switch (Opcode) {
3982 case Instruction::Add:
3983 Opcode = Instruction::Sub;
3984 break;
3985 case Instruction::FAdd:
3986 Opcode = Instruction::FSub;
3987 break;
3988 default:
3989 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3990 }
3991 [[fallthrough]];
3992 case ExpressionTypes::ExtMulAccReduction: {
3993 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3994 if (RedR->isPartialReduction()) {
3995 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3996 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3997 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3998 return Ctx.TTI.getPartialReductionCost(
3999 Opcode, getOperand(0)->getScalarType(),
4000 getOperand(1)->getScalarType(), RedTy, VF,
4002 Ext0R->getOpcode()),
4004 Ext1R->getOpcode()),
4005 Mul->getOpcode(), Ctx.CostKind,
4006 RedTy->isFloatingPointTy()
4007 ? std::optional{RedR->getFastMathFlagsOrNone()}
4008 : std::nullopt);
4009 }
4010 assert(Opcode != Instruction::FSub && "Only integer types are supported");
4011 return Ctx.TTI.getMulAccReductionCost(
4012 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
4013 Instruction::ZExt,
4014 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
4015 }
4016 case ExpressionTypes::FoldedVPMerge:
4017 llvm_unreachable("Folded vp.merge expression should be handled eariler");
4018 }
4019 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
4020}
4021
4023 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
4024 return R->mayReadFromMemory() || R->mayWriteToMemory();
4025 });
4026}
4027
4029 assert(
4030 none_of(ExpressionRecipes,
4031 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
4032 "expression cannot contain recipes with side-effects");
4033 return false;
4034}
4035
4037 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
4038 return RR && !RR->isPartialReduction();
4039}
4040
4041#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4042
4044 VPSlotTracker &SlotTracker) const {
4045 O << Indent << "EXPRESSION ";
4047 O << " = ";
4048 if (ExpressionType == ExpressionTypes::FoldedVPMerge) {
4049 VPSingleDefRecipe *InLoopOp = ExpressionRecipes[0];
4050 unsigned NumInLoopOps = InLoopOp->getNumOperands();
4051 O << "vp.merge ";
4052 getOperand(NumInLoopOps)->printAsOperand(O, SlotTracker);
4053 O << ", ";
4054 auto PrintInLoopOperands = [&]() {
4055 O << "(";
4056 interleaveComma(make_range(op_begin(), op_begin() + NumInLoopOps), O,
4057 [&O, &SlotTracker](VPValue *Op) {
4058 Op->printAsOperand(O, SlotTracker);
4059 });
4060 O << ")";
4061 };
4062
4063 if (auto *WidenIntrinsic = dyn_cast<VPWidenIntrinsicRecipe>(InLoopOp)) {
4064 O << WidenIntrinsic->getIntrinsicName();
4065 WidenIntrinsic->printFlags(O);
4066 PrintInLoopOperands();
4067 } else if (auto *Widen = dyn_cast<VPWidenRecipe>(InLoopOp)) {
4068 O << Instruction::getOpcodeName(Widen->getOpcode());
4069 Widen->printFlags(O);
4070 PrintInLoopOperands();
4071 }
4072 O << ", ";
4073 interleaveComma(make_range(op_begin() + NumInLoopOps + 1,
4074 op_begin() + NumInLoopOps + 3),
4075 O, [&O, &SlotTracker](VPValue *Op) {
4076 Op->printAsOperand(O, SlotTracker);
4077 });
4078
4079 return;
4080 }
4081
4082 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
4083 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
4084 VPValue *Mask = getLastOperand();
4085 VPValue *EVL =
4087 ? getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1))
4088 : nullptr;
4089 VPValue *RdxStart = getOperand(
4090 getNumOperands() - (Red->isConditional() ? 2 : 1) - (EVL ? 1 : 0));
4091 auto PrintEVLAndMask = [&]() {
4092 if (EVL) {
4093 O << ", ";
4094 EVL->printAsOperand(O, SlotTracker);
4095 }
4096 if (Red->isConditional()) {
4097 O << ", ";
4098 Mask->printAsOperand(O, SlotTracker);
4099 }
4100 };
4101
4102 switch (ExpressionType) {
4103 case ExpressionTypes::NegatedExtendedReduction:
4104 case ExpressionTypes::ExtendedReduction: {
4105 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
4107 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4108 O << Instruction::getOpcodeName(Opcode) << " (";
4109 if (Negated)
4110 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
4112 if (Negated)
4113 O << ")";
4114 Red->printFlags(O);
4115
4116 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4117 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4118 << *Ext0->getScalarType();
4119 PrintEVLAndMask();
4120 O << ")";
4121 break;
4122 }
4123 case ExpressionTypes::ExtNegatedMulAccReduction: {
4124 RdxStart->printAsOperand(O, SlotTracker);
4125 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4127 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4128 << " (sub (0, mul";
4129 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
4130 Mul->printFlags(O);
4131 O << "(";
4133 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4134 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4135 << *Ext0->getScalarType() << "), (";
4137 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4138 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4139 << *Ext1->getScalarType() << ")";
4140 PrintEVLAndMask();
4141 O << "))";
4142 break;
4143 }
4144 case ExpressionTypes::MulAccReduction:
4145 case ExpressionTypes::ExtMulAccReduction: {
4146 RdxStart->printAsOperand(O, SlotTracker);
4147 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4149 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4150 << " (";
4151 O << "mul";
4152 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
4153 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
4154 : ExpressionRecipes[0]);
4155 Mul->printFlags(O);
4156 if (IsExtended)
4157 O << "(";
4159 if (IsExtended) {
4160 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4161 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4162 << *Ext0->getScalarType() << "), (";
4163 } else {
4164 O << ", ";
4165 }
4167 if (IsExtended) {
4168 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4169 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4170 << *Ext1->getScalarType() << ")";
4171 }
4172 PrintEVLAndMask();
4173 O << ")";
4174 break;
4175 }
4176 default:
4177 llvm_unreachable("Unhandled VPExpressionRecipe::ExpressionTypes enum");
4178 }
4179}
4180
4182 VPSlotTracker &SlotTracker) const {
4183 if (isPartialReduction())
4184 O << Indent << "PARTIAL-REDUCE ";
4185 else
4186 O << Indent << "REDUCE ";
4188 O << " = ";
4190 O << " +";
4191 printFlags(O);
4192 O << " reduce.";
4194 O << " (";
4196 if (isConditional()) {
4197 O << ", ";
4199 }
4200 O << ")";
4201}
4202
4204 VPSlotTracker &SlotTracker) const {
4205 if (isPartialReduction())
4206 O << Indent << "PARTIAL-REDUCE ";
4207 else
4208 O << Indent << "REDUCE ";
4210 O << " = ";
4212 O << " +";
4213 printFlags(O);
4214 O << " vp.reduce."
4217 << " (";
4219 O << ", ";
4221 if (isConditional()) {
4222 O << ", ";
4224 }
4225 O << ")";
4226}
4227
4228#endif
4229
4231 assert(IsSingleScalar &&
4232 "VPReplicateRecipes must be unrolled before ::execute");
4233 auto *Instr = getUnderlyingInstr();
4234 Instruction *Cloned = Instr->clone();
4235 Type *ResultTy = getScalarType();
4236 if (!ResultTy->isVoidTy()) {
4237 Cloned->setName(Instr->getName() + ".cloned");
4238 // The operands of the replicate recipe may have been narrowed, resulting in
4239 // a narrower result type. Update the type of the cloned instruction to the
4240 // correct type.
4241 if (ResultTy != Cloned->getType())
4242 Cloned->mutateType(ResultTy);
4243 }
4244
4247 Cloned->dropPoisonGeneratingFlags();
4248 applyFlags(*Cloned);
4249 applyMetadata(*Cloned);
4250
4251 if (hasPredicate())
4252 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
4253
4254 // Replace the operands of the cloned instructions with their scalar
4255 // equivalents in the new loop.
4256 for (unsigned Idx : seq(Cloned->getNumOperands()))
4257 Cloned->setOperand(Idx, State.get(getOperand(Idx), true));
4258
4259 // Place the cloned scalar in the new loop.
4260 State.Builder.Insert(Cloned);
4261
4262 State.set(this, Cloned, true);
4263
4264 // If we just cloned a new assumption, add it the assumption cache.
4265 if (auto *II = dyn_cast<AssumeInst>(Cloned))
4266 State.AC->registerAssumption(II);
4267}
4268
4269/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
4270/// which the legacy cost model computes a SCEV expression when computing the
4271/// address cost. Computing SCEVs for VPValues is incomplete and returns
4272/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
4273/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
4274static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
4276 const Loop *L) {
4277 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
4278 if (isa<SCEVCouldNotCompute>(Addr))
4279 return Addr;
4280
4281 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
4282}
4283
4285 VPCostContext &Ctx) const {
4287 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
4288 // transform, avoid computing their cost multiple times for now.
4289 Ctx.SkipCostComputation.insert(UI);
4290
4291 if (VF.isScalable() && !isSingleScalar())
4293
4294 switch (UI->getOpcode()) {
4295 case Instruction::Alloca:
4296 if (VF.isScalable())
4298 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4299 this->getScalarType(), Ctx.CostKind);
4300 case Instruction::GetElementPtr:
4301 // We mark this instruction as zero-cost because the cost of GEPs in
4302 // vectorized code depends on whether the corresponding memory instruction
4303 // is scalarized or not. Therefore, we handle GEPs with the memory
4304 // instruction cost.
4305 return 0;
4306 case Instruction::Call: {
4307 auto *CalledFn = cast<Function>(getLastOperand()->getLiveInIRValue());
4308 Type *ResultTy = this->getScalarType();
4309 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
4310 isSingleScalar(), VF, Ctx);
4311 }
4312 case Instruction::FNeg:
4313 case Instruction::Add:
4314 case Instruction::Sub:
4315 case Instruction::FAdd:
4316 case Instruction::FSub:
4317 case Instruction::Mul:
4318 case Instruction::FMul:
4319 case Instruction::FDiv:
4320 case Instruction::FRem:
4321 case Instruction::Shl:
4322 case Instruction::LShr:
4323 case Instruction::AShr:
4324 case Instruction::And:
4325 case Instruction::Or:
4326 case Instruction::Xor:
4327 case Instruction::ICmp:
4328 case Instruction::FCmp:
4329 case Instruction::Freeze:
4330 case Instruction::BitCast:
4331 case Instruction::SExt:
4332 case Instruction::ZExt:
4333 case Instruction::FPToUI:
4334 case Instruction::FPToSI:
4335 case Instruction::FPExt:
4336 case Instruction::PtrToInt:
4337 case Instruction::PtrToAddr:
4338 case Instruction::IntToPtr:
4339 case Instruction::SIToFP:
4340 case Instruction::UIToFP:
4341 case Instruction::Trunc:
4342 case Instruction::FPTrunc:
4343 case Instruction::Select:
4344 case Instruction::AddrSpaceCast:
4345 case Instruction::SDiv:
4346 case Instruction::UDiv:
4347 case Instruction::SRem:
4348 case Instruction::URem: {
4349 InstructionCost ScalarCost =
4351 if (isSingleScalar())
4352 return ScalarCost;
4353
4354 // If any of the operands is from a different replicate region and has its
4355 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
4356 // model to avoid cost mis-match.
4357 if (!Ctx.Opts.force_vplan_cost_model) {
4358 switch (UI->getOpcode()) {
4359 case Instruction::SDiv:
4360 case Instruction::UDiv:
4361 case Instruction::SRem:
4362 case Instruction::URem:
4363 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
4364 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
4365 if (!PredR)
4366 return false;
4367 return Ctx.skipCostComputation(
4369 PredR->getOperand(0)->getUnderlyingValue()),
4370 VF.isVector());
4371 }))
4372 return Ctx.getLegacyCost(UI, VF);
4373 }
4374 }
4375
4376 ScalarCost = ScalarCost * VF.getFixedValue() +
4377 Ctx.getScalarizationOverhead(this->getScalarType(),
4378 to_vector(operands()), VF);
4379 // If the recipe is not predicated (i.e. not in a replicate region), return
4380 // the scalar cost. Otherwise handle predicated cost.
4381 const VPRegionBlock *ParentRegion = getRegion();
4382 if (!ParentRegion || !ParentRegion->isReplicator())
4383 return ScalarCost;
4384
4385 // Account for the phi nodes that we will create.
4386 ScalarCost += VF.getFixedValue() *
4387 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4388 // Scale the cost by the probability of executing the predicated blocks.
4389 // This assumes the predicated block for each vector lane is equally
4390 // likely.
4391 ScalarCost /= Ctx.getCostDivisor(
4392 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4393 return ScalarCost;
4394 }
4395 case Instruction::Load:
4396 case Instruction::Store: {
4397 bool IsLoad = UI->getOpcode() == Instruction::Load;
4398 const VPValue *PtrOp = getOperand(!IsLoad);
4399 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
4401 // Fall back to the legacy cost model, unless the access is single-scalar
4402 // (PtrSCEV is unused) or predicated (legacy cost includes the region).
4403 const VPRegionBlock *ParentRegion = getRegion();
4404 if (!Ctx.Opts.force_vplan_cost_model && !isSingleScalar() &&
4405 (!ParentRegion || !ParentRegion->isReplicator()))
4406 return Ctx.getLegacyCost(UI, VF);
4407 PtrSCEV = nullptr;
4408 }
4409
4410 Type *ValTy = vputils::getLoadStoreValueType(this);
4411 Type *ScalarPtrTy = PtrOp->getScalarType();
4412 const Align Alignment = getLoadStoreAlignment(UI);
4413 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
4415 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
4416 bool UsedByLoadStoreAddress =
4417 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
4418 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
4419 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
4420 UsedByLoadStoreAddress ? UI : nullptr);
4421
4422 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
4423 InstructionCost ScalarCost =
4424 ScalarMemOpCost +
4425 Ctx.TTI.getAddressComputationCost(
4426 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
4427 Ctx.CostKind);
4428 if (isSingleScalar())
4429 return ScalarCost;
4430
4431 SmallVector<const VPValue *> OpsToScalarize;
4432 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
4433 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
4434 // don't assign scalarization overhead in general, if the target prefers
4435 // vectorized addressing or the loaded value is used as part of an address
4436 // of another load or store.
4437 if (!UsedByLoadStoreAddress) {
4438 bool EfficientVectorLoadStore =
4439 Ctx.TTI.supportsEfficientVectorElementLoadStore();
4440 if (!(IsLoad && !PreferVectorizedAddressing) &&
4441 !(!IsLoad && EfficientVectorLoadStore))
4442 append_range(OpsToScalarize, operands());
4443
4444 if (!EfficientVectorLoadStore)
4445 ResultTy = this->getScalarType();
4446 }
4447
4449 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
4451 (ScalarCost * VF.getFixedValue()) +
4452 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
4453
4454 const VPRegionBlock *ParentRegion = getRegion();
4455 if (ParentRegion && ParentRegion->isReplicator()) {
4456 // The cost of the branches is accounted for by the replicate region.
4457 Cost /= Ctx.getCostDivisor(
4458 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4459
4460 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
4461 // Artificially setting to a high enough value to practically disable
4462 // vectorization with such operations.
4463 return 3000000;
4464 }
4465 }
4466 return Cost;
4467 }
4468 case Instruction::ExtractValue:
4469 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
4470 default:
4471 // This opcode is unknown. Assume that it is the same as 'mul'.
4472 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4473 this->getScalarType(), Ctx.CostKind) *
4474 (isSingleScalar() ? 1 : VF.getFixedValue());
4475 }
4476}
4477
4479 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
4480 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
4482 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
4483
4484 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
4485 auto GetIntrinsicCost = [&] {
4486 if (!IntrinID)
4488 return Ctx.TTI.getIntrinsicInstrCost(
4489 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4490 };
4491
4492 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4493 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4494 return 0;
4495 }
4496
4497 InstructionCost ScalarCallCost =
4498 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4499 if (IsSingleScalar) {
4500 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4501 return ScalarCallCost;
4502 }
4503
4504 // Scalarization overhead is undefined for scalable VFs.
4505 if (VF.isScalable())
4507
4508 return ScalarCallCost * VF.getFixedValue() +
4509 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4510}
4511
4512#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4514 VPSlotTracker &SlotTracker) const {
4515 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4516
4517 if (!getScalarType()->isVoidTy()) {
4519 O << " = ";
4520 }
4521 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4522 O << "call";
4523 printFlags(O);
4524 O << "@" << CB->getCalledFunction()->getName() << "(";
4526 Op->printAsOperand(O, SlotTracker);
4527 });
4528 O << ")";
4529 } else {
4531 printFlags(O);
4533 }
4534
4535 // Find if the recipe is used by a widened recipe via an intervening
4536 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4537 if (any_of(users(), [](const VPUser *U) {
4538 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4539 return !vputils::onlyScalarValuesUsed(PredR);
4540 return false;
4541 }))
4542 O << " (S->V)";
4543}
4544#endif
4545
4547 llvm_unreachable("recipe must be removed when dissolving replicate region");
4548}
4549
4551 VPCostContext &Ctx) const {
4552 // Replicating isn't supported for scalable vectors.
4553 if (VF.isScalable())
4555 auto *VecI1Ty = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
4556 return Ctx.TTI.getScalarizationOverhead(
4557 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4558 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind) +
4559 VF.getFixedValue() *
4560 Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
4561}
4562
4564 llvm_unreachable("recipe must be removed when dissolving replicate region");
4565}
4566
4567#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4569 VPSlotTracker &SlotTracker) const {
4570 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4572 O << " = ";
4574}
4575#endif
4576
4578const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4579
4582
4584const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4585
4588
4590 VPCostContext &Ctx) const {
4591 const VPRecipeBase *R = getAsRecipe();
4593 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4594 : R->getOperand(1)->getScalarType();
4595 Type *Ty = toVectorTy(ScalarTy, VF);
4596 unsigned AS =
4597 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4598 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4599
4600 if (!Consecutive) {
4601 // TODO: Using the original IR may not be accurate.
4602 // Currently, ARM will use the underlying IR to calculate gather/scatter
4603 // instruction cost.
4604 Type *PtrTy = getAddr()->getScalarType();
4605 const Value *Ptr = getAddr()->getUnderlyingValue();
4606
4607 // If the address value is uniform across all lanes, then the address can be
4608 // calculated with scalar type and broadcast.
4610 PtrTy = toVectorTy(PtrTy, VF);
4611
4612 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4613 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4614 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4615 : Intrinsic::vp_scatter;
4616 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4617 Ctx.CostKind) +
4618 Ctx.TTI.getMemIntrinsicInstrCost(
4620 &Ingredient),
4621 Ctx.CostKind);
4622 }
4623
4625 if (IsMasked) {
4626 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4627 : Intrinsic::masked_store;
4628 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4629 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4630 } else {
4631 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4633 : R->getOperand(1));
4634 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4635 OpInfo, &Ingredient);
4636 }
4637 return Cost;
4638}
4639
4641 Type *ScalarDataTy = getScalarType();
4642 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4643 bool CreateGather = !isConsecutive();
4644
4645 auto &Builder = State.Builder;
4646 Value *Mask = nullptr;
4647 if (auto *VPMask = getMask())
4648 Mask = State.get(VPMask);
4649
4650 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateGather);
4651 Value *NewLI;
4652 if (CreateGather) {
4653 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4654 "wide.masked.gather");
4655 } else if (Mask) {
4656 NewLI =
4657 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4658 PoisonValue::get(DataTy), "wide.masked.load");
4659 } else {
4660 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4661 }
4663 State.set(this, NewLI);
4664}
4665
4666#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4668 VPSlotTracker &SlotTracker) const {
4669 O << Indent << "WIDEN ";
4671 O << " = load ";
4673 O << ", align " << getAlign().value();
4674}
4675#endif
4676
4678 Type *ScalarDataTy = getScalarType();
4679 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4680 bool CreateGather = !isConsecutive();
4681
4682 auto &Builder = State.Builder;
4683 CallInst *NewLI;
4684 Value *EVL = State.get(getEVL(), VPLane(0));
4685 Value *Addr = State.get(getAddr(), !CreateGather);
4686 Value *Mask = nullptr;
4687 if (VPValue *VPMask = getMask())
4688 Mask = State.get(VPMask);
4689 else
4690 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4691
4692 if (CreateGather) {
4693 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4694 {Addr, Mask, EVL}, nullptr,
4695 "wide.masked.gather");
4696 } else {
4697 NewLI = Builder.CreateIntrinsicWithoutFolding(
4698 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4699 }
4700 NewLI->addParamAttr(
4702 applyMetadata(*NewLI);
4703 State.set(this, NewLI);
4704}
4705
4707 VPCostContext &Ctx) const {
4708 if (!Consecutive || IsMasked)
4709 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4710
4711 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4712 // here because the EVL recipes using EVL to replace the tail mask. But in the
4713 // legacy model, it will always calculate the cost of mask.
4714 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4715 // don't need to compare to the legacy cost model.
4716 Type *Ty = toVectorTy(getScalarType(), VF);
4717 unsigned AS =
4718 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4719 return Ctx.TTI.getMemIntrinsicInstrCost(
4720 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4721 Ctx.CostKind);
4722}
4723
4724#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4726 VPSlotTracker &SlotTracker) const {
4727 O << Indent << "WIDEN ";
4729 O << " = vp.load ";
4731 O << ", align " << getAlign().value();
4732}
4733#endif
4734
4736 VPValue *StoredVPValue = getStoredValue();
4737 bool CreateScatter = !isConsecutive();
4738
4739 auto &Builder = State.Builder;
4740
4741 Value *Mask = nullptr;
4742 if (auto *VPMask = getMask())
4743 Mask = State.get(VPMask);
4744
4745 Value *StoredVal = State.get(StoredVPValue);
4746 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateScatter);
4747 Instruction *NewSI = nullptr;
4748 if (CreateScatter)
4749 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4750 else if (Mask)
4751 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4752 else
4753 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4754 applyMetadata(*NewSI);
4755}
4756
4757#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4759 VPSlotTracker &SlotTracker) const {
4760 O << Indent << "WIDEN store ";
4762 O << ", align " << getAlign().value();
4763}
4764#endif
4765
4767 VPValue *StoredValue = getStoredValue();
4768 bool CreateScatter = !isConsecutive();
4769
4770 auto &Builder = State.Builder;
4771
4772 CallInst *NewSI = nullptr;
4773 Value *StoredVal = State.get(StoredValue);
4774 Value *EVL = State.get(getEVL(), VPLane(0));
4775 Value *Mask = nullptr;
4776 if (VPValue *VPMask = getMask())
4777 Mask = State.get(VPMask);
4778 else
4779 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4780
4781 Value *Addr = State.get(getAddr(), !CreateScatter);
4782 if (CreateScatter) {
4783 NewSI = Builder.CreateIntrinsicWithoutFolding(
4784 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4785 {StoredVal, Addr, Mask, EVL});
4786 } else {
4787 NewSI = Builder.CreateIntrinsicWithoutFolding(
4788 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4789 {StoredVal, Addr, Mask, EVL});
4790 }
4791 NewSI->addParamAttr(
4793 applyMetadata(*NewSI);
4794}
4795
4797 VPCostContext &Ctx) const {
4798 if (!Consecutive || IsMasked)
4799 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4800
4801 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4802 // here because the EVL recipes using EVL to replace the tail mask. But in the
4803 // legacy model, it will always calculate the cost of mask.
4804 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4805 // don't need to compare to the legacy cost model.
4806 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4807 unsigned AS =
4808 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4809 return Ctx.TTI.getMemIntrinsicInstrCost(
4810 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4811 Ctx.CostKind);
4812}
4813
4814#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4816 VPSlotTracker &SlotTracker) const {
4817 O << Indent << "WIDEN vp.store ";
4819 O << ", align " << getAlign().value();
4820}
4821#endif
4822
4824 VectorType *DstVTy, const DataLayout &DL) {
4825 // Verify that V is a vector type with same number of elements as DstVTy.
4826 auto VF = DstVTy->getElementCount();
4827 auto *SrcVecTy = cast<VectorType>(V->getType());
4828 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4829 Type *SrcElemTy = SrcVecTy->getElementType();
4830 Type *DstElemTy = DstVTy->getElementType();
4831 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4832 "Vector elements must have same size");
4833
4834 // Do a direct cast if element types are castable.
4835 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4836 return Builder.CreateBitOrPointerCast(V, DstVTy);
4837 }
4838 // V cannot be directly casted to desired vector type.
4839 // May happen when V is a floating point vector but DstVTy is a vector of
4840 // pointers or vice-versa. Handle this using a two-step bitcast using an
4841 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4842 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4843 "Only one type should be a pointer type");
4844 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4845 "Only one type should be a floating point type");
4846 Type *IntTy =
4847 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4848 auto *VecIntTy = VectorType::get(IntTy, VF);
4849 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4850 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4851}
4852
4853/// Return a vector containing interleaved elements from multiple
4854/// smaller input vectors.
4856 const Twine &Name) {
4857 unsigned Factor = Vals.size();
4858 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4859
4860 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4861#ifndef NDEBUG
4862 for (Value *Val : Vals)
4863 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4864#endif
4865
4866 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4867 // must use intrinsics to interleave.
4868 if (VecTy->isScalableTy()) {
4869 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4870 return Builder.CreateVectorInterleave(Vals, Name);
4871 }
4872
4873 // Fixed length. Start by concatenating all vectors into a wide vector.
4874 Value *WideVec = concatenateVectors(Builder, Vals);
4875
4876 // Interleave the elements into the wide vector.
4877 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4878 return Builder.CreateShuffleVector(
4879 WideVec, createInterleaveMask(NumElts, Factor), Name);
4880}
4881
4882// Try to vectorize the interleave group that \p Instr belongs to.
4883//
4884// E.g. Translate following interleaved load group (factor = 3):
4885// for (i = 0; i < N; i+=3) {
4886// R = Pic[i]; // Member of index 0
4887// G = Pic[i+1]; // Member of index 1
4888// B = Pic[i+2]; // Member of index 2
4889// ... // do something to R, G, B
4890// }
4891// To:
4892// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4893// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4894// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4895// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4896//
4897// Or translate following interleaved store group (factor = 3):
4898// for (i = 0; i < N; i+=3) {
4899// ... do something to R, G, B
4900// Pic[i] = R; // Member of index 0
4901// Pic[i+1] = G; // Member of index 1
4902// Pic[i+2] = B; // Member of index 2
4903// }
4904// To:
4905// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4906// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4907// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4908// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4909// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4911 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4912 "Masking gaps for scalable vectors is not yet supported.");
4914 Instruction *Instr = Group->getInsertPos();
4915
4916 // Prepare for the vector type of the interleaved load/store.
4917 Type *ScalarTy = getLoadStoreType(Instr);
4918 unsigned InterleaveFactor = Group->getFactor();
4919 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4920
4921 VPValue *BlockInMask = getMask();
4922 VPValue *Addr = getAddr();
4923 Value *ResAddr = State.get(Addr, VPLane(0));
4924
4925 auto CreateGroupMask = [&BlockInMask, &State,
4926 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4927 if (State.VF.isScalable()) {
4928 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4929 assert(InterleaveFactor <= 8 &&
4930 "Unsupported deinterleave factor for scalable vectors");
4931 auto *ResBlockInMask = State.get(BlockInMask);
4932 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4933 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4934 }
4935
4936 if (!BlockInMask)
4937 return MaskForGaps;
4938
4939 Value *ResBlockInMask = State.get(BlockInMask);
4940 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4941 ResBlockInMask,
4942 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4943 "interleaved.mask");
4944 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4945 ShuffledMask, MaskForGaps)
4946 : ShuffledMask;
4947 };
4948
4949 const DataLayout &DL = Instr->getDataLayout();
4950 // Vectorize the interleaved load group.
4951 if (isa<LoadInst>(Instr)) {
4952 Value *MaskForGaps = nullptr;
4953 if (needsMaskForGaps()) {
4954 MaskForGaps =
4955 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4956 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4957 }
4958
4959 Instruction *NewLoad;
4960 if (BlockInMask || MaskForGaps) {
4961 Value *GroupMask = CreateGroupMask(MaskForGaps);
4962 Value *PoisonVec = PoisonValue::get(VecTy);
4963 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4964 Group->getAlign(), GroupMask,
4965 PoisonVec, "wide.masked.vec");
4966 } else
4967 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4968 Group->getAlign(), "wide.vec");
4969 applyMetadata(*NewLoad);
4970 // TODO: Also manage existing metadata using VPIRMetadata.
4971 Group->addMetadata(NewLoad);
4972
4974 if (VecTy->isScalableTy()) {
4975 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4976 // so must use intrinsics to deinterleave.
4977 assert(InterleaveFactor <= 8 &&
4978 "Unsupported deinterleave factor for scalable vectors");
4979 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4980 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4981 NewLoad->getType(), NewLoad,
4982 /*FMFSource=*/nullptr, "strided.vec");
4983 }
4984
4985 auto CreateStridedVector = [&InterleaveFactor, &State,
4986 &NewLoad](unsigned Index) -> Value * {
4987 assert(Index < InterleaveFactor && "Illegal group index");
4988 if (State.VF.isScalable())
4989 return State.Builder.CreateExtractValue(NewLoad, Index);
4990
4991 // For fixed length VF, use shuffle to extract the sub-vectors from the
4992 // wide load.
4993 auto StrideMask =
4994 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4995 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4996 "strided.vec");
4997 };
4998
4999 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
5000 Instruction *Member = Group->getMember(I);
5001
5002 // Skip the gaps in the group.
5003 if (!Member)
5004 continue;
5005
5006 Value *StridedVec = CreateStridedVector(I);
5007
5008 // If this member has different type, cast the result type.
5009 if (Member->getType() != ScalarTy) {
5010 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
5011 StridedVec =
5012 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
5013 }
5014
5015 if (Group->isReverse())
5016 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
5017
5018 State.set(VPDefs[J], StridedVec);
5019 ++J;
5020 }
5021 return;
5022 }
5023
5024 // The sub vector type for current instruction.
5025 auto *SubVT = VectorType::get(ScalarTy, State.VF);
5026
5027 // Vectorize the interleaved store group.
5028 Value *MaskForGaps =
5029 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
5030 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
5031 "Mismatch between NeedsMaskForGaps and MaskForGaps");
5032 ArrayRef<VPValue *> StoredValues = getStoredValues();
5033 // Collect the stored vector from each member.
5034 SmallVector<Value *, 4> StoredVecs;
5035 unsigned StoredIdx = 0;
5036 for (unsigned i = 0; i < InterleaveFactor; i++) {
5037 assert((Group->getMember(i) || MaskForGaps) &&
5038 "Fail to get a member from an interleaved store group");
5039 Instruction *Member = Group->getMember(i);
5040
5041 // Skip the gaps in the group.
5042 if (!Member) {
5043 Value *Undef = PoisonValue::get(SubVT);
5044 StoredVecs.push_back(Undef);
5045 continue;
5046 }
5047
5048 Value *StoredVec = State.get(StoredValues[StoredIdx]);
5049 ++StoredIdx;
5050
5051 if (Group->isReverse())
5052 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
5053
5054 // If this member has different type, cast it to a unified type.
5055
5056 if (StoredVec->getType() != SubVT)
5057 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
5058
5059 StoredVecs.push_back(StoredVec);
5060 }
5061
5062 // Interleave all the smaller vectors into one wider vector.
5063 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
5064 Instruction *NewStoreInstr;
5065 if (BlockInMask || MaskForGaps) {
5066 Value *GroupMask = CreateGroupMask(MaskForGaps);
5067 NewStoreInstr = State.Builder.CreateMaskedStore(
5068 IVec, ResAddr, Group->getAlign(), GroupMask);
5069 } else
5070 NewStoreInstr =
5071 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
5072
5073 applyMetadata(*NewStoreInstr);
5074 // TODO: Also manage existing metadata using VPIRMetadata.
5075 Group->addMetadata(NewStoreInstr);
5076}
5077
5078#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5080 VPSlotTracker &SlotTracker) const {
5082 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
5084 VPValue *Mask = getMask();
5085 if (Mask) {
5086 O << ", ";
5087 Mask->printAsOperand(O, SlotTracker);
5088 }
5089
5090 unsigned OpIdx = 0;
5091 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5092 if (!IG->getMember(i))
5093 continue;
5094 if (getNumStoreOperands() > 0) {
5095 O << "\n" << Indent << " store ";
5096 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
5097 O << " to index " << i;
5098 } else {
5099 O << "\n" << Indent << " ";
5101 O << " = load from index " << i;
5102 }
5103 ++OpIdx;
5104 }
5105}
5106#endif
5107
5109 assert(State.VF.isScalable() &&
5110 "Only support scalable VF for EVL tail-folding.");
5112 "Masking gaps for scalable vectors is not yet supported.");
5114 Instruction *Instr = Group->getInsertPos();
5115
5116 // Prepare for the vector type of the interleaved load/store.
5117 Type *ScalarTy = getLoadStoreType(Instr);
5118 unsigned InterleaveFactor = Group->getFactor();
5119 assert(InterleaveFactor <= 8 &&
5120 "Unsupported deinterleave/interleave factor for scalable vectors");
5121 ElementCount WideVF = State.VF * InterleaveFactor;
5122 auto *VecTy = VectorType::get(ScalarTy, WideVF);
5123
5124 VPValue *Addr = getAddr();
5125 Value *ResAddr = State.get(Addr, VPLane(0));
5126 Value *EVL = State.get(getEVL(), VPLane(0));
5127 Value *InterleaveEVL = State.Builder.CreateMul(
5128 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
5129 /* NUW= */ true, /* NSW= */ true);
5130 LLVMContext &Ctx = State.Builder.getContext();
5131
5132 Value *GroupMask = nullptr;
5133 if (VPValue *BlockInMask = getMask()) {
5134 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
5135 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
5136 } else {
5137 GroupMask =
5138 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
5139 }
5140
5141 // Vectorize the interleaved load group.
5142 if (isa<LoadInst>(Instr)) {
5143 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5144 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
5145 "wide.vp.load");
5146 NewLoad->addParamAttr(0,
5147 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5148
5149 applyMetadata(*NewLoad);
5150 // TODO: Also manage existing metadata using VPIRMetadata.
5151 Group->addMetadata(NewLoad);
5152
5153 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
5154 // so must use intrinsics to deinterleave.
5155 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5156 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
5157 NewLoad->getType(), NewLoad,
5158 /*FMFSource=*/nullptr, "strided.vec");
5159
5160 const DataLayout &DL = Instr->getDataLayout();
5161 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
5162 Instruction *Member = Group->getMember(I);
5163 // Skip the gaps in the group.
5164 if (!Member)
5165 continue;
5166
5167 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
5168 // If this member has different type, cast the result type.
5169 if (Member->getType() != ScalarTy) {
5170 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
5171 StridedVec =
5172 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
5173 }
5174
5175 State.set(getVPValue(J), StridedVec);
5176 ++J;
5177 }
5178 return;
5179 } // End for interleaved load.
5180
5181 // The sub vector type for current instruction.
5182 auto *SubVT = VectorType::get(ScalarTy, State.VF);
5183 // Vectorize the interleaved store group.
5184 ArrayRef<VPValue *> StoredValues = getStoredValues();
5185 // Collect the stored vector from each member.
5186 SmallVector<Value *, 4> StoredVecs;
5187 const DataLayout &DL = Instr->getDataLayout();
5188 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
5189 Instruction *Member = Group->getMember(I);
5190 // Skip the gaps in the group.
5191 if (!Member) {
5192 StoredVecs.push_back(PoisonValue::get(SubVT));
5193 continue;
5194 }
5195
5196 Value *StoredVec = State.get(StoredValues[StoredIdx]);
5197 // If this member has different type, cast it to a unified type.
5198 if (StoredVec->getType() != SubVT)
5199 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
5200
5201 StoredVecs.push_back(StoredVec);
5202 ++StoredIdx;
5203 }
5204
5205 // Interleave all the smaller vectors into one wider vector.
5206 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
5207 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
5208 Type::getVoidTy(Ctx), Intrinsic::vp_store,
5209 {IVec, ResAddr, GroupMask, InterleaveEVL});
5210
5211 NewStore->addParamAttr(1,
5212 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5213
5214 applyMetadata(*NewStore);
5215 // TODO: Also manage existing metadata using VPIRMetadata.
5216 Group->addMetadata(NewStore);
5217}
5218
5219#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5221 VPSlotTracker &SlotTracker) const {
5223 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
5225 O << ", ";
5227 if (VPValue *Mask = getMask()) {
5228 O << ", ";
5229 Mask->printAsOperand(O, SlotTracker);
5230 }
5231
5232 unsigned OpIdx = 0;
5233 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5234 if (!IG->getMember(i))
5235 continue;
5236 if (getNumStoreOperands() > 0) {
5237 O << "\n" << Indent << " vp.store ";
5238 getOperand(2 + OpIdx)->printAsOperand(O, SlotTracker);
5239 O << " to index " << i;
5240 } else {
5241 O << "\n" << Indent << " ";
5243 O << " = vp.load from index " << i;
5244 }
5245 ++OpIdx;
5246 }
5247}
5248#endif
5249
5251 VPCostContext &Ctx) const {
5252 Instruction *InsertPos = getInsertPos();
5253 // Find the VPValue index of the interleave group. We need to skip gaps.
5254 unsigned InsertPosIdx = 0;
5255 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
5256 if (auto *Member = IG->getMember(Idx)) {
5257 if (Member == InsertPos)
5258 break;
5259 InsertPosIdx++;
5260 }
5261 const VPValue *ValV = getNumDefinedValues() > 0
5262 ? getVPValue(InsertPosIdx)
5263 : getStoredValues()[InsertPosIdx];
5264 Type *ValTy = ValV->getScalarType();
5265 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5266 unsigned AS =
5267 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
5268
5269 unsigned InterleaveFactor = IG->getFactor();
5270 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5271
5272 // Holds the indices of existing members in the interleaved group.
5274 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5275 if (IG->getMember(IF))
5276 Indices.push_back(IF);
5277
5278 // Calculate the cost of the whole interleaved group.
5279 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
5280 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
5281 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
5282
5283 if (!IG->isReverse())
5284 return Cost;
5285
5286 return Cost + IG->getNumMembers() *
5287 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5288 VectorTy, VectorTy, Ctx.CostKind, {},
5289 0);
5290}
5291
5294 VPCostContext &Ctx) const {
5295 // The recipe creates a scalar phi, a GEP to increment the induction and
5296 // vector add to compute the vector of pointers.
5297 // TODO: Charge costs for induction increment and vector add as well.
5298 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5299}
5300
5305
5306#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5308 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5309 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
5310 "unexpected number of operands");
5311 O << Indent << "EMIT ";
5313 O << " = WIDEN-POINTER-INDUCTION ";
5315 O << ", ";
5317 O << ", ";
5319 if (getNumOperands() == 5) {
5320 O << ", ";
5322 O << ", ";
5324 }
5325}
5326
5328 VPSlotTracker &SlotTracker) const {
5329 O << Indent << "EMIT ";
5331 O << " = EXPAND SCEV " << *Expr;
5332 if (ExpandInIR)
5333 O << " (in IR)";
5334}
5335#endif
5336
5337#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5339 VPSlotTracker &SlotTracker) const {
5340 O << Indent << "EMIT ";
5342 O << " = WIDEN-CANONICAL-INDUCTION";
5343 printFlags(O);
5345}
5346#endif
5347
5349 auto &Builder = State.Builder;
5350 // Create a vector from the initial value.
5351 auto *VectorInit = getStartValue()->getLiveInIRValue();
5352
5353 Type *VecTy = State.VF.isScalar()
5354 ? VectorInit->getType()
5355 : VectorType::get(VectorInit->getType(), State.VF);
5356
5357 BasicBlock *VectorPH =
5358 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5359 if (State.VF.isVector()) {
5360 auto *IdxTy = Builder.getInt32Ty();
5361 auto *One = ConstantInt::get(IdxTy, 1);
5362 IRBuilder<>::InsertPointGuard Guard(Builder);
5363 Builder.SetInsertPoint(VectorPH->getTerminator());
5364 auto *RuntimeVF = Builder.CreateElementCount(IdxTy, State.VF);
5365 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
5366 VectorInit = Builder.CreateInsertElement(
5367 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
5368 }
5369
5370 // Create a phi node for the new recurrence.
5371 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
5372 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
5373 Phi->addIncoming(VectorInit, VectorPH);
5374 State.set(this, Phi);
5375}
5376
5379 VPCostContext &Ctx) const {
5380 if (VF.isScalar())
5381 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5382
5383 return 0;
5384}
5385
5386#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5388 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5389 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
5391 O << " = phi ";
5393}
5394#endif
5395
5397 // Reductions do not have to start at zero. They can start with
5398 // any loop invariant values.
5399 VPValue *StartVPV = getStartValue();
5400
5401 // In order to support recurrences we need to be able to vectorize Phi nodes.
5402 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
5403 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
5404 // this value when we vectorize all of the instructions that use the PHI.
5405 BasicBlock *VectorPH =
5406 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5407 bool ScalarPHI = State.VF.isScalar() || isInLoop();
5408 Value *StartV = State.get(StartVPV, ScalarPHI);
5409 Type *VecTy = StartV->getType();
5410
5411 BasicBlock *HeaderBB = State.CFG.PrevBB;
5412 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
5413 "recipe must be in the vector loop header");
5414 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
5415 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
5416 State.set(this, Phi, isInLoop());
5417
5418 Phi->addIncoming(StartV, VectorPH);
5419}
5420
5421#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5423 VPSlotTracker &SlotTracker) const {
5424 O << Indent << "WIDEN-REDUCTION-PHI ";
5425
5427 O << " = phi (";
5428 printRecurrenceKind(O, Kind);
5429 O << ")";
5430 printFlags(O);
5432 if (getVFScaleFactor() > 1)
5433 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
5434}
5435#endif
5436
5438 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
5440 "Blend should propagate first lane use");
5441 return vputils::onlyFirstLaneUsed(this);
5442}
5443
5444#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5446 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5447 O << Indent << "CONDITIONAL-INDUCTION-PHI ";
5448
5450 O << " = phi ";
5452}
5453#endif
5454
5456 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
5457}
5458
5460 VPCostContext &Ctx) const {
5461 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5462}
5463
5464#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5466 VPSlotTracker &SlotTracker) const {
5467 O << Indent << "WIDEN-PHI ";
5468
5470 O << " = phi ";
5472}
5473#endif
5474
5476 BasicBlock *VectorPH =
5477 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5478 Value *StartMask = State.get(getOperand(0));
5479 PHINode *Phi =
5480 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
5481 Phi->addIncoming(StartMask, VectorPH);
5482 State.set(this, Phi);
5483}
5484
5485#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5487 VPSlotTracker &SlotTracker) const {
5488 O << Indent << "ACTIVE-LANE-MASK-PHI ";
5489
5491 O << " = phi ";
5493}
5494#endif
5495
5496#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5498 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5499 O << Indent << "CURRENT-ITERATION-PHI ";
5500
5502 O << " = phi ";
5504}
5505#endif
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
bool IsScalable
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
AMDGPU Lower Kernel Arguments
AMDGPU Register Bank Select
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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[]
SmallVector< MachineOperand, 4 > Cond
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 MachineInstr &MI)
static bool isOrdered(const Instruction *I)
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
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 AttributeSet getCalleeFnAttrs(const VPInstruction &VPI)
Return the function attributes of the callee of VPI, which must be a call or intrinsic VPInstruction.
static const ConstantFP * getConstantFP(const VPValue *V)
Returns the ConstantFP V wraps, or nullptr if it does not wrap one.
static SmallVector< unsigned > getExtractValueIndices(ArrayRef< VPValue * > Ops)
static void executePhiRecipe(VPSingleDefRecipe *R, VPPhiAccessors &Phi, VPTransformState &State, bool IsScalar, const Twine &Name)
Shared execute logic for VPPhi and VPWidenPHIRecipe.
static bool alwaysGeneratesSingleScalar(unsigned Opcode)
Returns true if VPInstructions with Opcode always generate a single scalar.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
static Instruction::BinaryOps getSubRecurOpcode(RecurKind Kind)
static Function * getCalledFunction(ArrayRef< VPValue * > Operands)
For call VPInstruction operands, return the called function.
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:
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
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 stores enough information to efficiently remove some attributes from an existing AttrBuild...
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
bool hasAttributes() const
Return true if attributes exists in this set.
Definition Attributes.h:526
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:529
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
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:61
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:236
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:549
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)
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:63
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
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:321
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:309
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
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
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
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
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:577
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:111
const DataLayout & getDataLayout() const
Get data layout.
Definition IRBuilder.h:182
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:513
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
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 ...
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1940
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:1218
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.
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
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:2814
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:528
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1114
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2094
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2360
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:289
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:2462
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:476
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1772
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:471
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2595
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1856
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2458
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1156
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
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.
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:456
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2470
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1780
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1959
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
LLVM_ABI Value * CreateStepVector(Type *DstType, const Twine &Name="")
Creates a vector of type DstType with the linear sequence <0, 1, ...>
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2230
Value * CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, Value *Idx, const Twine &Name="")
Create a call to the vector.insert intrinsic.
Definition IRBuilder.h:1128
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1458
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.
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
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.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI void dropPoisonGeneratingAttributes()
Drops attributes that may generate poison.
LLVM_ABI void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef< unsigned > KnownIDs={})
This function drops non-debug unknown metadata (through dropUnknownNonDebugMetadata).
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:333
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:76
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1087
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
Information for memory intrinsic cost model.
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
Root of the metadata hierarchy.
Definition Metadata.h:65
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(cond,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.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
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.
@ 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:295
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:294
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:267
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
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:298
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
unsigned getNumOperands() const
Definition User.h:229
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:4509
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:3065
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3060
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:3056
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:79
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:212
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.
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.
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:572
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:545
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:557
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:567
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4317
VPValue * getIndex() const
Definition VPlan.h:4314
VPValue * getStepValue() const
Definition VPlan.h:4315
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:4313
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR=false)
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 usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
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:2502
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:2217
void printFnAttrs(raw_ostream &O) const
Print function attributes carried with this object.
void printRetAttrs(raw_ostream &O) const
Print return-value attributes carried with this object.
MemoryEffects getMemoryEffects(AttributeSet CalleeFnAttrs) const
Returns the memory effects of a call with these attributes to a callee with function attributes Calle...
Definition VPlan.h:1281
VPIRAttributes()=default
void intersectAttrs(const VPIRAttributes &Other, LLVMContext &Ctx)
Keep only the attributes valid for both this and Other.
void printParamAttrs(raw_ostream &O, unsigned ArgIdx) const
Print per-arg attributes for argument ArgIdx.
void applyAttrs(CallInst &WideCall) const
Apply the stored attributes to the widened call WideCall.
Definition VPlan.h:1275
Class to record and manage LLVM IR flags.
Definition VPlan.h:667
FastMathFlagsTy FMFs
Definition VPlan.h:759
ReductionFlagsTy ReductionFlags
Definition VPlan.h:761
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:753
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:962
static LLVM_ABI_FOR_TEST 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:1023
TruncFlagsTy TruncFlags
Definition VPlan.h:754
CmpInst::Predicate getPredicate() const
Definition VPlan.h:934
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:756
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:757
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:952
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:957
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:755
FCmpFlagsTy FCmpFlags
Definition VPlan.h:760
NonNegFlagsTy NonNegFlags
Definition VPlan.h:758
bool isReductionInLoop() const
Definition VPlan.h:1029
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:899
uint8_t CmpPredStorage
Definition VPlan.h:752
RecurKind getRecurKind() const
Definition VPlan.h:1017
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:1735
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:1189
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:1310
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPInstruction.
bool doesGenerateSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:1596
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:1424
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1436
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1414
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1428
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1432
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1418
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1365
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1410
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1360
@ CanonicalIVIncrementForPart
Definition VPlan.h:1346
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1368
bool hasResult() const
Definition VPlan.h:1536
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
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={}, std::optional< bool > GeneratesSingleScalar=std::nullopt)
unsigned getOpcode() const
Definition VPlan.h:1518
bool usesFirstPartOnly() const override
Returns true if the recipe only uses the first part of all operands.
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.
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1565
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:1539
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:3169
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3173
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3171
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3163
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3188
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3157
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3262
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:3275
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:3225
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
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.
LLVM_ABI_FOR_TEST 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:1664
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:386
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
void moveBefore(RecipeListTy::iterator I)
Unlink this recipe and insert it before I.
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:4914
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:107
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:499
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...
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:531
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.
VPRecipeBase(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:446
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:349
friend class VPValue
Definition VPlanValue.h:328
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:3436
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:2920
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2939
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:3375
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:3388
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3390
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3371
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3377
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3386
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3381
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:4740
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4816
const VPBranchOnMaskRecipe * getEntryBranchOnMask() const
Return the VPBranchOnMaskRecipe from the entry block of this replicating region.
Definition VPlan.cpp:702
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:3515
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:3553
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:4372
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4380
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:589
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:652
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, Value *UV=nullptr, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:591
LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
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:212
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1513
operand_range operands()
Definition VPlanValue.h:472
unsigned getNumOperands() const
Definition VPlanValue.h:436
operand_iterator op_begin()
Definition VPlanValue.h:468
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
bool operands_empty() const
Definition VPlanValue.h:476
VPValue * getLastOperand() const
Returns the last operand.
Definition VPlanValue.h:443
void addOperand(VPValue *Operand)
Definition VPlanValue.h:422
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:139
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:133
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1465
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:120
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1509
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
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:2328
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:2325
int64_t getStride() const
Definition VPlan.h:2326
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2400
Type * getSourceElementType() const
Definition VPlan.h:2415
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:2402
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:2169
Function * getCalledScalarFunction() const
Definition VPlan.h:2165
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:1925
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Produce widened copies of the cast.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:2282
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:2571
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2588
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
bool isTruncated() const
Returns true if this induction is evaluated in a narrower type than the start value.
Definition VPlan.h:2670
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
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.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment, VPCostContext &Ctx)
Helper function for computing the cost of vector memory intrinsic.
Type * getAccessType(ElementCount VF) const
Returns the data type of the memory access at VF.
void execute(VPTransformState &State) override
Produce a widened version of the vector memory intrinsic.
unsigned getAddrOpIdx() const
Returns the address operand index of the VPWidenMemIntrinsicRecipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector memory intrinsic.
VPValue * getMask() const
Returns the mask of a predicated VPWidenMemIntrinsicRecipe.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3834
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3859
Instruction & Ingredient
Definition VPlan.h:3825
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3831
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3869
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3828
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3876
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3862
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 VPWidenPointerInductionRecipe.
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:1867
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4927
const DataLayout & getDataLayout() const
Definition VPlan.h:5128
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:5234
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:389
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
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:314
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.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
self_iterator getIterator()
Definition ilist_node.h:123
typename base_list_type::iterator iterator
Definition ilist.h:121
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
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:83
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.
auto m_ZExtOrTrunc(const Op0_t &Op0)
int_pred_ty< is_zero_int, 1 > m_False()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::ExplicitVectorLength, Op0_t > m_EVL(const Op0_t &Op0)
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)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
BranchProbability getExecutionProbability(BlockFrequency Freq)
Returns Freq as a BranchProbability, relative to the full mass.
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,...
Intrinsic::ID getIntrinsicID(const Ty *R)
Return the intrinsic ID underlying a call.
Definition VPlanUtils.h:103
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used by all users.
bool propagatesFirstLaneUse(const VPUser *U, const VPValue *Op)
Returns true if checking whether U uses the first lane of Op requires recursively checking Op's users...
Type * getLoadStoreValueType(const VPSingleDefRecipe *R)
Get the value type of a VPInstruction or VPReplicateRecipe load or store.
Definition VPlanUtils.h:253
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.
LLVM_ABI_FOR_TEST 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:316
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:846
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:1755
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:2575
LLVM_ABI std::optional< unsigned > getVectorStoreIntrinsicDataArgIdx(Intrinsic::ID ID)
Returns the argument index of the data value of the vector store intrinsic ID, or std::nullopt if the...
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.
VPBuilderBase<> VPBuilder
Definition VPlan.h:65
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2334
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:1762
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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:376
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:1769
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
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
@ Other
Any other memory.
Definition ModRef.h:68
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.
LLVM_ABI std::optional< unsigned > getVectorMemoryIntrinsicPointerArgIdx(Intrinsic::ID ID)
Returns the argument index of the pointer parameter for the vector memory intrinsic ID,...
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.
@ FMaxSelectNoFMF
FMax as select(cmp()) lacking nnan or nsz, on IEEE types with IEEE denormals.
@ 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(cond,x,y) where one of (x,y) is loop invariant, and both x and y are inte...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max as select(cmp()) with nnan/nsz, or llvm.maxnum.
@ FMinSelectNoFMF
FMin as select(cmp()) lacking nnan or nsz, on IEEE types with IEEE denormals.
@ 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 as select(cmp()) with nnan/nsz, or llvm.minnum.
@ 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 std::optional< unsigned > getVectorIntrinsicMaskArgIdx(Intrinsic::ID ID)
Returns the argument index of the mask for the vector intrinsic ID, or std::nullopt if the intrinsic ...
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
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
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:2210
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
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
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
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:1925
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:1128
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
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:1790
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
PHINode & getIRPhi() const
Definition VPlan.h:1803
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
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.
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1080
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
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
Value * get(const VPValue *Def, bool NeedsSingleScalar=false)
Get the generated vector Value for a given VPValue Def if NeedsSingleScalar is false,...
Definition VPlan.cpp:267
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:3963
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:4066
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:4069
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:4013