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 = getRuntimeVF(Builder, 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 = getRuntimeVF(Builder, 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: Take the gather and scatter into account as well. For now we're
2709 // generating the same cost as the fallback path, but we'll likely
2710 // need to create a new TTI method for determining the cost, including
2711 // whether we can use base + vec-of-smaller-indices or just
2712 // vec-of-pointers.
2713 assert(VF.isVector() && "Invalid VF for histogram cost");
2714 Type *AddressTy = getOperand(0)->getScalarType();
2715 VPValue *IncAmt = getOperand(1);
2716 Type *IncTy = IncAmt->getScalarType();
2717 VectorType *VTy = VectorType::get(IncTy, VF);
2718
2719 // For umin/umax, there's no multiplication — the increment value is compared
2720 // directly. For add/sub/uadd.sat, assume that a non-constant update value
2721 // (or a constant != 1) requires a multiply.
2723 if (!match(IncAmt, m_One()) && UpdateKind != HistogramUpdateKind::UMax &&
2724 UpdateKind != HistogramUpdateKind::UMin)
2725 MulCost =
2726 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2727
2728 // Find the cost of the histogram operation itself.
2729 Type *PtrTy = VectorType::get(AddressTy, VF);
2730 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2731 IntrinsicCostAttributes ICA(getHistogramIntrinsicID(),
2732 Type::getVoidTy(Ctx.LLVMCtx),
2733 {PtrTy, IncTy, MaskTy});
2734
2735 // The histogram intrinsic's TTI cost already includes the update operation
2736 // (load + update + store), so no separate UpdateCost is needed.
2737 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost;
2738}
2739
2740#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2742 VPSlotTracker &SlotTracker) const {
2743 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2745
2746 switch (UpdateKind) {
2748 O << ", inc: ";
2749 break;
2751 O << ", dec: ";
2752 break;
2754 O << ", saturated inc: ";
2755 break;
2757 O << ", max: ";
2758 break;
2760 O << ", min: ";
2761 break;
2762 }
2764
2765 if (VPValue *Mask = getMask()) {
2766 O << ", mask: ";
2767 Mask->printAsOperand(O, SlotTracker);
2768 }
2769}
2770#endif
2771
2772VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2773 AllowReassoc = FMF.allowReassoc();
2774 NoNaNs = FMF.noNaNs();
2775 NoInfs = FMF.noInfs();
2776 NoSignedZeros = FMF.noSignedZeros();
2777 AllowReciprocal = FMF.allowReciprocal();
2778 AllowContract = FMF.allowContract();
2779 ApproxFunc = FMF.approxFunc();
2780}
2781
2782VPIRFlags VPIRFlags::getDefaultFlags(unsigned Opcode, Type *ResultTy) {
2783 switch (Opcode) {
2784 case Instruction::Add:
2785 case Instruction::Sub:
2786 case Instruction::Mul:
2787 case Instruction::Shl:
2789 return WrapFlagsTy(false, false);
2790 case Instruction::Trunc:
2791 return TruncFlagsTy(false, false);
2792 case Instruction::Or:
2793 return DisjointFlagsTy(false);
2794 case Instruction::AShr:
2795 case Instruction::LShr:
2796 case Instruction::UDiv:
2797 case Instruction::SDiv:
2798 return ExactFlagsTy(false);
2799 case Instruction::GetElementPtr:
2802 return GEPNoWrapFlags::none();
2803 case Instruction::ZExt:
2804 case Instruction::UIToFP:
2805 return NonNegFlagsTy(false);
2806 case Instruction::FAdd:
2807 case Instruction::FSub:
2808 case Instruction::FMul:
2809 case Instruction::FDiv:
2810 case Instruction::FRem:
2811 case Instruction::FNeg:
2812 case Instruction::FPExt:
2813 case Instruction::FPTrunc:
2814 return FastMathFlags();
2815 case Instruction::Select:
2816 case Instruction::PHI:
2817 case Instruction::Call:
2818 // Selects, phis and calls only have fast-math flags if they have a
2819 // supported floating-point result type.
2821 return FastMathFlags();
2822 return VPIRFlags();
2823 case Instruction::ICmp:
2824 case Instruction::FCmp:
2826 llvm_unreachable("opcode requires explicit flags");
2827 default:
2828 return VPIRFlags();
2829 }
2830}
2831
2832#if !defined(NDEBUG)
2833bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2834 switch (OpType) {
2835 case OperationType::OverflowingBinOp:
2836 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2837 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2838 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2839 case OperationType::Trunc:
2840 return Opcode == Instruction::Trunc;
2841 case OperationType::DisjointOp:
2842 return Opcode == Instruction::Or;
2843 case OperationType::PossiblyExactOp:
2844 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2845 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2846 case OperationType::GEPOp:
2847 return Opcode == Instruction::GetElementPtr ||
2848 Opcode == VPInstruction::PtrAdd ||
2849 Opcode == VPInstruction::WidePtrAdd;
2850 case OperationType::FPMathOp:
2851 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2852 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2853 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2854 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2855 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2856 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2857 Opcode == Instruction::UIToFP ||
2858 Opcode == VPInstruction::WideIVStep ||
2860 case OperationType::FCmp:
2861 return Opcode == Instruction::FCmp;
2862 case OperationType::NonNegOp:
2863 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2864 case OperationType::Cmp:
2865 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2866 case OperationType::ReductionOp:
2868 case OperationType::Other:
2869 return true;
2870 }
2871 llvm_unreachable("Unknown OperationType enum");
2872}
2873
2875 Type *ResultTy) const {
2876 // Handle opcodes without default flags.
2877 if (Opcode == Instruction::ICmp)
2878 return OpType == OperationType::Cmp;
2879 if (Opcode == Instruction::FCmp)
2880 return OpType == OperationType::FCmp;
2882 return OpType == OperationType::ReductionOp;
2883
2884 OperationType Required = getDefaultFlags(Opcode, ResultTy).OpType;
2885 return Required == OperationType::Other || Required == OpType;
2886}
2887#endif
2888
2889#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2890static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2891 switch (Kind) {
2892 case RecurKind::None:
2893 OS << "none";
2894 break;
2895 case RecurKind::Add:
2896 OS << "add";
2897 break;
2898 case RecurKind::Sub:
2899 OS << "sub";
2900 break;
2902 OS << "add-chain-with-subs";
2903 break;
2904 case RecurKind::Mul:
2905 OS << "mul";
2906 break;
2907 case RecurKind::Or:
2908 OS << "or";
2909 break;
2910 case RecurKind::And:
2911 OS << "and";
2912 break;
2913 case RecurKind::Xor:
2914 OS << "xor";
2915 break;
2916 case RecurKind::SMin:
2917 OS << "smin";
2918 break;
2919 case RecurKind::SMax:
2920 OS << "smax";
2921 break;
2922 case RecurKind::UMin:
2923 OS << "umin";
2924 break;
2925 case RecurKind::UMax:
2926 OS << "umax";
2927 break;
2928 case RecurKind::FAdd:
2929 OS << "fadd";
2930 break;
2932 OS << "fadd-chain-with-subs";
2933 break;
2934 case RecurKind::FSub:
2935 OS << "fsub";
2936 break;
2937 case RecurKind::FMul:
2938 OS << "fmul";
2939 break;
2940 case RecurKind::FMin:
2941 OS << "fmin";
2942 break;
2943 case RecurKind::FMax:
2944 OS << "fmax";
2945 break;
2946 case RecurKind::FMinNum:
2947 OS << "fminnum";
2948 break;
2949 case RecurKind::FMaxNum:
2950 OS << "fmaxnum";
2951 break;
2953 OS << "fminimum";
2954 break;
2956 OS << "fmaximum";
2957 break;
2959 OS << "fminimumnum";
2960 break;
2962 OS << "fmaximumnum";
2963 break;
2964 case RecurKind::FMulAdd:
2965 OS << "fmuladd";
2966 break;
2967 case RecurKind::AnyOf:
2968 OS << "any-of";
2969 break;
2970 case RecurKind::FindIV:
2971 OS << "find-iv";
2972 break;
2974 OS << "find-last";
2975 break;
2976 }
2977}
2978
2980 switch (OpType) {
2981 case OperationType::Cmp:
2983 break;
2984 case OperationType::FCmp:
2987 break;
2988 case OperationType::DisjointOp:
2989 if (DisjointFlags.IsDisjoint)
2990 O << " disjoint";
2991 break;
2992 case OperationType::PossiblyExactOp:
2993 if (ExactFlags.IsExact)
2994 O << " exact";
2995 break;
2996 case OperationType::OverflowingBinOp:
2997 if (WrapFlags.HasNUW)
2998 O << " nuw";
2999 if (WrapFlags.HasNSW)
3000 O << " nsw";
3001 break;
3002 case OperationType::Trunc:
3003 if (TruncFlags.HasNUW)
3004 O << " nuw";
3005 if (TruncFlags.HasNSW)
3006 O << " nsw";
3007 break;
3008 case OperationType::FPMathOp:
3010 break;
3011 case OperationType::GEPOp: {
3013 if (Flags.isInBounds())
3014 O << " inbounds";
3015 else if (Flags.hasNoUnsignedSignedWrap())
3016 O << " nusw";
3017 if (Flags.hasNoUnsignedWrap())
3018 O << " nuw";
3019 break;
3020 }
3021 case OperationType::NonNegOp:
3022 if (NonNegFlags.NonNeg)
3023 O << " nneg";
3024 break;
3025 case OperationType::ReductionOp: {
3026 O << " (";
3028 if (isReductionInLoop())
3029 O << ", in-loop";
3030 if (isReductionOrdered())
3031 O << ", ordered";
3032 O << ")";
3034 break;
3035 }
3036 case OperationType::Other:
3037 break;
3038 }
3039 O << " ";
3040}
3041#endif
3042
3044 auto &Builder = State.Builder;
3045 switch (Opcode) {
3046 case Instruction::Call:
3047 case Instruction::UncondBr:
3048 case Instruction::CondBr:
3049 case Instruction::PHI:
3050 case Instruction::GetElementPtr:
3051 llvm_unreachable("This instruction is handled by a different recipe.");
3052 case Instruction::UDiv:
3053 case Instruction::SDiv:
3054 case Instruction::SRem:
3055 case Instruction::URem:
3056 case Instruction::Add:
3057 case Instruction::FAdd:
3058 case Instruction::Sub:
3059 case Instruction::FSub:
3060 case Instruction::FNeg:
3061 case Instruction::Mul:
3062 case Instruction::FMul:
3063 case Instruction::FDiv:
3064 case Instruction::FRem:
3065 case Instruction::Shl:
3066 case Instruction::LShr:
3067 case Instruction::AShr:
3068 case Instruction::And:
3069 case Instruction::Or:
3070 case Instruction::Xor: {
3071 // Just widen unops and binops.
3073 for (VPValue *VPOp : operands())
3074 Ops.push_back(State.get(VPOp));
3075
3076 Value *V = Builder.CreateNAryOp(Opcode, Ops);
3077
3078 if (auto *VecOp = dyn_cast<Instruction>(V)) {
3079 applyFlags(*VecOp);
3080 applyMetadata(*VecOp);
3081 }
3082
3083 // Use this vector value for all users of the original instruction.
3084 State.set(this, V);
3085 break;
3086 }
3087 case Instruction::ExtractValue: {
3088 Value *Op = State.get(getOperand(0));
3089 Value *Extract =
3090 Builder.CreateExtractValue(Op, getExtractValueIndices(operands()));
3091 State.set(this, Extract);
3092 break;
3093 }
3094 case Instruction::Freeze: {
3095 Value *Op = State.get(getOperand(0));
3096 Value *Freeze = Builder.CreateFreeze(Op);
3097 State.set(this, Freeze);
3098 break;
3099 }
3100 case Instruction::ICmp:
3101 case Instruction::FCmp: {
3102 // Widen compares. Generate vector compares.
3103 bool FCmp = Opcode == Instruction::FCmp;
3104 Value *A = State.get(getOperand(0));
3105 Value *B = State.get(getOperand(1));
3106 Value *C = nullptr;
3107 if (FCmp) {
3108 C = Builder.CreateFCmp(getPredicate(), A, B);
3109 } else {
3110 C = Builder.CreateICmp(getPredicate(), A, B);
3111 }
3112 if (auto *I = dyn_cast<Instruction>(C)) {
3113 applyFlags(*I);
3114 applyMetadata(*I);
3115 }
3116 State.set(this, C);
3117 break;
3118 }
3119 case Instruction::Select: {
3120 VPValue *CondOp = getOperand(0);
3121 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
3122 Value *Op0 = State.get(getOperand(1));
3123 Value *Op1 = State.get(getOperand(2));
3124 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
3125 State.set(this, Sel);
3126 if (auto *I = dyn_cast<Instruction>(Sel)) {
3128 applyFlags(*I);
3129 applyMetadata(*I);
3130 }
3131 break;
3132 }
3133 default:
3134 // This instruction is not vectorized by simple widening.
3135 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
3136 << Instruction::getOpcodeName(Opcode));
3137 llvm_unreachable("Unhandled instruction!");
3138 } // end of switch.
3139
3140#if !defined(NDEBUG)
3141 // Verify that VPlan type inference results agree with the type of the
3142 // generated values.
3143 assert(VectorType::get(this->getScalarType(), State.VF) ==
3144 State.get(this)->getType() &&
3145 "inferred type and type from generated instructions do not match");
3146#endif
3147}
3148
3150 VPCostContext &Ctx) const {
3151 switch (Opcode) {
3152 case Instruction::UDiv:
3153 case Instruction::SDiv:
3154 case Instruction::SRem:
3155 case Instruction::URem:
3156 // If the div/rem operation isn't safe to speculate and requires
3157 // predication, then the only way we can even create a vplan is to insert
3158 // a select on the second input operand to ensure we use the value of 1
3159 // for the inactive lanes. The select will be costed separately.
3160 case Instruction::FNeg:
3161 case Instruction::Add:
3162 case Instruction::FAdd:
3163 case Instruction::Sub:
3164 case Instruction::FSub:
3165 case Instruction::Mul:
3166 case Instruction::FMul:
3167 case Instruction::FDiv:
3168 case Instruction::FRem:
3169 case Instruction::Shl:
3170 case Instruction::LShr:
3171 case Instruction::AShr:
3172 case Instruction::And:
3173 case Instruction::Or:
3174 case Instruction::Xor:
3175 case Instruction::Freeze:
3176 case Instruction::ExtractValue:
3177 case Instruction::ICmp:
3178 case Instruction::FCmp:
3179 case Instruction::Select:
3180 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
3181 default:
3182 llvm_unreachable("Unsupported opcode for instruction");
3183 }
3184}
3185
3186#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3188 VPSlotTracker &SlotTracker) const {
3189 O << Indent << "WIDEN ";
3191 O << " = " << Instruction::getOpcodeName(Opcode);
3192 printFlags(O);
3194}
3195#endif
3196
3198 auto &Builder = State.Builder;
3199 /// Vectorize casts.
3200 assert(State.VF.isVector() && "Not vectorizing?");
3201 Type *DestTy = VectorType::get(getScalarType(), State.VF);
3202 VPValue *Op = getOperand(0);
3203 Value *A = State.get(Op);
3204 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
3205 State.set(this, Cast);
3206 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
3207 applyFlags(*CastOp);
3208 applyMetadata(*CastOp);
3209 }
3210}
3211
3216
3217#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3219 VPSlotTracker &SlotTracker) const {
3220 O << Indent << "WIDEN-CAST ";
3222 O << " = " << Instruction::getOpcodeName(Opcode);
3223 printFlags(O);
3225 O << " to " << *getScalarType();
3226}
3227#endif
3228
3230 VPCostContext &Ctx) const {
3231 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3232}
3233
3234#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3236 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
3237 O << Indent;
3239 O << " = WIDEN-INDUCTION";
3240 printFlags(O);
3242
3243 if (isTruncated())
3244 O << " (truncated to " << *getScalarType() << ")";
3245}
3246#endif
3247
3249 // The step may be defined by a recipe in the preheader (e.g. if it requires
3250 // SCEV expansion), but for the canonical induction the step is required to be
3251 // 1, which is represented as live-in.
3252 return match(getStartValue(), m_ZeroInt()) &&
3253 match(getStepValue(), m_One()) &&
3254 getScalarType() == getRegion()->getCanonicalIVType();
3255}
3256
3259 VPCostContext &Ctx) const {
3260 // A widened induction generates a vector phi and increments it by the
3261 // splatted step each iteration.
3263 InstructionCost Cost = Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3264 Type *StepTy = getScalarType();
3265 unsigned IncOpc = ID.getKind() == InductionDescriptor::IK_IntInduction
3266 ? Instruction::Add
3267 : ID.getInductionOpcode();
3268 assert(IncOpc != Instruction::BinaryOpsEnd &&
3269 "induction must have a valid increment opcode");
3270 return Cost + Ctx.TTI.getArithmeticInstrCost(IncOpc, toVectorTy(StepTy, VF),
3271 Ctx.CostKind);
3272}
3273
3274/// Returns the ConstantFP \p V wraps, or nullptr if it does not wrap one.
3275static const ConstantFP *getConstantFP(const VPValue *V) {
3276 auto *C = dyn_cast<VPConstant>(V);
3277 return C ? dyn_cast<ConstantFP>(C->getConstant()) : nullptr;
3278}
3279
3281 VPCostContext &Ctx) const {
3282 // The cost model for this is modelled on expandVPDerivedIV in
3283 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
3284 // negatively affect vectorization it takes into account any expected
3285 // simplifications that happen in simplifyRecipe.
3286 switch (getInductionKind()) {
3287 default:
3288 // TODO: Compute cost for remaining kinds.
3289 break;
3291 // There are currently no tests that expose a path where all lanes are
3292 // used, so it's better to bail out for now.
3293 if (!vputils::onlyFirstLaneUsed(this))
3294 break;
3295
3296 // Start off by assuming we need both mul and add, then refine this.
3297 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
3298
3299 // If the start value is zero the add gets folded away.
3300 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
3301 NeedsAdd = !StartC->isZero();
3302
3303 // For some values of step the arithmetic changes:
3304 // 1. A step of 1 requires no operation.
3305 // 2. A step of -1 requires a negate.
3306 // 3. A power-of-2 step will use a shl, instead of a mul.
3307 Type *StepTy = getStepValue()->getScalarType();
3309 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
3310 if (StepC->isOne())
3311 NeedsMul = false;
3312 else if (StepC->getAPInt().isAllOnes()) {
3313 // This will most likely end up as a negate in simplifyRecipe, and
3314 // the negate will be combined with the add to make a sub.
3315 // NOTE: This is perhaps an invalid assumption that the cost of an
3316 // 'add' is the same as a 'sub'.
3317 NeedsMul = false;
3318 NeedsAdd = true;
3319 } else if (StepC->getAPInt().isPowerOf2()) {
3320 // This will most likely end up as a shift-left in simplifyRecipe
3321 NeedsMul = false;
3322 NeedsShl = true;
3323 }
3324 }
3325
3326 // Add the cost of the conversion from index to step type if the index
3327 // will be used.
3328 Type *IndexTy = getIndex()->getScalarType();
3329 unsigned StepTySize = StepTy->getScalarSizeInBits();
3330 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3331 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3332 unsigned CastOpc =
3333 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::ZExt;
3334 Cost += Ctx.TTI.getCastInstrCost(
3335 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3336 }
3337
3338 if (NeedsMul)
3339 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3340 Ctx.CostKind);
3341 if (NeedsShl)
3342 Cost += Ctx.TTI.getArithmeticInstrCost(
3343 Instruction::Shl, StepTy, Ctx.CostKind,
3344 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3345 {TargetTransformInfo::OK_UniformConstantValue,
3346 TargetTransformInfo::OP_None});
3347 if (NeedsAdd)
3348 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3349 Ctx.CostKind);
3350 return Cost;
3351 }
3353 // There are currently no tests that expose a path where all lanes are
3354 // used, so it's better to bail out for now.
3355 if (!vputils::onlyFirstLaneUsed(this))
3356 break;
3357
3358 // Unlike the integer case, converting the index to the FP step type is
3359 // unavoidable: the index is always the integer canonical IV, so this
3360 // cast is never folded away.
3361 Type *StepTy = getStepValue()->getScalarType();
3362 Type *IndexTy = getIndex()->getScalarType();
3364 Ctx.TTI.getCastInstrCost(Instruction::UIToFP, StepTy, IndexTy,
3365 TTI::CastContextHint::None, Ctx.CostKind);
3366
3367 // If the step is 1.0, the multiply is an exact identity and gets folded
3368 // away, independent of fast-math flags.
3369 const ConstantFP *StepC = getConstantFP(getStepValue());
3370 bool NeedsMul = !StepC || !StepC->isOne();
3371
3372 // "fadd -0.0, X" folds to X unconditionally, but "fadd 0.0, X" only folds
3373 // to X without nsz if X can be proven to never be -0.0, which we cannot, as
3374 // Step may be -0.0.
3375 // TODO: Consider fast-math flags when they are available in
3376 // VPDerivedIVRecipe.
3377 const ConstantFP *StartC = getConstantFP(getStartValue());
3378 bool AddFolds = getFPBinOp()->getOpcode() == Instruction::FAdd && StartC &&
3379 StartC->isZero() && (StartC->isNegZero() || !NeedsMul);
3380
3381 if (NeedsMul)
3382 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::FMul, StepTy,
3383 Ctx.CostKind);
3384 if (!AddFolds)
3385 Cost += Ctx.TTI.getArithmeticInstrCost(getFPBinOp()->getOpcode(), StepTy,
3386 Ctx.CostKind);
3387 return Cost;
3388 }
3389 }
3390
3391 return 0;
3392}
3393
3394#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3396 VPSlotTracker &SlotTracker) const {
3397 O << Indent;
3399 O << " = DERIVED-IV";
3400 printFlags(O);
3401 getStartValue()->printAsOperand(O, SlotTracker);
3402 O << " + ";
3403 getOperand(1)->printAsOperand(O, SlotTracker);
3404 O << " * ";
3405 getStepValue()->printAsOperand(O, SlotTracker);
3406}
3407#endif
3408
3412
3414 VPCostContext &Ctx) const {
3415 Type *BaseIVTy = getOperand(0)->getScalarType();
3416 assert((BaseIVTy->isIntegerTy() || BaseIVTy->isFloatingPointTy()) &&
3417 "VPScalarIVStepsRecipe is only created for integer and FP inductions");
3418
3419 // If only the first lane is used, then there won't be any code that remains
3420 // in the loop for the first unrolled part.
3422 return 0;
3423
3424 // If the vector body executes at most once, the canonical IV is a constant
3425 // and every lane's step folds away with it.
3426 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
3427 return 0;
3428
3429 // Typically the operations are:
3430 // 1. Add the start index to each lane value.
3431 // 2. Multiply the start index by the step.
3432 // 3. Add the scaled start index to base IV.
3433 // Any code generated for 1 and 2 should be loop invariant and therefore
3434 // hoisted out of the loop. We only need to add on the cost of 3.
3436 if (BaseIVTy->isFloatingPointTy()) {
3437 // Unlike the integer case, the users of an FP induction cannot be re-based
3438 // on a common value, so each lane needs its own FAdd/FSub.
3439 assert(!VF.isScalable() &&
3440 "FP scalar steps for all lanes are only created for fixed VFs");
3441 Cost = Ctx.TTI.getArithmeticInstrCost(InductionOpcode, BaseIVTy,
3442 Ctx.CostKind) *
3443 (VF.getFixedValue() - 1);
3444 } else {
3445 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3446 // %add1 = add i32 %iv, 0
3447 // %add2 = add i32 %iv, 1
3448 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3449 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3450 // it's very likely that these GEPs will all be rewritten to have a common
3451 // base such that what's left is just
3452 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3453 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3454 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3455 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3456 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3457 Cost = Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3458 Ctx.CostKind);
3459 }
3460
3461 // If the steps are generated inside a replicate region, scale by execution
3462 // probability.
3463 const VPRegionBlock *Region = getRegion();
3464 if (Region && Region->isReplicator())
3465 Cost /= Ctx.getCostDivisor(
3466 Region->getEntryBranchOnMask()->getExecutionFrequency());
3467 return Cost;
3468}
3469
3471 // Fast-math-flags propagate from the original induction instruction.
3472 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3473 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3474
3475 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3476 /// variable on which to base the steps, \p Step is the size of the step.
3477
3478 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3479 Value *Step = State.get(getStepValue(), VPLane(0));
3480 IRBuilderBase &Builder = State.Builder;
3481
3482 // Ensure step has the same type as that of scalar IV.
3483 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3484 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3485
3486 // We build scalar steps for both integer and floating-point induction
3487 // variables. Here, we determine the kind of arithmetic we will perform.
3490 if (BaseIVTy->isIntegerTy()) {
3491 AddOp = Instruction::Add;
3492 MulOp = Instruction::Mul;
3493 } else {
3494 AddOp = InductionOpcode;
3495 MulOp = Instruction::FMul;
3496 }
3497
3498 // Lanes other than the first have been materialized as separate
3499 // single-scalar recipes by replicateByVF, each with its own start index.
3500 assert((vputils::onlyFirstLaneUsed(this) || State.VF.isScalar()) &&
3501 "must have been replicated by VF");
3502 Value *StartIdx = getStartIndex() ? State.get(getStartIndex(), true)
3503 : Constant::getNullValue(BaseIVTy);
3504 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3505 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3506 State.set(this, Add, VPLane(0));
3507}
3508
3509#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3511 VPSlotTracker &SlotTracker) const {
3512 O << Indent;
3514 O << " = SCALAR-STEPS ";
3516}
3517#endif
3518
3520 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3522}
3523
3525 assert(State.VF.isVector() && "not widening");
3526 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3527 return State.get(Op, vputils::isSingleScalar(Op));
3528 });
3529 auto *GEP =
3530 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3531 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3532 State.set(this, GEP, vputils::isSingleScalar(this));
3533}
3534
3535#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3537 VPSlotTracker &SlotTracker) const {
3538 O << Indent << "WIDEN-GEP ";
3540 O << " = getelementptr";
3541 printFlags(O);
3543}
3544#endif
3545
3547 assert(!getOffset() && "Unexpected offset operand");
3548 VPBuilder Builder(this);
3549 VPlan &Plan = *getParent()->getPlan();
3550 VPValue *VFVal = getVFValue();
3551 const DataLayout &DL = Plan.getDataLayout();
3552 Type *IndexTy = DL.getIndexType(this->getScalarType());
3553 VPValue *Stride =
3554 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3555 VPValue *VF =
3556 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3557
3558 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3559 VPInstruction *VFMinusOne =
3560 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3561 DebugLoc::getUnknown(), "", {true, true});
3562 VPInstruction *Offset0 =
3563 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3564
3565 // Offset for PartN = Offset0 + Part * Stride * VF.
3566 VPValue *PartxStride =
3567 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3568 VPValue *Offset = Builder.createAdd(
3569 Offset0,
3570 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3572}
3573
3575 auto &Builder = State.Builder;
3576 assert(getOffset() && "Expected prior materialization of offset");
3577 Value *Ptr = State.get(getPointer(), true);
3578 Value *Offset = State.get(getOffset(), true);
3579 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3581 State.set(this, ResultPtr, /*IsScalar*/ true);
3582}
3583
3584#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3586 VPSlotTracker &SlotTracker) const {
3587 O << Indent;
3589 O << " = vector-end-pointer";
3590 printFlags(O);
3591 getSourceElementType()->print(O);
3592 O << ", ";
3594}
3595#endif
3596
3598 assert(getVFxPart() &&
3599 "Expected prior simplification of recipe without VFxPart");
3600
3601 auto &Builder = State.Builder;
3602 Value *Ptr = State.get(getOperand(0), VPLane(0));
3603 Value *Offset = State.get(getVFxPart(), true);
3604 // TODO: Expand to VPInstruction to support constant folding.
3605 if (!match(getStride(), m_One())) {
3606 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3607 Offset->getType());
3608 Offset = Builder.CreateMul(Offset, Stride);
3609 }
3610 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3612 State.set(this, ResultPtr, /*IsScalar*/ true);
3613}
3614
3615#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3617 VPSlotTracker &SlotTracker) const {
3618 O << Indent;
3620 O << " = vector-pointer";
3621 printFlags(O);
3622 getSourceElementType()->print(O);
3623 O << ", ";
3625}
3626#endif
3627
3629 VPCostContext &Ctx) const {
3630 // A blend will be expanded to a select VPInstruction, which will generate a
3631 // scalar select if only the first lane is used.
3633 VF = ElementCount::getFixed(1);
3634
3635 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3636 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3637
3639 for (unsigned I = 1, E = getNumIncomingValues(); I != E; ++I) {
3640 CmpPredicate Pred;
3641 if (!match(getMask(I), m_Cmp(Pred, m_VPValue(), m_VPValue())))
3642 Pred = getScalarType()->isFloatingPointTy() ? CmpInst::BAD_FCMP_PREDICATE
3644 Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3645 Pred, Ctx.CostKind);
3646 }
3647 return Cost;
3648}
3649
3650#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3652 VPSlotTracker &SlotTracker) const {
3653 O << Indent << "BLEND ";
3655 O << " =";
3656 printFlags(O);
3657 if (getNumIncomingValues() == 1) {
3658 // Not a User of any mask: not really blending, this is a
3659 // single-predecessor phi.
3660 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3661 } else {
3662 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3663 if (I != 0)
3664 O << " ";
3665 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3666 if (I == 0 && isNormalized())
3667 continue;
3668 O << "/";
3669 getMask(I)->printAsOperand(O, SlotTracker);
3670 }
3671 }
3672}
3673#endif
3674
3678 "In-loop AnyOf reductions aren't currently supported");
3679 // Propagate the fast-math flags carried by the underlying instruction.
3680 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3681 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3682 Value *NewVecOp = State.get(getVecOp());
3683 if (VPValue *Cond = getCondOp()) {
3684 Value *NewCond = State.get(Cond, State.VF.isScalar());
3685 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3686 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3687
3688 Value *Start =
3690 if (State.VF.isVector())
3691 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3692
3693 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3694 NewVecOp = Select;
3695 }
3696 Value *NewRed;
3697 Value *NextInChain;
3698 if (isOrdered()) {
3699 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3700 if (State.VF.isVector())
3701 NewRed =
3702 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3703 else
3704 NewRed = State.Builder.CreateBinOp(
3706 PrevInChain, NewVecOp);
3707 PrevInChain = NewRed;
3708 NextInChain = NewRed;
3709 } else if (isPartialReduction()) {
3710 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3711 "Unexpected partial reduction kind");
3712 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/false);
3713 NewRed = State.Builder.CreateIntrinsic(
3714 PrevInChain->getType(),
3715 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3716 : Intrinsic::vector_partial_reduce_fadd,
3717 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3718 "partial.reduce");
3719 PrevInChain = NewRed;
3720 NextInChain = NewRed;
3721 } else {
3722 assert(isInLoop() &&
3723 "The reduction must either be ordered, partial or in-loop");
3724 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3725 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3727 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3728 else
3729 NextInChain = State.Builder.CreateBinOp(
3731 PrevInChain, NewRed);
3732 }
3733 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3734}
3735
3737
3738 assert(State.VF.isVector() &&
3739 "Shouldn't generate VPReductionEVLRecipe with scalar VF");
3740 auto &Builder = State.Builder;
3741 // Propagate the fast-math flags carried by the underlying instruction.
3742 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3743 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3744
3746 Value *Prev =
3747 State.get(getChainOp(), /*NeedsSingleScalar=*/!isPartialReduction());
3748 Value *VecOp = State.get(getVecOp());
3749 Value *EVL = State.get(getEVL(), VPLane(0));
3750
3751 Value *Mask;
3752 if (VPValue *CondOp = getCondOp())
3753 Mask = State.get(CondOp);
3754 else
3755 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3756
3757 Value *NewRed;
3758 if (isPartialReduction()) {
3759 // For partial reductions, we need to generate a predicated select
3760 // (vp.merge) since `@llvm.vector.partial.reduce()` doesn't have a vector
3761 // predicated version.
3762 VectorType *VecTy = cast<VectorType>(VecOp->getType());
3763 Value *Identity = getRecurrenceIdentity(Kind, VecTy->getElementType(),
3765 Identity =
3766 State.Builder.CreateVectorSplat(VecTy->getElementCount(), Identity);
3767
3768 // TODO: Calculate the predicate cost for the partial reduction.
3769 Value *NewVecOp = State.Builder.CreateIntrinsic(
3770 VecTy, Intrinsic::vp_merge, {Mask, VecOp, Identity, EVL});
3771 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3772 "Unexpected partial reduction kind");
3773 NewRed = State.Builder.CreateIntrinsic(
3774 Prev->getType(),
3775 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3776 : Intrinsic::vector_partial_reduce_fadd,
3777 {Prev, NewVecOp}, State.Builder.getFastMathFlags(), "partial.reduce");
3778 } else if (isOrdered()) {
3779 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3780 } else {
3781 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3783 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3784 else
3785 NewRed = Builder.CreateBinOp(
3787 Prev);
3788 }
3789 State.set(this, NewRed, !isPartialReduction());
3790}
3791
3793 VPCostContext &Ctx) const {
3794 RecurKind RdxKind = getRecurrenceKind();
3795 Type *ElementTy = this->getScalarType();
3796 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3797 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3799 std::optional<FastMathFlags> OptionalFMF =
3800 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3801
3802 if (isPartialReduction()) {
3803 InstructionCost CondCost = 0;
3804 if (isConditional()) {
3806 auto *CondTy =
3808 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3809 CondTy, Pred, Ctx.CostKind);
3810 }
3811 return CondCost + Ctx.TTI.getPartialReductionCost(
3812 Opcode, ElementTy, nullptr, ElementTy, VF,
3813 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3814 OptionalFMF);
3815 }
3816
3817 // TODO: Support any-of reductions.
3818 assert(
3820 Ctx.Opts.force_target_instruction_cost) &&
3821 "Any-of reduction not implemented in VPlan-based cost model currently.");
3822
3823 // Note that TTI should model the cost of moving result to the scalar register
3824 // and the BinOp cost in the getMinMaxReductionCost().
3827 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3828 }
3829
3830 // Note that TTI should model the cost of moving result to the scalar register
3831 // and the BinOp cost in the getArithmeticReductionCost().
3832 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3833 Ctx.CostKind);
3834}
3835
3837 ExpressionTypes ExpressionType,
3838 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3839 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3840 [&]() {
3841 if (ExpressionType == ExpressionTypes::FoldedVPMerge)
3842 return ExpressionRecipes.back()->getScalarType();
3844 ExpressionRecipes.back())
3845 ->getChainOp()
3846 ->getScalarType();
3847 }()),
3848 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3849 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3850 assert(
3851 none_of(ExpressionRecipes,
3852 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3853 "expression cannot contain recipes with side-effects");
3854
3855 // Maintain a copy of the expression recipes as a set of users.
3856 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3857 for (auto *R : ExpressionRecipes)
3858 ExpressionRecipesAsSetOfUsers.insert(R);
3859
3860 // Recipes in the expression, except the last one, must only be used by
3861 // (other) recipes inside the expression. If there are other users, external
3862 // to the expression, use a clone of the recipe for external users.
3863 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3864 if (R != ExpressionRecipes.back() &&
3865 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3866 return !ExpressionRecipesAsSetOfUsers.contains(U);
3867 })) {
3868 // There are users outside of the expression. Clone the recipe and use the
3869 // clone those external users.
3870 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3871 R->replaceUsesWithIf(CopyForExtUsers,
3872 [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3873 return !ExpressionRecipesAsSetOfUsers.contains(U);
3874 });
3875 CopyForExtUsers->insertBefore(R);
3876 }
3877 if (R->getParent())
3878 R->removeFromParent();
3879 }
3880
3881 // Internalize all external operands to the expression recipes. To do so,
3882 // create new temporary VPValues for all operands defined by a recipe outside
3883 // the expression. The original operands are added as operands of the
3884 // VPExpressionRecipe itself.
3885 for (auto *R : ExpressionRecipes) {
3886 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3887 auto *Def = Op->getDefiningRecipe();
3888 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3889 continue;
3890 addOperand(Op);
3891 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3892 }
3893 }
3894
3895 // Replace each external operand with the first one created for it in
3896 // LiveInPlaceholders.
3897 for (auto *R : ExpressionRecipes)
3898 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3899 R->replaceUsesOfWith(LiveIn, Tmp);
3900}
3901
3903 for (auto *R : ExpressionRecipes)
3904 // Since the list could contain duplicates, make sure the recipe hasn't
3905 // already been inserted.
3906 if (!R->getParent())
3907 R->insertBefore(this);
3908
3909 for (const auto &[Idx, Op] : enumerate(operands()))
3910 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3911
3912 replaceAllUsesWith(ExpressionRecipes.back());
3913 SmallVector<VPSingleDefRecipe *> DecomposedRecipes(ExpressionRecipes);
3914 ExpressionRecipes.clear();
3915 return DecomposedRecipes;
3916}
3917
3919 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3920 // The last operand of a folded operation is the vp.merge EVL.
3921 if (ExpressionType == ExpressionTypes::FoldedVPMerge &&
3922 Op == getLastOperand()) {
3923 assert(match(Op, m_EVL(m_VPValue())) &&
3924 "Expected an explicit vector length recipe");
3925 return true;
3926 }
3927
3928 return false;
3929}
3930
3932 VPCostContext &Ctx) const {
3933 // The last recipes in the chain will be optimized away, so igonre the cost.
3934 if (ExpressionType == ExpressionTypes::FoldedVPMerge) {
3936 for (auto *R : drop_end(ExpressionRecipes))
3937 Cost += R->cost(VF, Ctx);
3938 return Cost;
3939 }
3940
3941 Type *RedTy = this->getScalarType();
3942 auto *SrcVecTy =
3944 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3945 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3946 switch (ExpressionType) {
3947 case ExpressionTypes::NegatedExtendedReduction:
3948 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3949 "Unexpected opcode");
3950 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3951 [[fallthrough]];
3952 case ExpressionTypes::ExtendedReduction: {
3953 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3954 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3955
3956 if (RedR->isPartialReduction())
3957 return Ctx.TTI.getPartialReductionCost(
3958 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3960 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3961 RedTy->isFloatingPointTy()
3962 ? std::optional{RedR->getFastMathFlagsOrNone()}
3963 : std::nullopt);
3964 else if (!RedTy->isFloatingPointTy())
3965 // TTI::getExtendedReductionCost only supports integer types.
3966 return Ctx.TTI.getExtendedReductionCost(
3967 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3968 std::nullopt, Ctx.CostKind);
3969 else
3971 }
3972 case ExpressionTypes::MulAccReduction:
3973 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3974 Ctx.CostKind);
3975
3976 case ExpressionTypes::ExtNegatedMulAccReduction:
3977 switch (Opcode) {
3978 case Instruction::Add:
3979 Opcode = Instruction::Sub;
3980 break;
3981 case Instruction::FAdd:
3982 Opcode = Instruction::FSub;
3983 break;
3984 default:
3985 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3986 }
3987 [[fallthrough]];
3988 case ExpressionTypes::ExtMulAccReduction: {
3989 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3990 if (RedR->isPartialReduction()) {
3991 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3992 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3993 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3994 return Ctx.TTI.getPartialReductionCost(
3995 Opcode, getOperand(0)->getScalarType(),
3996 getOperand(1)->getScalarType(), RedTy, VF,
3998 Ext0R->getOpcode()),
4000 Ext1R->getOpcode()),
4001 Mul->getOpcode(), Ctx.CostKind,
4002 RedTy->isFloatingPointTy()
4003 ? std::optional{RedR->getFastMathFlagsOrNone()}
4004 : std::nullopt);
4005 }
4006 assert(Opcode != Instruction::FSub && "Only integer types are supported");
4007 return Ctx.TTI.getMulAccReductionCost(
4008 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
4009 Instruction::ZExt,
4010 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
4011 }
4012 case ExpressionTypes::FoldedVPMerge:
4013 llvm_unreachable("Folded vp.merge expression should be handled eariler");
4014 }
4015 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
4016}
4017
4019 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
4020 return R->mayReadFromMemory() || R->mayWriteToMemory();
4021 });
4022}
4023
4025 assert(
4026 none_of(ExpressionRecipes,
4027 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
4028 "expression cannot contain recipes with side-effects");
4029 return false;
4030}
4031
4033 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
4034 return RR && !RR->isPartialReduction();
4035}
4036
4037#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4038
4040 VPSlotTracker &SlotTracker) const {
4041 O << Indent << "EXPRESSION ";
4043 O << " = ";
4044 if (ExpressionType == ExpressionTypes::FoldedVPMerge) {
4045 VPSingleDefRecipe *InLoopOp = ExpressionRecipes[0];
4046 unsigned NumInLoopOps = InLoopOp->getNumOperands();
4047 O << "vp.merge ";
4048 getOperand(NumInLoopOps)->printAsOperand(O, SlotTracker);
4049 O << ", ";
4050 auto PrintInLoopOperands = [&]() {
4051 O << "(";
4052 interleaveComma(make_range(op_begin(), op_begin() + NumInLoopOps), O,
4053 [&O, &SlotTracker](VPValue *Op) {
4054 Op->printAsOperand(O, SlotTracker);
4055 });
4056 O << ")";
4057 };
4058
4059 if (auto *WidenIntrinsic = dyn_cast<VPWidenIntrinsicRecipe>(InLoopOp)) {
4060 O << WidenIntrinsic->getIntrinsicName();
4061 WidenIntrinsic->printFlags(O);
4062 PrintInLoopOperands();
4063 } else if (auto *Widen = dyn_cast<VPWidenRecipe>(InLoopOp)) {
4064 O << Instruction::getOpcodeName(Widen->getOpcode());
4065 Widen->printFlags(O);
4066 PrintInLoopOperands();
4067 }
4068 O << ", ";
4069 interleaveComma(make_range(op_begin() + NumInLoopOps + 1,
4070 op_begin() + NumInLoopOps + 3),
4071 O, [&O, &SlotTracker](VPValue *Op) {
4072 Op->printAsOperand(O, SlotTracker);
4073 });
4074
4075 return;
4076 }
4077
4078 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
4079 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
4080 VPValue *Mask = getLastOperand();
4081 VPValue *EVL =
4083 ? getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1))
4084 : nullptr;
4085 VPValue *RdxStart = getOperand(
4086 getNumOperands() - (Red->isConditional() ? 2 : 1) - (EVL ? 1 : 0));
4087 auto PrintEVLAndMask = [&]() {
4088 if (EVL) {
4089 O << ", ";
4090 EVL->printAsOperand(O, SlotTracker);
4091 }
4092 if (Red->isConditional()) {
4093 O << ", ";
4094 Mask->printAsOperand(O, SlotTracker);
4095 }
4096 };
4097
4098 switch (ExpressionType) {
4099 case ExpressionTypes::NegatedExtendedReduction:
4100 case ExpressionTypes::ExtendedReduction: {
4101 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
4103 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4104 O << Instruction::getOpcodeName(Opcode) << " (";
4105 if (Negated)
4106 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
4108 if (Negated)
4109 O << ")";
4110 Red->printFlags(O);
4111
4112 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4113 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4114 << *Ext0->getScalarType();
4115 PrintEVLAndMask();
4116 O << ")";
4117 break;
4118 }
4119 case ExpressionTypes::ExtNegatedMulAccReduction: {
4120 RdxStart->printAsOperand(O, SlotTracker);
4121 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4123 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4124 << " (sub (0, mul";
4125 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
4126 Mul->printFlags(O);
4127 O << "(";
4129 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4130 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4131 << *Ext0->getScalarType() << "), (";
4133 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4134 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4135 << *Ext1->getScalarType() << ")";
4136 PrintEVLAndMask();
4137 O << "))";
4138 break;
4139 }
4140 case ExpressionTypes::MulAccReduction:
4141 case ExpressionTypes::ExtMulAccReduction: {
4142 RdxStart->printAsOperand(O, SlotTracker);
4143 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4145 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4146 << " (";
4147 O << "mul";
4148 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
4149 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
4150 : ExpressionRecipes[0]);
4151 Mul->printFlags(O);
4152 if (IsExtended)
4153 O << "(";
4155 if (IsExtended) {
4156 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4157 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4158 << *Ext0->getScalarType() << "), (";
4159 } else {
4160 O << ", ";
4161 }
4163 if (IsExtended) {
4164 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4165 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4166 << *Ext1->getScalarType() << ")";
4167 }
4168 PrintEVLAndMask();
4169 O << ")";
4170 break;
4171 }
4172 default:
4173 llvm_unreachable("Unhandled VPExpressionRecipe::ExpressionTypes enum");
4174 }
4175}
4176
4178 VPSlotTracker &SlotTracker) const {
4179 if (isPartialReduction())
4180 O << Indent << "PARTIAL-REDUCE ";
4181 else
4182 O << Indent << "REDUCE ";
4184 O << " = ";
4186 O << " +";
4187 printFlags(O);
4188 O << " reduce.";
4190 O << " (";
4192 if (isConditional()) {
4193 O << ", ";
4195 }
4196 O << ")";
4197}
4198
4200 VPSlotTracker &SlotTracker) const {
4201 if (isPartialReduction())
4202 O << Indent << "PARTIAL-REDUCE ";
4203 else
4204 O << Indent << "REDUCE ";
4206 O << " = ";
4208 O << " +";
4209 printFlags(O);
4210 O << " vp.reduce."
4213 << " (";
4215 O << ", ";
4217 if (isConditional()) {
4218 O << ", ";
4220 }
4221 O << ")";
4222}
4223
4224#endif
4225
4227 assert(IsSingleScalar &&
4228 "VPReplicateRecipes must be unrolled before ::execute");
4229 auto *Instr = getUnderlyingInstr();
4230 Instruction *Cloned = Instr->clone();
4231 Type *ResultTy = getScalarType();
4232 if (!ResultTy->isVoidTy()) {
4233 Cloned->setName(Instr->getName() + ".cloned");
4234 // The operands of the replicate recipe may have been narrowed, resulting in
4235 // a narrower result type. Update the type of the cloned instruction to the
4236 // correct type.
4237 if (ResultTy != Cloned->getType())
4238 Cloned->mutateType(ResultTy);
4239 }
4240
4243 Cloned->dropPoisonGeneratingFlags();
4244 applyFlags(*Cloned);
4245 applyMetadata(*Cloned);
4246
4247 if (hasPredicate())
4248 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
4249
4250 // Replace the operands of the cloned instructions with their scalar
4251 // equivalents in the new loop.
4252 for (unsigned Idx : seq(Cloned->getNumOperands()))
4253 Cloned->setOperand(Idx, State.get(getOperand(Idx), true));
4254
4255 // Place the cloned scalar in the new loop.
4256 State.Builder.Insert(Cloned);
4257
4258 State.set(this, Cloned, true);
4259
4260 // If we just cloned a new assumption, add it the assumption cache.
4261 if (auto *II = dyn_cast<AssumeInst>(Cloned))
4262 State.AC->registerAssumption(II);
4263}
4264
4265/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
4266/// which the legacy cost model computes a SCEV expression when computing the
4267/// address cost. Computing SCEVs for VPValues is incomplete and returns
4268/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
4269/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
4270static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
4272 const Loop *L) {
4273 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
4274 if (isa<SCEVCouldNotCompute>(Addr))
4275 return Addr;
4276
4277 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
4278}
4279
4281 VPCostContext &Ctx) const {
4283 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
4284 // transform, avoid computing their cost multiple times for now.
4285 Ctx.SkipCostComputation.insert(UI);
4286
4287 if (VF.isScalable() && !isSingleScalar())
4289
4290 switch (UI->getOpcode()) {
4291 case Instruction::Alloca:
4292 if (VF.isScalable())
4294 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4295 this->getScalarType(), Ctx.CostKind);
4296 case Instruction::GetElementPtr:
4297 // We mark this instruction as zero-cost because the cost of GEPs in
4298 // vectorized code depends on whether the corresponding memory instruction
4299 // is scalarized or not. Therefore, we handle GEPs with the memory
4300 // instruction cost.
4301 return 0;
4302 case Instruction::Call: {
4303 auto *CalledFn = cast<Function>(getLastOperand()->getLiveInIRValue());
4304 Type *ResultTy = this->getScalarType();
4305 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
4306 isSingleScalar(), VF, Ctx);
4307 }
4308 case Instruction::FNeg:
4309 case Instruction::Add:
4310 case Instruction::Sub:
4311 case Instruction::FAdd:
4312 case Instruction::FSub:
4313 case Instruction::Mul:
4314 case Instruction::FMul:
4315 case Instruction::FDiv:
4316 case Instruction::FRem:
4317 case Instruction::Shl:
4318 case Instruction::LShr:
4319 case Instruction::AShr:
4320 case Instruction::And:
4321 case Instruction::Or:
4322 case Instruction::Xor:
4323 case Instruction::ICmp:
4324 case Instruction::FCmp:
4325 case Instruction::Freeze:
4326 case Instruction::BitCast:
4327 case Instruction::SExt:
4328 case Instruction::ZExt:
4329 case Instruction::FPToUI:
4330 case Instruction::FPToSI:
4331 case Instruction::FPExt:
4332 case Instruction::PtrToInt:
4333 case Instruction::PtrToAddr:
4334 case Instruction::IntToPtr:
4335 case Instruction::SIToFP:
4336 case Instruction::UIToFP:
4337 case Instruction::Trunc:
4338 case Instruction::FPTrunc:
4339 case Instruction::Select:
4340 case Instruction::AddrSpaceCast: {
4342 Ctx) *
4343 (isSingleScalar() ? 1 : VF.getFixedValue());
4344 }
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 (any_of(operands(), [&Ctx, VF](VPValue *Op) {
4358 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
4359 if (!PredR)
4360 return false;
4361 return Ctx.skipCostComputation(
4363 PredR->getOperand(0)->getUnderlyingValue()),
4364 VF.isVector());
4365 }))
4366 return Ctx.getLegacyCost(UI, VF);
4367
4368 ScalarCost = ScalarCost * VF.getFixedValue() +
4369 Ctx.getScalarizationOverhead(this->getScalarType(),
4370 to_vector(operands()), VF);
4371 // If the recipe is not predicated (i.e. not in a replicate region), return
4372 // the scalar cost. Otherwise handle predicated cost.
4373 const VPRegionBlock *ParentRegion = getRegion();
4374 if (!ParentRegion || !ParentRegion->isReplicator())
4375 return ScalarCost;
4376
4377 // Account for the phi nodes that we will create.
4378 ScalarCost += VF.getFixedValue() *
4379 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4380 // Scale the cost by the probability of executing the predicated blocks.
4381 // This assumes the predicated block for each vector lane is equally
4382 // likely.
4383 ScalarCost /= Ctx.getCostDivisor(
4384 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4385 return ScalarCost;
4386 }
4387 case Instruction::Load:
4388 case Instruction::Store: {
4389 bool IsLoad = UI->getOpcode() == Instruction::Load;
4390 const VPValue *PtrOp = getOperand(!IsLoad);
4391 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
4393 // Fall back to the legacy cost model, unless the access is single-scalar
4394 // (PtrSCEV is unused) or predicated (legacy cost includes the region).
4395 const VPRegionBlock *ParentRegion = getRegion();
4396 if (!isSingleScalar() && (!ParentRegion || !ParentRegion->isReplicator()))
4397 return Ctx.getLegacyCost(UI, VF);
4398 PtrSCEV = nullptr;
4399 }
4400
4401 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
4402 Type *ScalarPtrTy = PtrOp->getScalarType();
4403 const Align Alignment = getLoadStoreAlignment(UI);
4404 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
4406 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
4407 bool UsedByLoadStoreAddress =
4408 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
4409 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
4410 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
4411 UsedByLoadStoreAddress ? UI : nullptr);
4412
4413 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
4414 InstructionCost ScalarCost =
4415 ScalarMemOpCost +
4416 Ctx.TTI.getAddressComputationCost(
4417 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
4418 Ctx.CostKind);
4419 if (isSingleScalar())
4420 return ScalarCost;
4421
4422 SmallVector<const VPValue *> OpsToScalarize;
4423 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
4424 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
4425 // don't assign scalarization overhead in general, if the target prefers
4426 // vectorized addressing or the loaded value is used as part of an address
4427 // of another load or store.
4428 if (!UsedByLoadStoreAddress) {
4429 bool EfficientVectorLoadStore =
4430 Ctx.TTI.supportsEfficientVectorElementLoadStore();
4431 if (!(IsLoad && !PreferVectorizedAddressing) &&
4432 !(!IsLoad && EfficientVectorLoadStore))
4433 append_range(OpsToScalarize, operands());
4434
4435 if (!EfficientVectorLoadStore)
4436 ResultTy = this->getScalarType();
4437 }
4438
4440 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
4442 (ScalarCost * VF.getFixedValue()) +
4443 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
4444
4445 const VPRegionBlock *ParentRegion = getRegion();
4446 if (ParentRegion && ParentRegion->isReplicator()) {
4447 // The cost of the branches is accounted for by the replicate region.
4448 Cost /= Ctx.getCostDivisor(
4449 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4450
4451 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
4452 // Artificially setting to a high enough value to practically disable
4453 // vectorization with such operations.
4454 return 3000000;
4455 }
4456 }
4457 return Cost;
4458 }
4459 case Instruction::ExtractValue:
4460 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
4461 default:
4462 // This opcode is unknown. Assume that it is the same as 'mul'.
4463 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4464 this->getScalarType(), Ctx.CostKind) *
4465 (isSingleScalar() ? 1 : VF.getFixedValue());
4466 }
4467}
4468
4470 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
4471 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
4473 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
4474
4475 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
4476 auto GetIntrinsicCost = [&] {
4477 if (!IntrinID)
4479 return Ctx.TTI.getIntrinsicInstrCost(
4480 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4481 };
4482
4483 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4484 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4485 return 0;
4486 }
4487
4488 InstructionCost ScalarCallCost =
4489 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4490 if (IsSingleScalar) {
4491 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4492 return ScalarCallCost;
4493 }
4494
4495 // Scalarization overhead is undefined for scalable VFs.
4496 if (VF.isScalable())
4498
4499 return ScalarCallCost * VF.getFixedValue() +
4500 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4501}
4502
4503#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4505 VPSlotTracker &SlotTracker) const {
4506 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4507
4508 if (!getScalarType()->isVoidTy()) {
4510 O << " = ";
4511 }
4512 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4513 O << "call";
4514 printFlags(O);
4515 O << "@" << CB->getCalledFunction()->getName() << "(";
4517 Op->printAsOperand(O, SlotTracker);
4518 });
4519 O << ")";
4520 } else {
4522 printFlags(O);
4524 }
4525
4526 // Find if the recipe is used by a widened recipe via an intervening
4527 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4528 if (any_of(users(), [](const VPUser *U) {
4529 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4530 return !vputils::onlyScalarValuesUsed(PredR);
4531 return false;
4532 }))
4533 O << " (S->V)";
4534}
4535#endif
4536
4538 llvm_unreachable("recipe must be removed when dissolving replicate region");
4539}
4540
4542 VPCostContext &Ctx) const {
4543 // Replicating isn't supported for scalable vectors.
4544 if (VF.isScalable())
4546 auto *VecI1Ty = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
4547 return Ctx.TTI.getScalarizationOverhead(
4548 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4549 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind) +
4550 VF.getFixedValue() *
4551 Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
4552}
4553
4555 llvm_unreachable("recipe must be removed when dissolving replicate region");
4556}
4557
4558#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4560 VPSlotTracker &SlotTracker) const {
4561 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4563 O << " = ";
4565}
4566#endif
4567
4569const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4570
4573
4575const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4576
4579
4581 VPCostContext &Ctx) const {
4582 const VPRecipeBase *R = getAsRecipe();
4584 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4585 : R->getOperand(1)->getScalarType();
4586 Type *Ty = toVectorTy(ScalarTy, VF);
4587 unsigned AS =
4588 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4589 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4590
4591 if (!Consecutive) {
4592 // TODO: Using the original IR may not be accurate.
4593 // Currently, ARM will use the underlying IR to calculate gather/scatter
4594 // instruction cost.
4595 Type *PtrTy = getAddr()->getScalarType();
4596 const Value *Ptr = getAddr()->getUnderlyingValue();
4597
4598 // If the address value is uniform across all lanes, then the address can be
4599 // calculated with scalar type and broadcast.
4601 PtrTy = toVectorTy(PtrTy, VF);
4602
4603 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4604 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4605 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4606 : Intrinsic::vp_scatter;
4607 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4608 Ctx.CostKind) +
4609 Ctx.TTI.getMemIntrinsicInstrCost(
4611 &Ingredient),
4612 Ctx.CostKind);
4613 }
4614
4616 if (IsMasked) {
4617 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4618 : Intrinsic::masked_store;
4619 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4620 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4621 } else {
4622 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4624 : R->getOperand(1));
4625 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4626 OpInfo, &Ingredient);
4627 }
4628 return Cost;
4629}
4630
4632 Type *ScalarDataTy = getScalarType();
4633 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4634 bool CreateGather = !isConsecutive();
4635
4636 auto &Builder = State.Builder;
4637 Value *Mask = nullptr;
4638 if (auto *VPMask = getMask())
4639 Mask = State.get(VPMask);
4640
4641 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateGather);
4642 Value *NewLI;
4643 if (CreateGather) {
4644 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4645 "wide.masked.gather");
4646 } else if (Mask) {
4647 NewLI =
4648 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4649 PoisonValue::get(DataTy), "wide.masked.load");
4650 } else {
4651 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4652 }
4654 State.set(this, NewLI);
4655}
4656
4657#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4659 VPSlotTracker &SlotTracker) const {
4660 O << Indent << "WIDEN ";
4662 O << " = load ";
4664 O << ", align " << getAlign().value();
4665}
4666#endif
4667
4669 Type *ScalarDataTy = getScalarType();
4670 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4671 bool CreateGather = !isConsecutive();
4672
4673 auto &Builder = State.Builder;
4674 CallInst *NewLI;
4675 Value *EVL = State.get(getEVL(), VPLane(0));
4676 Value *Addr = State.get(getAddr(), !CreateGather);
4677 Value *Mask = nullptr;
4678 if (VPValue *VPMask = getMask())
4679 Mask = State.get(VPMask);
4680 else
4681 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4682
4683 if (CreateGather) {
4684 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4685 {Addr, Mask, EVL}, nullptr,
4686 "wide.masked.gather");
4687 } else {
4688 NewLI = Builder.CreateIntrinsicWithoutFolding(
4689 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4690 }
4691 NewLI->addParamAttr(
4693 applyMetadata(*NewLI);
4694 State.set(this, NewLI);
4695}
4696
4698 VPCostContext &Ctx) const {
4699 if (!Consecutive || IsMasked)
4700 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4701
4702 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4703 // here because the EVL recipes using EVL to replace the tail mask. But in the
4704 // legacy model, it will always calculate the cost of mask.
4705 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4706 // don't need to compare to the legacy cost model.
4707 Type *Ty = toVectorTy(getScalarType(), VF);
4708 unsigned AS =
4709 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4710 return Ctx.TTI.getMemIntrinsicInstrCost(
4711 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4712 Ctx.CostKind);
4713}
4714
4715#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4717 VPSlotTracker &SlotTracker) const {
4718 O << Indent << "WIDEN ";
4720 O << " = vp.load ";
4722 O << ", align " << getAlign().value();
4723}
4724#endif
4725
4727 VPValue *StoredVPValue = getStoredValue();
4728 bool CreateScatter = !isConsecutive();
4729
4730 auto &Builder = State.Builder;
4731
4732 Value *Mask = nullptr;
4733 if (auto *VPMask = getMask())
4734 Mask = State.get(VPMask);
4735
4736 Value *StoredVal = State.get(StoredVPValue);
4737 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateScatter);
4738 Instruction *NewSI = nullptr;
4739 if (CreateScatter)
4740 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4741 else if (Mask)
4742 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4743 else
4744 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4745 applyMetadata(*NewSI);
4746}
4747
4748#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4750 VPSlotTracker &SlotTracker) const {
4751 O << Indent << "WIDEN store ";
4753 O << ", align " << getAlign().value();
4754}
4755#endif
4756
4758 VPValue *StoredValue = getStoredValue();
4759 bool CreateScatter = !isConsecutive();
4760
4761 auto &Builder = State.Builder;
4762
4763 CallInst *NewSI = nullptr;
4764 Value *StoredVal = State.get(StoredValue);
4765 Value *EVL = State.get(getEVL(), VPLane(0));
4766 Value *Mask = nullptr;
4767 if (VPValue *VPMask = getMask())
4768 Mask = State.get(VPMask);
4769 else
4770 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4771
4772 Value *Addr = State.get(getAddr(), !CreateScatter);
4773 if (CreateScatter) {
4774 NewSI = Builder.CreateIntrinsicWithoutFolding(
4775 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4776 {StoredVal, Addr, Mask, EVL});
4777 } else {
4778 NewSI = Builder.CreateIntrinsicWithoutFolding(
4779 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4780 {StoredVal, Addr, Mask, EVL});
4781 }
4782 NewSI->addParamAttr(
4784 applyMetadata(*NewSI);
4785}
4786
4788 VPCostContext &Ctx) const {
4789 if (!Consecutive || IsMasked)
4790 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4791
4792 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4793 // here because the EVL recipes using EVL to replace the tail mask. But in the
4794 // legacy model, it will always calculate the cost of mask.
4795 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4796 // don't need to compare to the legacy cost model.
4797 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4798 unsigned AS =
4799 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4800 return Ctx.TTI.getMemIntrinsicInstrCost(
4801 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4802 Ctx.CostKind);
4803}
4804
4805#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4807 VPSlotTracker &SlotTracker) const {
4808 O << Indent << "WIDEN vp.store ";
4810 O << ", align " << getAlign().value();
4811}
4812#endif
4813
4815 VectorType *DstVTy, const DataLayout &DL) {
4816 // Verify that V is a vector type with same number of elements as DstVTy.
4817 auto VF = DstVTy->getElementCount();
4818 auto *SrcVecTy = cast<VectorType>(V->getType());
4819 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4820 Type *SrcElemTy = SrcVecTy->getElementType();
4821 Type *DstElemTy = DstVTy->getElementType();
4822 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4823 "Vector elements must have same size");
4824
4825 // Do a direct cast if element types are castable.
4826 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4827 return Builder.CreateBitOrPointerCast(V, DstVTy);
4828 }
4829 // V cannot be directly casted to desired vector type.
4830 // May happen when V is a floating point vector but DstVTy is a vector of
4831 // pointers or vice-versa. Handle this using a two-step bitcast using an
4832 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4833 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4834 "Only one type should be a pointer type");
4835 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4836 "Only one type should be a floating point type");
4837 Type *IntTy =
4838 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4839 auto *VecIntTy = VectorType::get(IntTy, VF);
4840 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4841 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4842}
4843
4844/// Return a vector containing interleaved elements from multiple
4845/// smaller input vectors.
4847 const Twine &Name) {
4848 unsigned Factor = Vals.size();
4849 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4850
4851 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4852#ifndef NDEBUG
4853 for (Value *Val : Vals)
4854 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4855#endif
4856
4857 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4858 // must use intrinsics to interleave.
4859 if (VecTy->isScalableTy()) {
4860 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4861 return Builder.CreateVectorInterleave(Vals, Name);
4862 }
4863
4864 // Fixed length. Start by concatenating all vectors into a wide vector.
4865 Value *WideVec = concatenateVectors(Builder, Vals);
4866
4867 // Interleave the elements into the wide vector.
4868 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4869 return Builder.CreateShuffleVector(
4870 WideVec, createInterleaveMask(NumElts, Factor), Name);
4871}
4872
4873// Try to vectorize the interleave group that \p Instr belongs to.
4874//
4875// E.g. Translate following interleaved load group (factor = 3):
4876// for (i = 0; i < N; i+=3) {
4877// R = Pic[i]; // Member of index 0
4878// G = Pic[i+1]; // Member of index 1
4879// B = Pic[i+2]; // Member of index 2
4880// ... // do something to R, G, B
4881// }
4882// To:
4883// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4884// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4885// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4886// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4887//
4888// Or translate following interleaved store group (factor = 3):
4889// for (i = 0; i < N; i+=3) {
4890// ... do something to R, G, B
4891// Pic[i] = R; // Member of index 0
4892// Pic[i+1] = G; // Member of index 1
4893// Pic[i+2] = B; // Member of index 2
4894// }
4895// To:
4896// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4897// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4898// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4899// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4900// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4902 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4903 "Masking gaps for scalable vectors is not yet supported.");
4905 Instruction *Instr = Group->getInsertPos();
4906
4907 // Prepare for the vector type of the interleaved load/store.
4908 Type *ScalarTy = getLoadStoreType(Instr);
4909 unsigned InterleaveFactor = Group->getFactor();
4910 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4911
4912 VPValue *BlockInMask = getMask();
4913 VPValue *Addr = getAddr();
4914 Value *ResAddr = State.get(Addr, VPLane(0));
4915
4916 auto CreateGroupMask = [&BlockInMask, &State,
4917 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4918 if (State.VF.isScalable()) {
4919 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4920 assert(InterleaveFactor <= 8 &&
4921 "Unsupported deinterleave factor for scalable vectors");
4922 auto *ResBlockInMask = State.get(BlockInMask);
4923 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4924 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4925 }
4926
4927 if (!BlockInMask)
4928 return MaskForGaps;
4929
4930 Value *ResBlockInMask = State.get(BlockInMask);
4931 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4932 ResBlockInMask,
4933 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4934 "interleaved.mask");
4935 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4936 ShuffledMask, MaskForGaps)
4937 : ShuffledMask;
4938 };
4939
4940 const DataLayout &DL = Instr->getDataLayout();
4941 // Vectorize the interleaved load group.
4942 if (isa<LoadInst>(Instr)) {
4943 Value *MaskForGaps = nullptr;
4944 if (needsMaskForGaps()) {
4945 MaskForGaps =
4946 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4947 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4948 }
4949
4950 Instruction *NewLoad;
4951 if (BlockInMask || MaskForGaps) {
4952 Value *GroupMask = CreateGroupMask(MaskForGaps);
4953 Value *PoisonVec = PoisonValue::get(VecTy);
4954 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4955 Group->getAlign(), GroupMask,
4956 PoisonVec, "wide.masked.vec");
4957 } else
4958 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4959 Group->getAlign(), "wide.vec");
4960 applyMetadata(*NewLoad);
4961 // TODO: Also manage existing metadata using VPIRMetadata.
4962 Group->addMetadata(NewLoad);
4963
4965 if (VecTy->isScalableTy()) {
4966 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4967 // so must use intrinsics to deinterleave.
4968 assert(InterleaveFactor <= 8 &&
4969 "Unsupported deinterleave factor for scalable vectors");
4970 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4971 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4972 NewLoad->getType(), NewLoad,
4973 /*FMFSource=*/nullptr, "strided.vec");
4974 }
4975
4976 auto CreateStridedVector = [&InterleaveFactor, &State,
4977 &NewLoad](unsigned Index) -> Value * {
4978 assert(Index < InterleaveFactor && "Illegal group index");
4979 if (State.VF.isScalable())
4980 return State.Builder.CreateExtractValue(NewLoad, Index);
4981
4982 // For fixed length VF, use shuffle to extract the sub-vectors from the
4983 // wide load.
4984 auto StrideMask =
4985 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4986 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4987 "strided.vec");
4988 };
4989
4990 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4991 Instruction *Member = Group->getMember(I);
4992
4993 // Skip the gaps in the group.
4994 if (!Member)
4995 continue;
4996
4997 Value *StridedVec = CreateStridedVector(I);
4998
4999 // If this member has different type, cast the result type.
5000 if (Member->getType() != ScalarTy) {
5001 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
5002 StridedVec =
5003 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
5004 }
5005
5006 if (Group->isReverse())
5007 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
5008
5009 State.set(VPDefs[J], StridedVec);
5010 ++J;
5011 }
5012 return;
5013 }
5014
5015 // The sub vector type for current instruction.
5016 auto *SubVT = VectorType::get(ScalarTy, State.VF);
5017
5018 // Vectorize the interleaved store group.
5019 Value *MaskForGaps =
5020 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
5021 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
5022 "Mismatch between NeedsMaskForGaps and MaskForGaps");
5023 ArrayRef<VPValue *> StoredValues = getStoredValues();
5024 // Collect the stored vector from each member.
5025 SmallVector<Value *, 4> StoredVecs;
5026 unsigned StoredIdx = 0;
5027 for (unsigned i = 0; i < InterleaveFactor; i++) {
5028 assert((Group->getMember(i) || MaskForGaps) &&
5029 "Fail to get a member from an interleaved store group");
5030 Instruction *Member = Group->getMember(i);
5031
5032 // Skip the gaps in the group.
5033 if (!Member) {
5034 Value *Undef = PoisonValue::get(SubVT);
5035 StoredVecs.push_back(Undef);
5036 continue;
5037 }
5038
5039 Value *StoredVec = State.get(StoredValues[StoredIdx]);
5040 ++StoredIdx;
5041
5042 if (Group->isReverse())
5043 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
5044
5045 // If this member has different type, cast it to a unified type.
5046
5047 if (StoredVec->getType() != SubVT)
5048 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
5049
5050 StoredVecs.push_back(StoredVec);
5051 }
5052
5053 // Interleave all the smaller vectors into one wider vector.
5054 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
5055 Instruction *NewStoreInstr;
5056 if (BlockInMask || MaskForGaps) {
5057 Value *GroupMask = CreateGroupMask(MaskForGaps);
5058 NewStoreInstr = State.Builder.CreateMaskedStore(
5059 IVec, ResAddr, Group->getAlign(), GroupMask);
5060 } else
5061 NewStoreInstr =
5062 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
5063
5064 applyMetadata(*NewStoreInstr);
5065 // TODO: Also manage existing metadata using VPIRMetadata.
5066 Group->addMetadata(NewStoreInstr);
5067}
5068
5069#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5071 VPSlotTracker &SlotTracker) const {
5073 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
5075 VPValue *Mask = getMask();
5076 if (Mask) {
5077 O << ", ";
5078 Mask->printAsOperand(O, SlotTracker);
5079 }
5080
5081 unsigned OpIdx = 0;
5082 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5083 if (!IG->getMember(i))
5084 continue;
5085 if (getNumStoreOperands() > 0) {
5086 O << "\n" << Indent << " store ";
5087 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
5088 O << " to index " << i;
5089 } else {
5090 O << "\n" << Indent << " ";
5092 O << " = load from index " << i;
5093 }
5094 ++OpIdx;
5095 }
5096}
5097#endif
5098
5100 assert(State.VF.isScalable() &&
5101 "Only support scalable VF for EVL tail-folding.");
5103 "Masking gaps for scalable vectors is not yet supported.");
5105 Instruction *Instr = Group->getInsertPos();
5106
5107 // Prepare for the vector type of the interleaved load/store.
5108 Type *ScalarTy = getLoadStoreType(Instr);
5109 unsigned InterleaveFactor = Group->getFactor();
5110 assert(InterleaveFactor <= 8 &&
5111 "Unsupported deinterleave/interleave factor for scalable vectors");
5112 ElementCount WideVF = State.VF * InterleaveFactor;
5113 auto *VecTy = VectorType::get(ScalarTy, WideVF);
5114
5115 VPValue *Addr = getAddr();
5116 Value *ResAddr = State.get(Addr, VPLane(0));
5117 Value *EVL = State.get(getEVL(), VPLane(0));
5118 Value *InterleaveEVL = State.Builder.CreateMul(
5119 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
5120 /* NUW= */ true, /* NSW= */ true);
5121 LLVMContext &Ctx = State.Builder.getContext();
5122
5123 Value *GroupMask = nullptr;
5124 if (VPValue *BlockInMask = getMask()) {
5125 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
5126 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
5127 } else {
5128 GroupMask =
5129 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
5130 }
5131
5132 // Vectorize the interleaved load group.
5133 if (isa<LoadInst>(Instr)) {
5134 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5135 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
5136 "wide.vp.load");
5137 NewLoad->addParamAttr(0,
5138 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5139
5140 applyMetadata(*NewLoad);
5141 // TODO: Also manage existing metadata using VPIRMetadata.
5142 Group->addMetadata(NewLoad);
5143
5144 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
5145 // so must use intrinsics to deinterleave.
5146 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5147 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
5148 NewLoad->getType(), NewLoad,
5149 /*FMFSource=*/nullptr, "strided.vec");
5150
5151 const DataLayout &DL = Instr->getDataLayout();
5152 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
5153 Instruction *Member = Group->getMember(I);
5154 // Skip the gaps in the group.
5155 if (!Member)
5156 continue;
5157
5158 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
5159 // If this member has different type, cast the result type.
5160 if (Member->getType() != ScalarTy) {
5161 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
5162 StridedVec =
5163 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
5164 }
5165
5166 State.set(getVPValue(J), StridedVec);
5167 ++J;
5168 }
5169 return;
5170 } // End for interleaved load.
5171
5172 // The sub vector type for current instruction.
5173 auto *SubVT = VectorType::get(ScalarTy, State.VF);
5174 // Vectorize the interleaved store group.
5175 ArrayRef<VPValue *> StoredValues = getStoredValues();
5176 // Collect the stored vector from each member.
5177 SmallVector<Value *, 4> StoredVecs;
5178 const DataLayout &DL = Instr->getDataLayout();
5179 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
5180 Instruction *Member = Group->getMember(I);
5181 // Skip the gaps in the group.
5182 if (!Member) {
5183 StoredVecs.push_back(PoisonValue::get(SubVT));
5184 continue;
5185 }
5186
5187 Value *StoredVec = State.get(StoredValues[StoredIdx]);
5188 // If this member has different type, cast it to a unified type.
5189 if (StoredVec->getType() != SubVT)
5190 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
5191
5192 StoredVecs.push_back(StoredVec);
5193 ++StoredIdx;
5194 }
5195
5196 // Interleave all the smaller vectors into one wider vector.
5197 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
5198 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
5199 Type::getVoidTy(Ctx), Intrinsic::vp_store,
5200 {IVec, ResAddr, GroupMask, InterleaveEVL});
5201
5202 NewStore->addParamAttr(1,
5203 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5204
5205 applyMetadata(*NewStore);
5206 // TODO: Also manage existing metadata using VPIRMetadata.
5207 Group->addMetadata(NewStore);
5208}
5209
5210#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5212 VPSlotTracker &SlotTracker) const {
5214 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
5216 O << ", ";
5218 if (VPValue *Mask = getMask()) {
5219 O << ", ";
5220 Mask->printAsOperand(O, SlotTracker);
5221 }
5222
5223 unsigned OpIdx = 0;
5224 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5225 if (!IG->getMember(i))
5226 continue;
5227 if (getNumStoreOperands() > 0) {
5228 O << "\n" << Indent << " vp.store ";
5229 getOperand(2 + OpIdx)->printAsOperand(O, SlotTracker);
5230 O << " to index " << i;
5231 } else {
5232 O << "\n" << Indent << " ";
5234 O << " = vp.load from index " << i;
5235 }
5236 ++OpIdx;
5237 }
5238}
5239#endif
5240
5242 VPCostContext &Ctx) const {
5243 Instruction *InsertPos = getInsertPos();
5244 // Find the VPValue index of the interleave group. We need to skip gaps.
5245 unsigned InsertPosIdx = 0;
5246 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
5247 if (auto *Member = IG->getMember(Idx)) {
5248 if (Member == InsertPos)
5249 break;
5250 InsertPosIdx++;
5251 }
5252 const VPValue *ValV = getNumDefinedValues() > 0
5253 ? getVPValue(InsertPosIdx)
5254 : getStoredValues()[InsertPosIdx];
5255 Type *ValTy = ValV->getScalarType();
5256 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5257 unsigned AS =
5258 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
5259
5260 unsigned InterleaveFactor = IG->getFactor();
5261 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5262
5263 // Holds the indices of existing members in the interleaved group.
5265 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5266 if (IG->getMember(IF))
5267 Indices.push_back(IF);
5268
5269 // Calculate the cost of the whole interleaved group.
5270 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
5271 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
5272 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
5273
5274 if (!IG->isReverse())
5275 return Cost;
5276
5277 return Cost + IG->getNumMembers() *
5278 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5279 VectorTy, VectorTy, Ctx.CostKind, {},
5280 0);
5281}
5282
5285 VPCostContext &Ctx) const {
5286 // The recipe creates a scalar phi, a GEP to increment the induction and
5287 // vector add to compute the vector of pointers.
5288 // TODO: Charge costs for induction increment and vector add as well.
5289 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5290}
5291
5296
5297#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5299 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5300 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
5301 "unexpected number of operands");
5302 O << Indent << "EMIT ";
5304 O << " = WIDEN-POINTER-INDUCTION ";
5306 O << ", ";
5308 O << ", ";
5310 if (getNumOperands() == 5) {
5311 O << ", ";
5313 O << ", ";
5315 }
5316}
5317
5319 VPSlotTracker &SlotTracker) const {
5320 O << Indent << "EMIT ";
5322 O << " = EXPAND SCEV " << *Expr;
5323 if (ExpandInIR)
5324 O << " (in IR)";
5325}
5326#endif
5327
5328#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5330 VPSlotTracker &SlotTracker) const {
5331 O << Indent << "EMIT ";
5333 O << " = WIDEN-CANONICAL-INDUCTION";
5334 printFlags(O);
5336}
5337#endif
5338
5340 auto &Builder = State.Builder;
5341 // Create a vector from the initial value.
5342 auto *VectorInit = getStartValue()->getLiveInIRValue();
5343
5344 Type *VecTy = State.VF.isScalar()
5345 ? VectorInit->getType()
5346 : VectorType::get(VectorInit->getType(), State.VF);
5347
5348 BasicBlock *VectorPH =
5349 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5350 if (State.VF.isVector()) {
5351 auto *IdxTy = Builder.getInt32Ty();
5352 auto *One = ConstantInt::get(IdxTy, 1);
5353 IRBuilder<>::InsertPointGuard Guard(Builder);
5354 Builder.SetInsertPoint(VectorPH->getTerminator());
5355 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
5356 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
5357 VectorInit = Builder.CreateInsertElement(
5358 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
5359 }
5360
5361 // Create a phi node for the new recurrence.
5362 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
5363 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
5364 Phi->addIncoming(VectorInit, VectorPH);
5365 State.set(this, Phi);
5366}
5367
5370 VPCostContext &Ctx) const {
5371 if (VF.isScalar())
5372 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5373
5374 return 0;
5375}
5376
5377#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5379 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5380 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
5382 O << " = phi ";
5384}
5385#endif
5386
5388 // Reductions do not have to start at zero. They can start with
5389 // any loop invariant values.
5390 VPValue *StartVPV = getStartValue();
5391
5392 // In order to support recurrences we need to be able to vectorize Phi nodes.
5393 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
5394 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
5395 // this value when we vectorize all of the instructions that use the PHI.
5396 BasicBlock *VectorPH =
5397 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5398 bool ScalarPHI = State.VF.isScalar() || isInLoop();
5399 Value *StartV = State.get(StartVPV, ScalarPHI);
5400 Type *VecTy = StartV->getType();
5401
5402 BasicBlock *HeaderBB = State.CFG.PrevBB;
5403 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
5404 "recipe must be in the vector loop header");
5405 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
5406 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
5407 State.set(this, Phi, isInLoop());
5408
5409 Phi->addIncoming(StartV, VectorPH);
5410}
5411
5412#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5414 VPSlotTracker &SlotTracker) const {
5415 O << Indent << "WIDEN-REDUCTION-PHI ";
5416
5418 O << " = phi (";
5419 printRecurrenceKind(O, Kind);
5420 O << ")";
5421 printFlags(O);
5423 if (getVFScaleFactor() > 1)
5424 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
5425}
5426#endif
5427
5429 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
5431 "Blend should propagate first lane use");
5432 return vputils::onlyFirstLaneUsed(this);
5433}
5434
5437 VPCostContext &Ctx) const {
5438 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5439}
5440
5441#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5443 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5444 O << Indent << "CONDITIONAL-INDUCTION-PHI ";
5445
5447 O << " = phi ";
5449}
5450#endif
5451
5453 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
5454}
5455
5457 VPCostContext &Ctx) const {
5458 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5459}
5460
5461#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5463 VPSlotTracker &SlotTracker) const {
5464 O << Indent << "WIDEN-PHI ";
5465
5467 O << " = phi ";
5469}
5470#endif
5471
5473 BasicBlock *VectorPH =
5474 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5475 Value *StartMask = State.get(getOperand(0));
5476 PHINode *Phi =
5477 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
5478 Phi->addIncoming(StartMask, VectorPH);
5479 State.set(this, Phi);
5480}
5481
5482#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5484 VPSlotTracker &SlotTracker) const {
5485 O << Indent << "ACTIVE-LANE-MASK-PHI ";
5486
5488 O << " = phi ";
5490}
5491#endif
5492
5493#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5495 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5496 O << Indent << "CURRENT-ITERATION-PHI ";
5497
5499 O << " = phi ";
5501}
5502#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[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets the address access SCEV for Ptr, if it should be used for cost modeling according to isAddressSC...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const Value *V)
static bool isOrdered(const Instruction *I)
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
SI Fold Operands
static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, EVT VT, SDValue A, SDValue B, SDValue GlueChain, SDNodeFlags Flags)
This file contains some templates that are useful if you are working with the STL at all.
This file defines less commonly used SmallVector utilities.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static 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:306
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:448
bool hasAttributes() const
Return true if attributes exists in this set.
Definition Attributes.h:529
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:532
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:126
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
static LLVM_ABI StringRef getPredicateName(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h: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:64
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:127
static DebugLoc getUnknown()
Definition DebugLoc.h:154
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.
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(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
This class represents the LLVM 'select' instruction.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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:4546
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:3097
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3092
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:3088
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:95
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:228
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.
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...
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:4353
VPValue * getIndex() const
Definition VPlan.h:4350
VPValue * getStepValue() const
Definition VPlan.h:4351
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:4349
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:2518
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:2230
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:1293
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:1287
Class to record and manage LLVM IR flags.
Definition VPlan.h:683
FastMathFlagsTy FMFs
Definition VPlan.h:775
ReductionFlagsTy ReductionFlags
Definition VPlan.h:777
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:769
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:978
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:1033
TruncFlagsTy TruncFlags
Definition VPlan.h:770
CmpInst::Predicate getPredicate() const
Definition VPlan.h:950
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:772
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:773
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:968
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:973
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:771
FCmpFlagsTy FCmpFlags
Definition VPlan.h:776
NonNegFlagsTy NonNegFlags
Definition VPlan.h:774
bool isReductionInLoop() const
Definition VPlan.h:1039
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:915
uint8_t CmpPredStorage
Definition VPlan.h:768
RecurKind getRecurKind() const
Definition VPlan.h:1027
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:1748
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:1201
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:1322
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:1609
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:1437
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1449
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1427
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1441
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1445
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1431
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1378
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1423
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1373
@ CanonicalIVIncrementForPart
Definition VPlan.h:1358
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1381
bool hasResult() const
Definition VPlan.h:1549
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:1612
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:1531
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:1578
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:1552
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:3201
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3205
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3203
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3195
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3224
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3189
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3298
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:3311
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:3261
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:1627
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:1677
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1636
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:402
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:4951
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:106
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:515
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:547
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:462
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:3472
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:2945
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2964
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:3411
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:3424
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3426
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3407
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3413
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3422
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3417
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:4777
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4853
const VPBranchOnMaskRecipe * getEntryBranchOnMask() const
Return the VPBranchOnMaskRecipe from the entry block of this replicating region.
Definition VPlan.cpp:703
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:3551
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:3589
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:4408
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4416
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:605
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:668
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, Value *UV=nullptr, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:607
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:1515
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:138
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:132
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1467
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:119
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1511
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:2341
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:2338
int64_t getStride() const
Definition VPlan.h:2339
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2413
Type * getSourceElementType() const
Definition VPlan.h:2428
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:2415
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:2182
Function * getCalledScalarFunction() const
Definition VPlan.h:2178
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:1938
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:2295
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:2596
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2613
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:2695
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:2053
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:3870
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3895
Instruction & Ingredient
Definition VPlan.h:3861
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3867
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3905
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3864
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3912
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3898
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:1880
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4964
const DataLayout & getDataLayout() const
Definition VPlan.h:5165
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:5271
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:102
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...
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:66
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
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:373
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.
@ FMinimum
FP min with llvm.minimum semantics.
@ FMaxNum
FP max with llvm.maxnum semantics including NaNs.
@ Mul
Product of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ None
Not a recurrence.
@ AnyOf
AnyOf reduction with select(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max implemented in terms of select(cmp()).
@ FMaximum
FP max with llvm.maximum semantics.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min implemented in terms of select(cmp()).
@ FMinNum
FP min with llvm.minnum semantics including NaNs.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ FMaximumNum
FP max with llvm.maximumnum semantics.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
DWARFExpression::Operation Op
LLVM_ABI 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:1927
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:1140
void execute(VPTransformState &State) override
Generate the phi nodes.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1803
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
PHINode & getIRPhi() const
Definition VPlan.h:1816
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:1090
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:266
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:3999
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:4102
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:4105
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:4049