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 InstructionCost RecipeCost;
360 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
361 RecipeCost = 0;
362 } else {
363 RecipeCost = computeCost(VF, Ctx);
364 if (Ctx.Opts.force_target_instruction_cost && RecipeCost.isValid()) {
365 // VPDerivedIVRecipe, VPScalarIVStepsRecipe and VPBranchOnMaskRecipe never
366 // have underlying instructions.
367 if (UI ||
369 this))
370 RecipeCost = InstructionCost(*Ctx.Opts.force_target_instruction_cost);
371 else
372 RecipeCost = InstructionCost(0);
373 }
374 }
375
376 LLVM_DEBUG({
377 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
378 if (VPSlotTracker *SlotTracker = Ctx.getSlotTracker()) {
379 print(dbgs(), "", *SlotTracker);
380 dbgs() << "\n";
381 } else {
382 dump();
383 }
384 });
385 return RecipeCost;
386}
387
389 VPCostContext &Ctx) const {
390 llvm_unreachable("subclasses should implement computeCost");
391}
392
394 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
396}
397
399 assert(OpType == Other.OpType && "OpType must match");
400 switch (OpType) {
401 case OperationType::OverflowingBinOp:
402 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
403 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
404 break;
405 case OperationType::Trunc:
406 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
407 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
408 break;
409 case OperationType::DisjointOp:
410 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
411 break;
412 case OperationType::PossiblyExactOp:
413 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
414 break;
415 case OperationType::GEPOp:
416 GEPFlagsStorage &= Other.GEPFlagsStorage;
417 break;
418 case OperationType::FPMathOp:
419 case OperationType::FCmp:
420 assert((OpType != OperationType::FCmp ||
421 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
422 "Cannot drop CmpPredicate");
423 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
424 break;
425 case OperationType::NonNegOp:
426 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
427 break;
428 case OperationType::Cmp:
429 assert(CmpPredStorage == Other.CmpPredStorage &&
430 "Cannot drop CmpPredicate");
431 break;
432 case OperationType::ReductionOp:
433 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
434 "Cannot change RecurKind");
435 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
436 "Cannot change IsOrdered");
437 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
438 "Cannot change IsInLoop");
439 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
440 break;
441 case OperationType::Other:
442 break;
443 }
444}
445
447 if (!hasFastMathFlags())
448 return {};
449 const FastMathFlagsTy &F = getFMFsRef();
450 FastMathFlags Res;
451 Res.setAllowReassoc(F.AllowReassoc);
452 Res.setNoNaNs(F.NoNaNs);
453 Res.setNoInfs(F.NoInfs);
454 Res.setNoSignedZeros(F.NoSignedZeros);
455 Res.setAllowReciprocal(F.AllowReciprocal);
456 Res.setAllowContract(F.AllowContract);
457 Res.setApproxFunc(F.ApproxFunc);
458 return Res;
459}
460
461#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
463
464void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
465 VPSlotTracker &SlotTracker) const {
466 printRecipe(O, Indent, SlotTracker);
467 if (auto DL = getDebugLoc()) {
468 O << ", !dbg ";
469 DL.print(O);
470 }
471
472 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
474}
475#endif
476
477VPExpandSCEVRecipe::VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR)
478 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
479 Expr(Expr), ExpandInIR(ExpandInIR) {}
480
486
489 assert(!Operands.empty() &&
490 "zero-operand VPInstruction opcodes must pass explicit ResultTy");
491 // Assert operand \p Idx (if present and typed) has type \p ExpectedTy.
492 [[maybe_unused]] auto AssertOperandType = [&Operands](unsigned Idx,
493 Type *ExpectedTy) {
494 if (!ExpectedTy || Operands.size() <= Idx)
495 return;
496 [[maybe_unused]] Type *OpTy = Operands[Idx]->getScalarType();
497 assert((!OpTy || OpTy == ExpectedTy) &&
498 "different types inferred for different operands");
499 };
500
501 Type *Op0Ty = Operands[0]->getScalarType();
502 LLVMContext &Ctx = Op0Ty->getContext();
503 switch (Opcode) {
505 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
506 return Type::getVoidTy(Ctx);
508 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
509 AssertOperandType(1, IntegerType::get(Ctx, 1));
510 return Type::getVoidTy(Ctx);
512 assert(Op0Ty->isIntegerTy() && "expected integer operand");
513 AssertOperandType(1, Op0Ty);
514 return Type::getVoidTy(Ctx);
516 assert(Op0Ty->isIntegerTy() && "expected integer operand");
517 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
518 AssertOperandType(Idx, Op0Ty);
519 return Op0Ty;
520 case Instruction::Switch:
521 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
522 AssertOperandType(Idx, Op0Ty);
523 return Type::getVoidTy(Ctx);
525 case Instruction::Store:
526 return Type::getVoidTy(Ctx);
527 case Instruction::ICmp:
528 assert(Op0Ty->isIntOrPtrTy() && "expected integer or pointer operand");
529 AssertOperandType(1, Op0Ty);
530 return IntegerType::get(Ctx, 1);
531 case Instruction::FCmp:
532 assert(Op0Ty->isFloatingPointTy() && "expected floating-point operand");
533 AssertOperandType(1, Op0Ty);
534 return IntegerType::get(Ctx, 1);
537 assert(Op0Ty->isIntegerTy() && "expected integer operand");
538 AssertOperandType(1, Op0Ty);
539 return IntegerType::get(Ctx, 1);
541 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
542 return IntegerType::get(Ctx, 1);
545 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
546 AssertOperandType(1, Op0Ty);
547 return IntegerType::get(Ctx, 1);
549 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
550 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
551 AssertOperandType(Idx, Op0Ty);
552 return IntegerType::get(Ctx, 1);
554 assert(Op0Ty->isIntegerTy() && "expected integer operand");
555 return IntegerType::get(Ctx, 32);
556 case Instruction::Select: {
557 assert((!Op0Ty || Op0Ty->isIntegerTy(1)) &&
558 "select condition must be bool");
559 Type *Op1Ty = Operands[1]->getScalarType();
560 AssertOperandType(2, Op1Ty);
561 return Op1Ty;
562 }
563 case Instruction::InsertElement:
564 // The inserted scalar (operand 1) must match the vector element type;
565 // operand 2 must be an integer.
566 AssertOperandType(1, Op0Ty);
567 assert(Operands[2]->getScalarType()->isIntegerTy() &&
568 "expected integer operand");
569 return Op0Ty;
571 // The start value and the identity value (operands 0 and 1) fill the same
572 // vector and must match in type; operand 2 is the scaling factor.
573 AssertOperandType(1, Op0Ty);
574 return Op0Ty;
576 assert(Operands.size() >= 2 && "ExtractLane requires a lane operand and "
577 "at least one source vector operand");
578 // Operand 0 is the lane index, used for integer arithmetic.
579 assert(Op0Ty->isIntegerTy() && "expected integer operand");
580 Type *Op1Ty = Operands[1]->getScalarType();
581 for (unsigned Idx = 2; Idx != Operands.size(); ++Idx)
582 AssertOperandType(Idx, Op1Ty);
583 return Op1Ty;
584 }
587 assert(Operands[0]->getScalarType()->isPointerTy() &&
588 "expected pointer operand");
589 assert(Operands[1]->getScalarType()->isIntegerTy() &&
590 "expected integer operand");
591 return Op0Ty;
592 case Instruction::ExtractValue:
600 case Instruction::Load:
601 case Instruction::Alloca:
602 llvm_unreachable("type must be passed explicitly");
603 case Instruction::Call:
607 "BuildVector operands must be valid vector elements");
608 break;
609 default:
610 if (Instruction::isCast(Opcode))
611 llvm_unreachable("type must be passed explicitly");
612 break;
613 }
614
615 // Opcodes that require all operands to share the same scalar type as the
616 // result.
617 bool AllOperandsSameType =
618 Instruction::isBinaryOp(Opcode) ||
622 Opcode);
623 if (AllOperandsSameType)
624 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
625 AssertOperandType(Idx, Op0Ty);
626
627 return Op0Ty;
628}
629
632 unsigned Opcode = I->getOpcode();
633 if (Instruction::isCast(Opcode) ||
634 is_contained(ArrayRef<unsigned>({Instruction::Load, Instruction::Alloca}),
635 Opcode))
636 return I->getType();
638}
639
641 const VPIRFlags &Flags, const VPIRMetadata &MD,
642 DebugLoc DL, const Twine &Name, Type *ResultTy,
643 const VPIRAttributes &Attrs)
645 VPRecipeBase::VPInstructionSC, Operands,
646 ResultTy ? ResultTy
648 Flags, DL),
649 VPIRMetadata(MD), VPIRAttributes(Attrs), Opcode(Opcode),
650 Name(Name.str()) {
652 "Set flags not supported for the provided opcode");
654 "Opcode requires specific flags to be set");
658 "number of operands does not match opcode");
659}
660
662 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
663 return 1;
664
665 if (Instruction::isBinaryOp(Opcode))
666 return 2;
667
668 switch (Opcode) {
671 return 0;
672 case Instruction::Alloca:
673 case Instruction::Freeze:
674 case Instruction::Load:
687 return 1;
688 case Instruction::ICmp:
689 case Instruction::FCmp:
690 case Instruction::ExtractElement:
691 case Instruction::Store:
703 return 2;
704 case Instruction::InsertElement:
705 case Instruction::Select:
709 return 3;
711 return 4;
712 case Instruction::Call:
713 return getCalledFnOperandIndex(operands()) + 1;
714 case Instruction::GetElementPtr:
715 case Instruction::PHI:
716 case Instruction::Switch:
717 case Instruction::AtomicRMW:
718 case Instruction::AtomicCmpXchg:
719 case Instruction::ExtractValue:
720 case Instruction::Fence:
731 // Cannot determine the number of operands from the opcode.
732 return -1u;
733 }
734 llvm_unreachable("all cases should be handled above");
735}
736
738 return Opcode == VPInstruction::Unpack ||
740}
741
742bool VPInstruction::doesGenerateSingleScalar() const {
744 return true;
745 switch (Opcode) {
746 case Instruction::Freeze:
747 case Instruction::ICmp:
748 case Instruction::PHI:
749 case Instruction::Select:
758 return vputils::onlyFirstLaneUsed(this);
759 default:
761 }
762}
763
765 if (Kind == RecurKind::Sub)
766 return Instruction::Add;
767 if (Kind == RecurKind::FSub)
768 return Instruction::FAdd;
769 llvm_unreachable("RecurKind should be Sub/FSub.");
770}
771
772Value *VPInstruction::generate(VPTransformState &State,
773 bool GenerateSingleScalar) {
774 IRBuilderBase &Builder = State.Builder;
775
777 Value *A = State.get(getOperand(0), GenerateSingleScalar);
778 Value *B = State.get(getOperand(1), GenerateSingleScalar);
779 auto *Res =
780 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
781 if (auto *I = dyn_cast<Instruction>(Res))
782 applyFlags(*I);
783 return Res;
784 }
786 Value *Op = State.get(getOperand(0), VPLane(0));
788 getScalarType());
789 if (auto *CastOp = dyn_cast<Instruction>(Res)) {
790 applyFlags(*CastOp);
791 applyMetadata(*CastOp);
792 }
793 return Res;
794 }
795
796 switch (getOpcode()) {
797 case VPInstruction::Not: {
798 Value *A = State.get(getOperand(0), GenerateSingleScalar);
799 return Builder.CreateNot(A, Name);
800 }
802 // TODO: Use IsSingleScalar to produce a scalar value.
803 Value *A = State.get(getOperand(0));
804 Value *B = State.get(getOperand(1));
805 return Builder.CreateLogicalAnd(A, B, Name);
806 }
808 // TODO: Use IsSingleScalar to produce a scalar value.
809 Value *A = State.get(getOperand(0));
810 Value *B = State.get(getOperand(1));
811 return Builder.CreateLogicalOr(A, B, Name);
812 }
813 case Instruction::ExtractElement: {
814 assert(GenerateSingleScalar &&
815 "Can only generate first lane for ExtractElement");
816 assert(State.VF.isVector() && "Only extract elements from vectors");
817 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
818 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
819 Value *Vec = State.get(getOperand(0));
820 Value *Idx = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
821 return Builder.CreateExtractElement(Vec, Idx, Name);
822 }
823 case Instruction::InsertElement: {
824 assert(!GenerateSingleScalar &&
825 "Cannot generate scalar value for InsertElement");
826 assert(State.VF.isVector() && "Can only insert elements into vectors");
827 Value *Vec = State.get(getOperand(0), /*NeedsSingleScalar=*/false);
828 Value *Elt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
829 Value *Idx = State.get(getOperand(2), /*NeedsSingleScalar=*/true);
830 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
831 }
832 case Instruction::Freeze: {
833 Value *Op = State.get(getOperand(0), GenerateSingleScalar);
834 return Builder.CreateFreeze(Op, Name);
835 }
836 case Instruction::FCmp:
837 case Instruction::ICmp: {
838 Value *A = State.get(getOperand(0), GenerateSingleScalar);
839 Value *B = State.get(getOperand(1), GenerateSingleScalar);
840 return Builder.CreateCmp(getPredicate(), A, B, Name);
841 }
842 case Instruction::PHI: {
843 llvm_unreachable("should be handled by VPPhi::execute");
844 }
845 case Instruction::Select: {
846 Value *Cond =
847 State.get(getOperand(0), GenerateSingleScalar ||
849 Value *Op1 = State.get(getOperand(1), GenerateSingleScalar);
850 Value *Op2 = State.get(getOperand(2), GenerateSingleScalar);
851 Value *Sel =
852 Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(), Name);
853 if (auto *I = dyn_cast<Instruction>(Sel))
855 return Sel;
856 }
859 // Can produce either a scalar value as a icmp of a phi, or a vector value,
860 // as a get.active.lane.mask intrinsic.
861 // Get first lane of vector induction variable.
862 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
863 // Get the original loop tripcount.
864 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
865
866 uint64_t Multiplier =
868 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
869 : 1;
870
871 // If this part of the active lane mask is scalar, generate the CMP directly
872 // to avoid unnecessary extracts.
873 if (State.VF.isScalar() && Multiplier == 1)
874 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
875 Name);
876
877 auto *PredTy = VectorType::get(Builder.getInt1Ty(), State.VF * Multiplier);
878 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
879 {PredTy, ScalarTC->getType()},
880 {VIVElem0, ScalarTC}, nullptr, Name);
881 }
883 assert(GenerateSingleScalar &&
884 "Can only generate first lane for NumActiveLanes");
885 Value *Op = State.get(getOperand(0));
886 auto *VecTy = cast<VectorType>(Op->getType());
887 assert(VecTy->getScalarSizeInBits() == 1 &&
888 "NumActiveLanes only implemented for i1 vectors");
889
890 Type *Ty = getScalarType();
891 Value *ZExt = Builder.CreateCast(
892 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
893 Value *NumActive =
894 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
895 return NumActive;
896 }
898 // Generate code to combine the previous and current values in vector v3.
899 //
900 // vector.ph:
901 // v_init = vector(..., ..., ..., a[-1])
902 // br vector.body
903 //
904 // vector.body
905 // i = phi [0, vector.ph], [i+4, vector.body]
906 // v1 = phi [v_init, vector.ph], [v2, vector.body]
907 // v2 = a[i, i+1, i+2, i+3];
908 // v3 = vector(v1(3), v2(0, 1, 2))
909
910 auto *V1 = State.get(getOperand(0));
911 if (!V1->getType()->isVectorTy())
912 return V1;
913 Value *V2 = State.get(getOperand(1));
914 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
915 }
917 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
918 // be outside of the main loop.
919 assert(GenerateSingleScalar &&
920 "Can only generate first lane for ExplicitVectorLength");
921 Value *AVL = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
922 // Compute EVL
923 assert(AVL->getType()->isIntegerTy() &&
924 "Requested vector length should be an integer.");
925
926 assert(State.VF.isScalable() && "Expected scalable vector factor.");
927 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
928
929 Value *EVL = Builder.CreateIntrinsic(
930 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
931 {AVL, VFArg, Builder.getTrue()});
932 return EVL;
933 }
935 assert(GenerateSingleScalar &&
936 "Can only generate first lane for BranchOnCond");
937 Value *Cond = State.get(getOperand(0), VPLane(0));
938 // Replace the temporary unreachable terminator with a new conditional
939 // branch, hooking it up to backward destination for latch blocks now, and
940 // to forward destination(s) later when they are created.
941 // Second successor may be backwards - iff it is already in VPBB2IRBB.
942 VPBasicBlock *SecondVPSucc =
943 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
944 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
945 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
946 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
947 // First successor is always forward, reset it to nullptr.
948 Br->setSuccessor(0, nullptr);
950 applyMetadata(*Br);
951 return Br;
952 }
954 assert(!GenerateSingleScalar &&
955 "Cannot generate scalar value for Broadcast");
956 return Builder.CreateVectorSplat(
957 State.VF, State.get(getOperand(0), /*NeedsSingleScalar=*/true),
958 "broadcast");
959 }
961 assert(!GenerateSingleScalar &&
962 "Cannot generate scalar value for BuildVector");
963 Value *Res = PoisonValue::get(
965 for (const auto &[Idx, Op] : enumerate(operands()))
966 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
967 Builder.getInt64(Idx));
968 return Res;
969 }
971 Type *ScalarTy = getScalarType();
972 auto *WideTy = VectorType::get(ScalarTy, State.VF * getNumOperands());
973 Value *Res = PoisonValue::get(WideTy);
974 for (const auto &[Idx, Op] : enumerate(operands()))
975 Res = Builder.CreateInsertVector(WideTy, Res, State.get(Op),
976 Idx * State.VF.getKnownMinValue());
977 return Res;
978 }
980 if (State.VF.isScalar())
981 return State.get(getOperand(0), true);
982 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
984 // If this start vector is scaled then it should produce a vector with fewer
985 // elements than the VF.
986 ElementCount VF = State.VF.divideCoefficientBy(
987 cast<VPConstantInt>(getOperand(2))->getZExtValue());
988 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
989 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
990 Builder.getInt64(0));
991 }
993 assert(GenerateSingleScalar &&
994 "Can only generate first lane for ComputeReductionResult");
995 RecurKind RK = getRecurKind();
996 bool IsOrdered = isReductionOrdered();
997 bool IsInLoop = isReductionInLoop();
999 "FindIV should use min/max reduction kinds");
1000
1001 // The recipe may have multiple operands to be reduced together.
1002 unsigned NumOperandsToReduce = getNumOperands();
1003 SmallVector<Value *, 2> RdxParts(NumOperandsToReduce);
1004 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
1005 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
1006
1007 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
1009
1010 // Reduce multiple operands into one.
1011 Value *ReducedPartRdx = RdxParts[0];
1012 if (IsOrdered) {
1013 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
1014 } else {
1015 // Floating-point operations should have some FMF to enable the reduction.
1016 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
1017 Value *RdxPart = RdxParts[Part];
1019 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
1020 else {
1021 // For sub-recurrences, each part's reduction variable is already
1022 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
1023 Instruction::BinaryOps Opcode =
1025 ? getSubRecurOpcode(RK)
1026 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
1027 ReducedPartRdx =
1028 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
1029 }
1030 }
1031 }
1032
1033 // Create the reduction after the loop. Note that inloop reductions create
1034 // the target reduction in the loop using a Reduction recipe.
1035 if (State.VF.isVector() && !IsInLoop) {
1036 // TODO: Support in-order reductions based on the recurrence descriptor.
1037 // All ops in the reduction inherit fast-math-flags from the recurrence
1038 // descriptor.
1039 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
1040 }
1041
1042 return ReducedPartRdx;
1043 }
1046 assert(GenerateSingleScalar &&
1047 "Can only generate first lane for ExtractLane and "
1048 "ExtractPenultimateElement");
1049 unsigned Offset =
1051 Value *Res;
1052 if (State.VF.isVector()) {
1053 assert(Offset <= State.VF.getKnownMinValue() &&
1054 "invalid offset to extract from");
1055 // Extract lane VF - Offset from the operand.
1056 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
1057 } else {
1058 // TODO: Remove ExtractLastLane for scalar VFs.
1059 assert(Offset <= 1 && "invalid offset to extract from");
1060 Res = State.get(getOperand(0));
1061 }
1062 if (isa<ExtractElementInst>(Res))
1063 Res->setName(Name);
1064 return Res;
1065 }
1066 case VPInstruction::PtrAdd: {
1067 assert(GenerateSingleScalar && "Can only generate first lane for PtrAdd");
1068 Value *Ptr = State.get(getOperand(0), VPLane(0));
1069 Value *Addend = State.get(getOperand(1), VPLane(0));
1070 // TODO: Require that offset matches index type in VPlan.
1071 Addend = Builder.CreateSExtOrTrunc(
1072 Addend, Builder.getDataLayout().getIndexType(Ptr->getType()));
1073 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1074 }
1076 assert(!GenerateSingleScalar &&
1077 "Cannot generate scalar value for WidePtrAdd");
1078 Value *Ptr =
1080 Value *Addend = State.get(getOperand(1));
1081 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1082 }
1083 case VPInstruction::AnyOf: {
1084 assert(GenerateSingleScalar && "Can only generate first lane for AnyOf");
1085 Value *Res = State.get(getOperand(0));
1086 for (VPValue *Op : drop_begin(operands()))
1087 Res = Builder.CreateOr(Res, State.get(Op));
1088 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1089 }
1091 assert(GenerateSingleScalar &&
1092 "Can only generate first lane for ExtractLane");
1093 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1094 "simplified to ExtractElement.");
1095 Value *LaneToExtract = State.get(getOperand(0), true);
1096 Type *IdxTy = getOperand(0)->getScalarType();
1097 Value *Res = nullptr;
1098 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1099
1100 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1101 Value *VectorStart =
1102 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1103 Value *VectorIdx = Idx == 1
1104 ? LaneToExtract
1105 : Builder.CreateSub(LaneToExtract, VectorStart);
1106 Value *Ext = State.VF.isScalar()
1107 ? State.get(getOperand(Idx))
1108 : Builder.CreateExtractElement(
1109 State.get(getOperand(Idx)), VectorIdx);
1110 if (Res) {
1111 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1112 Res = Builder.CreateSelect(Cmp, Ext, Res);
1113 } else {
1114 Res = Ext;
1115 }
1116 }
1117 return Res;
1118 }
1120 assert(GenerateSingleScalar &&
1121 "Can only generate first lane for FirstActiveLane");
1122 Type *Ty = this->getScalarType();
1123 if (getNumOperands() == 1) {
1124 Value *Mask = State.get(getOperand(0));
1125 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1126 /*ZeroIsPoison=*/false, Name);
1127 }
1128 // If there are multiple operands, create a chain of selects to pick the
1129 // first operand with an active lane and add the number of lanes of the
1130 // preceding operands.
1131 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
1132 unsigned LastOpIdx = getNumOperands() - 1;
1133 Value *Res = nullptr;
1134 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1135 Value *TrailingZeros =
1136 State.VF.isScalar()
1137 ? Builder.CreateZExt(
1138 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1139 Builder.getFalse()),
1140 Ty)
1142 Ty, State.get(getOperand(Idx)),
1143 /*ZeroIsPoison=*/false, Name);
1144 Value *Current = Builder.CreateAdd(
1145 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1146 TrailingZeros);
1147 if (Res) {
1148 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1149 Res = Builder.CreateSelect(Cmp, Current, Res);
1150 } else {
1151 Res = Current;
1152 }
1153 }
1154
1155 return Res;
1156 }
1158 assert(GenerateSingleScalar &&
1159 "Can only generate first lane for ResumeForEpilogue");
1160 return State.get(getOperand(0), true);
1162 assert(!GenerateSingleScalar && "Cannot generate scalar value for Reverse");
1163 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1165 assert(GenerateSingleScalar &&
1166 "Can only generate first lane for ExtractLastActive");
1167 Value *Result = State.get(getOperand(0), /*NeedsSingleScalar=*/true);
1168 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1169 Value *Data = State.get(getOperand(Idx));
1170 Value *Mask = State.get(getOperand(Idx + 1));
1171 Type *VTy = Data->getType();
1172
1173 if (State.VF.isScalar())
1174 Result = Builder.CreateSelect(Mask, Data, Result);
1175 else
1176 Result = Builder.CreateIntrinsic(
1177 Intrinsic::experimental_vector_extract_last_active, {VTy},
1178 {Data, Mask, Result});
1179 }
1180
1181 return Result;
1182 }
1184 assert(!GenerateSingleScalar &&
1185 "Cannot generate scalar value for ExtractVectorForPart");
1186 Value *Src = State.get(getOperand(0));
1187 Type *DstTy = VectorType::get(getScalarType(), State.VF);
1188 uint64_t Part = cast<VPConstantInt>(getOperand(1))->getZExtValue();
1189
1190 if (Src->getType() == DstTy)
1191 return Src;
1192
1193 return Builder.CreateExtractVector(
1194 DstTy, Src, Builder.getInt64(State.VF.getKnownMinValue() * Part), Name);
1195 }
1197 assert(!GenerateSingleScalar &&
1198 "Cannot generate scalar value for StepVector");
1199 return State.Builder.CreateStepVector(
1200 VectorType::get(getScalarType(), State.VF));
1202 assert(GenerateSingleScalar &&
1203 "Can only generate first lane for Intrinsic");
1204 SmallVector<Value *, 2> Args;
1205 for (VPValue *Op : drop_end(operands()))
1206 Args.push_back(State.get(Op, /*NeedsSingleScalar=*/true));
1207 return State.Builder.CreateIntrinsic(getScalarType(),
1208 vputils::getIntrinsicID(this), Args,
1209 /*FMFSource=*/nullptr, getName());
1210 }
1212 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1213 auto *WideDataTy = VectorType::get(getScalarType(), State.VF * Multiplier);
1214
1215 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1216 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1217 LoadInst *WideLI = Builder.CreateAlignedLoad(WideDataTy, Addr, Alignment);
1218 applyMetadata(*WideLI);
1219 return WideLI;
1220 }
1222 unsigned Multiplier = cast<VPConstantInt>(getOperand(0))->getZExtValue();
1223 Value *WideData = State.get(getOperand(3));
1224 assert(cast<VectorType>(WideData->getType())->getElementCount() ==
1225 State.VF * Multiplier &&
1226 "stored value does not match wide element count");
1227 (void)Multiplier;
1228
1229 Value *Addr = State.get(getOperand(1), /*IsScalar=*/true);
1230 Align Alignment = Align(cast<VPConstantInt>(getOperand(2))->getZExtValue());
1231 StoreInst *WideSI = Builder.CreateAlignedStore(WideData, Addr, Alignment);
1232 applyMetadata(*WideSI);
1233 return WideSI;
1234 }
1235 default:
1236 llvm_unreachable("Unsupported opcode for instruction");
1237 }
1238}
1239
1241 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1242 Type *ScalarTy = this->getScalarType();
1243 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1244 switch (Opcode) {
1245 case Instruction::FNeg:
1246 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1247 case Instruction::UDiv:
1248 case Instruction::SDiv:
1249 case Instruction::SRem:
1250 case Instruction::URem:
1251 case Instruction::Add:
1252 case Instruction::FAdd:
1253 case Instruction::Sub:
1254 case Instruction::FSub:
1255 case Instruction::Mul:
1256 case Instruction::FMul:
1257 case Instruction::FDiv:
1258 case Instruction::FRem:
1259 case Instruction::Shl:
1260 case Instruction::LShr:
1261 case Instruction::AShr:
1262 case Instruction::And:
1263 case Instruction::Or:
1264 case Instruction::Xor: {
1265 // Certain instructions can be cheaper if they have a constant second
1266 // operand. One example of this are shifts on x86.
1267 VPValue *RHS = getOperand(1);
1268 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1269
1270 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1273
1276 if (CtxI)
1277 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1278 return Ctx.TTI.getArithmeticInstrCost(
1279 Opcode, ResultTy, Ctx.CostKind,
1280 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1281 RHSInfo, Operands, CtxI, &Ctx.TLI);
1282 }
1283 case Instruction::Freeze:
1284 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1285 // requires the actual vector instruction. Instead, both here and in the
1286 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1287 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1288 // them in sync.
1289 return TTI::TCC_Free;
1290 case Instruction::ExtractValue:
1291 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1292 Ctx.CostKind);
1293 case Instruction::ICmp:
1294 case Instruction::FCmp: {
1295 Type *ScalarOpTy = getOperand(0)->getScalarType();
1296 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1298 return Ctx.TTI.getCmpSelInstrCost(
1300 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1301 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1302 }
1303 case Instruction::BitCast: {
1304 Type *ScalarTy = this->getScalarType();
1305 if (ScalarTy->isPointerTy())
1306 return 0;
1307 [[fallthrough]];
1308 }
1309 case Instruction::SExt:
1310 case Instruction::ZExt:
1311 case Instruction::FPToUI:
1312 case Instruction::FPToSI:
1313 case Instruction::FPExt:
1314 case Instruction::PtrToInt:
1315 case Instruction::PtrToAddr:
1316 case Instruction::IntToPtr:
1317 case Instruction::SIToFP:
1318 case Instruction::UIToFP:
1319 case Instruction::Trunc:
1320 case Instruction::FPTrunc:
1321 case Instruction::AddrSpaceCast: {
1322 // Computes the CastContextHint from a recipe that may access memory.
1323 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1324 if (isa<VPInterleaveBase>(R))
1326 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1327 // Only compute CCH for memory operations, matching the legacy model
1328 // which only considers loads/stores for cast context hints.
1329 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1330 if (!isa<LoadInst, StoreInst>(UI))
1332 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1334 }
1335 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1336 if (WidenMemoryRecipe == nullptr)
1338 if (VF.isScalar())
1340 if (!WidenMemoryRecipe->isConsecutive())
1342 if (WidenMemoryRecipe->isMasked())
1345 };
1346
1347 VPValue *Operand = getOperand(0);
1349 bool IsReverse = false;
1350 // For Trunc/FPTrunc, get the context from the only user.
1351 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1352 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1353 if (match(Recipe,
1357 IsReverse = true;
1359 Recipe->getVPSingleValue()->getSingleUser());
1360 }
1361 if (Recipe)
1362 CCH = ComputeCCH(Recipe);
1363 }
1364 }
1365 // For Z/Sext, get the context from the operand.
1366 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1367 Opcode == Instruction::FPExt) {
1368 if (auto *Recipe = Operand->getDefiningRecipe()) {
1369 VPValue *ReverseOp;
1370 if (match(Recipe,
1371 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1373 m_VPValue(ReverseOp))))) {
1374 Recipe = ReverseOp->getDefiningRecipe();
1375 IsReverse = true;
1376 }
1377 if (Recipe)
1378 CCH = ComputeCCH(Recipe);
1379 }
1380 }
1381 if (IsReverse && CCH != TTI::CastContextHint::None)
1383
1384 auto *ScalarSrcTy = Operand->getScalarType();
1385 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1386 // Arm TTI will use the underlying instruction to determine the cost.
1387 return Ctx.TTI.getCastInstrCost(
1388 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1390 }
1391 case Instruction::Select: {
1393 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1394 Type *ScalarTy = this->getScalarType();
1395
1396 VPValue *Op0, *Op1;
1397 bool IsLogicalAnd =
1398 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1399 bool IsLogicalOr =
1400 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1401 // Also match the inverted forms:
1402 // select x, false, y --> !x & y (still AND)
1403 // select x, y, true --> !x | y (still OR)
1404 IsLogicalAnd |=
1405 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1406 IsLogicalOr |=
1407 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1408
1409 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1410 (IsLogicalAnd || IsLogicalOr)) {
1411 // select x, y, false --> x & y
1412 // select x, true, y --> x | y
1413 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1414 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1415
1417 if (SI && all_of(operands(),
1418 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1419 append_range(Operands, SI->operands());
1420 return Ctx.TTI.getArithmeticInstrCost(
1421 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1422 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1423 }
1424
1425 Type *CondTy = getOperand(0)->getScalarType();
1426 if (!IsScalarCond && VF.isVector())
1427 CondTy = VectorType::get(CondTy, VF);
1428
1429 llvm::CmpPredicate Pred;
1430 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1431 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1432 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1433 Pred = Cmp->getPredicate();
1434 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1435 return Ctx.TTI.getCmpSelInstrCost(
1436 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1437 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1438 }
1439 }
1440 llvm_unreachable("called for unsupported opcode");
1441}
1442
1444 VPCostContext &Ctx) const {
1445 // NOTE: At the moment it seems only possible to expose this path for
1446 // the trunc, zext and sext opcodes.
1447 // TODO: Update VF arg to use onlyFirstLaneUsed once WidenCast is unified.
1449 // A scalar zext/trunc that only adjusts the width of an
1450 // ExplicitVectorLength to the canonical IV type is free: it feeds only
1451 // the IV increment and AVL decrement, which are modeled as free below.
1452 if (match(this, m_ZExtOrTrunc(m_EVL(m_VPValue()))))
1453 return 0;
1455 Ctx);
1456 }
1457
1459 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1460 // TODO: Compute cost for VPInstructions without underlying values once
1461 // the legacy cost model has been retired.
1462 return 0;
1463 }
1464
1466 "Should only generate a vector value or single scalar, not scalars "
1467 "for all lanes.");
1469 getOpcode(),
1471 }
1472
1473 switch (getOpcode()) {
1474 case Instruction::Select: {
1476 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1477 auto *CondTy = getOperand(0)->getScalarType();
1478 auto *VecTy = getOperand(1)->getScalarType();
1479 if (!vputils::onlyFirstLaneUsed(this)) {
1480 CondTy = toVectorTy(CondTy, VF);
1481 VecTy = toVectorTy(VecTy, VF);
1482 }
1483 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1484 Ctx.CostKind);
1485 }
1486 case Instruction::ExtractElement:
1488 if (VF.isScalar()) {
1489 // ExtractLane with VF=1 takes care of handling extracting across multiple
1490 // parts.
1491 return 0;
1492 }
1493
1494 // Add on the cost of extracting the element.
1495 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1496 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1497 Ctx.CostKind);
1498 }
1499 case VPInstruction::AnyOf: {
1500 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1501 return Ctx.TTI.getArithmeticReductionCost(
1502 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1503 }
1505 Type *Ty = this->getScalarType();
1506 Type *ScalarTy = getOperand(0)->getScalarType();
1507 if (VF.isScalar())
1508 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1510 CmpInst::ICMP_EQ, Ctx.CostKind);
1511 // Calculate the cost of determining the lane index.
1512 auto *PredTy = toVectorTy(ScalarTy, VF);
1513 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1514 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1515 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1516 }
1518 Type *Ty = this->getScalarType();
1519 Type *ScalarTy = getOperand(0)->getScalarType();
1520 if (VF.isScalar())
1521 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1523 CmpInst::ICMP_EQ, Ctx.CostKind);
1524 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1525 auto *PredTy = toVectorTy(ScalarTy, VF);
1526 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1527 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1528 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1529 // Add cost of NOT operation on the predicate.
1530 Cost += Ctx.TTI.getArithmeticInstrCost(
1531 Instruction::Xor, PredTy, Ctx.CostKind,
1532 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1533 {TargetTransformInfo::OK_UniformConstantValue,
1534 TargetTransformInfo::OP_None});
1535 // Add cost of SUB operation on the index.
1536 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1537 return Cost;
1538 }
1540 Type *ScalarTy = this->getScalarType();
1541 Type *VecTy = toVectorTy(ScalarTy, VF);
1542 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1544 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1545 {VecTy, MaskTy, ScalarTy});
1546 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1547 }
1549 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1550 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1551 return Ctx.TTI.getShuffleCost(
1553 cast<VectorType>(VectorTy), Ctx.CostKind, {}, -1);
1554 }
1557 Type *ArgTy = getOperand(0)->getScalarType();
1558 uint64_t Multiplier =
1560 ? cast<VPConstantInt>(getOperand(2))->getZExtValue()
1561 : 1;
1562 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1563 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1564 {ArgTy, ArgTy});
1565 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1566 }
1568 Type *Arg0Ty = getOperand(0)->getScalarType();
1569 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1570 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1571 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1572 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1573 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1574 }
1576 assert(VF.isVector() && "Reverse operation must be vector type");
1577 Type *EltTy = this->getScalarType();
1578 // Skip the reverse operation cost for the mask.
1579 // FIXME: Remove this once redundant mask reverse operations can be
1580 // eliminated by VPlanTransforms::cse before cost computation.
1581 if (EltTy->isIntegerTy(1))
1582 return 0;
1583 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1584 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1585 VectorTy, Ctx.CostKind, /*Mask=*/{},
1586 /*Index=*/0);
1587 }
1589 // Add on the cost of extracting the element.
1590 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1591 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1592 VecTy, Ctx.CostKind, 0);
1593 }
1594 case VPInstruction::Not: {
1595 Type *ValTy = this->getScalarType();
1596 // InstCombine will fold `xor` to the conditional branch.
1597 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1598 if (match(U, m_BranchOnCond(m_VPValue())))
1599 return 0;
1600 if (!vputils::onlyFirstLaneUsed(this))
1601 ValTy = toVectorTy(ValTy, VF);
1602 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1603 Ctx.CostKind);
1604 }
1606 // If TC <= VF then this is just a branch.
1607 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1608 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1609 // some cases we get a cost that's too high due to counting a cmp that
1610 // later gets removed.
1611 // FIXME: The compare could also be removed if TC = M * vscale,
1612 // VF = N * vscale, and M <= N. Detecting that would require having the
1613 // trip count as a SCEV though.
1614 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
1615 return 0;
1616 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1617 Type *ValTy = getOperand(0)->getScalarType();
1618 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1620 CmpInst::ICMP_EQ, Ctx.CostKind);
1621 }
1623 Type *Ty = getScalarType();
1625 for (const VPValue *Op : drop_end(operands()))
1626 ArgTys.push_back(Op->getScalarType());
1627 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1628 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1629 }
1631 // TODO: This isn't quite right since even if the step-vector is hoisted
1632 // out of the loop it has a non-zero cost in the middle block, etc.
1633 // Once the stepvector is correctly hoisted out of the vector loop by the
1634 // licm transform we can add the cost here so that it doesn't incorrectly
1635 // affect the choice of VF.
1636 return 0;
1638 // It isn't currently possible to expose cases where WideIVStep's cost is
1639 // queried.
1640 llvm_unreachable("Unhandled opcode");
1641 case Instruction::FCmp:
1642 case Instruction::ICmp:
1644 getOpcode(),
1647 if (VF == ElementCount::getScalable(1))
1649 [[fallthrough]];
1650 default:
1651 // TODO: Compute cost other VPInstructions once the legacy cost model has
1652 // been retired.
1654 "unexpected VPInstruction witht underlying value");
1655 return 0;
1656 }
1657}
1658
1671
1673 switch (getOpcode()) {
1674 case Instruction::Load:
1675 case Instruction::PHI:
1679 return true;
1680 default:
1682 }
1683}
1684
1686#ifndef NDEBUG
1687 Type *Ty = Op->getScalarType();
1688 switch (getOpcode()) {
1692 assert(Ty == getOperand(0)->getScalarType() &&
1693 "types of operand 0 and new operand must match");
1694 break;
1698 assert(Ty == getOperand(0)->getScalarType() &&
1699 "appended operand must match operand 0's scalar type");
1700 break;
1702 assert(Ty == getOperand(1)->getScalarType() &&
1703 "appended operand must match operand 1's scalar type");
1704 break;
1706 // The recipe is constructed with 3 operands (result, data, mask). Extra
1707 // operands beyond that are appended in (data, mask) pairs.
1708 constexpr unsigned NumInitialOperands = 3;
1709 assert(getNumOperands() >= NumInitialOperands &&
1710 "ExtractLastActive must have at least the initial 3 operands");
1711 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1712 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1713 : Ty == getOperand(1)->getScalarType()) &&
1714 "ExtractLastActive expects alternating data/mask operands "
1715 "matching operand 1's type and i1, respectively");
1716 break;
1717 }
1718 default:
1719 llvm_unreachable("opcode does not support growing the operand list "
1720 "outside of construction");
1721 }
1722#endif
1724}
1725
1727 assert(!isMasked() && "cannot execute masked VPInstruction");
1728 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1730 "Set flags not supported for the provided opcode");
1732 "Opcode requires specific flags to be set");
1733 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1734 bool GenerateSingleScalar = State.VF.isScalar() || doesGenerateSingleScalar();
1735 Value *GeneratedValue = generate(State, GenerateSingleScalar);
1736 if (!hasResult())
1737 return;
1738 assert(GeneratedValue && "generate must produce a value");
1739 assert(GeneratedValue->getType()->isVectorTy() == !GenerateSingleScalar &&
1740 "scalar value but not only first lane defined");
1741 State.set(this, GeneratedValue, GenerateSingleScalar);
1743 getOpcode() == Instruction::Freeze) {
1744 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1745 // resume phis, and to let epilogue vectorization recover the frozen
1746 // reduction start from the main plan. Must be removed once epilogue
1747 // vectorization explicitly connects VPlans.
1748 setUnderlyingValue(GeneratedValue);
1749 }
1750}
1751
1755 return false;
1756 switch (getOpcode()) {
1757 case Instruction::ExtractValue:
1758 case Instruction::GetElementPtr:
1759 case Instruction::ExtractElement:
1760 case Instruction::InsertElement:
1761 case Instruction::Freeze:
1762 case Instruction::FCmp:
1763 case Instruction::ICmp:
1764 case Instruction::Select:
1765 case Instruction::PHI:
1792 case VPInstruction::Not:
1801 return false;
1803 case Instruction::Call:
1805 default:
1806 return true;
1807 }
1808}
1809
1811 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1813 return vputils::onlyFirstLaneUsed(this);
1814
1815 switch (getOpcode()) {
1816 default:
1817 return false;
1818 case Instruction::ExtractElement:
1819 return Op == getOperand(1);
1820 case Instruction::InsertElement:
1821 return Op == getOperand(1) || Op == getOperand(2);
1823 return Op == getOperand(0);
1824 case Instruction::PHI:
1825 case Instruction::Load:
1839 return true;
1841 return Op == getOperand(0) || Op == getOperand(1) || Op == getOperand(2);
1845 return Op == getOperand(0);
1846 }
1847}
1848
1850 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1852 return vputils::onlyFirstPartUsed(this);
1853
1854 switch (getOpcode()) {
1855 default:
1856 return false;
1857 case Instruction::FCmp:
1858 case Instruction::ICmp:
1859 case Instruction::Select:
1860 return vputils::onlyFirstPartUsed(this);
1865 return true;
1866 };
1867 llvm_unreachable("switch should return");
1868}
1869
1870#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1872 VPSlotTracker SlotTracker(getParent()->getPlan());
1874}
1875
1877 VPSlotTracker &SlotTracker) const {
1878 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1879
1880 if (hasResult()) {
1882 O << " = ";
1883 }
1884
1885 switch (getOpcode()) {
1886 case VPInstruction::Not:
1887 O << "not";
1888 break;
1890 O << "active lane mask";
1891 break;
1893 O << "wide active lane mask";
1894 break;
1896 O << "wide vector load";
1897 break;
1899 O << "wide vector store";
1900 break;
1902 O << "concat-vectors";
1903 break;
1905 O << "incoming-alias-mask";
1906 break;
1908 O << "EXPLICIT-VECTOR-LENGTH";
1909 break;
1911 O << "first-order splice";
1912 break;
1914 O << "branch-on-cond";
1915 break;
1917 O << "branch-on-two-conds";
1918 break;
1920 O << "VF * Part +";
1921 break;
1923 O << "branch-on-count";
1924 break;
1926 O << "broadcast";
1927 break;
1929 O << "buildvector";
1930 break;
1932 O << "exiting-iv-value";
1933 break;
1935 O << "masked-cond";
1936 break;
1938 O << "extract-lane";
1939 break;
1941 O << "extract-last-lane";
1942 break;
1944 O << "extract-last-part";
1945 break;
1947 O << "extract-penultimate-element";
1948 break;
1950 O << "extract-vector-for-part";
1951 break;
1953 O << "compute-reduction-result";
1954 break;
1956 O << "logical-and";
1957 break;
1959 O << "logical-or";
1960 break;
1962 O << "ptradd";
1963 break;
1965 O << "wide-ptradd";
1966 break;
1968 O << "any-of";
1969 break;
1971 O << "first-active-lane";
1972 break;
1974 O << "last-active-lane";
1975 break;
1977 O << "reduction-start-vector";
1978 break;
1980 O << "resume-for-epilogue";
1981 break;
1983 O << "reverse";
1984 break;
1986 O << "unpack";
1987 break;
1989 O << "extract-last-active";
1990 break;
1992 O << "num-active-lanes";
1993 break;
1995 O << "wide-iv-step";
1996 break;
1998 O << "step-vector " << *getScalarType();
1999 break;
2001 case Instruction::Call: {
2002 O << "call";
2003 printFlags(O);
2004 printRetAttrs(O);
2005 O << *getScalarType() << " ";
2006 unsigned NumArgs;
2009 NumArgs = getNumOperands() - 1;
2010 } else {
2011 getCalledFunction(operands())->printAsOperand(O, /*PrintType=*/false);
2012 NumArgs = getCalledFnOperandIndex(operands());
2013 }
2014 O << "(";
2016 O, [&O, &SlotTracker, this](const auto &IndexedOp) {
2017 auto [Idx, Op] = IndexedOp;
2018 printParamAttrs(O, Idx);
2019 Op->printAsOperand(O, SlotTracker);
2020 });
2021 O << ")";
2022 printFnAttrs(O);
2023 if (VPValue *Mask = getMask()) {
2024 O << ", ";
2025 Mask->printAsOperand(O, SlotTracker);
2026 }
2027 return;
2028 }
2029 case Instruction::Load:
2030 O << "load";
2031 break;
2032 default:
2034 }
2035
2036 if (!operands_empty()) {
2037 printFlags(O);
2039 }
2041 O << " to " << *getScalarType();
2042}
2043#endif
2044
2045/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
2046/// adds incoming values, and stores the result in State. For header phis, only
2047/// the preheader incoming value is added; the backedge is fixed up later by
2048/// VPlan::execute().
2050 VPTransformState &State, bool IsScalar,
2051 const Twine &Name) {
2052 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
2053 ? 1
2054 : Phi.getNumIncoming();
2055 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
2056 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
2057 NewPhi->addIncoming(FirstInc,
2058 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
2059 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
2060 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
2061 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
2062 State.set(R, NewPhi, IsScalar);
2063}
2064
2066 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
2067}
2068
2069#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2070void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
2071 VPSlotTracker &SlotTracker) const {
2072 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
2074 O << " = phi";
2075 printFlags(O);
2077}
2078#endif
2079
2080VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
2081 if (auto *Phi = dyn_cast<PHINode>(&I))
2082 return new VPIRPhi(*Phi);
2083 return new VPIRInstruction(I);
2084}
2085
2087 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
2088 "PHINodes must be handled by VPIRPhi");
2089 // Advance the insert point after the wrapped IR instruction. This allows
2090 // interleaving VPIRInstructions and other recipes.
2091 State.Builder.SetInsertPoint(std::next(I.getIterator()));
2092}
2093
2095 VPCostContext &Ctx) const {
2096 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2097 // hence it does not contribute to the cost-modeling for the VPlan.
2098 return 0;
2099}
2100
2101#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2103 VPSlotTracker &SlotTracker) const {
2104 O << Indent << "IR " << I;
2105}
2106#endif
2107
2109 PHINode *Phi = &getIRPhi();
2110 for (const auto &[Idx, Op] : enumerate(operands())) {
2111 VPValue *ExitValue = Op;
2112 auto Lane = vputils::isSingleScalar(ExitValue)
2114 : VPLane::getLastLaneForVF(State.VF);
2115 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2116 auto *PredVPBB = Pred->getExitingBasicBlock();
2117 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2118 // Set insertion point in PredBB in case an extract needs to be generated.
2119 // TODO: Model extracts explicitly.
2120 State.Builder.SetInsertPoint(PredBB->getTerminator());
2121 Value *V = State.get(ExitValue, VPLane(Lane));
2122 // If there is no existing block for PredBB in the phi, add a new incoming
2123 // value. Otherwise update the existing incoming value for PredBB.
2124 if (Phi->getBasicBlockIndex(PredBB) == -1)
2125 Phi->addIncoming(V, PredBB);
2126 else
2127 Phi->setIncomingValueForBlock(PredBB, V);
2128 }
2129
2130 // Advance the insert point after the wrapped IR instruction. This allows
2131 // interleaving VPIRInstructions and other recipes.
2132 State.Builder.SetInsertPoint(std::next(Phi->getIterator()));
2133}
2134
2136 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2137 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2138 "Number of phi operands must match number of predecessors");
2139 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2140 R->removeOperand(Position);
2141}
2142
2143VPValue *
2145 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2146 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2147}
2148
2150 VPValue *V) const {
2151 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2152 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2153}
2154
2155#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2157 VPSlotTracker &SlotTracker) const {
2159 O << "[ ";
2160 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2161 O << ", ";
2162 std::get<1>(Op)->printAsOperand(O);
2163 O << " ]";
2164 });
2165}
2166#endif
2167
2168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2170 VPSlotTracker &SlotTracker) const {
2172
2173 if (getNumOperands() != 0) {
2174 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2176 [&O, &SlotTracker](auto Op) {
2177 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2178 O << " from ";
2179 std::get<1>(Op)->printAsOperand(O);
2180 });
2181 O << ")";
2182 }
2183}
2184#endif
2185
2187 if (Metadata.empty())
2188 return;
2189 // Frequencies and estimated branch weights are VPlan-internal and must not
2190 // reach IR.
2191 unsigned ExecFreqKind = getMDKindID(ExecutionFrequencyMDName);
2192 unsigned EstProfKind = getMDKindID(EstimatedProfileMDName);
2193 for (const auto &[Kind, Node] : Metadata)
2194 if (Kind != ExecFreqKind && Kind != EstProfKind)
2195 I.setMetadata(Kind, Node);
2196}
2197
2198/// Returns the execution frequency recorded in \p Node.
2200 assert(Node->getNumOperands() <= 2 && "unexpected frequency node shape");
2201 uint64_t Freq =
2202 mdconst::extract<ConstantInt>(Node->getOperand(0))->getZExtValue();
2204 "frequency cannot exceed the one of an always executing block");
2205 return {BlockFrequency(Freq), Node->getNumOperands() == 2};
2206}
2207
2209 std::optional<VPExecutionFrequency> Freq, LLVMContext &Ctx) {
2210 // A recipe that always executes needs no annotation.
2211 if (!Freq || vputils::getExecutionProbability(Freq->Freq).isOne())
2212 return;
2214 ConstantInt::get(Type::getInt64Ty(Ctx), Freq->Freq.getFrequency()))};
2215 if (Freq->IsEstimated)
2217 setMetadata(Ctx.getMDKindID(ExecutionFrequencyMDName), MDNode::get(Ctx, Ops));
2218}
2219
2220std::optional<VPExecutionFrequency>
2222 if (MDNode *Node = getInternalMetadata(ExecutionFrequencyMDName))
2224 return std::nullopt;
2225}
2226
2228 if (Metadata.empty())
2229 return;
2230 unsigned ID = getMDKindID(ExecutionFrequencyMDName);
2231 erase_if(Metadata, [ID](const auto &P) { return P.first == ID; });
2232}
2233
2235 erase_if(Metadata,
2236 [&](const auto &MD) { return !is_contained(Other.Metadata, MD); });
2237}
2238
2239#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2241 const Module *M = SlotTracker.getModule();
2242 if (Metadata.empty() || !M)
2243 return;
2244
2245 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2246 O << " (";
2247 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2248 auto [Kind, Node] = KindNodePair;
2249 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2250 "Unexpected unnamed metadata kind");
2251 O << "!" << MDNames[Kind] << " ";
2252 // Print the values of branch weights, which are more informative than the
2253 // ID of the metadata node holding them.
2254 SmallVector<uint32_t> Weights;
2255 bool IsEstimatedProfile = MDNames[Kind] == EstimatedProfileMDName;
2256 if ((Kind == LLVMContext::MD_prof || IsEstimatedProfile) &&
2257 extractBranchWeights(Node, Weights)) {
2258 if (IsEstimatedProfile)
2259 O << "estimated ";
2260 O << "{";
2261 interleaveComma(Weights, O);
2262 O << "}";
2263 } else if (MDNames[Kind] == ExecutionFrequencyMDName) {
2264 // Print the frequency together with the probability it corresponds to.
2265 auto [Freq, IsEstimated] = getExecutionFrequencyFromMD(Node);
2266 const fltSemantics &Sem = APFloat::IEEEdouble();
2267 uint64_t Full =
2269 APFloat Percent = APFloat(Sem, Freq.getFrequency()) * APFloat(Sem, 100) /
2270 APFloat(Sem, Full);
2271 SmallString<16> PercentStr;
2272 Percent.toString(PercentStr, /*FormatPrecision=*/4);
2273 O << Freq.getFrequency() << " (" << PercentStr << "%"
2274 << (IsEstimated ? ", estimated" : "") << ")";
2275 } else {
2276 SlotTracker.printMetadataAsOperand(O, Node);
2277 }
2278 });
2279 O << ")";
2280}
2281#endif
2282
2284 FunctionType *WideTy) {
2285 assert(Call.getOpcode() == Instruction::Call && "expected call");
2286 unsigned NumArgs = getCalledFnOperandIndex(Call.operands());
2287 assert(NumArgs <= WideTy->getNumParams() &&
2288 "widened call must take all scalar arguments");
2289 LLVMContext &Ctx = WideTy->getContext();
2290 AttributeList ScalarAttrs = Call.CallAttrs;
2291
2292 // Limit initial supported set of attributes to subset of poison-generating
2293 // ones that can be transferred to the widened return value and arguments.
2294 // TODO: Support additional attributes.
2295 static constexpr Attribute::AttrKind PropagatableAttrKinds[] = {
2296 Attribute::Alignment, Attribute::NonNull, Attribute::NoFPClass,
2297 Attribute::Range};
2298
2299 // Only keep allowed attributes (which do not trigger UB) and ones that are
2300 // compatible with the widened type Ty.
2301 auto Filter = [&](Type *Ty, AttributeSet AS) {
2302 AttributeMask Incompatible = AttributeFuncs::typeIncompatible(Ty, AS);
2303 AttrBuilder AB(Ctx);
2304 for (Attribute::AttrKind K : PropagatableAttrKinds)
2305 if (AS.hasAttribute(K) && !Incompatible.contains(K))
2306 AB.addAttribute(AS.getAttribute(K));
2307 return AttributeSet::get(Ctx, AB);
2308 };
2309
2310 AttributeSet RetAttrs =
2311 Filter(WideTy->getReturnType(), ScalarAttrs.getRetAttrs());
2312
2313 // For masked calls, the widened call also executes for lanes the scalar call
2314 // did not execute for. Masked variants ignore the inactive lanes of widened
2315 // arguments, but scalar (uniform or linear) arguments are shared by all
2316 // lanes, e.g. linear arguments pass the value of the first lane, which may
2317 // be inactive. Unmasked variants process all lanes.
2318 bool IsMaskedVariant = WideTy->getNumParams() > NumArgs;
2319 SmallVector<AttributeSet> ArgAttrs(WideTy->getNumParams());
2320 for (unsigned I = 0; I != NumArgs; ++I) {
2321 Type *WideArgTy = WideTy->getParamType(I);
2322 bool IsWidenedArg = WideArgTy != Call.getOperand(I)->getScalarType();
2323 if (Call.isMasked() && (!IsMaskedVariant || !IsWidenedArg))
2324 continue;
2325 ArgAttrs[I] = Filter(WideArgTy, ScalarAttrs.getParamAttrs(I));
2326 }
2327
2328 CallAttrs = AttributeList::get(Ctx, AttributeSet(), RetAttrs, ArgAttrs);
2329}
2330
2332 LLVMContext &Ctx) {
2333 CallAttrs =
2334 CallAttrs.intersectWith(Ctx, Other.CallAttrs).value_or(AttributeList());
2335}
2336
2337#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2339 AttributeSet RetAttrs = CallAttrs.getRetAttrs();
2340 if (RetAttrs.hasAttributes())
2341 O << RetAttrs.getAsString() << " ";
2342}
2343
2344void VPIRAttributes::printParamAttrs(raw_ostream &O, unsigned ArgIdx) const {
2345 AttributeSet PA = CallAttrs.getParamAttrs(ArgIdx);
2346 if (PA.hasAttributes())
2347 O << PA.getAsString() << " ";
2348}
2349
2351 AttributeSet FnAttrs = CallAttrs.getFnAttrs();
2352 if (FnAttrs.hasAttributes())
2353 O << " " << FnAttrs.getAsString();
2354}
2355#endif
2356
2358 assert(State.VF.isVector() && "not widening");
2359 assert(Variant != nullptr && "Can't create vector function.");
2360
2361 FunctionType *VFTy = Variant->getFunctionType();
2362 // Add return type if intrinsic is overloaded on it.
2364 for (const auto &I : enumerate(args())) {
2365 Value *Arg;
2366 // Some vectorized function variants may also take a scalar argument,
2367 // e.g. linear parameters for pointers. This needs to be the scalar value
2368 // from the start of the respective part when interleaving.
2369 if (!VFTy->getParamType(I.index())->isVectorTy())
2370 Arg = State.get(I.value(), VPLane(0));
2371 else
2372 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2373 Args.push_back(Arg);
2374 }
2375
2376 CallInst *V = State.Builder.CreateCall(Variant, Args);
2377 applyFlags(*V);
2378 applyMetadata(*V);
2379 applyAttrs(*V);
2380 V->setCallingConv(Variant->getCallingConv());
2381
2382 if (!V->getType()->isVoidTy())
2383 State.set(this, V);
2384}
2385
2387 VPCostContext &Ctx) const {
2388 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2389 "Variant return type must match VF");
2390 return computeCallCost(Variant, Ctx);
2391}
2392
2394 VPCostContext &Ctx) {
2395 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2396 Variant->getFunctionType()->params(),
2397 Ctx.CostKind);
2398}
2399
2401 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2402 assert(Variant && "Variant not set");
2403 FunctionType *VFTy = Variant->getFunctionType();
2404 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2405 auto [Idx, V] = Arg;
2406 Type *ArgTy = VFTy->getParamType(Idx);
2407 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2408 ArgTy->isPointerTy() || ArgTy->isByteTy();
2409 });
2410}
2411
2412#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2414 VPSlotTracker &SlotTracker) const {
2415 O << Indent << "WIDEN-CALL ";
2416
2417 Function *CalledFn = getCalledScalarFunction();
2418 if (CalledFn->getReturnType()->isVoidTy())
2419 O << "void ";
2420 else {
2422 O << " = ";
2423 }
2424
2425 O << "call";
2426 printFlags(O);
2427 printRetAttrs(O);
2428 O << "@" << CalledFn->getName() << "(";
2430 [&O, &SlotTracker, this](const auto &IndexedOp) {
2431 auto [Idx, Op] = IndexedOp;
2432 printParamAttrs(O, Idx);
2433 Op->printAsOperand(O, SlotTracker);
2434 });
2435 O << ")";
2436
2437 O << " (using library function";
2438 if (Variant->hasName())
2439 O << ": " << Variant->getName();
2440 O << ")";
2441}
2442#endif
2443
2445 assert(State.VF.isVector() && "not widening");
2446
2447 SmallVector<Type *, 2> TysForDecl;
2448 // Add return type if intrinsic is overloaded on it.
2449 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2450 State.TTI)) {
2451 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2452 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2453 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2455 Idx, State.TTI))
2456 TysForDecl.push_back(Ty);
2457 }
2458 }
2460 for (const auto &I : enumerate(operands())) {
2461 // Some intrinsics have a scalar argument - don't replace it with a
2462 // vector.
2463 Value *Arg;
2464 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2465 State.TTI))
2466 Arg = State.get(I.value(), VPLane(0));
2467 else
2468 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2469 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2470 State.TTI))
2471 TysForDecl.push_back(Arg->getType());
2472 Args.push_back(Arg);
2473 }
2474
2475 // Use vector version of the intrinsic.
2476 Module *M = State.Builder.getModule();
2477 Function *VectorF =
2478 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2479 assert(VectorF &&
2480 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2481
2482 CallInst *V = State.Builder.CreateCall(VectorF, Args);
2483
2484 applyFlags(*V);
2485 applyMetadata(*V);
2486
2487 return V;
2488}
2489
2491 CallInst *V = createVectorCall(State);
2492 if (!V->getType()->isVoidTy())
2493 State.set(this, V);
2494}
2495
2498 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2499 Type *ScalarRetTy = R.getScalarType();
2500 // Skip the reverse operation cost for the mask.
2501 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2502 // by VPlanTransforms::cse before cost computation.
2503 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2504 return InstructionCost(0);
2505
2506 // Some backends analyze intrinsic arguments to determine cost. Use the
2507 // underlying value for the operand if it has one. Otherwise try to use the
2508 // operand of the underlying call instruction, if there is one. Otherwise
2509 // clear Arguments.
2510 // TODO: Rework TTI interface to be independent of concrete IR values.
2512 for (const auto &[Idx, Op] : enumerate(Operands)) {
2513 auto *V = Op->getUnderlyingValue();
2514 if (!V) {
2515 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2516 Arguments.push_back(UI->getArgOperand(Idx));
2517 continue;
2518 }
2519 Arguments.clear();
2520 break;
2521 }
2522 Arguments.push_back(V);
2523 }
2524
2525 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2526 SmallVector<Type *> ParamTys =
2527 map_to_vector(Operands, [&](const VPValue *Op) {
2528 return toVectorTy(Op->getScalarType(), VF);
2529 });
2530
2532 for (const VPValue *Op : Operands)
2533 if (isa<VPWidenRecipe>(Op) &&
2536 break;
2537 }
2538
2539 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2540 IntrinsicCostAttributes CostAttrs(
2541 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2542 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2544 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2545}
2546
2548 VPCostContext &Ctx) const {
2549 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2550}
2551
2553 return Intrinsic::getBaseName(VectorIntrinsicID);
2554}
2555
2557 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2558 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2559 auto [Idx, V] = X;
2561 Idx, nullptr);
2562 });
2563}
2564
2565#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2567 VPSlotTracker &SlotTracker) const {
2568 O << Indent << "WIDEN-INTRINSIC ";
2569 if (getScalarType()->isVoidTy()) {
2570 O << "void ";
2571 } else {
2573 O << " = ";
2574 }
2575
2576 O << "call";
2577 printFlags(O);
2578 O << getIntrinsicName() << "(";
2580 O << ")";
2581}
2582#endif
2583
2585 CallInst *MemI = createVectorCall(State);
2587 MemI->getContext(), Alignment));
2588 if (!MemI->getType()->isVoidTy())
2589 State.set(this, MemI);
2590}
2591
2594 assert(MaskPos && "Expected a memory intrinsic with a valid mask position");
2595 return getOperand(*MaskPos);
2596}
2597
2600 assert(PtrPos && "Expected a memory intrinsic with a valid pointer position");
2601 return *PtrPos;
2602}
2603
2605 Type *DataTy;
2607 DataTy = getOperand(*DataPos)->getScalarType();
2608 else
2609 DataTy = getScalarType();
2610 assert(!DataTy->isVoidTy() && "Expected a non-void data type");
2611 return toVectorTy(DataTy, VF);
2612}
2613
2615 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2616 VPCostContext &Ctx) {
2617 return Ctx.TTI.getMemIntrinsicInstrCost(
2618 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2619 Ctx.CostKind);
2620}
2621
2628
2630 IRBuilderBase &Builder = State.Builder;
2631
2632 Value *Address = State.get(getOperand(0));
2633 Value *IncAmt = State.get(getOperand(1), /*NeedsSingleScalar=*/true);
2634 VectorType *VTy = cast<VectorType>(Address->getType());
2635
2636 // The histogram intrinsic requires a mask even if the recipe doesn't;
2637 // if the mask operand was omitted then all lanes should be executed and
2638 // we just need to synthesize an all-true mask.
2639 Value *Mask = nullptr;
2640 if (VPValue *VPMask = getMask())
2641 Mask = State.get(VPMask);
2642 else
2643 Mask =
2644 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2645
2646 // If this is a subtract, we want to invert the increment amount and use
2647 // the histogram_add intrinsic.
2648 if (mustNegateIncrement())
2649 IncAmt = Builder.CreateNeg(IncAmt);
2650
2651 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2652 getHistogramIntrinsicID(), {VTy, IncAmt->getType()},
2653 {Address, IncAmt, Mask});
2654 applyMetadata(*HistogramInst);
2655}
2656
2657Intrinsic::ID VPHistogramRecipe::getHistogramIntrinsicID() const {
2658 switch (UpdateKind) {
2661 return Intrinsic::experimental_vector_histogram_add;
2663 return Intrinsic::experimental_vector_histogram_uadd_sat;
2665 return Intrinsic::experimental_vector_histogram_umax;
2667 return Intrinsic::experimental_vector_histogram_umin;
2668 }
2669 llvm_unreachable("Unknown HistogramUpdateKind");
2670}
2671
2673 VPCostContext &Ctx) const {
2674 // FIXME: Take the gather and scatter into account as well. For now we're
2675 // generating the same cost as the fallback path, but we'll likely
2676 // need to create a new TTI method for determining the cost, including
2677 // whether we can use base + vec-of-smaller-indices or just
2678 // vec-of-pointers.
2679 assert(VF.isVector() && "Invalid VF for histogram cost");
2680 Type *AddressTy = getOperand(0)->getScalarType();
2681 VPValue *IncAmt = getOperand(1);
2682 Type *IncTy = IncAmt->getScalarType();
2683 VectorType *VTy = VectorType::get(IncTy, VF);
2684
2685 // For umin/umax, there's no multiplication — the increment value is compared
2686 // directly. For add/sub/uadd.sat, assume that a non-constant update value
2687 // (or a constant != 1) requires a multiply.
2689 if (!match(IncAmt, m_One()) && UpdateKind != HistogramUpdateKind::UMax &&
2690 UpdateKind != HistogramUpdateKind::UMin)
2691 MulCost =
2692 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2693
2694 // Find the cost of the histogram operation itself.
2695 Type *PtrTy = VectorType::get(AddressTy, VF);
2696 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2697 IntrinsicCostAttributes ICA(getHistogramIntrinsicID(),
2698 Type::getVoidTy(Ctx.LLVMCtx),
2699 {PtrTy, IncTy, MaskTy});
2700
2701 // The histogram intrinsic's TTI cost already includes the update operation
2702 // (load + update + store), so no separate UpdateCost is needed.
2703 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost;
2704}
2705
2706#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2708 VPSlotTracker &SlotTracker) const {
2709 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2711
2712 switch (UpdateKind) {
2714 O << ", inc: ";
2715 break;
2717 O << ", dec: ";
2718 break;
2720 O << ", saturated inc: ";
2721 break;
2723 O << ", max: ";
2724 break;
2726 O << ", min: ";
2727 break;
2728 }
2730
2731 if (VPValue *Mask = getMask()) {
2732 O << ", mask: ";
2733 Mask->printAsOperand(O, SlotTracker);
2734 }
2735}
2736#endif
2737
2738VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2739 AllowReassoc = FMF.allowReassoc();
2740 NoNaNs = FMF.noNaNs();
2741 NoInfs = FMF.noInfs();
2742 NoSignedZeros = FMF.noSignedZeros();
2743 AllowReciprocal = FMF.allowReciprocal();
2744 AllowContract = FMF.allowContract();
2745 ApproxFunc = FMF.approxFunc();
2746}
2747
2748VPIRFlags VPIRFlags::getDefaultFlags(unsigned Opcode, Type *ResultTy) {
2749 switch (Opcode) {
2750 case Instruction::Add:
2751 case Instruction::Sub:
2752 case Instruction::Mul:
2753 case Instruction::Shl:
2755 return WrapFlagsTy(false, false);
2756 case Instruction::Trunc:
2757 return TruncFlagsTy(false, false);
2758 case Instruction::Or:
2759 return DisjointFlagsTy(false);
2760 case Instruction::AShr:
2761 case Instruction::LShr:
2762 case Instruction::UDiv:
2763 case Instruction::SDiv:
2764 return ExactFlagsTy(false);
2765 case Instruction::GetElementPtr:
2768 return GEPNoWrapFlags::none();
2769 case Instruction::ZExt:
2770 case Instruction::UIToFP:
2771 return NonNegFlagsTy(false);
2772 case Instruction::FAdd:
2773 case Instruction::FSub:
2774 case Instruction::FMul:
2775 case Instruction::FDiv:
2776 case Instruction::FRem:
2777 case Instruction::FNeg:
2778 case Instruction::FPExt:
2779 case Instruction::FPTrunc:
2780 return FastMathFlags();
2781 case Instruction::Select:
2782 case Instruction::PHI:
2783 case Instruction::Call:
2784 // Selects, phis and calls only have fast-math flags if they have a
2785 // supported floating-point result type.
2787 return FastMathFlags();
2788 return VPIRFlags();
2789 case Instruction::ICmp:
2790 case Instruction::FCmp:
2792 llvm_unreachable("opcode requires explicit flags");
2793 default:
2794 return VPIRFlags();
2795 }
2796}
2797
2798#if !defined(NDEBUG)
2799bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2800 switch (OpType) {
2801 case OperationType::OverflowingBinOp:
2802 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2803 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2804 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2805 case OperationType::Trunc:
2806 return Opcode == Instruction::Trunc;
2807 case OperationType::DisjointOp:
2808 return Opcode == Instruction::Or;
2809 case OperationType::PossiblyExactOp:
2810 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2811 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2812 case OperationType::GEPOp:
2813 return Opcode == Instruction::GetElementPtr ||
2814 Opcode == VPInstruction::PtrAdd ||
2815 Opcode == VPInstruction::WidePtrAdd;
2816 case OperationType::FPMathOp:
2817 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2818 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2819 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2820 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2821 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2822 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2823 Opcode == Instruction::UIToFP ||
2824 Opcode == VPInstruction::WideIVStep ||
2826 case OperationType::FCmp:
2827 return Opcode == Instruction::FCmp;
2828 case OperationType::NonNegOp:
2829 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2830 case OperationType::Cmp:
2831 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2832 case OperationType::ReductionOp:
2834 case OperationType::Other:
2835 return true;
2836 }
2837 llvm_unreachable("Unknown OperationType enum");
2838}
2839
2841 Type *ResultTy) const {
2842 // Handle opcodes without default flags.
2843 if (Opcode == Instruction::ICmp)
2844 return OpType == OperationType::Cmp;
2845 if (Opcode == Instruction::FCmp)
2846 return OpType == OperationType::FCmp;
2848 return OpType == OperationType::ReductionOp;
2849
2850 OperationType Required = getDefaultFlags(Opcode, ResultTy).OpType;
2851 return Required == OperationType::Other || Required == OpType;
2852}
2853#endif
2854
2855#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2856static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2857 switch (Kind) {
2858 case RecurKind::None:
2859 OS << "none";
2860 break;
2861 case RecurKind::Add:
2862 OS << "add";
2863 break;
2864 case RecurKind::Sub:
2865 OS << "sub";
2866 break;
2868 OS << "add-chain-with-subs";
2869 break;
2870 case RecurKind::Mul:
2871 OS << "mul";
2872 break;
2873 case RecurKind::Or:
2874 OS << "or";
2875 break;
2876 case RecurKind::And:
2877 OS << "and";
2878 break;
2879 case RecurKind::Xor:
2880 OS << "xor";
2881 break;
2882 case RecurKind::SMin:
2883 OS << "smin";
2884 break;
2885 case RecurKind::SMax:
2886 OS << "smax";
2887 break;
2888 case RecurKind::UMin:
2889 OS << "umin";
2890 break;
2891 case RecurKind::UMax:
2892 OS << "umax";
2893 break;
2894 case RecurKind::FAdd:
2895 OS << "fadd";
2896 break;
2898 OS << "fadd-chain-with-subs";
2899 break;
2900 case RecurKind::FSub:
2901 OS << "fsub";
2902 break;
2903 case RecurKind::FMul:
2904 OS << "fmul";
2905 break;
2906 case RecurKind::FMin:
2907 OS << "fmin";
2908 break;
2909 case RecurKind::FMax:
2910 OS << "fmax";
2911 break;
2912 case RecurKind::FMinNum:
2913 OS << "fminnum";
2914 break;
2915 case RecurKind::FMaxNum:
2916 OS << "fmaxnum";
2917 break;
2919 OS << "fminimum";
2920 break;
2922 OS << "fmaximum";
2923 break;
2925 OS << "fminimumnum";
2926 break;
2928 OS << "fmaximumnum";
2929 break;
2930 case RecurKind::FMulAdd:
2931 OS << "fmuladd";
2932 break;
2933 case RecurKind::AnyOf:
2934 OS << "any-of";
2935 break;
2936 case RecurKind::FindIV:
2937 OS << "find-iv";
2938 break;
2940 OS << "find-last";
2941 break;
2942 }
2943}
2944
2946 switch (OpType) {
2947 case OperationType::Cmp:
2949 break;
2950 case OperationType::FCmp:
2953 break;
2954 case OperationType::DisjointOp:
2955 if (DisjointFlags.IsDisjoint)
2956 O << " disjoint";
2957 break;
2958 case OperationType::PossiblyExactOp:
2959 if (ExactFlags.IsExact)
2960 O << " exact";
2961 break;
2962 case OperationType::OverflowingBinOp:
2963 if (WrapFlags.HasNUW)
2964 O << " nuw";
2965 if (WrapFlags.HasNSW)
2966 O << " nsw";
2967 break;
2968 case OperationType::Trunc:
2969 if (TruncFlags.HasNUW)
2970 O << " nuw";
2971 if (TruncFlags.HasNSW)
2972 O << " nsw";
2973 break;
2974 case OperationType::FPMathOp:
2976 break;
2977 case OperationType::GEPOp: {
2979 if (Flags.isInBounds())
2980 O << " inbounds";
2981 else if (Flags.hasNoUnsignedSignedWrap())
2982 O << " nusw";
2983 if (Flags.hasNoUnsignedWrap())
2984 O << " nuw";
2985 break;
2986 }
2987 case OperationType::NonNegOp:
2988 if (NonNegFlags.NonNeg)
2989 O << " nneg";
2990 break;
2991 case OperationType::ReductionOp: {
2992 O << " (";
2994 if (isReductionInLoop())
2995 O << ", in-loop";
2996 if (isReductionOrdered())
2997 O << ", ordered";
2998 O << ")";
3000 break;
3001 }
3002 case OperationType::Other:
3003 break;
3004 }
3005 O << " ";
3006}
3007#endif
3008
3010 auto &Builder = State.Builder;
3011 switch (Opcode) {
3012 case Instruction::Call:
3013 case Instruction::UncondBr:
3014 case Instruction::CondBr:
3015 case Instruction::PHI:
3016 case Instruction::GetElementPtr:
3017 llvm_unreachable("This instruction is handled by a different recipe.");
3018 case Instruction::UDiv:
3019 case Instruction::SDiv:
3020 case Instruction::SRem:
3021 case Instruction::URem:
3022 case Instruction::Add:
3023 case Instruction::FAdd:
3024 case Instruction::Sub:
3025 case Instruction::FSub:
3026 case Instruction::FNeg:
3027 case Instruction::Mul:
3028 case Instruction::FMul:
3029 case Instruction::FDiv:
3030 case Instruction::FRem:
3031 case Instruction::Shl:
3032 case Instruction::LShr:
3033 case Instruction::AShr:
3034 case Instruction::And:
3035 case Instruction::Or:
3036 case Instruction::Xor: {
3037 // Just widen unops and binops.
3039 for (VPValue *VPOp : operands())
3040 Ops.push_back(State.get(VPOp));
3041
3042 Value *V = Builder.CreateNAryOp(Opcode, Ops);
3043
3044 if (auto *VecOp = dyn_cast<Instruction>(V)) {
3045 applyFlags(*VecOp);
3046 applyMetadata(*VecOp);
3047 }
3048
3049 // Use this vector value for all users of the original instruction.
3050 State.set(this, V);
3051 break;
3052 }
3053 case Instruction::ExtractValue: {
3054 Value *Op = State.get(getOperand(0));
3055 Value *Extract =
3056 Builder.CreateExtractValue(Op, getExtractValueIndices(operands()));
3057 State.set(this, Extract);
3058 break;
3059 }
3060 case Instruction::Freeze: {
3061 Value *Op = State.get(getOperand(0));
3062 Value *Freeze = Builder.CreateFreeze(Op);
3063 State.set(this, Freeze);
3064 break;
3065 }
3066 case Instruction::ICmp:
3067 case Instruction::FCmp: {
3068 // Widen compares. Generate vector compares.
3069 bool FCmp = Opcode == Instruction::FCmp;
3070 Value *A = State.get(getOperand(0));
3071 Value *B = State.get(getOperand(1));
3072 Value *C = nullptr;
3073 if (FCmp) {
3074 C = Builder.CreateFCmp(getPredicate(), A, B);
3075 } else {
3076 C = Builder.CreateICmp(getPredicate(), A, B);
3077 }
3078 if (auto *I = dyn_cast<Instruction>(C)) {
3079 applyFlags(*I);
3080 applyMetadata(*I);
3081 }
3082 State.set(this, C);
3083 break;
3084 }
3085 case Instruction::Select: {
3086 VPValue *CondOp = getOperand(0);
3087 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
3088 Value *Op0 = State.get(getOperand(1));
3089 Value *Op1 = State.get(getOperand(2));
3090 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
3091 State.set(this, Sel);
3092 if (auto *I = dyn_cast<Instruction>(Sel)) {
3094 applyFlags(*I);
3095 applyMetadata(*I);
3096 }
3097 break;
3098 }
3099 default:
3100 // This instruction is not vectorized by simple widening.
3101 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
3102 << Instruction::getOpcodeName(Opcode));
3103 llvm_unreachable("Unhandled instruction!");
3104 } // end of switch.
3105
3106#if !defined(NDEBUG)
3107 // Verify that VPlan type inference results agree with the type of the
3108 // generated values.
3109 assert(VectorType::get(this->getScalarType(), State.VF) ==
3110 State.get(this)->getType() &&
3111 "inferred type and type from generated instructions do not match");
3112#endif
3113}
3114
3116 VPCostContext &Ctx) const {
3117 switch (Opcode) {
3118 case Instruction::UDiv:
3119 case Instruction::SDiv:
3120 case Instruction::SRem:
3121 case Instruction::URem:
3122 // If the div/rem operation isn't safe to speculate and requires
3123 // predication, then the only way we can even create a vplan is to insert
3124 // a select on the second input operand to ensure we use the value of 1
3125 // for the inactive lanes. The select will be costed separately.
3126 case Instruction::FNeg:
3127 case Instruction::Add:
3128 case Instruction::FAdd:
3129 case Instruction::Sub:
3130 case Instruction::FSub:
3131 case Instruction::Mul:
3132 case Instruction::FMul:
3133 case Instruction::FDiv:
3134 case Instruction::FRem:
3135 case Instruction::Shl:
3136 case Instruction::LShr:
3137 case Instruction::AShr:
3138 case Instruction::And:
3139 case Instruction::Or:
3140 case Instruction::Xor:
3141 case Instruction::Freeze:
3142 case Instruction::ExtractValue:
3143 case Instruction::ICmp:
3144 case Instruction::FCmp:
3145 case Instruction::Select:
3146 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
3147 default:
3148 llvm_unreachable("Unsupported opcode for instruction");
3149 }
3150}
3151
3152#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3154 VPSlotTracker &SlotTracker) const {
3155 O << Indent << "WIDEN ";
3157 O << " = " << Instruction::getOpcodeName(Opcode);
3158 printFlags(O);
3160}
3161#endif
3162
3164 auto &Builder = State.Builder;
3165 /// Vectorize casts.
3166 assert(State.VF.isVector() && "Not vectorizing?");
3167 Type *DestTy = VectorType::get(getScalarType(), State.VF);
3168 VPValue *Op = getOperand(0);
3169 Value *A = State.get(Op);
3170 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
3171 State.set(this, Cast);
3172 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
3173 applyFlags(*CastOp);
3174 applyMetadata(*CastOp);
3175 }
3176}
3177
3182
3183#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3185 VPSlotTracker &SlotTracker) const {
3186 O << Indent << "WIDEN-CAST ";
3188 O << " = " << Instruction::getOpcodeName(Opcode);
3189 printFlags(O);
3191 O << " to " << *getScalarType();
3192}
3193#endif
3194
3196 VPCostContext &Ctx) const {
3197 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3198}
3199
3200#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3202 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
3203 O << Indent;
3205 O << " = WIDEN-INDUCTION";
3206 printFlags(O);
3208
3209 if (isTruncated())
3210 O << " (truncated to " << *getScalarType() << ")";
3211}
3212#endif
3213
3215 // The step may be defined by a recipe in the preheader (e.g. if it requires
3216 // SCEV expansion), but for the canonical induction the step is required to be
3217 // 1, which is represented as live-in.
3218 return match(getStartValue(), m_ZeroInt()) &&
3219 match(getStepValue(), m_One()) &&
3220 getScalarType() == getRegion()->getCanonicalIVType();
3221}
3222
3225 VPCostContext &Ctx) const {
3226 // A widened induction generates a vector phi and increments it by the
3227 // splatted step each iteration.
3229 InstructionCost Cost = Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3230 Type *StepTy = getScalarType();
3231 unsigned IncOpc = ID.getKind() == InductionDescriptor::IK_IntInduction
3232 ? Instruction::Add
3233 : ID.getInductionOpcode();
3234 assert(IncOpc != Instruction::BinaryOpsEnd &&
3235 "induction must have a valid increment opcode");
3236 return Cost + Ctx.TTI.getArithmeticInstrCost(IncOpc, toVectorTy(StepTy, VF),
3237 Ctx.CostKind);
3238}
3239
3240/// Returns the ConstantFP \p V wraps, or nullptr if it does not wrap one.
3241static const ConstantFP *getConstantFP(const VPValue *V) {
3242 auto *C = dyn_cast<VPConstant>(V);
3243 return C ? dyn_cast<ConstantFP>(C->getConstant()) : nullptr;
3244}
3245
3247 VPCostContext &Ctx) const {
3248 // The cost model for this is modelled on expandVPDerivedIV in
3249 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
3250 // negatively affect vectorization it takes into account any expected
3251 // simplifications that happen in simplifyRecipe.
3252 switch (getInductionKind()) {
3253 default:
3254 // TODO: Compute cost for remaining kinds.
3255 break;
3257 // There are currently no tests that expose a path where all lanes are
3258 // used, so it's better to bail out for now.
3259 if (!vputils::onlyFirstLaneUsed(this))
3260 break;
3261
3262 // Start off by assuming we need both mul and add, then refine this.
3263 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
3264
3265 // If the start value is zero the add gets folded away.
3266 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
3267 NeedsAdd = !StartC->isZero();
3268
3269 // For some values of step the arithmetic changes:
3270 // 1. A step of 1 requires no operation.
3271 // 2. A step of -1 requires a negate.
3272 // 3. A power-of-2 step will use a shl, instead of a mul.
3273 Type *StepTy = getStepValue()->getScalarType();
3275 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
3276 if (StepC->isOne())
3277 NeedsMul = false;
3278 else if (StepC->getAPInt().isAllOnes()) {
3279 // This will most likely end up as a negate in simplifyRecipe, and
3280 // the negate will be combined with the add to make a sub.
3281 // NOTE: This is perhaps an invalid assumption that the cost of an
3282 // 'add' is the same as a 'sub'.
3283 NeedsMul = false;
3284 NeedsAdd = true;
3285 } else if (StepC->getAPInt().isPowerOf2()) {
3286 // This will most likely end up as a shift-left in simplifyRecipe
3287 NeedsMul = false;
3288 NeedsShl = true;
3289 }
3290 }
3291
3292 // Add the cost of the conversion from index to step type if the index
3293 // will be used.
3294 Type *IndexTy = getIndex()->getScalarType();
3295 unsigned StepTySize = StepTy->getScalarSizeInBits();
3296 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3297 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3298 unsigned CastOpc =
3299 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::ZExt;
3300 Cost += Ctx.TTI.getCastInstrCost(
3301 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3302 }
3303
3304 if (NeedsMul)
3305 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3306 Ctx.CostKind);
3307 if (NeedsShl)
3308 Cost += Ctx.TTI.getArithmeticInstrCost(
3309 Instruction::Shl, StepTy, Ctx.CostKind,
3310 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3311 {TargetTransformInfo::OK_UniformConstantValue,
3312 TargetTransformInfo::OP_None});
3313 if (NeedsAdd)
3314 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3315 Ctx.CostKind);
3316 return Cost;
3317 }
3319 // There are currently no tests that expose a path where all lanes are
3320 // used, so it's better to bail out for now.
3321 if (!vputils::onlyFirstLaneUsed(this))
3322 break;
3323
3324 // Unlike the integer case, converting the index to the FP step type is
3325 // unavoidable: the index is always the integer canonical IV, so this
3326 // cast is never folded away.
3327 Type *StepTy = getStepValue()->getScalarType();
3328 Type *IndexTy = getIndex()->getScalarType();
3330 Ctx.TTI.getCastInstrCost(Instruction::SIToFP, StepTy, IndexTy,
3331 TTI::CastContextHint::None, Ctx.CostKind);
3332
3333 // If the step is 1.0, the multiply is an exact identity and gets folded
3334 // away, independent of fast-math flags.
3335 const ConstantFP *StepC = getConstantFP(getStepValue());
3336 bool NeedsMul = !StepC || !StepC->isOne();
3337
3338 // "fadd -0.0, X" folds to X unconditionally, but "fadd 0.0, X" only folds
3339 // to X without nsz if X can be proven to never be -0.0, which we cannot, as
3340 // Step may be -0.0.
3341 // TODO: Consider fast-math flags when they are available in
3342 // VPDerivedIVRecipe.
3343 const ConstantFP *StartC = getConstantFP(getStartValue());
3344 bool AddFolds = getFPBinOp()->getOpcode() == Instruction::FAdd && StartC &&
3345 StartC->isZero() && (StartC->isNegZero() || !NeedsMul);
3346
3347 if (NeedsMul)
3348 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::FMul, StepTy,
3349 Ctx.CostKind);
3350 if (!AddFolds)
3351 Cost += Ctx.TTI.getArithmeticInstrCost(getFPBinOp()->getOpcode(), StepTy,
3352 Ctx.CostKind);
3353 return Cost;
3354 }
3355 }
3356
3357 return 0;
3358}
3359
3360#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3362 VPSlotTracker &SlotTracker) const {
3363 O << Indent;
3365 O << " = DERIVED-IV";
3366 printFlags(O);
3367 getStartValue()->printAsOperand(O, SlotTracker);
3368 O << " + ";
3369 getOperand(1)->printAsOperand(O, SlotTracker);
3370 O << " * ";
3371 getStepValue()->printAsOperand(O, SlotTracker);
3372}
3373#endif
3374
3378
3380 VPCostContext &Ctx) const {
3381 Type *BaseIVTy = getOperand(0)->getScalarType();
3382 assert((BaseIVTy->isIntegerTy() || BaseIVTy->isFloatingPointTy()) &&
3383 "VPScalarIVStepsRecipe is only created for integer and FP inductions");
3384
3385 // If only the first lane is used, then there won't be any code that remains
3386 // in the loop for the first unrolled part.
3388 return 0;
3389
3390 // If the vector body executes at most once, the canonical IV is a constant
3391 // and every lane's step folds away with it.
3392 if (VPCostContext::executesAtMostOnce(*getParent()->getPlan(), VF))
3393 return 0;
3394
3395 // Typically the operations are:
3396 // 1. Add the start index to each lane value.
3397 // 2. Multiply the start index by the step.
3398 // 3. Add the scaled start index to base IV.
3399 // Any code generated for 1 and 2 should be loop invariant and therefore
3400 // hoisted out of the loop. We only need to add on the cost of 3.
3402 if (BaseIVTy->isFloatingPointTy()) {
3403 // Unlike the integer case, the users of an FP induction cannot be re-based
3404 // on a common value, so each lane needs its own FAdd/FSub.
3405 assert(!VF.isScalable() &&
3406 "FP scalar steps for all lanes are only created for fixed VFs");
3407 Cost = Ctx.TTI.getArithmeticInstrCost(InductionOpcode, BaseIVTy,
3408 Ctx.CostKind) *
3409 (VF.getFixedValue() - 1);
3410 } else {
3411 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3412 // %add1 = add i32 %iv, 0
3413 // %add2 = add i32 %iv, 1
3414 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3415 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3416 // it's very likely that these GEPs will all be rewritten to have a common
3417 // base such that what's left is just
3418 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3419 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3420 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3421 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3422 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3423 Cost = Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3424 Ctx.CostKind);
3425 }
3426
3427 // If the steps are generated inside a replicate region, scale by execution
3428 // probability.
3429 const VPRegionBlock *Region = getRegion();
3430 if (Region && Region->isReplicator())
3431 Cost /= Ctx.getCostDivisor(
3432 Region->getEntryBranchOnMask()->getExecutionFrequency());
3433 return Cost;
3434}
3435
3437 // Fast-math-flags propagate from the original induction instruction.
3438 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3439 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3440
3441 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3442 /// variable on which to base the steps, \p Step is the size of the step.
3443
3444 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3445 Value *Step = State.get(getStepValue(), VPLane(0));
3446 IRBuilderBase &Builder = State.Builder;
3447
3448 // Ensure step has the same type as that of scalar IV.
3449 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3450 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3451
3452 // We build scalar steps for both integer and floating-point induction
3453 // variables. Here, we determine the kind of arithmetic we will perform.
3456 if (BaseIVTy->isIntegerTy()) {
3457 AddOp = Instruction::Add;
3458 MulOp = Instruction::Mul;
3459 } else {
3460 AddOp = InductionOpcode;
3461 MulOp = Instruction::FMul;
3462 }
3463
3464 // Lanes other than the first have been materialized as separate
3465 // single-scalar recipes by replicateByVF, each with its own start index.
3466 assert((vputils::onlyFirstLaneUsed(this) || State.VF.isScalar()) &&
3467 "must have been replicated by VF");
3468 Value *StartIdx = getStartIndex() ? State.get(getStartIndex(), true)
3469 : Constant::getNullValue(BaseIVTy);
3470 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3471 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3472 State.set(this, Add, VPLane(0));
3473}
3474
3475#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3477 VPSlotTracker &SlotTracker) const {
3478 O << Indent;
3480 O << " = SCALAR-STEPS ";
3482}
3483#endif
3484
3486 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3488}
3489
3491 assert(State.VF.isVector() && "not widening");
3492 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3493 return State.get(Op, vputils::isSingleScalar(Op));
3494 });
3495 auto *GEP =
3496 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3497 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3498 State.set(this, GEP, vputils::isSingleScalar(this));
3499}
3500
3501#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3503 VPSlotTracker &SlotTracker) const {
3504 O << Indent << "WIDEN-GEP ";
3506 O << " = getelementptr";
3507 printFlags(O);
3509}
3510#endif
3511
3513 assert(!getOffset() && "Unexpected offset operand");
3514 VPBuilder Builder(this);
3515 VPlan &Plan = *getParent()->getPlan();
3516 VPValue *VFVal = getVFValue();
3517 const DataLayout &DL = Plan.getDataLayout();
3518 Type *IndexTy = DL.getIndexType(this->getScalarType());
3519 VPValue *Stride =
3520 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3521 VPValue *VF =
3522 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3523
3524 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3525 VPInstruction *VFMinusOne =
3526 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3527 DebugLoc::getUnknown(), "", {true, true});
3528 VPInstruction *Offset0 =
3529 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3530
3531 // Offset for PartN = Offset0 + Part * Stride * VF.
3532 VPValue *PartxStride =
3533 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3534 VPValue *Offset = Builder.createAdd(
3535 Offset0,
3536 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3538}
3539
3541 auto &Builder = State.Builder;
3542 assert(getOffset() && "Expected prior materialization of offset");
3543 Value *Ptr = State.get(getPointer(), true);
3544 Value *Offset = State.get(getOffset(), true);
3545 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3547 State.set(this, ResultPtr, /*IsScalar*/ true);
3548}
3549
3550#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3552 VPSlotTracker &SlotTracker) const {
3553 O << Indent;
3555 O << " = vector-end-pointer";
3556 printFlags(O);
3557 getSourceElementType()->print(O);
3558 O << ", ";
3560}
3561#endif
3562
3564 assert(getVFxPart() &&
3565 "Expected prior simplification of recipe without VFxPart");
3566
3567 auto &Builder = State.Builder;
3568 Value *Ptr = State.get(getOperand(0), VPLane(0));
3569 Value *Offset = State.get(getVFxPart(), true);
3570 // TODO: Expand to VPInstruction to support constant folding.
3571 if (!match(getStride(), m_One())) {
3572 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3573 Offset->getType());
3574 Offset = Builder.CreateMul(Offset, Stride);
3575 }
3576 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3578 State.set(this, ResultPtr, /*IsScalar*/ true);
3579}
3580
3581#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3583 VPSlotTracker &SlotTracker) const {
3584 O << Indent;
3586 O << " = vector-pointer";
3587 printFlags(O);
3588 getSourceElementType()->print(O);
3589 O << ", ";
3591}
3592#endif
3593
3595 VPCostContext &Ctx) const {
3596 // A blend will be expanded to a select VPInstruction, which will generate a
3597 // scalar select if only the first lane is used.
3599 VF = ElementCount::getFixed(1);
3600
3601 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3602 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3603
3605 for (unsigned I = 1, E = getNumIncomingValues(); I != E; ++I) {
3606 CmpPredicate Pred;
3607 if (!match(getMask(I), m_Cmp(Pred, m_VPValue(), m_VPValue())))
3608 Pred = getScalarType()->isFloatingPointTy() ? CmpInst::BAD_FCMP_PREDICATE
3610 Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3611 Pred, Ctx.CostKind);
3612 }
3613 return Cost;
3614}
3615
3616#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3618 VPSlotTracker &SlotTracker) const {
3619 O << Indent << "BLEND ";
3621 O << " =";
3622 printFlags(O);
3623 if (getNumIncomingValues() == 1) {
3624 // Not a User of any mask: not really blending, this is a
3625 // single-predecessor phi.
3626 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3627 } else {
3628 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3629 if (I != 0)
3630 O << " ";
3631 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3632 if (I == 0 && isNormalized())
3633 continue;
3634 O << "/";
3635 getMask(I)->printAsOperand(O, SlotTracker);
3636 }
3637 }
3638}
3639#endif
3640
3644 "In-loop AnyOf reductions aren't currently supported");
3645 // Propagate the fast-math flags carried by the underlying instruction.
3646 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3647 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3648 Value *NewVecOp = State.get(getVecOp());
3649 if (VPValue *Cond = getCondOp()) {
3650 Value *NewCond = State.get(Cond, State.VF.isScalar());
3651 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3652 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3653
3654 Value *Start =
3656 if (State.VF.isVector())
3657 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3658
3659 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3660 NewVecOp = Select;
3661 }
3662 Value *NewRed;
3663 Value *NextInChain;
3664 if (isOrdered()) {
3665 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3666 if (State.VF.isVector())
3667 NewRed =
3668 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3669 else
3670 NewRed = State.Builder.CreateBinOp(
3672 PrevInChain, NewVecOp);
3673 PrevInChain = NewRed;
3674 NextInChain = NewRed;
3675 } else if (isPartialReduction()) {
3676 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3677 "Unexpected partial reduction kind");
3678 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/false);
3679 NewRed = State.Builder.CreateIntrinsic(
3680 PrevInChain->getType(),
3681 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3682 : Intrinsic::vector_partial_reduce_fadd,
3683 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3684 "partial.reduce");
3685 PrevInChain = NewRed;
3686 NextInChain = NewRed;
3687 } else {
3688 assert(isInLoop() &&
3689 "The reduction must either be ordered, partial or in-loop");
3690 Value *PrevInChain = State.get(getChainOp(), /*NeedsSingleScalar=*/true);
3691 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3693 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3694 else
3695 NextInChain = State.Builder.CreateBinOp(
3697 PrevInChain, NewRed);
3698 }
3699 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3700}
3701
3703
3704 assert(State.VF.isVector() &&
3705 "Shouldn't generate VPReductionEVLRecipe with scalar VF");
3706 auto &Builder = State.Builder;
3707 // Propagate the fast-math flags carried by the underlying instruction.
3708 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3709 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3710
3712 Value *Prev =
3713 State.get(getChainOp(), /*NeedsSingleScalar=*/!isPartialReduction());
3714 Value *VecOp = State.get(getVecOp());
3715 Value *EVL = State.get(getEVL(), VPLane(0));
3716
3717 Value *Mask;
3718 if (VPValue *CondOp = getCondOp())
3719 Mask = State.get(CondOp);
3720 else
3721 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3722
3723 Value *NewRed;
3724 if (isPartialReduction()) {
3725 // For partial reductions, we need to generate a predicated select
3726 // (vp.merge) since `@llvm.vector.partial.reduce()` doesn't have a vector
3727 // predicated version.
3728 VectorType *VecTy = cast<VectorType>(VecOp->getType());
3729 Value *Identity = getRecurrenceIdentity(Kind, VecTy->getElementType(),
3731 Identity =
3732 State.Builder.CreateVectorSplat(VecTy->getElementCount(), Identity);
3733
3734 // TODO: Calculate the predicate cost for the partial reduction.
3735 Value *NewVecOp = State.Builder.CreateIntrinsic(
3736 VecTy, Intrinsic::vp_merge, {Mask, VecOp, Identity, EVL});
3737 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3738 "Unexpected partial reduction kind");
3739 NewRed = State.Builder.CreateIntrinsic(
3740 Prev->getType(),
3741 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3742 : Intrinsic::vector_partial_reduce_fadd,
3743 {Prev, NewVecOp}, State.Builder.getFastMathFlags(), "partial.reduce");
3744 } else if (isOrdered()) {
3745 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3746 } else {
3747 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3749 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3750 else
3751 NewRed = Builder.CreateBinOp(
3753 Prev);
3754 }
3755 State.set(this, NewRed, !isPartialReduction());
3756}
3757
3759 VPCostContext &Ctx) const {
3760 RecurKind RdxKind = getRecurrenceKind();
3761 Type *ElementTy = this->getScalarType();
3762 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3763 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3765 std::optional<FastMathFlags> OptionalFMF =
3766 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3767
3768 if (isPartialReduction()) {
3769 InstructionCost CondCost = 0;
3770 if (isConditional()) {
3772 auto *CondTy =
3774 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3775 CondTy, Pred, Ctx.CostKind);
3776 }
3777 return CondCost + Ctx.TTI.getPartialReductionCost(
3778 Opcode, ElementTy, nullptr, ElementTy, VF,
3779 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3780 OptionalFMF);
3781 }
3782
3783 // TODO: Support any-of reductions.
3784 assert(
3786 Ctx.Opts.force_target_instruction_cost) &&
3787 "Any-of reduction not implemented in VPlan-based cost model currently.");
3788
3789 // Note that TTI should model the cost of moving result to the scalar register
3790 // and the BinOp cost in the getMinMaxReductionCost().
3793 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3794 }
3795
3796 // Note that TTI should model the cost of moving result to the scalar register
3797 // and the BinOp cost in the getArithmeticReductionCost().
3798 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3799 Ctx.CostKind);
3800}
3801
3803 ExpressionTypes ExpressionType,
3804 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3805 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3806 cast<VPReductionRecipe>(ExpressionRecipes.back())
3807 ->getChainOp()
3808 ->getScalarType()),
3809 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3810 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3811 assert(
3812 none_of(ExpressionRecipes,
3813 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3814 "expression cannot contain recipes with side-effects");
3815
3816 // Maintain a copy of the expression recipes as a set of users.
3817 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3818 for (auto *R : ExpressionRecipes)
3819 ExpressionRecipesAsSetOfUsers.insert(R);
3820
3821 // Recipes in the expression, except the last one, must only be used by
3822 // (other) recipes inside the expression. If there are other users, external
3823 // to the expression, use a clone of the recipe for external users.
3824 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3825 if (R != ExpressionRecipes.back() &&
3826 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3827 return !ExpressionRecipesAsSetOfUsers.contains(U);
3828 })) {
3829 // There are users outside of the expression. Clone the recipe and use the
3830 // clone those external users.
3831 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3832 R->replaceUsesWithIf(CopyForExtUsers,
3833 [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3834 return !ExpressionRecipesAsSetOfUsers.contains(U);
3835 });
3836 CopyForExtUsers->insertBefore(R);
3837 }
3838 if (R->getParent())
3839 R->removeFromParent();
3840 }
3841
3842 // Internalize all external operands to the expression recipes. To do so,
3843 // create new temporary VPValues for all operands defined by a recipe outside
3844 // the expression. The original operands are added as operands of the
3845 // VPExpressionRecipe itself.
3846 for (auto *R : ExpressionRecipes) {
3847 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3848 auto *Def = Op->getDefiningRecipe();
3849 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3850 continue;
3851 addOperand(Op);
3852 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3853 }
3854 }
3855
3856 // Replace each external operand with the first one created for it in
3857 // LiveInPlaceholders.
3858 for (auto *R : ExpressionRecipes)
3859 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3860 R->replaceUsesOfWith(LiveIn, Tmp);
3861}
3862
3864 for (auto *R : ExpressionRecipes)
3865 // Since the list could contain duplicates, make sure the recipe hasn't
3866 // already been inserted.
3867 if (!R->getParent())
3868 R->insertBefore(this);
3869
3870 for (const auto &[Idx, Op] : enumerate(operands()))
3871 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3872
3873 replaceAllUsesWith(ExpressionRecipes.back());
3874 SmallVector<VPSingleDefRecipe *> DecomposedRecipes(ExpressionRecipes);
3875 ExpressionRecipes.clear();
3876 return DecomposedRecipes;
3877}
3878
3880 VPCostContext &Ctx) const {
3881 Type *RedTy = this->getScalarType();
3882 auto *SrcVecTy =
3884 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3885 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3886 switch (ExpressionType) {
3887 case ExpressionTypes::NegatedExtendedReduction:
3888 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3889 "Unexpected opcode");
3890 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3891 [[fallthrough]];
3892 case ExpressionTypes::ExtendedReduction: {
3893 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3894 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3895
3896 if (RedR->isPartialReduction())
3897 return Ctx.TTI.getPartialReductionCost(
3898 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3900 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3901 RedTy->isFloatingPointTy()
3902 ? std::optional{RedR->getFastMathFlagsOrNone()}
3903 : std::nullopt);
3904 else if (!RedTy->isFloatingPointTy())
3905 // TTI::getExtendedReductionCost only supports integer types.
3906 return Ctx.TTI.getExtendedReductionCost(
3907 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3908 std::nullopt, Ctx.CostKind);
3909 else
3911 }
3912 case ExpressionTypes::MulAccReduction:
3913 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3914 Ctx.CostKind);
3915
3916 case ExpressionTypes::ExtNegatedMulAccReduction:
3917 switch (Opcode) {
3918 case Instruction::Add:
3919 Opcode = Instruction::Sub;
3920 break;
3921 case Instruction::FAdd:
3922 Opcode = Instruction::FSub;
3923 break;
3924 default:
3925 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3926 }
3927 [[fallthrough]];
3928 case ExpressionTypes::ExtMulAccReduction: {
3929 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3930 if (RedR->isPartialReduction()) {
3931 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3932 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3933 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3934 return Ctx.TTI.getPartialReductionCost(
3935 Opcode, getOperand(0)->getScalarType(),
3936 getOperand(1)->getScalarType(), RedTy, VF,
3938 Ext0R->getOpcode()),
3940 Ext1R->getOpcode()),
3941 Mul->getOpcode(), Ctx.CostKind,
3942 RedTy->isFloatingPointTy()
3943 ? std::optional{RedR->getFastMathFlagsOrNone()}
3944 : std::nullopt);
3945 }
3946 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3947 return Ctx.TTI.getMulAccReductionCost(
3948 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3949 Instruction::ZExt,
3950 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3951 }
3952 }
3953 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3954}
3955
3957 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3958 return R->mayReadFromMemory() || R->mayWriteToMemory();
3959 });
3960}
3961
3963 assert(
3964 none_of(ExpressionRecipes,
3965 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3966 "expression cannot contain recipes with side-effects");
3967 return false;
3968}
3969
3971 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3972 return RR && !RR->isPartialReduction();
3973}
3974
3975#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3976
3978 VPSlotTracker &SlotTracker) const {
3979 O << Indent << "EXPRESSION ";
3981 O << " = ";
3982 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3983 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3984 VPValue *Mask = getLastOperand();
3985 VPValue *EVL =
3987 ? getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1))
3988 : nullptr;
3989 VPValue *RdxStart = getOperand(
3990 getNumOperands() - (Red->isConditional() ? 2 : 1) - (EVL ? 1 : 0));
3991 auto PrintEVLAndMask = [&]() {
3992 if (EVL) {
3993 O << ", ";
3994 EVL->printAsOperand(O, SlotTracker);
3995 }
3996 if (Red->isConditional()) {
3997 O << ", ";
3998 Mask->printAsOperand(O, SlotTracker);
3999 }
4000 };
4001
4002 switch (ExpressionType) {
4003 case ExpressionTypes::NegatedExtendedReduction:
4004 case ExpressionTypes::ExtendedReduction: {
4005 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
4007 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4008 O << Instruction::getOpcodeName(Opcode) << " (";
4009 if (Negated)
4010 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
4012 if (Negated)
4013 O << ")";
4014 Red->printFlags(O);
4015
4016 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4017 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4018 << *Ext0->getScalarType();
4019 PrintEVLAndMask();
4020 O << ")";
4021 break;
4022 }
4023 case ExpressionTypes::ExtNegatedMulAccReduction: {
4024 RdxStart->printAsOperand(O, SlotTracker);
4025 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4027 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4028 << " (sub (0, mul";
4029 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
4030 Mul->printFlags(O);
4031 O << "(";
4033 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4034 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4035 << *Ext0->getScalarType() << "), (";
4037 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4038 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4039 << *Ext1->getScalarType() << ")";
4040 PrintEVLAndMask();
4041 O << "))";
4042 break;
4043 }
4044 case ExpressionTypes::MulAccReduction:
4045 case ExpressionTypes::ExtMulAccReduction: {
4046 RdxStart->printAsOperand(O, SlotTracker);
4047 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
4049 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
4050 << " (";
4051 O << "mul";
4052 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
4053 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
4054 : ExpressionRecipes[0]);
4055 Mul->printFlags(O);
4056 if (IsExtended)
4057 O << "(";
4059 if (IsExtended) {
4060 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
4061 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
4062 << *Ext0->getScalarType() << "), (";
4063 } else {
4064 O << ", ";
4065 }
4067 if (IsExtended) {
4068 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
4069 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
4070 << *Ext1->getScalarType() << ")";
4071 }
4072 PrintEVLAndMask();
4073 O << ")";
4074 break;
4075 }
4076 }
4077}
4078
4080 VPSlotTracker &SlotTracker) const {
4081 if (isPartialReduction())
4082 O << Indent << "PARTIAL-REDUCE ";
4083 else
4084 O << Indent << "REDUCE ";
4086 O << " = ";
4088 O << " +";
4089 printFlags(O);
4090 O << " reduce.";
4092 O << " (";
4094 if (isConditional()) {
4095 O << ", ";
4097 }
4098 O << ")";
4099}
4100
4102 VPSlotTracker &SlotTracker) const {
4103 if (isPartialReduction())
4104 O << Indent << "PARTIAL-REDUCE ";
4105 else
4106 O << Indent << "REDUCE ";
4108 O << " = ";
4110 O << " +";
4111 printFlags(O);
4112 O << " vp.reduce."
4115 << " (";
4117 O << ", ";
4119 if (isConditional()) {
4120 O << ", ";
4122 }
4123 O << ")";
4124}
4125
4126#endif
4127
4129 assert(IsSingleScalar &&
4130 "VPReplicateRecipes must be unrolled before ::execute");
4131 auto *Instr = getUnderlyingInstr();
4132 Instruction *Cloned = Instr->clone();
4133 Type *ResultTy = getScalarType();
4134 if (!ResultTy->isVoidTy()) {
4135 Cloned->setName(Instr->getName() + ".cloned");
4136 // The operands of the replicate recipe may have been narrowed, resulting in
4137 // a narrower result type. Update the type of the cloned instruction to the
4138 // correct type.
4139 if (ResultTy != Cloned->getType())
4140 Cloned->mutateType(ResultTy);
4141 }
4142
4145 Cloned->dropPoisonGeneratingFlags();
4146 applyFlags(*Cloned);
4147 applyMetadata(*Cloned);
4148
4149 if (hasPredicate())
4150 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
4151
4152 // Replace the operands of the cloned instructions with their scalar
4153 // equivalents in the new loop.
4154 for (unsigned Idx : seq(Cloned->getNumOperands()))
4155 Cloned->setOperand(Idx, State.get(getOperand(Idx), true));
4156
4157 // Place the cloned scalar in the new loop.
4158 State.Builder.Insert(Cloned);
4159
4160 State.set(this, Cloned, true);
4161
4162 // If we just cloned a new assumption, add it the assumption cache.
4163 if (auto *II = dyn_cast<AssumeInst>(Cloned))
4164 State.AC->registerAssumption(II);
4165}
4166
4167/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
4168/// which the legacy cost model computes a SCEV expression when computing the
4169/// address cost. Computing SCEVs for VPValues is incomplete and returns
4170/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
4171/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
4172static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
4174 const Loop *L) {
4175 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
4176 if (isa<SCEVCouldNotCompute>(Addr))
4177 return Addr;
4178
4179 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
4180}
4181
4183 VPCostContext &Ctx) const {
4185 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
4186 // transform, avoid computing their cost multiple times for now.
4187 Ctx.SkipCostComputation.insert(UI);
4188
4189 if (VF.isScalable() && !isSingleScalar())
4191
4192 switch (UI->getOpcode()) {
4193 case Instruction::Alloca:
4194 if (VF.isScalable())
4196 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
4197 this->getScalarType(), Ctx.CostKind);
4198 case Instruction::GetElementPtr:
4199 // We mark this instruction as zero-cost because the cost of GEPs in
4200 // vectorized code depends on whether the corresponding memory instruction
4201 // is scalarized or not. Therefore, we handle GEPs with the memory
4202 // instruction cost.
4203 return 0;
4204 case Instruction::Call: {
4205 auto *CalledFn = cast<Function>(getLastOperand()->getLiveInIRValue());
4206 Type *ResultTy = this->getScalarType();
4207 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
4208 isSingleScalar(), VF, Ctx);
4209 }
4210 case Instruction::Add:
4211 case Instruction::Sub:
4212 case Instruction::FAdd:
4213 case Instruction::FSub:
4214 case Instruction::Mul:
4215 case Instruction::FMul:
4216 case Instruction::FDiv:
4217 case Instruction::FRem:
4218 case Instruction::Shl:
4219 case Instruction::LShr:
4220 case Instruction::AShr:
4221 case Instruction::And:
4222 case Instruction::Or:
4223 case Instruction::Xor:
4224 case Instruction::ICmp:
4225 case Instruction::FCmp:
4227 Ctx) *
4228 (isSingleScalar() ? 1 : VF.getFixedValue());
4229 case Instruction::SDiv:
4230 case Instruction::UDiv:
4231 case Instruction::SRem:
4232 case Instruction::URem: {
4233 InstructionCost ScalarCost =
4235 if (isSingleScalar())
4236 return ScalarCost;
4237
4238 // If any of the operands is from a different replicate region and has its
4239 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
4240 // model to avoid cost mis-match.
4241 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
4242 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
4243 if (!PredR)
4244 return false;
4245 return Ctx.skipCostComputation(
4247 PredR->getOperand(0)->getUnderlyingValue()),
4248 VF.isVector());
4249 }))
4250 break;
4251
4252 ScalarCost = ScalarCost * VF.getFixedValue() +
4253 Ctx.getScalarizationOverhead(this->getScalarType(),
4254 to_vector(operands()), VF);
4255 // If the recipe is not predicated (i.e. not in a replicate region), return
4256 // the scalar cost. Otherwise handle predicated cost.
4257 const VPRegionBlock *ParentRegion = getRegion();
4258 if (!ParentRegion || !ParentRegion->isReplicator())
4259 return ScalarCost;
4260
4261 // Account for the phi nodes that we will create.
4262 ScalarCost += VF.getFixedValue() *
4263 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4264 // Scale the cost by the probability of executing the predicated blocks.
4265 // This assumes the predicated block for each vector lane is equally
4266 // likely.
4267 ScalarCost /= Ctx.getCostDivisor(
4268 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4269 return ScalarCost;
4270 }
4271 case Instruction::Load:
4272 case Instruction::Store: {
4273 bool IsLoad = UI->getOpcode() == Instruction::Load;
4274 const VPValue *PtrOp = getOperand(!IsLoad);
4275 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
4277 break;
4278
4279 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
4280 Type *ScalarPtrTy = PtrOp->getScalarType();
4281 const Align Alignment = getLoadStoreAlignment(UI);
4282 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
4284 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
4285 bool UsedByLoadStoreAddress =
4286 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
4287 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
4288 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
4289 UsedByLoadStoreAddress ? UI : nullptr);
4290
4291 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
4292 InstructionCost ScalarCost =
4293 ScalarMemOpCost +
4294 Ctx.TTI.getAddressComputationCost(
4295 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
4296 Ctx.CostKind);
4297 if (isSingleScalar())
4298 return ScalarCost;
4299
4300 SmallVector<const VPValue *> OpsToScalarize;
4301 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
4302 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
4303 // don't assign scalarization overhead in general, if the target prefers
4304 // vectorized addressing or the loaded value is used as part of an address
4305 // of another load or store.
4306 if (!UsedByLoadStoreAddress) {
4307 bool EfficientVectorLoadStore =
4308 Ctx.TTI.supportsEfficientVectorElementLoadStore();
4309 if (!(IsLoad && !PreferVectorizedAddressing) &&
4310 !(!IsLoad && EfficientVectorLoadStore))
4311 append_range(OpsToScalarize, operands());
4312
4313 if (!EfficientVectorLoadStore)
4314 ResultTy = this->getScalarType();
4315 }
4316
4318 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
4320 (ScalarCost * VF.getFixedValue()) +
4321 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
4322
4323 const VPRegionBlock *ParentRegion = getRegion();
4324 if (ParentRegion && ParentRegion->isReplicator()) {
4325 // The cost of the branches is accounted for by the replicate region.
4326 Cost /= Ctx.getCostDivisor(
4327 ParentRegion->getEntryBranchOnMask()->getExecutionFrequency());
4328
4329 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
4330 // Artificially setting to a high enough value to practically disable
4331 // vectorization with such operations.
4332 return 3000000;
4333 }
4334 }
4335 return Cost;
4336 }
4337 case Instruction::SExt:
4338 case Instruction::ZExt:
4339 case Instruction::FPToUI:
4340 case Instruction::FPToSI:
4341 case Instruction::FPExt:
4342 case Instruction::PtrToInt:
4343 case Instruction::PtrToAddr:
4344 case Instruction::IntToPtr:
4345 case Instruction::SIToFP:
4346 case Instruction::UIToFP:
4347 case Instruction::Trunc:
4348 case Instruction::FPTrunc:
4349 case Instruction::Select:
4350 case Instruction::AddrSpaceCast: {
4352 Ctx) *
4353 (isSingleScalar() ? 1 : VF.getFixedValue());
4354 }
4355 case Instruction::ExtractValue:
4356 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
4357 }
4358
4359 return Ctx.getLegacyCost(UI, VF);
4360}
4361
4363 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
4364 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
4366 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
4367
4368 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
4369 auto GetIntrinsicCost = [&] {
4370 if (!IntrinID)
4372 return Ctx.TTI.getIntrinsicInstrCost(
4373 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4374 };
4375
4376 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4377 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4378 return 0;
4379 }
4380
4381 InstructionCost ScalarCallCost =
4382 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4383 if (IsSingleScalar) {
4384 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4385 return ScalarCallCost;
4386 }
4387
4388 // Scalarization overhead is undefined for scalable VFs.
4389 if (VF.isScalable())
4391
4392 return ScalarCallCost * VF.getFixedValue() +
4393 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4394}
4395
4396#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4398 VPSlotTracker &SlotTracker) const {
4399 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4400
4401 if (!getScalarType()->isVoidTy()) {
4403 O << " = ";
4404 }
4405 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4406 O << "call";
4407 printFlags(O);
4408 O << "@" << CB->getCalledFunction()->getName() << "(";
4410 Op->printAsOperand(O, SlotTracker);
4411 });
4412 O << ")";
4413 } else {
4415 printFlags(O);
4417 }
4418
4419 // Find if the recipe is used by a widened recipe via an intervening
4420 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4421 if (any_of(users(), [](const VPUser *U) {
4422 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4423 return !vputils::onlyScalarValuesUsed(PredR);
4424 return false;
4425 }))
4426 O << " (S->V)";
4427}
4428#endif
4429
4431 llvm_unreachable("recipe must be removed when dissolving replicate region");
4432}
4433
4435 VPCostContext &Ctx) const {
4436 // Replicating isn't supported for scalable vectors.
4437 if (VF.isScalable())
4439 auto *VecI1Ty = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
4440 return Ctx.TTI.getScalarizationOverhead(
4441 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4442 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind) +
4443 VF.getFixedValue() *
4444 Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
4445}
4446
4448 llvm_unreachable("recipe must be removed when dissolving replicate region");
4449}
4450
4451#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4453 VPSlotTracker &SlotTracker) const {
4454 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4456 O << " = ";
4458}
4459#endif
4460
4462const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4463
4466
4468const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4469
4472
4474 VPCostContext &Ctx) const {
4475 const VPRecipeBase *R = getAsRecipe();
4477 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4478 : R->getOperand(1)->getScalarType();
4479 Type *Ty = toVectorTy(ScalarTy, VF);
4480 unsigned AS =
4481 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4482 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4483
4484 if (!Consecutive) {
4485 // TODO: Using the original IR may not be accurate.
4486 // Currently, ARM will use the underlying IR to calculate gather/scatter
4487 // instruction cost.
4488 Type *PtrTy = getAddr()->getScalarType();
4489 const Value *Ptr = getAddr()->getUnderlyingValue();
4490
4491 // If the address value is uniform across all lanes, then the address can be
4492 // calculated with scalar type and broadcast.
4494 PtrTy = toVectorTy(PtrTy, VF);
4495
4496 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4497 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4498 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4499 : Intrinsic::vp_scatter;
4500 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4501 Ctx.CostKind) +
4502 Ctx.TTI.getMemIntrinsicInstrCost(
4504 &Ingredient),
4505 Ctx.CostKind);
4506 }
4507
4509 if (IsMasked) {
4510 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4511 : Intrinsic::masked_store;
4512 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4513 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4514 } else {
4515 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4517 : R->getOperand(1));
4518 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4519 OpInfo, &Ingredient);
4520 }
4521 return Cost;
4522}
4523
4525 Type *ScalarDataTy = getScalarType();
4526 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4527 bool CreateGather = !isConsecutive();
4528
4529 auto &Builder = State.Builder;
4530 Value *Mask = nullptr;
4531 if (auto *VPMask = getMask())
4532 Mask = State.get(VPMask);
4533
4534 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateGather);
4535 Value *NewLI;
4536 if (CreateGather) {
4537 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4538 "wide.masked.gather");
4539 } else if (Mask) {
4540 NewLI =
4541 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4542 PoisonValue::get(DataTy), "wide.masked.load");
4543 } else {
4544 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4545 }
4547 State.set(this, NewLI);
4548}
4549
4550#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4552 VPSlotTracker &SlotTracker) const {
4553 O << Indent << "WIDEN ";
4555 O << " = load ";
4557 O << ", align " << getAlign().value();
4558}
4559#endif
4560
4562 Type *ScalarDataTy = getScalarType();
4563 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4564 bool CreateGather = !isConsecutive();
4565
4566 auto &Builder = State.Builder;
4567 CallInst *NewLI;
4568 Value *EVL = State.get(getEVL(), VPLane(0));
4569 Value *Addr = State.get(getAddr(), !CreateGather);
4570 Value *Mask = nullptr;
4571 if (VPValue *VPMask = getMask())
4572 Mask = State.get(VPMask);
4573 else
4574 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4575
4576 if (CreateGather) {
4577 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4578 {Addr, Mask, EVL}, nullptr,
4579 "wide.masked.gather");
4580 } else {
4581 NewLI = Builder.CreateIntrinsicWithoutFolding(
4582 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4583 }
4584 NewLI->addParamAttr(
4586 applyMetadata(*NewLI);
4587 State.set(this, NewLI);
4588}
4589
4591 VPCostContext &Ctx) const {
4592 if (!Consecutive || IsMasked)
4593 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4594
4595 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4596 // here because the EVL recipes using EVL to replace the tail mask. But in the
4597 // legacy model, it will always calculate the cost of mask.
4598 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4599 // don't need to compare to the legacy cost model.
4600 Type *Ty = toVectorTy(getScalarType(), VF);
4601 unsigned AS =
4602 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4603 return Ctx.TTI.getMemIntrinsicInstrCost(
4604 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4605 Ctx.CostKind);
4606}
4607
4608#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4610 VPSlotTracker &SlotTracker) const {
4611 O << Indent << "WIDEN ";
4613 O << " = vp.load ";
4615 O << ", align " << getAlign().value();
4616}
4617#endif
4618
4620 VPValue *StoredVPValue = getStoredValue();
4621 bool CreateScatter = !isConsecutive();
4622
4623 auto &Builder = State.Builder;
4624
4625 Value *Mask = nullptr;
4626 if (auto *VPMask = getMask())
4627 Mask = State.get(VPMask);
4628
4629 Value *StoredVal = State.get(StoredVPValue);
4630 Value *Addr = State.get(getAddr(), /*NeedsSingleScalar=*/!CreateScatter);
4631 Instruction *NewSI = nullptr;
4632 if (CreateScatter)
4633 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4634 else if (Mask)
4635 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4636 else
4637 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4638 applyMetadata(*NewSI);
4639}
4640
4641#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4643 VPSlotTracker &SlotTracker) const {
4644 O << Indent << "WIDEN store ";
4646 O << ", align " << getAlign().value();
4647}
4648#endif
4649
4651 VPValue *StoredValue = getStoredValue();
4652 bool CreateScatter = !isConsecutive();
4653
4654 auto &Builder = State.Builder;
4655
4656 CallInst *NewSI = nullptr;
4657 Value *StoredVal = State.get(StoredValue);
4658 Value *EVL = State.get(getEVL(), VPLane(0));
4659 Value *Mask = nullptr;
4660 if (VPValue *VPMask = getMask())
4661 Mask = State.get(VPMask);
4662 else
4663 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4664
4665 Value *Addr = State.get(getAddr(), !CreateScatter);
4666 if (CreateScatter) {
4667 NewSI = Builder.CreateIntrinsicWithoutFolding(
4668 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4669 {StoredVal, Addr, Mask, EVL});
4670 } else {
4671 NewSI = Builder.CreateIntrinsicWithoutFolding(
4672 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4673 {StoredVal, Addr, Mask, EVL});
4674 }
4675 NewSI->addParamAttr(
4677 applyMetadata(*NewSI);
4678}
4679
4681 VPCostContext &Ctx) const {
4682 if (!Consecutive || IsMasked)
4683 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4684
4685 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4686 // here because the EVL recipes using EVL to replace the tail mask. But in the
4687 // legacy model, it will always calculate the cost of mask.
4688 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4689 // don't need to compare to the legacy cost model.
4690 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4691 unsigned AS =
4692 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4693 return Ctx.TTI.getMemIntrinsicInstrCost(
4694 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4695 Ctx.CostKind);
4696}
4697
4698#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4700 VPSlotTracker &SlotTracker) const {
4701 O << Indent << "WIDEN vp.store ";
4703 O << ", align " << getAlign().value();
4704}
4705#endif
4706
4708 VectorType *DstVTy, const DataLayout &DL) {
4709 // Verify that V is a vector type with same number of elements as DstVTy.
4710 auto VF = DstVTy->getElementCount();
4711 auto *SrcVecTy = cast<VectorType>(V->getType());
4712 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4713 Type *SrcElemTy = SrcVecTy->getElementType();
4714 Type *DstElemTy = DstVTy->getElementType();
4715 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4716 "Vector elements must have same size");
4717
4718 // Do a direct cast if element types are castable.
4719 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4720 return Builder.CreateBitOrPointerCast(V, DstVTy);
4721 }
4722 // V cannot be directly casted to desired vector type.
4723 // May happen when V is a floating point vector but DstVTy is a vector of
4724 // pointers or vice-versa. Handle this using a two-step bitcast using an
4725 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4726 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4727 "Only one type should be a pointer type");
4728 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4729 "Only one type should be a floating point type");
4730 Type *IntTy =
4731 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4732 auto *VecIntTy = VectorType::get(IntTy, VF);
4733 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4734 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4735}
4736
4737/// Return a vector containing interleaved elements from multiple
4738/// smaller input vectors.
4740 const Twine &Name) {
4741 unsigned Factor = Vals.size();
4742 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4743
4744 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4745#ifndef NDEBUG
4746 for (Value *Val : Vals)
4747 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4748#endif
4749
4750 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4751 // must use intrinsics to interleave.
4752 if (VecTy->isScalableTy()) {
4753 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4754 return Builder.CreateVectorInterleave(Vals, Name);
4755 }
4756
4757 // Fixed length. Start by concatenating all vectors into a wide vector.
4758 Value *WideVec = concatenateVectors(Builder, Vals);
4759
4760 // Interleave the elements into the wide vector.
4761 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4762 return Builder.CreateShuffleVector(
4763 WideVec, createInterleaveMask(NumElts, Factor), Name);
4764}
4765
4766// Try to vectorize the interleave group that \p Instr belongs to.
4767//
4768// E.g. Translate following interleaved load group (factor = 3):
4769// for (i = 0; i < N; i+=3) {
4770// R = Pic[i]; // Member of index 0
4771// G = Pic[i+1]; // Member of index 1
4772// B = Pic[i+2]; // Member of index 2
4773// ... // do something to R, G, B
4774// }
4775// To:
4776// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4777// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4778// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4779// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4780//
4781// Or translate following interleaved store group (factor = 3):
4782// for (i = 0; i < N; i+=3) {
4783// ... do something to R, G, B
4784// Pic[i] = R; // Member of index 0
4785// Pic[i+1] = G; // Member of index 1
4786// Pic[i+2] = B; // Member of index 2
4787// }
4788// To:
4789// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4790// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4791// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4792// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4793// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4795 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4796 "Masking gaps for scalable vectors is not yet supported.");
4798 Instruction *Instr = Group->getInsertPos();
4799
4800 // Prepare for the vector type of the interleaved load/store.
4801 Type *ScalarTy = getLoadStoreType(Instr);
4802 unsigned InterleaveFactor = Group->getFactor();
4803 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4804
4805 VPValue *BlockInMask = getMask();
4806 VPValue *Addr = getAddr();
4807 Value *ResAddr = State.get(Addr, VPLane(0));
4808
4809 auto CreateGroupMask = [&BlockInMask, &State,
4810 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4811 if (State.VF.isScalable()) {
4812 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4813 assert(InterleaveFactor <= 8 &&
4814 "Unsupported deinterleave factor for scalable vectors");
4815 auto *ResBlockInMask = State.get(BlockInMask);
4816 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4817 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4818 }
4819
4820 if (!BlockInMask)
4821 return MaskForGaps;
4822
4823 Value *ResBlockInMask = State.get(BlockInMask);
4824 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4825 ResBlockInMask,
4826 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4827 "interleaved.mask");
4828 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4829 ShuffledMask, MaskForGaps)
4830 : ShuffledMask;
4831 };
4832
4833 const DataLayout &DL = Instr->getDataLayout();
4834 // Vectorize the interleaved load group.
4835 if (isa<LoadInst>(Instr)) {
4836 Value *MaskForGaps = nullptr;
4837 if (needsMaskForGaps()) {
4838 MaskForGaps =
4839 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4840 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4841 }
4842
4843 Instruction *NewLoad;
4844 if (BlockInMask || MaskForGaps) {
4845 Value *GroupMask = CreateGroupMask(MaskForGaps);
4846 Value *PoisonVec = PoisonValue::get(VecTy);
4847 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4848 Group->getAlign(), GroupMask,
4849 PoisonVec, "wide.masked.vec");
4850 } else
4851 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4852 Group->getAlign(), "wide.vec");
4853 applyMetadata(*NewLoad);
4854 // TODO: Also manage existing metadata using VPIRMetadata.
4855 Group->addMetadata(NewLoad);
4856
4858 if (VecTy->isScalableTy()) {
4859 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4860 // so must use intrinsics to deinterleave.
4861 assert(InterleaveFactor <= 8 &&
4862 "Unsupported deinterleave factor for scalable vectors");
4863 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4864 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4865 NewLoad->getType(), NewLoad,
4866 /*FMFSource=*/nullptr, "strided.vec");
4867 }
4868
4869 auto CreateStridedVector = [&InterleaveFactor, &State,
4870 &NewLoad](unsigned Index) -> Value * {
4871 assert(Index < InterleaveFactor && "Illegal group index");
4872 if (State.VF.isScalable())
4873 return State.Builder.CreateExtractValue(NewLoad, Index);
4874
4875 // For fixed length VF, use shuffle to extract the sub-vectors from the
4876 // wide load.
4877 auto StrideMask =
4878 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4879 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4880 "strided.vec");
4881 };
4882
4883 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4884 Instruction *Member = Group->getMember(I);
4885
4886 // Skip the gaps in the group.
4887 if (!Member)
4888 continue;
4889
4890 Value *StridedVec = CreateStridedVector(I);
4891
4892 // If this member has different type, cast the result type.
4893 if (Member->getType() != ScalarTy) {
4894 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4895 StridedVec =
4896 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4897 }
4898
4899 if (Group->isReverse())
4900 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4901
4902 State.set(VPDefs[J], StridedVec);
4903 ++J;
4904 }
4905 return;
4906 }
4907
4908 // The sub vector type for current instruction.
4909 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4910
4911 // Vectorize the interleaved store group.
4912 Value *MaskForGaps =
4913 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4914 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4915 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4916 ArrayRef<VPValue *> StoredValues = getStoredValues();
4917 // Collect the stored vector from each member.
4918 SmallVector<Value *, 4> StoredVecs;
4919 unsigned StoredIdx = 0;
4920 for (unsigned i = 0; i < InterleaveFactor; i++) {
4921 assert((Group->getMember(i) || MaskForGaps) &&
4922 "Fail to get a member from an interleaved store group");
4923 Instruction *Member = Group->getMember(i);
4924
4925 // Skip the gaps in the group.
4926 if (!Member) {
4927 Value *Undef = PoisonValue::get(SubVT);
4928 StoredVecs.push_back(Undef);
4929 continue;
4930 }
4931
4932 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4933 ++StoredIdx;
4934
4935 if (Group->isReverse())
4936 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4937
4938 // If this member has different type, cast it to a unified type.
4939
4940 if (StoredVec->getType() != SubVT)
4941 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4942
4943 StoredVecs.push_back(StoredVec);
4944 }
4945
4946 // Interleave all the smaller vectors into one wider vector.
4947 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4948 Instruction *NewStoreInstr;
4949 if (BlockInMask || MaskForGaps) {
4950 Value *GroupMask = CreateGroupMask(MaskForGaps);
4951 NewStoreInstr = State.Builder.CreateMaskedStore(
4952 IVec, ResAddr, Group->getAlign(), GroupMask);
4953 } else
4954 NewStoreInstr =
4955 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4956
4957 applyMetadata(*NewStoreInstr);
4958 // TODO: Also manage existing metadata using VPIRMetadata.
4959 Group->addMetadata(NewStoreInstr);
4960}
4961
4962#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4964 VPSlotTracker &SlotTracker) const {
4966 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4968 VPValue *Mask = getMask();
4969 if (Mask) {
4970 O << ", ";
4971 Mask->printAsOperand(O, SlotTracker);
4972 }
4973
4974 unsigned OpIdx = 0;
4975 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4976 if (!IG->getMember(i))
4977 continue;
4978 if (getNumStoreOperands() > 0) {
4979 O << "\n" << Indent << " store ";
4980 getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
4981 O << " to index " << i;
4982 } else {
4983 O << "\n" << Indent << " ";
4985 O << " = load from index " << i;
4986 }
4987 ++OpIdx;
4988 }
4989}
4990#endif
4991
4993 assert(State.VF.isScalable() &&
4994 "Only support scalable VF for EVL tail-folding.");
4996 "Masking gaps for scalable vectors is not yet supported.");
4998 Instruction *Instr = Group->getInsertPos();
4999
5000 // Prepare for the vector type of the interleaved load/store.
5001 Type *ScalarTy = getLoadStoreType(Instr);
5002 unsigned InterleaveFactor = Group->getFactor();
5003 assert(InterleaveFactor <= 8 &&
5004 "Unsupported deinterleave/interleave factor for scalable vectors");
5005 ElementCount WideVF = State.VF * InterleaveFactor;
5006 auto *VecTy = VectorType::get(ScalarTy, WideVF);
5007
5008 VPValue *Addr = getAddr();
5009 Value *ResAddr = State.get(Addr, VPLane(0));
5010 Value *EVL = State.get(getEVL(), VPLane(0));
5011 Value *InterleaveEVL = State.Builder.CreateMul(
5012 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
5013 /* NUW= */ true, /* NSW= */ true);
5014 LLVMContext &Ctx = State.Builder.getContext();
5015
5016 Value *GroupMask = nullptr;
5017 if (VPValue *BlockInMask = getMask()) {
5018 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
5019 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
5020 } else {
5021 GroupMask =
5022 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
5023 }
5024
5025 // Vectorize the interleaved load group.
5026 if (isa<LoadInst>(Instr)) {
5027 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5028 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
5029 "wide.vp.load");
5030 NewLoad->addParamAttr(0,
5031 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5032
5033 applyMetadata(*NewLoad);
5034 // TODO: Also manage existing metadata using VPIRMetadata.
5035 Group->addMetadata(NewLoad);
5036
5037 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
5038 // so must use intrinsics to deinterleave.
5039 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
5040 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
5041 NewLoad->getType(), NewLoad,
5042 /*FMFSource=*/nullptr, "strided.vec");
5043
5044 const DataLayout &DL = Instr->getDataLayout();
5045 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
5046 Instruction *Member = Group->getMember(I);
5047 // Skip the gaps in the group.
5048 if (!Member)
5049 continue;
5050
5051 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
5052 // If this member has different type, cast the result type.
5053 if (Member->getType() != ScalarTy) {
5054 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
5055 StridedVec =
5056 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
5057 }
5058
5059 State.set(getVPValue(J), StridedVec);
5060 ++J;
5061 }
5062 return;
5063 } // End for interleaved load.
5064
5065 // The sub vector type for current instruction.
5066 auto *SubVT = VectorType::get(ScalarTy, State.VF);
5067 // Vectorize the interleaved store group.
5068 ArrayRef<VPValue *> StoredValues = getStoredValues();
5069 // Collect the stored vector from each member.
5070 SmallVector<Value *, 4> StoredVecs;
5071 const DataLayout &DL = Instr->getDataLayout();
5072 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
5073 Instruction *Member = Group->getMember(I);
5074 // Skip the gaps in the group.
5075 if (!Member) {
5076 StoredVecs.push_back(PoisonValue::get(SubVT));
5077 continue;
5078 }
5079
5080 Value *StoredVec = State.get(StoredValues[StoredIdx]);
5081 // If this member has different type, cast it to a unified type.
5082 if (StoredVec->getType() != SubVT)
5083 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
5084
5085 StoredVecs.push_back(StoredVec);
5086 ++StoredIdx;
5087 }
5088
5089 // Interleave all the smaller vectors into one wider vector.
5090 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
5091 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
5092 Type::getVoidTy(Ctx), Intrinsic::vp_store,
5093 {IVec, ResAddr, GroupMask, InterleaveEVL});
5094
5095 NewStore->addParamAttr(1,
5096 Attribute::getWithAlignment(Ctx, Group->getAlign()));
5097
5098 applyMetadata(*NewStore);
5099 // TODO: Also manage existing metadata using VPIRMetadata.
5100 Group->addMetadata(NewStore);
5101}
5102
5103#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5105 VPSlotTracker &SlotTracker) const {
5107 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
5109 O << ", ";
5111 if (VPValue *Mask = getMask()) {
5112 O << ", ";
5113 Mask->printAsOperand(O, SlotTracker);
5114 }
5115
5116 unsigned OpIdx = 0;
5117 for (unsigned i = 0; i < IG->getFactor(); ++i) {
5118 if (!IG->getMember(i))
5119 continue;
5120 if (getNumStoreOperands() > 0) {
5121 O << "\n" << Indent << " vp.store ";
5122 getOperand(2 + OpIdx)->printAsOperand(O, SlotTracker);
5123 O << " to index " << i;
5124 } else {
5125 O << "\n" << Indent << " ";
5127 O << " = vp.load from index " << i;
5128 }
5129 ++OpIdx;
5130 }
5131}
5132#endif
5133
5135 VPCostContext &Ctx) const {
5136 Instruction *InsertPos = getInsertPos();
5137 // Find the VPValue index of the interleave group. We need to skip gaps.
5138 unsigned InsertPosIdx = 0;
5139 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
5140 if (auto *Member = IG->getMember(Idx)) {
5141 if (Member == InsertPos)
5142 break;
5143 InsertPosIdx++;
5144 }
5145 const VPValue *ValV = getNumDefinedValues() > 0
5146 ? getVPValue(InsertPosIdx)
5147 : getStoredValues()[InsertPosIdx];
5148 Type *ValTy = ValV->getScalarType();
5149 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5150 unsigned AS =
5151 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
5152
5153 unsigned InterleaveFactor = IG->getFactor();
5154 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5155
5156 // Holds the indices of existing members in the interleaved group.
5158 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5159 if (IG->getMember(IF))
5160 Indices.push_back(IF);
5161
5162 // Calculate the cost of the whole interleaved group.
5163 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
5164 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
5165 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
5166
5167 if (!IG->isReverse())
5168 return Cost;
5169
5170 return Cost + IG->getNumMembers() *
5171 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5172 VectorTy, VectorTy, Ctx.CostKind, {},
5173 0);
5174}
5175
5178 VPCostContext &Ctx) const {
5179 // The recipe creates a scalar phi, a GEP to increment the induction and
5180 // vector add to compute the vector of pointers.
5181 // TODO: Charge costs for induction increment and vector add as well.
5182 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5183}
5184
5189
5190#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5192 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5193 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
5194 "unexpected number of operands");
5195 O << Indent << "EMIT ";
5197 O << " = WIDEN-POINTER-INDUCTION ";
5199 O << ", ";
5201 O << ", ";
5203 if (getNumOperands() == 5) {
5204 O << ", ";
5206 O << ", ";
5208 }
5209}
5210
5212 VPSlotTracker &SlotTracker) const {
5213 O << Indent << "EMIT ";
5215 O << " = EXPAND SCEV " << *Expr;
5216 if (ExpandInIR)
5217 O << " (in IR)";
5218}
5219#endif
5220
5221#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5223 VPSlotTracker &SlotTracker) const {
5224 O << Indent << "EMIT ";
5226 O << " = WIDEN-CANONICAL-INDUCTION";
5227 printFlags(O);
5229}
5230#endif
5231
5233 auto &Builder = State.Builder;
5234 // Create a vector from the initial value.
5235 auto *VectorInit = getStartValue()->getLiveInIRValue();
5236
5237 Type *VecTy = State.VF.isScalar()
5238 ? VectorInit->getType()
5239 : VectorType::get(VectorInit->getType(), State.VF);
5240
5241 BasicBlock *VectorPH =
5242 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5243 if (State.VF.isVector()) {
5244 auto *IdxTy = Builder.getInt32Ty();
5245 auto *One = ConstantInt::get(IdxTy, 1);
5246 IRBuilder<>::InsertPointGuard Guard(Builder);
5247 Builder.SetInsertPoint(VectorPH->getTerminator());
5248 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
5249 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
5250 VectorInit = Builder.CreateInsertElement(
5251 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
5252 }
5253
5254 // Create a phi node for the new recurrence.
5255 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
5256 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
5257 Phi->addIncoming(VectorInit, VectorPH);
5258 State.set(this, Phi);
5259}
5260
5263 VPCostContext &Ctx) const {
5264 if (VF.isScalar())
5265 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5266
5267 return 0;
5268}
5269
5270#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5272 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5273 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
5275 O << " = phi ";
5277}
5278#endif
5279
5281 // Reductions do not have to start at zero. They can start with
5282 // any loop invariant values.
5283 VPValue *StartVPV = getStartValue();
5284
5285 // In order to support recurrences we need to be able to vectorize Phi nodes.
5286 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
5287 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
5288 // this value when we vectorize all of the instructions that use the PHI.
5289 BasicBlock *VectorPH =
5290 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5291 bool ScalarPHI = State.VF.isScalar() || isInLoop();
5292 Value *StartV = State.get(StartVPV, ScalarPHI);
5293 Type *VecTy = StartV->getType();
5294
5295 BasicBlock *HeaderBB = State.CFG.PrevBB;
5296 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
5297 "recipe must be in the vector loop header");
5298 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
5299 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
5300 State.set(this, Phi, isInLoop());
5301
5302 Phi->addIncoming(StartV, VectorPH);
5303}
5304
5305#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5307 VPSlotTracker &SlotTracker) const {
5308 O << Indent << "WIDEN-REDUCTION-PHI ";
5309
5311 O << " = phi (";
5312 printRecurrenceKind(O, Kind);
5313 O << ")";
5314 printFlags(O);
5316 if (getVFScaleFactor() > 1)
5317 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
5318}
5319#endif
5320
5322 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
5324 "Blend should propagate first lane use");
5325 return vputils::onlyFirstLaneUsed(this);
5326}
5327
5330 VPCostContext &Ctx) const {
5331 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5332}
5333
5334#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5336 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5337 O << Indent << "CONDITIONAL-INDUCTION-PHI ";
5338
5340 O << " = phi ";
5342}
5343#endif
5344
5346 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
5347}
5348
5350 VPCostContext &Ctx) const {
5351 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
5352}
5353
5354#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5356 VPSlotTracker &SlotTracker) const {
5357 O << Indent << "WIDEN-PHI ";
5358
5360 O << " = phi ";
5362}
5363#endif
5364
5366 BasicBlock *VectorPH =
5367 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
5368 Value *StartMask = State.get(getOperand(0));
5369 PHINode *Phi =
5370 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
5371 Phi->addIncoming(StartMask, VectorPH);
5372 State.set(this, Phi);
5373}
5374
5375#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5377 VPSlotTracker &SlotTracker) const {
5378 O << Indent << "ACTIVE-LANE-MASK-PHI ";
5379
5381 O << " = phi ";
5383}
5384#endif
5385
5386#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5388 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
5389 O << Indent << "CURRENT-ITERATION-PHI ";
5390
5392 O << " = phi ";
5394}
5395#endif
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 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 const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
bool hasAttributes() const
Return true if attributes exists in this set.
Definition Attributes.h:484
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h: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:548
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:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:321
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:309
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
Definition Operator.h:302
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:290
void setAllowContract(bool B=true)
Definition FMF.h:90
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setAllowReciprocal(bool B=true)
Definition FMF.h:87
bool allowReciprocal() const
Definition FMF.h:68
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool approxFunc() const
Definition FMF.h:70
void setNoNaNs(bool B=true)
Definition FMF.h:78
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:75
bool noNaNs() const
Definition FMF.h:65
void setApproxFunc(bool B=true)
Definition FMF.h:93
void setNoInfs(bool B=true)
Definition FMF.h:81
bool allowContract() const
Definition FMF.h:69
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
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:181
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2709
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:507
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2697
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:1934
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:1212
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 Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2775
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:522
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1108
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2092
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2324
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:288
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:2426
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:470
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1766
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:465
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2556
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1850
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2422
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1150
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1435
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2161
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1418
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:450
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1727
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2434
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1774
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1953
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
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:2194
Value * CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, Value *Idx, const Twine &Name="")
Create a call to the vector.insert intrinsic.
Definition IRBuilder.h:1122
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1452
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:338
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isReverse() const
InstTy * getInsertPos() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
Align getAlign() const
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
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:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
This class represents the LLVM 'select' instruction.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
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:300
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
value_op_iterator value_op_end()
Definition User.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
value_op_iterator value_op_begin()
Definition User.h:285
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:4522
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:3087
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3082
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:3078
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:577
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:550
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:562
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:572
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4329
VPValue * getIndex() const
Definition VPlan.h:4326
VPValue * getStepValue() const
Definition VPlan.h:4327
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:4325
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 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:2508
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:2216
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:1731
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 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:1532
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:1595
unsigned getOpcode() const
Definition VPlan.h:1514
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.
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={})
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:1561
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1535
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:3191
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3195
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3193
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3185
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3214
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3179
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3288
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:3301
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:3251
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:1610
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:1660
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1619
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:4927
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:110
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:3462
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:2935
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2954
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:3401
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:3414
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3416
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3397
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3403
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3412
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3407
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:4753
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4829
const VPBranchOnMaskRecipe * getEntryBranchOnMask() const
Return the VPBranchOnMaskRecipe from the entry block of this replicating region.
Definition VPlan.cpp:707
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:3541
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:3579
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:4384
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4392
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:1521
operand_range operands()
Definition VPlanValue.h:472
unsigned getNumOperands() const
Definition VPlanValue.h:436
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:142
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:136
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1473
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:123
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1517
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:2327
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:2324
int64_t getStride() const
Definition VPlan.h:2325
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2401
Type * getSourceElementType() const
Definition VPlan.h:2416
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:2403
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:2168
Function * getCalledScalarFunction() const
Definition VPlan.h:2164
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:1924
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:2281
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:2586
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2603
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:2685
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:2039
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:3846
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3871
Instruction & Ingredient
Definition VPlan.h:3837
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3843
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3881
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3840
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3888
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3874
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:1866
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4940
const DataLayout & getDataLayout() const
Definition VPlan.h:5141
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:5247
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:679
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,...
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used by all users.
Intrinsic::ID getIntrinsicID(const Ty *R)
Return the intrinsic ID underlying a call.
Definition VPlanUtils.h:98
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:2570
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
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2329
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:2208
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:1933
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:1789
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
PHINode & getIRPhi() const
Definition VPlan.h:1802
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:270
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:3975
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:4078
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:4081
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:4025