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