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"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
36#include "llvm/Support/Debug.h"
40#include <cassert>
41
42using namespace llvm;
43using namespace llvm::VPlanPatternMatch;
44
46
47#define LV_NAME "loop-vectorize"
48#define DEBUG_TYPE LV_NAME
49
50#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
51// It is sometimes necessary to disable printing of metadata in tests in order
52// to avoid non-deterministic behaviour due to metadata introduced by VPlan
53// that wasn't present in the original scalar IR.
55 "vplan-print-metadata", cl::init(true), cl::Hidden,
56 cl::desc("Controls the printing of recipe metadata when debugging."));
57#endif
58
60 switch (getVPRecipeID()) {
61 case VPExpressionSC:
62 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
63 case VPInstructionSC: {
64 auto *VPI = cast<VPInstruction>(this);
65 // Loads read from memory but don't write to memory.
66 if (VPI->getOpcode() == Instruction::Load)
67 return false;
68 return VPI->opcodeMayReadOrWriteFromMemory();
69 }
70 case VPInterleaveEVLSC:
71 case VPInterleaveSC:
72 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
73 case VPWidenStoreEVLSC:
74 case VPWidenStoreSC:
75 return true;
76 case VPReplicateSC:
77 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
78 ->mayWriteToMemory();
79 case VPWidenCallSC:
80 return !cast<VPWidenCallRecipe>(this)
81 ->getCalledScalarFunction()
82 ->onlyReadsMemory();
83 case VPWidenMemIntrinsicSC:
84 case VPWidenIntrinsicSC:
85 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
86 case VPActiveLaneMaskPHISC:
87 case VPCurrentIterationPHISC:
88 case VPBranchOnMaskSC:
89 case VPDerivedIVSC:
90 case VPFirstOrderRecurrencePHISC:
91 case VPReductionPHISC:
92 case VPScalarIVStepsSC:
93 case VPPredInstPHISC:
94 return false;
95 case VPBlendSC:
96 case VPReductionEVLSC:
97 case VPReductionSC:
98 case VPVectorPointerSC:
99 case VPWidenCanonicalIVSC:
100 case VPWidenCastSC:
101 case VPWidenGEPSC:
102 case VPWidenIntOrFpInductionSC:
103 case VPWidenLoadEVLSC:
104 case VPWidenLoadSC:
105 case VPWidenPHISC:
106 case VPWidenPointerInductionSC:
107 case VPWidenSC: {
108 const Instruction *I =
109 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
110 (void)I;
111 assert((!I || !I->mayWriteToMemory()) &&
112 "underlying instruction may write to memory");
113 return false;
114 }
115 default:
116 return true;
117 }
118}
119
121 switch (getVPRecipeID()) {
122 case VPExpressionSC:
123 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
124 case VPInstructionSC:
125 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
126 case VPWidenLoadEVLSC:
127 case VPWidenLoadSC:
128 return true;
129 case VPReplicateSC:
130 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
131 ->mayReadFromMemory();
132 case VPWidenCallSC:
133 return !cast<VPWidenCallRecipe>(this)
134 ->getCalledScalarFunction()
135 ->onlyWritesMemory();
136 case VPWidenMemIntrinsicSC:
137 case VPWidenIntrinsicSC:
138 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
139 case VPBranchOnMaskSC:
140 case VPDerivedIVSC:
141 case VPCurrentIterationPHISC:
142 case VPFirstOrderRecurrencePHISC:
143 case VPReductionPHISC:
144 case VPPredInstPHISC:
145 case VPScalarIVStepsSC:
146 case VPWidenStoreEVLSC:
147 case VPWidenStoreSC:
148 return false;
149 case VPBlendSC:
150 case VPReductionEVLSC:
151 case VPReductionSC:
152 case VPVectorPointerSC:
153 case VPWidenCanonicalIVSC:
154 case VPWidenCastSC:
155 case VPWidenGEPSC:
156 case VPWidenIntOrFpInductionSC:
157 case VPWidenPHISC:
158 case VPWidenPointerInductionSC:
159 case VPWidenSC: {
160 const Instruction *I =
161 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
162 (void)I;
163 assert((!I || !I->mayReadFromMemory()) &&
164 "underlying instruction may read from memory");
165 return false;
166 }
167 default:
168 // FIXME: Return false if the recipe represents an interleaved store.
169 return true;
170 }
171}
172
174 switch (getVPRecipeID()) {
175 case VPExpressionSC:
176 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
177 case VPActiveLaneMaskPHISC:
178 case VPDerivedIVSC:
179 case VPCurrentIterationPHISC:
180 case VPFirstOrderRecurrencePHISC:
181 case VPReductionPHISC:
182 case VPPredInstPHISC:
183 case VPVectorEndPointerSC:
184 return false;
185 case VPInstructionSC: {
186 auto *VPI = cast<VPInstruction>(this);
187 return mayWriteToMemory() ||
188 VPI->getOpcode() == VPInstruction::BranchOnCount ||
189 VPI->getOpcode() == VPInstruction::BranchOnCond ||
190 VPI->getOpcode() == VPInstruction::BranchOnTwoConds;
191 }
192 case VPWidenCallSC: {
193 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
194 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
195 }
196 case VPWidenMemIntrinsicSC:
197 case VPWidenIntrinsicSC:
198 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
199 case VPBlendSC:
200 case VPReductionEVLSC:
201 case VPReductionSC:
202 case VPScalarIVStepsSC:
203 case VPVectorPointerSC:
204 case VPWidenCanonicalIVSC:
205 case VPWidenCastSC:
206 case VPWidenGEPSC:
207 case VPWidenIntOrFpInductionSC:
208 case VPWidenPHISC:
209 case VPWidenPointerInductionSC:
210 case VPWidenSC: {
211 const Instruction *I =
212 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
213 (void)I;
214 assert((!I || !I->mayHaveSideEffects()) &&
215 "underlying instruction has side-effects");
216 return false;
217 }
218 case VPInterleaveEVLSC:
219 case VPInterleaveSC:
220 return mayWriteToMemory();
221 case VPWidenLoadEVLSC:
222 case VPWidenLoadSC:
223 case VPWidenStoreEVLSC:
224 case VPWidenStoreSC:
225 assert(
226 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
228 "mayHaveSideffects result for ingredient differs from this "
229 "implementation");
230 return mayWriteToMemory();
231 case VPReplicateSC: {
232 auto *R = cast<VPReplicateRecipe>(this);
233 return R->getUnderlyingInstr()->mayHaveSideEffects();
234 }
235 default:
236 return true;
237 }
238}
239
241 switch (getVPRecipeID()) {
242 default:
243 return false;
244 case VPInstructionSC: {
245 unsigned Opcode = cast<VPInstruction>(this)->getOpcode();
246 if (Instruction::isCast(Opcode))
247 return true;
248
249 switch (Opcode) {
250 default:
251 return false;
252 case Instruction::Add:
253 case Instruction::Sub:
254 case Instruction::Mul:
255 case Instruction::GetElementPtr:
256 return true;
257 }
258 }
259 }
260}
261
263 assert(!Parent && "Recipe already in some VPBasicBlock");
264 assert(InsertPos->getParent() &&
265 "Insertion position not in any VPBasicBlock");
266 InsertPos->getParent()->insert(this, InsertPos->getIterator());
267}
268
269void VPRecipeBase::insertBefore(VPBasicBlock &BB,
271 assert(!Parent && "Recipe already in some VPBasicBlock");
272 assert(I == BB.end() || I->getParent() == &BB);
273 BB.insert(this, I);
274}
275
277 assert(!Parent && "Recipe already in some VPBasicBlock");
278 assert(InsertPos->getParent() &&
279 "Insertion position not in any VPBasicBlock");
280 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
281}
282
284 assert(getParent() && "Recipe not in any VPBasicBlock");
286 Parent = nullptr;
287}
288
290 assert(getParent() && "Recipe not in any VPBasicBlock");
292}
293
296 insertAfter(InsertPos);
297}
298
304
306 // Get the underlying instruction for the recipe, if there is one. It is used
307 // to
308 // * decide if cost computation should be skipped for this recipe,
309 // * apply forced target instruction cost.
310 Instruction *UI = nullptr;
311 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
312 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
313 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
314 UI = IG->getInsertPos();
315 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
316 UI = &WidenMem->getIngredient();
317
318 InstructionCost RecipeCost;
319 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
320 RecipeCost = 0;
321 } else {
322 RecipeCost = computeCost(VF, Ctx);
323 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
324 RecipeCost.isValid()) {
325 if (UI)
327 else
328 RecipeCost = InstructionCost(0);
329 }
330 }
331
332 LLVM_DEBUG({
333 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
334 dump();
335 });
336 return RecipeCost;
337}
338
340 VPCostContext &Ctx) const {
341 llvm_unreachable("subclasses should implement computeCost");
342}
343
345 return (getVPRecipeID() >= VPFirstPHISC && getVPRecipeID() <= VPLastPHISC) ||
347}
348
350 assert(OpType == Other.OpType && "OpType must match");
351 switch (OpType) {
352 case OperationType::OverflowingBinOp:
353 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
354 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
355 break;
356 case OperationType::Trunc:
357 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
358 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
359 break;
360 case OperationType::DisjointOp:
361 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
362 break;
363 case OperationType::PossiblyExactOp:
364 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
365 break;
366 case OperationType::GEPOp:
367 GEPFlagsStorage &= Other.GEPFlagsStorage;
368 break;
369 case OperationType::FPMathOp:
370 case OperationType::FCmp:
371 assert((OpType != OperationType::FCmp ||
372 FCmpFlags.CmpPredStorage == Other.FCmpFlags.CmpPredStorage) &&
373 "Cannot drop CmpPredicate");
374 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
375 break;
376 case OperationType::NonNegOp:
377 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
378 break;
379 case OperationType::Cmp:
380 assert(CmpPredStorage == Other.CmpPredStorage &&
381 "Cannot drop CmpPredicate");
382 break;
383 case OperationType::ReductionOp:
384 assert(ReductionFlags.Kind == Other.ReductionFlags.Kind &&
385 "Cannot change RecurKind");
386 assert(ReductionFlags.IsOrdered == Other.ReductionFlags.IsOrdered &&
387 "Cannot change IsOrdered");
388 assert(ReductionFlags.IsInLoop == Other.ReductionFlags.IsInLoop &&
389 "Cannot change IsInLoop");
390 getFMFsRef() = getFastMathFlagsOrNone() & Other.getFastMathFlagsOrNone();
391 break;
392 case OperationType::Other:
393 break;
394 }
395}
396
398 if (!hasFastMathFlags())
399 return {};
400 const FastMathFlagsTy &F = getFMFsRef();
401 FastMathFlags Res;
402 Res.setAllowReassoc(F.AllowReassoc);
403 Res.setNoNaNs(F.NoNaNs);
404 Res.setNoInfs(F.NoInfs);
405 Res.setNoSignedZeros(F.NoSignedZeros);
406 Res.setAllowReciprocal(F.AllowReciprocal);
407 Res.setAllowContract(F.AllowContract);
408 Res.setApproxFunc(F.ApproxFunc);
409 return Res;
410}
411
412#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
414
415void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
416 VPSlotTracker &SlotTracker) const {
417 printRecipe(O, Indent, SlotTracker);
418 if (auto DL = getDebugLoc()) {
419 O << ", !dbg ";
420 DL.print(O);
421 }
422
423 if (auto *Metadata = dyn_cast<VPIRMetadata>(this))
425}
426#endif
427
429 : VPSingleDefRecipe(VPRecipeBase::VPExpandSCEVSC, {}, Expr->getType()),
430 Expr(Expr) {}
431
432/// For call VPInstruction operands, return the operand index of the called
433/// function. The function is either the last operand (for unmasked calls) or
434/// the second-to-last operand (for masked calls).
436 unsigned NumOps = Operands.size();
437 auto *LastOp = dyn_cast<VPIRValue>(Operands[NumOps - 1]);
438 if (LastOp && isa<Function>(LastOp->getValue()))
439 return NumOps - 1;
441 "expected function operand");
442 return NumOps - 2;
443}
444
445/// For call VPInstruction operands, return the called function.
447 unsigned Idx = getCalledFnOperandIndex(Operands);
448 return cast<Function>(cast<VPIRValue>(Operands[Idx])->getValue());
449}
450
452 ArrayRef<VPValue *> Operands) {
453 assert(!Operands.empty() &&
454 "zero-operand VPInstruction opcodes must pass explicit ResultTy");
455 // Assert operand \p Idx (if present and typed) has type \p ExpectedTy.
456 [[maybe_unused]] auto AssertOperandType = [&Operands](unsigned Idx,
457 Type *ExpectedTy) {
458 if (!ExpectedTy || Operands.size() <= Idx)
459 return;
460 [[maybe_unused]] Type *OpTy = Operands[Idx]->getScalarType();
461 assert((!OpTy || OpTy == ExpectedTy) &&
462 "different types inferred for different operands");
463 };
464
465 Type *Op0Ty = Operands[0]->getScalarType();
466 LLVMContext &Ctx = Op0Ty->getContext();
467 switch (Opcode) {
469 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
470 return Type::getVoidTy(Ctx);
472 assert(Op0Ty->isIntegerTy(1) && "expected bool condition");
473 AssertOperandType(1, IntegerType::get(Ctx, 1));
474 return Type::getVoidTy(Ctx);
476 assert(Op0Ty->isIntegerTy() && "expected integer operand");
477 AssertOperandType(1, Op0Ty);
478 return Type::getVoidTy(Ctx);
481 assert(Op0Ty->isIntegerTy() && "expected integer operand");
482 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
483 AssertOperandType(Idx, Op0Ty);
484 return Op0Ty;
485 case Instruction::Switch:
486 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
487 AssertOperandType(Idx, Op0Ty);
488 return Type::getVoidTy(Ctx);
489 case Instruction::Store:
490 return Type::getVoidTy(Ctx);
491 case Instruction::ICmp:
492 assert(Op0Ty->isIntOrPtrTy() && "expected integer or pointer operand");
493 AssertOperandType(1, Op0Ty);
494 return IntegerType::get(Ctx, 1);
495 case Instruction::FCmp:
496 assert(Op0Ty->isFloatingPointTy() && "expected floating-point operand");
497 AssertOperandType(1, Op0Ty);
498 return IntegerType::get(Ctx, 1);
500 assert(Op0Ty->isIntegerTy() && "expected integer operand");
501 AssertOperandType(1, Op0Ty);
502 return IntegerType::get(Ctx, 1);
504 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
505 return IntegerType::get(Ctx, 1);
508 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
509 AssertOperandType(1, Op0Ty);
510 return IntegerType::get(Ctx, 1);
512 assert(Op0Ty->isIntegerTy(1) && "expected bool operand");
513 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
514 AssertOperandType(Idx, Op0Ty);
515 return IntegerType::get(Ctx, 1);
517 assert(Op0Ty->isIntegerTy() && "expected integer operand");
518 return IntegerType::get(Ctx, 32);
519 case Instruction::Select: {
520 assert((!Op0Ty || Op0Ty->isIntegerTy(1)) &&
521 "select condition must be bool");
522 Type *Op1Ty = Operands[1]->getScalarType();
523 AssertOperandType(2, Op1Ty);
524 return Op1Ty;
525 }
526 case Instruction::InsertElement:
527 // The inserted scalar (operand 1) must match the vector element type;
528 // operand 2 must be an integer.
529 AssertOperandType(1, Op0Ty);
530 assert(Operands[2]->getScalarType()->isIntegerTy() &&
531 "expected integer operand");
532 return Op0Ty;
534 // The start value and the identity value (operands 0 and 1) fill the same
535 // vector and must match in type; operand 2 is the scaling factor.
536 AssertOperandType(1, Op0Ty);
537 return Op0Ty;
539 assert(Operands.size() >= 2 && "ExtractLane requires a lane operand and "
540 "at least one source vector operand");
541 // Operand 0 is the lane index, used for integer arithmetic.
542 assert(Op0Ty->isIntegerTy() && "expected integer operand");
543 Type *Op1Ty = Operands[1]->getScalarType();
544 for (unsigned Idx = 2; Idx != Operands.size(); ++Idx)
545 AssertOperandType(Idx, Op1Ty);
546 return Op1Ty;
547 }
550 assert(Operands[0]->getScalarType()->isPointerTy() &&
551 "expected pointer operand");
552 assert(Operands[1]->getScalarType()->isIntegerTy() &&
553 "expected integer operand");
554 return Op0Ty;
555 case Instruction::ExtractValue: {
556 assert(Operands.size() == 2 && "expected single level extractvalue");
557 auto *StructTy = cast<StructType>(Op0Ty);
558 return StructTy->getTypeAtIndex(
559 cast<VPConstantInt>(Operands[1])->getZExtValue());
560 }
565 case Instruction::Load:
566 case Instruction::Alloca:
567 llvm_unreachable("type must be passed explicitly");
568 case Instruction::Call:
569 return getCalledFunction(Operands)->getReturnType();
570 default:
571 break;
572 }
573
574 // Opcodes that require all operands to share the same scalar type as the
575 // result.
576 bool AllOperandsSameType =
577 Instruction::isBinaryOp(Opcode) ||
581 Opcode);
582 if (AllOperandsSameType)
583 for (unsigned Idx = 1; Idx != Operands.size(); ++Idx)
584 AssertOperandType(Idx, Op0Ty);
585
586 return Op0Ty;
587}
588
590 ArrayRef<VPValue *> Operands) {
591 unsigned Opcode = I->getOpcode();
592 if (Instruction::isCast(Opcode) ||
593 is_contained(ArrayRef<unsigned>({Instruction::ExtractValue,
594 Instruction::Load, Instruction::Alloca}),
595 Opcode))
596 return I->getType();
597 return computeScalarTypeForInstruction(Opcode, Operands);
598}
599
601 const VPIRFlags &Flags, const VPIRMetadata &MD,
602 DebugLoc DL, const Twine &Name, Type *ResultTy)
604 VPRecipeBase::VPInstructionSC, Operands,
605 ResultTy ? ResultTy
606 : computeScalarTypeForInstruction(Opcode, Operands),
607 Flags, DL),
608 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
610 "Set flags not supported for the provided opcode");
612 "Opcode requires specific flags to be set");
616 "number of operands does not match opcode");
617}
618
620 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
621 return 1;
622
623 if (Instruction::isBinaryOp(Opcode))
624 return 2;
625
626 switch (Opcode) {
629 return 0;
630 case Instruction::Alloca:
631 case Instruction::ExtractValue:
632 case Instruction::Freeze:
633 case Instruction::Load:
646 return 1;
647 case Instruction::ICmp:
648 case Instruction::FCmp:
649 case Instruction::ExtractElement:
650 case Instruction::Store:
661 return 2;
662 case Instruction::InsertElement:
663 case Instruction::Select:
666 return 3;
667 case Instruction::Call:
668 return getCalledFnOperandIndex(operands()) + 1;
669 case Instruction::GetElementPtr:
670 case Instruction::PHI:
671 case Instruction::Switch:
672 case Instruction::AtomicRMW:
673 case Instruction::AtomicCmpXchg:
674 case Instruction::Fence:
685 // Cannot determine the number of operands from the opcode.
686 return -1u;
687 }
688 llvm_unreachable("all cases should be handled above");
689}
690
692 return Opcode == VPInstruction::Unpack ||
694}
695
696bool VPInstruction::canGenerateScalarForFirstLane() const {
698 return true;
700 return true;
701 switch (Opcode) {
702 case Instruction::Freeze:
703 case Instruction::ICmp:
704 case Instruction::PHI:
705 case Instruction::Select:
715 return true;
716 default:
717 return false;
718 }
719}
720
722 if (Kind == RecurKind::Sub)
723 return Instruction::Add;
724 if (Kind == RecurKind::FSub)
725 return Instruction::FAdd;
726 llvm_unreachable("RecurKind should be Sub/FSub.");
727}
728
729Value *VPInstruction::generate(VPTransformState &State) {
730 IRBuilderBase &Builder = State.Builder;
731
733 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
734 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
735 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
736 auto *Res =
737 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
738 if (auto *I = dyn_cast<Instruction>(Res))
739 applyFlags(*I);
740 return Res;
741 }
742
743 switch (getOpcode()) {
744 case VPInstruction::Not: {
745 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
746 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
747 return Builder.CreateNot(A, Name);
748 }
749 case Instruction::ExtractElement: {
750 assert(State.VF.isVector() && "Only extract elements from vectors");
751 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
752 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
753 Value *Vec = State.get(getOperand(0));
754 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
755 return Builder.CreateExtractElement(Vec, Idx, Name);
756 }
757 case Instruction::InsertElement: {
758 assert(State.VF.isVector() && "Can only insert elements into vectors");
759 Value *Vec = State.get(getOperand(0), /*IsScalar=*/false);
760 Value *Elt = State.get(getOperand(1), /*IsScalar=*/true);
761 Value *Idx = State.get(getOperand(2), /*IsScalar=*/true);
762 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
763 }
764 case Instruction::Freeze: {
766 return Builder.CreateFreeze(Op, Name);
767 }
768 case Instruction::FCmp:
769 case Instruction::ICmp: {
770 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
771 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
772 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
773 return Builder.CreateCmp(getPredicate(), A, B, Name);
774 }
775 case Instruction::PHI: {
776 llvm_unreachable("should be handled by VPPhi::execute");
777 }
778 case Instruction::Select: {
779 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
780 Value *Cond =
781 State.get(getOperand(0),
782 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
783 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
784 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
785 return Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(),
786 Name);
787 }
789 // Get first lane of vector induction variable.
790 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
791 // Get the original loop tripcount.
792 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
793
794 // If this part of the active lane mask is scalar, generate the CMP directly
795 // to avoid unnecessary extracts.
796 if (State.VF.isScalar())
797 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
798 Name);
799
800 ElementCount EC = State.VF.multiplyCoefficientBy(
801 cast<VPConstantInt>(getOperand(2))->getZExtValue());
802 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
803 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
804 {PredTy, ScalarTC->getType()},
805 {VIVElem0, ScalarTC}, nullptr, Name);
806 }
808 Value *Op = State.get(getOperand(0));
809 auto *VecTy = cast<VectorType>(Op->getType());
810 assert(VecTy->getScalarSizeInBits() == 1 &&
811 "NumActiveLanes only implemented for i1 vectors");
812
813 Type *Ty = getScalarType();
814 Value *ZExt = Builder.CreateCast(
815 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
816 Value *NumActive =
817 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
818 return NumActive;
819 }
821 // Generate code to combine the previous and current values in vector v3.
822 //
823 // vector.ph:
824 // v_init = vector(..., ..., ..., a[-1])
825 // br vector.body
826 //
827 // vector.body
828 // i = phi [0, vector.ph], [i+4, vector.body]
829 // v1 = phi [v_init, vector.ph], [v2, vector.body]
830 // v2 = a[i, i+1, i+2, i+3];
831 // v3 = vector(v1(3), v2(0, 1, 2))
832
833 auto *V1 = State.get(getOperand(0));
834 if (!V1->getType()->isVectorTy())
835 return V1;
836 Value *V2 = State.get(getOperand(1));
837 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
838 }
840 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
841 Value *VFxUF = State.get(getOperand(1), VPLane(0));
842 Value *Sub = Builder.CreateSub(ScalarTC, VFxUF);
843 Value *Cmp =
844 Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, VFxUF);
846 return Builder.CreateSelect(Cmp, Sub, Zero);
847 }
849 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
850 // be outside of the main loop.
851 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
852 // Compute EVL
853 assert(AVL->getType()->isIntegerTy() &&
854 "Requested vector length should be an integer.");
855
856 assert(State.VF.isScalable() && "Expected scalable vector factor.");
857 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
858
859 Value *EVL = Builder.CreateIntrinsic(
860 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
861 {AVL, VFArg, Builder.getTrue()});
862 return EVL;
863 }
865 Value *Cond = State.get(getOperand(0), VPLane(0));
866 // Replace the temporary unreachable terminator with a new conditional
867 // branch, hooking it up to backward destination for latch blocks now, and
868 // to forward destination(s) later when they are created.
869 // Second successor may be backwards - iff it is already in VPBB2IRBB.
870 VPBasicBlock *SecondVPSucc =
871 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
872 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
873 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
874 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
875 // First successor is always forward, reset it to nullptr.
876 Br->setSuccessor(0, nullptr);
878 applyMetadata(*Br);
879 return Br;
880 }
882 return Builder.CreateVectorSplat(
883 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
884 }
886 // For struct types, we need to build a new 'wide' struct type, where each
887 // element is widened, i.e., we create a struct of vectors.
888 auto *StructTy = cast<StructType>(getOperand(0)->getScalarType());
889 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
890 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
891 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
892 FieldIndex++) {
893 Value *ScalarValue =
894 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
895 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
896 VectorValue =
897 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
898 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
899 }
900 }
901 return Res;
902 }
904 auto *ScalarTy = getOperand(0)->getScalarType();
905 auto NumOfElements = ElementCount::getFixed(getNumOperands());
906 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
907 for (const auto &[Idx, Op] : enumerate(operands()))
908 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
909 Builder.getInt32(Idx));
910 return Res;
911 }
913 if (State.VF.isScalar())
914 return State.get(getOperand(0), true);
915 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
917 // If this start vector is scaled then it should produce a vector with fewer
918 // elements than the VF.
919 ElementCount VF = State.VF.divideCoefficientBy(
920 cast<VPConstantInt>(getOperand(2))->getZExtValue());
921 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
922 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
923 Builder.getInt32(0));
924 }
926 RecurKind RK = getRecurKind();
927 bool IsOrdered = isReductionOrdered();
928 bool IsInLoop = isReductionInLoop();
930 "FindIV should use min/max reduction kinds");
931
932 // The recipe may have multiple operands to be reduced together.
933 unsigned NumOperandsToReduce = getNumOperands();
934 VectorParts RdxParts(NumOperandsToReduce);
935 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
936 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
937
938 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
940
941 // Reduce multiple operands into one.
942 Value *ReducedPartRdx = RdxParts[0];
943 if (IsOrdered) {
944 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
945 } else {
946 // Floating-point operations should have some FMF to enable the reduction.
947 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
948 Value *RdxPart = RdxParts[Part];
950 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
951 else {
952 // For sub-recurrences, each part's reduction variable is already
953 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
957 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
958 ReducedPartRdx =
959 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
960 }
961 }
962 }
963
964 // Create the reduction after the loop. Note that inloop reductions create
965 // the target reduction in the loop using a Reduction recipe.
966 if (State.VF.isVector() && !IsInLoop) {
967 // TODO: Support in-order reductions based on the recurrence descriptor.
968 // All ops in the reduction inherit fast-math-flags from the recurrence
969 // descriptor.
970 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
971 }
972
973 return ReducedPartRdx;
974 }
977 unsigned Offset =
979 Value *Res;
980 if (State.VF.isVector()) {
981 assert(Offset <= State.VF.getKnownMinValue() &&
982 "invalid offset to extract from");
983 // Extract lane VF - Offset from the operand.
984 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
985 } else {
986 // TODO: Remove ExtractLastLane for scalar VFs.
987 assert(Offset <= 1 && "invalid offset to extract from");
988 Res = State.get(getOperand(0));
989 }
991 Res->setName(Name);
992 return Res;
993 }
995 Value *A = State.get(getOperand(0));
996 Value *B = State.get(getOperand(1));
997 return Builder.CreateLogicalAnd(A, B, Name);
998 }
1000 Value *A = State.get(getOperand(0));
1001 Value *B = State.get(getOperand(1));
1002 return Builder.CreateLogicalOr(A, B, Name);
1003 }
1004 case VPInstruction::PtrAdd: {
1005 assert((State.VF.isScalar() || vputils::onlyFirstLaneUsed(this)) &&
1006 "can only generate first lane for PtrAdd");
1007 Value *Ptr = State.get(getOperand(0), VPLane(0));
1008 Value *Addend = State.get(getOperand(1), VPLane(0));
1009 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1010 }
1012 Value *Ptr =
1014 Value *Addend = State.get(getOperand(1));
1015 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1016 }
1017 case VPInstruction::AnyOf: {
1018 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
1019 for (VPValue *Op : drop_begin(operands()))
1020 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
1021 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1022 }
1024 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1025 "simplified to ExtractElement.");
1026 Value *LaneToExtract = State.get(getOperand(0), true);
1027 Type *IdxTy = getOperand(0)->getScalarType();
1028 Value *Res = nullptr;
1029 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1030
1031 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1032 Value *VectorStart =
1033 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1034 Value *VectorIdx = Idx == 1
1035 ? LaneToExtract
1036 : Builder.CreateSub(LaneToExtract, VectorStart);
1037 Value *Ext = State.VF.isScalar()
1038 ? State.get(getOperand(Idx))
1039 : Builder.CreateExtractElement(
1040 State.get(getOperand(Idx)), VectorIdx);
1041 if (Res) {
1042 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1043 Res = Builder.CreateSelect(Cmp, Ext, Res);
1044 } else {
1045 Res = Ext;
1046 }
1047 }
1048 return Res;
1049 }
1051 Type *Ty = this->getScalarType();
1052 if (getNumOperands() == 1) {
1053 Value *Mask = State.get(getOperand(0));
1054 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1055 /*ZeroIsPoison=*/false, Name);
1056 }
1057 // If there are multiple operands, create a chain of selects to pick the
1058 // first operand with an active lane and add the number of lanes of the
1059 // preceding operands.
1060 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
1061 unsigned LastOpIdx = getNumOperands() - 1;
1062 Value *Res = nullptr;
1063 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1064 Value *TrailingZeros =
1065 State.VF.isScalar()
1066 ? Builder.CreateZExt(
1067 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1068 Builder.getFalse()),
1069 Ty)
1071 Ty, State.get(getOperand(Idx)),
1072 /*ZeroIsPoison=*/false, Name);
1073 Value *Current = Builder.CreateAdd(
1074 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1075 TrailingZeros);
1076 if (Res) {
1077 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1078 Res = Builder.CreateSelect(Cmp, Current, Res);
1079 } else {
1080 Res = Current;
1081 }
1082 }
1083
1084 return Res;
1085 }
1087 return State.get(getOperand(0), true);
1089 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1091 Value *Result = State.get(getOperand(0), /*IsScalar=*/true);
1092 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1093 Value *Data = State.get(getOperand(Idx));
1094 Value *Mask = State.get(getOperand(Idx + 1));
1095 Type *VTy = Data->getType();
1096
1097 if (State.VF.isScalar())
1098 Result = Builder.CreateSelect(Mask, Data, Result);
1099 else
1100 Result = Builder.CreateIntrinsic(
1101 Intrinsic::experimental_vector_extract_last_active, {VTy},
1102 {Data, Mask, Result});
1103 }
1104
1105 return Result;
1106 }
1107 default:
1108 llvm_unreachable("Unsupported opcode for instruction");
1109 }
1110}
1111
1113 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1114 Type *ScalarTy = this->getScalarType();
1115 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1116 switch (Opcode) {
1117 case Instruction::FNeg:
1118 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1119 case Instruction::UDiv:
1120 case Instruction::SDiv:
1121 case Instruction::SRem:
1122 case Instruction::URem:
1123 case Instruction::Add:
1124 case Instruction::FAdd:
1125 case Instruction::Sub:
1126 case Instruction::FSub:
1127 case Instruction::Mul:
1128 case Instruction::FMul:
1129 case Instruction::FDiv:
1130 case Instruction::FRem:
1131 case Instruction::Shl:
1132 case Instruction::LShr:
1133 case Instruction::AShr:
1134 case Instruction::And:
1135 case Instruction::Or:
1136 case Instruction::Xor: {
1137 // Certain instructions can be cheaper if they have a constant second
1138 // operand. One example of this are shifts on x86.
1139 VPValue *RHS = getOperand(1);
1140 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1141
1142 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1145
1148 if (CtxI)
1149 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1150 return Ctx.TTI.getArithmeticInstrCost(
1151 Opcode, ResultTy, Ctx.CostKind,
1152 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1153 RHSInfo, Operands, CtxI, &Ctx.TLI);
1154 }
1155 case Instruction::Freeze:
1156 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1157 // requires the actual vector instruction. Instead, both here and in the
1158 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1159 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1160 // them in sync.
1161 return TTI::TCC_Free;
1162 case Instruction::ExtractValue:
1163 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1164 Ctx.CostKind);
1165 case Instruction::ICmp:
1166 case Instruction::FCmp: {
1167 Type *ScalarOpTy = getOperand(0)->getScalarType();
1168 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1170 return Ctx.TTI.getCmpSelInstrCost(
1172 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1173 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1174 }
1175 case Instruction::BitCast: {
1176 Type *ScalarTy = this->getScalarType();
1177 if (ScalarTy->isPointerTy())
1178 return 0;
1179 [[fallthrough]];
1180 }
1181 case Instruction::SExt:
1182 case Instruction::ZExt:
1183 case Instruction::FPToUI:
1184 case Instruction::FPToSI:
1185 case Instruction::FPExt:
1186 case Instruction::PtrToInt:
1187 case Instruction::PtrToAddr:
1188 case Instruction::IntToPtr:
1189 case Instruction::SIToFP:
1190 case Instruction::UIToFP:
1191 case Instruction::Trunc:
1192 case Instruction::FPTrunc:
1193 case Instruction::AddrSpaceCast: {
1194 // Computes the CastContextHint from a recipe that may access memory.
1195 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1196 if (isa<VPInterleaveBase>(R))
1198 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1199 // Only compute CCH for memory operations, matching the legacy model
1200 // which only considers loads/stores for cast context hints.
1201 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1202 if (!isa<LoadInst, StoreInst>(UI))
1204 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1206 }
1207 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1208 if (WidenMemoryRecipe == nullptr)
1210 if (VF.isScalar())
1212 if (!WidenMemoryRecipe->isConsecutive())
1214 if (WidenMemoryRecipe->isMasked())
1217 };
1218
1219 VPValue *Operand = getOperand(0);
1221 bool IsReverse = false;
1222 // For Trunc/FPTrunc, get the context from the only user.
1223 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1224 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1225 if (match(Recipe,
1229 IsReverse = true;
1231 Recipe->getVPSingleValue()->getSingleUser());
1232 }
1233 if (Recipe)
1234 CCH = ComputeCCH(Recipe);
1235 }
1236 }
1237 // For Z/Sext, get the context from the operand.
1238 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1239 Opcode == Instruction::FPExt) {
1240 if (auto *Recipe = Operand->getDefiningRecipe()) {
1241 VPValue *ReverseOp;
1242 if (match(Recipe,
1243 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1245 m_VPValue(ReverseOp))))) {
1246 Recipe = ReverseOp->getDefiningRecipe();
1247 IsReverse = true;
1248 }
1249 if (Recipe)
1250 CCH = ComputeCCH(Recipe);
1251 }
1252 }
1253 if (IsReverse && CCH != TTI::CastContextHint::None)
1255
1256 auto *ScalarSrcTy = Operand->getScalarType();
1257 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1258 // Arm TTI will use the underlying instruction to determine the cost.
1259 return Ctx.TTI.getCastInstrCost(
1260 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1262 }
1263 case Instruction::Select: {
1265 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1266 Type *ScalarTy = this->getScalarType();
1267
1268 VPValue *Op0, *Op1;
1269 bool IsLogicalAnd =
1270 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1271 bool IsLogicalOr =
1272 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1273 // Also match the inverted forms:
1274 // select x, false, y --> !x & y (still AND)
1275 // select x, y, true --> !x | y (still OR)
1276 IsLogicalAnd |=
1277 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1278 IsLogicalOr |=
1279 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1280
1281 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1282 (IsLogicalAnd || IsLogicalOr)) {
1283 // select x, y, false --> x & y
1284 // select x, true, y --> x | y
1285 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1286 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1287
1289 if (SI && all_of(operands(),
1290 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1291 append_range(Operands, SI->operands());
1292 return Ctx.TTI.getArithmeticInstrCost(
1293 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1294 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1295 }
1296
1297 Type *CondTy = getOperand(0)->getScalarType();
1298 if (!IsScalarCond && VF.isVector())
1299 CondTy = VectorType::get(CondTy, VF);
1300
1301 llvm::CmpPredicate Pred;
1302 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1303 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1304 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1305 Pred = Cmp->getPredicate();
1306 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1307 return Ctx.TTI.getCmpSelInstrCost(
1308 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1309 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1310 }
1311 }
1312 llvm_unreachable("called for unsupported opcode");
1313}
1314
1316 VPCostContext &Ctx) const {
1318 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1319 // TODO: Compute cost for VPInstructions without underlying values once
1320 // the legacy cost model has been retired.
1321 return 0;
1322 }
1323
1325 "Should only generate a vector value or single scalar, not scalars "
1326 "for all lanes.");
1328 getOpcode(),
1330 }
1331
1332 switch (getOpcode()) {
1333 case Instruction::Select: {
1335 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1336 auto *CondTy = getOperand(0)->getScalarType();
1337 auto *VecTy = getOperand(1)->getScalarType();
1338 if (!vputils::onlyFirstLaneUsed(this)) {
1339 CondTy = toVectorTy(CondTy, VF);
1340 VecTy = toVectorTy(VecTy, VF);
1341 }
1342 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1343 Ctx.CostKind);
1344 }
1345 case Instruction::ExtractElement:
1347 if (VF.isScalar()) {
1348 // ExtractLane with VF=1 takes care of handling extracting across multiple
1349 // parts.
1350 return 0;
1351 }
1352
1353 // Add on the cost of extracting the element.
1354 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1355 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1356 Ctx.CostKind);
1357 }
1358 case VPInstruction::AnyOf: {
1359 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1360 return Ctx.TTI.getArithmeticReductionCost(
1361 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1362 }
1364 Type *Ty = this->getScalarType();
1365 Type *ScalarTy = getOperand(0)->getScalarType();
1366 if (VF.isScalar())
1367 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1369 CmpInst::ICMP_EQ, Ctx.CostKind);
1370 // Calculate the cost of determining the lane index.
1371 auto *PredTy = toVectorTy(ScalarTy, VF);
1372 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1373 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1374 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1375 }
1377 Type *Ty = this->getScalarType();
1378 Type *ScalarTy = getOperand(0)->getScalarType();
1379 if (VF.isScalar())
1380 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1382 CmpInst::ICMP_EQ, Ctx.CostKind);
1383 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1384 auto *PredTy = toVectorTy(ScalarTy, VF);
1385 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1386 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1387 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1388 // Add cost of NOT operation on the predicate.
1389 Cost += Ctx.TTI.getArithmeticInstrCost(
1390 Instruction::Xor, PredTy, Ctx.CostKind,
1391 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1392 {TargetTransformInfo::OK_UniformConstantValue,
1393 TargetTransformInfo::OP_None});
1394 // Add cost of SUB operation on the index.
1395 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1396 return Cost;
1397 }
1399 Type *ScalarTy = this->getScalarType();
1400 Type *VecTy = toVectorTy(ScalarTy, VF);
1401 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1403 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1404 {VecTy, MaskTy, ScalarTy});
1405 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1406 }
1408 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1409 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1410 return Ctx.TTI.getShuffleCost(
1412 cast<VectorType>(VectorTy), {}, Ctx.CostKind, -1);
1413 }
1415 Type *ArgTy = getOperand(0)->getScalarType();
1416 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1417 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1418 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1419 {ArgTy, ArgTy});
1420 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1421 }
1423 Type *Arg0Ty = getOperand(0)->getScalarType();
1424 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1425 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1426 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1427 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1428 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1429 }
1431 assert(VF.isVector() && "Reverse operation must be vector type");
1432 Type *EltTy = this->getScalarType();
1433 // Skip the reverse operation cost for the mask.
1434 // FIXME: Remove this once redundant mask reverse operations can be
1435 // eliminated by VPlanTransforms::cse before cost computation.
1436 if (EltTy->isIntegerTy(1))
1437 return 0;
1438 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1439 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1440 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1441 /*Index=*/0);
1442 }
1444 // Add on the cost of extracting the element.
1445 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1446 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1447 VecTy, Ctx.CostKind, 0);
1448 }
1449 case VPInstruction::Not: {
1450 Type *ValTy = this->getScalarType();
1451 // InstCombine will fold `xor` to the conditional branch.
1452 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1453 if (match(U, m_BranchOnCond(m_VPValue())))
1454 return 0;
1455 if (!vputils::onlyFirstLaneUsed(this))
1456 ValTy = toVectorTy(ValTy, VF);
1457 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1458 Ctx.CostKind);
1459 }
1461 // If TC <= VF then this is just a branch.
1462 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1463 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1464 // some cases we get a cost that's too high due to counting a cmp that
1465 // later gets removed.
1466 // FIXME: The compare could also be removed if TC = M * vscale,
1467 // VF = N * vscale, and M <= N. Detecting that would require having the
1468 // trip count as a SCEV though.
1471 if (TCConst && TCConst->getValue().ule(VF.getKnownMinValue()))
1472 return 0;
1473 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1474 Type *ValTy = getOperand(0)->getScalarType();
1475 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1477 CmpInst::ICMP_EQ, Ctx.CostKind);
1478 }
1479 case Instruction::FCmp:
1480 case Instruction::ICmp:
1482 getOpcode(),
1485 if (VF == ElementCount::getScalable(1))
1487 [[fallthrough]];
1488 default:
1489 // TODO: Compute cost other VPInstructions once the legacy cost model has
1490 // been retired.
1492 "unexpected VPInstruction witht underlying value");
1493 return 0;
1494 }
1495}
1496
1509
1511 switch (getOpcode()) {
1512 case Instruction::Load:
1513 case Instruction::PHI:
1517 return true;
1518 default:
1520 }
1521}
1522
1524#ifndef NDEBUG
1525 Type *Ty = Op->getScalarType();
1526 switch (getOpcode()) {
1530 assert(Ty == getOperand(0)->getScalarType() &&
1531 "types of operand 0 and new operand must match");
1532 break;
1536 assert(Ty == getOperand(0)->getScalarType() &&
1537 "appended operand must match operand 0's scalar type");
1538 break;
1540 assert(Ty == getOperand(1)->getScalarType() &&
1541 "appended operand must match operand 1's scalar type");
1542 break;
1544 // The recipe is constructed with 3 operands (result, data, mask). Extra
1545 // operands beyond that are appended in (data, mask) pairs.
1546 constexpr unsigned NumInitialOperands = 3;
1547 assert(getNumOperands() >= NumInitialOperands &&
1548 "ExtractLastActive must have at least the initial 3 operands");
1549 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1550 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1551 : Ty == getOperand(1)->getScalarType()) &&
1552 "ExtractLastActive expects alternating data/mask operands "
1553 "matching operand 1's type and i1, respectively");
1554 break;
1555 }
1556 default:
1557 llvm_unreachable("opcode does not support growing the operand list "
1558 "outside of construction");
1559 }
1560#endif
1562}
1563
1565 assert(!isMasked() && "cannot execute masked VPInstruction");
1566 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1568 "Set flags not supported for the provided opcode");
1570 "Opcode requires specific flags to be set");
1571 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1572 Value *GeneratedValue = generate(State);
1573 if (!hasResult())
1574 return;
1575 assert(GeneratedValue && "generate must produce a value");
1576 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1579 assert((((GeneratedValue->getType()->isVectorTy() ||
1580 GeneratedValue->getType()->isStructTy()) ==
1581 !GeneratesPerFirstLaneOnly) ||
1582 State.VF.isScalar()) &&
1583 "scalar value but not only first lane defined");
1584 State.set(this, GeneratedValue,
1585 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1587 getOpcode() == Instruction::Freeze) {
1588 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1589 // resume phis, and to let epilogue vectorization recover the frozen
1590 // reduction start from the main plan. Must be removed once epilogue
1591 // vectorization explicitly connects VPlans.
1592 setUnderlyingValue(GeneratedValue);
1593 }
1594}
1595
1599 return false;
1600 switch (getOpcode()) {
1601 case Instruction::ExtractValue:
1602 case Instruction::InsertValue:
1603 case Instruction::GetElementPtr:
1604 case Instruction::ExtractElement:
1605 case Instruction::InsertElement:
1606 case Instruction::Freeze:
1607 case Instruction::FCmp:
1608 case Instruction::ICmp:
1609 case Instruction::Select:
1610 case Instruction::PHI:
1635 case VPInstruction::Not:
1643 return false;
1646 AttributeSet Attrs =
1648 return !Attrs.getMemoryEffects().doesNotAccessMemory();
1649 }
1650 case Instruction::Call:
1652 default:
1653 return true;
1654 }
1655}
1656
1658 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1660 return vputils::onlyFirstLaneUsed(this);
1661
1662 switch (getOpcode()) {
1663 default:
1664 return false;
1665 case Instruction::ExtractElement:
1666 return Op == getOperand(1);
1667 case Instruction::InsertElement:
1668 return Op == getOperand(1) || Op == getOperand(2);
1669 case Instruction::PHI:
1670 return true;
1671 case Instruction::FCmp:
1672 case Instruction::ICmp:
1673 case Instruction::Select:
1674 case Instruction::Or:
1675 case Instruction::Freeze:
1676 case VPInstruction::Not:
1677 // TODO: Cover additional opcodes.
1678 return vputils::onlyFirstLaneUsed(this);
1679 case Instruction::Load:
1691 return true;
1694 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1695 // operand, after replicating its operands only the first lane is used.
1696 // Before replicating, it will have only a single operand.
1697 return getNumOperands() > 1;
1699 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1701 // WidePtrAdd supports scalar and vector base addresses.
1702 return false;
1705 return Op == getOperand(0);
1706 };
1707 llvm_unreachable("switch should return");
1708}
1709
1711 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1713 return vputils::onlyFirstPartUsed(this);
1714
1715 switch (getOpcode()) {
1716 default:
1717 return false;
1718 case Instruction::FCmp:
1719 case Instruction::ICmp:
1720 case Instruction::Select:
1721 return vputils::onlyFirstPartUsed(this);
1726 return true;
1727 };
1728 llvm_unreachable("switch should return");
1729}
1730
1731#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1733 VPSlotTracker SlotTracker(getParent()->getPlan());
1735}
1736
1738 VPSlotTracker &SlotTracker) const {
1739 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1740
1741 if (hasResult()) {
1743 O << " = ";
1744 }
1745
1746 switch (getOpcode()) {
1747 case VPInstruction::Not:
1748 O << "not";
1749 break;
1751 O << "active lane mask";
1752 break;
1754 O << "incoming-alias-mask";
1755 break;
1757 O << "EXPLICIT-VECTOR-LENGTH";
1758 break;
1760 O << "first-order splice";
1761 break;
1763 O << "branch-on-cond";
1764 break;
1766 O << "branch-on-two-conds";
1767 break;
1769 O << "TC > VF ? TC - VF : 0";
1770 break;
1772 O << "VF * Part +";
1773 break;
1775 O << "branch-on-count";
1776 break;
1778 O << "broadcast";
1779 break;
1781 O << "buildstructvector";
1782 break;
1784 O << "buildvector";
1785 break;
1787 O << "exiting-iv-value";
1788 break;
1790 O << "masked-cond";
1791 break;
1793 O << "extract-lane";
1794 break;
1796 O << "extract-last-lane";
1797 break;
1799 O << "extract-last-part";
1800 break;
1802 O << "extract-penultimate-element";
1803 break;
1805 O << "compute-reduction-result";
1806 break;
1808 O << "logical-and";
1809 break;
1811 O << "logical-or";
1812 break;
1814 O << "ptradd";
1815 break;
1817 O << "wide-ptradd";
1818 break;
1820 O << "any-of";
1821 break;
1823 O << "first-active-lane";
1824 break;
1826 O << "last-active-lane";
1827 break;
1829 O << "reduction-start-vector";
1830 break;
1832 O << "resume-for-epilogue";
1833 break;
1835 O << "reverse";
1836 break;
1838 O << "unpack";
1839 break;
1841 O << "extract-last-active";
1842 break;
1844 O << "num-active-lanes";
1845 break;
1846 default:
1848 }
1849
1850 printFlags(O);
1852}
1853#endif
1854
1856 Type *ResultTy = getResultType();
1858 Value *Op = State.get(getOperand(0), VPLane(0));
1859 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1860 Op, ResultTy);
1861 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
1862 applyFlags(*CastOp);
1863 applyMetadata(*CastOp);
1864 }
1865 State.set(this, Cast, VPLane(0));
1866 return;
1867 }
1868 switch (getOpcode()) {
1870 Value *StepVector =
1871 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1872 State.set(this, StepVector);
1873 break;
1874 }
1877 for (VPValue *Op : drop_end(operands()))
1878 Args.push_back(State.get(Op, /*IsSingleScalar=*/true));
1879 Value *Call =
1880 State.Builder.CreateIntrinsic(ResultTy, vputils::getIntrinsicID(this),
1881 Args, /*FMFSource=*/nullptr, getName());
1882 State.set(this, Call, true);
1883 break;
1884 }
1885
1886 default:
1887 llvm_unreachable("opcode not implemented yet");
1888 }
1889}
1890
1892 VPCostContext &Ctx) const {
1893 // NOTE: At the moment it seems only possible to expose this path for
1894 // the trunc, zext and sext opcodes. However, isScalarCast also covers
1895 // int<>fp conversions, bitcasts, ptr<>int conversions, etc.
1898 Ctx);
1899
1900 switch (getOpcode()) {
1902 // TODO: This isn't quite right since even if the step-vector is hoisted
1903 // out of the loop it has a non-zero cost in the middle block, etc.
1904 // Once the stepvector is correctly hoisted out of the vector loop by the
1905 // licm transform we can add the cost here so that it doesn't incorrectly
1906 // affect the choice of VF.
1907 return 0;
1909 Type *Ty = getScalarType();
1911 for (const VPValue *Op : drop_end(operands()))
1912 ArgTys.push_back(Op->getScalarType());
1913 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1914 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1915 }
1916 default:
1917 // Although VPInstructionWithType is also used for
1918 // VPInstruction::WideIVStep it isn't currently possible to expose cases
1919 // where the cost is queried.
1920 llvm_unreachable("Unhandled opcode");
1921 }
1922 return 0;
1923}
1924
1925#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1927 VPSlotTracker &SlotTracker) const {
1928 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1930 O << " = ";
1931
1932 Type *ResultTy = getResultType();
1933 switch (getOpcode()) {
1935 O << "wide-iv-step ";
1937 break;
1939 O << "step-vector " << *ResultTy;
1940 break;
1942 O << "call " << *ResultTy << " @"
1945 Op->printAsOperand(O, SlotTracker);
1946 });
1947 O << ")";
1948 break;
1949 }
1950 case Instruction::Load:
1951 O << "load ";
1953 break;
1954 default:
1955 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1957 printFlags(O);
1959 O << " to " << *ResultTy;
1960 }
1961}
1962#endif
1963
1964/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
1965/// adds incoming values, and stores the result in State. For header phis, only
1966/// the preheader incoming value is added; the backedge is fixed up later by
1967/// VPlan::execute().
1969 VPTransformState &State, bool IsScalar,
1970 const Twine &Name) {
1971 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
1972 ? 1
1973 : Phi.getNumIncoming();
1974 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
1975 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
1976 NewPhi->addIncoming(FirstInc,
1977 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
1978 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
1979 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
1980 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
1981 State.set(R, NewPhi, IsScalar);
1982}
1983
1985 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
1986}
1987
1988#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1989void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1990 VPSlotTracker &SlotTracker) const {
1991 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1993 O << " = phi";
1994 printFlags(O);
1996}
1997#endif
1998
1999VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
2000 if (auto *Phi = dyn_cast<PHINode>(&I))
2001 return new VPIRPhi(*Phi);
2002 return new VPIRInstruction(I);
2003}
2004
2006 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
2007 "PHINodes must be handled by VPIRPhi");
2008 // Advance the insert point after the wrapped IR instruction. This allows
2009 // interleaving VPIRInstructions and other recipes.
2010 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
2011}
2012
2014 VPCostContext &Ctx) const {
2015 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2016 // hence it does not contribute to the cost-modeling for the VPlan.
2017 return 0;
2018}
2019
2020#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2022 VPSlotTracker &SlotTracker) const {
2023 O << Indent << "IR " << I;
2024}
2025#endif
2026
2028 PHINode *Phi = &getIRPhi();
2029 for (const auto &[Idx, Op] : enumerate(operands())) {
2030 VPValue *ExitValue = Op;
2031 auto Lane = vputils::isSingleScalar(ExitValue)
2033 : VPLane::getLastLaneForVF(State.VF);
2034 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2035 auto *PredVPBB = Pred->getExitingBasicBlock();
2036 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2037 // Set insertion point in PredBB in case an extract needs to be generated.
2038 // TODO: Model extracts explicitly.
2039 State.Builder.SetInsertPoint(PredBB->getTerminator());
2040 Value *V = State.get(ExitValue, VPLane(Lane));
2041 // If there is no existing block for PredBB in the phi, add a new incoming
2042 // value. Otherwise update the existing incoming value for PredBB.
2043 if (Phi->getBasicBlockIndex(PredBB) == -1)
2044 Phi->addIncoming(V, PredBB);
2045 else
2046 Phi->setIncomingValueForBlock(PredBB, V);
2047 }
2048
2049 // Advance the insert point after the wrapped IR instruction. This allows
2050 // interleaving VPIRInstructions and other recipes.
2051 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
2052}
2053
2055 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2056 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2057 "Number of phi operands must match number of predecessors");
2058 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2059 R->removeOperand(Position);
2060}
2061
2062VPValue *
2064 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2065 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2066}
2067
2069 VPValue *V) const {
2070 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2071 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2072}
2073
2074#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2076 VPSlotTracker &SlotTracker) const {
2078 O << "[ ";
2079 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2080 O << ", ";
2081 std::get<1>(Op)->printAsOperand(O);
2082 O << " ]";
2083 });
2084}
2085#endif
2086
2087#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2089 VPSlotTracker &SlotTracker) const {
2091
2092 if (getNumOperands() != 0) {
2093 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2095 [&O, &SlotTracker](auto Op) {
2096 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2097 O << " from ";
2098 std::get<1>(Op)->printAsOperand(O);
2099 });
2100 O << ")";
2101 }
2102}
2103#endif
2104
2106 for (const auto &[Kind, Node] : Metadata)
2107 I.setMetadata(Kind, Node);
2108}
2109
2111 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
2112 for (const auto &[KindA, MDA] : Metadata) {
2113 for (const auto &[KindB, MDB] : Other.Metadata) {
2114 if (KindA == KindB && MDA == MDB) {
2115 MetadataIntersection.emplace_back(KindA, MDA);
2116 break;
2117 }
2118 }
2119 }
2120 Metadata = std::move(MetadataIntersection);
2121}
2122
2123#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2125 const Module *M = SlotTracker.getModule();
2126 if (Metadata.empty() || !M || !VPlanPrintMetadata)
2127 return;
2128
2129 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2130 O << " (";
2131 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2132 auto [Kind, Node] = KindNodePair;
2133 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2134 "Unexpected unnamed metadata kind");
2135 O << "!" << MDNames[Kind] << " ";
2136 Node->printAsOperand(O, M);
2137 });
2138 O << ")";
2139}
2140#endif
2141
2143 assert(State.VF.isVector() && "not widening");
2144 assert(Variant != nullptr && "Can't create vector function.");
2145
2146 FunctionType *VFTy = Variant->getFunctionType();
2147 // Add return type if intrinsic is overloaded on it.
2149 for (const auto &I : enumerate(args())) {
2150 Value *Arg;
2151 // Some vectorized function variants may also take a scalar argument,
2152 // e.g. linear parameters for pointers. This needs to be the scalar value
2153 // from the start of the respective part when interleaving.
2154 if (!VFTy->getParamType(I.index())->isVectorTy())
2155 Arg = State.get(I.value(), VPLane(0));
2156 else
2157 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2158 Args.push_back(Arg);
2159 }
2160
2163 if (CI)
2164 CI->getOperandBundlesAsDefs(OpBundles);
2165
2166 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
2167 applyFlags(*V);
2168 applyMetadata(*V);
2169 V->setCallingConv(Variant->getCallingConv());
2170
2171 if (!V->getType()->isVoidTy())
2172 State.set(this, V);
2173}
2174
2176 VPCostContext &Ctx) const {
2177 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2178 "Variant return type must match VF");
2179 return computeCallCost(Variant, Ctx);
2180}
2181
2183 VPCostContext &Ctx) {
2184 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2185 Variant->getFunctionType()->params(),
2186 Ctx.CostKind);
2187}
2188
2190 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2191 assert(Variant && "Variant not set");
2192 FunctionType *VFTy = Variant->getFunctionType();
2193 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2194 auto [Idx, V] = Arg;
2195 Type *ArgTy = VFTy->getParamType(Idx);
2196 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2197 ArgTy->isPointerTy() || ArgTy->isByteTy();
2198 });
2199}
2200
2201#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2203 VPSlotTracker &SlotTracker) const {
2204 O << Indent << "WIDEN-CALL ";
2205
2206 Function *CalledFn = getCalledScalarFunction();
2207 if (CalledFn->getReturnType()->isVoidTy())
2208 O << "void ";
2209 else {
2211 O << " = ";
2212 }
2213
2214 O << "call";
2215 printFlags(O);
2216 O << "@" << CalledFn->getName() << "(";
2217 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
2218 Op->printAsOperand(O, SlotTracker);
2219 });
2220 O << ")";
2221
2222 O << " (using library function";
2223 if (Variant->hasName())
2224 O << ": " << Variant->getName();
2225 O << ")";
2226}
2227#endif
2228
2230 assert(State.VF.isVector() && "not widening");
2231
2232 SmallVector<Type *, 2> TysForDecl;
2233 // Add return type if intrinsic is overloaded on it.
2234 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2235 State.TTI)) {
2236 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2237 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2238 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2240 Idx, State.TTI))
2241 TysForDecl.push_back(Ty);
2242 }
2243 }
2245 for (const auto &I : enumerate(operands())) {
2246 // Some intrinsics have a scalar argument - don't replace it with a
2247 // vector.
2248 Value *Arg;
2249 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2250 State.TTI))
2251 Arg = State.get(I.value(), VPLane(0));
2252 else
2253 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2254 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2255 State.TTI))
2256 TysForDecl.push_back(Arg->getType());
2257 Args.push_back(Arg);
2258 }
2259
2260 // Use vector version of the intrinsic.
2261 Module *M = State.Builder.GetInsertBlock()->getModule();
2262 Function *VectorF =
2263 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2264 assert(VectorF &&
2265 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2266
2269 if (CI)
2270 CI->getOperandBundlesAsDefs(OpBundles);
2271
2272 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
2273
2274 applyFlags(*V);
2275 applyMetadata(*V);
2276
2277 return V;
2278}
2279
2281 CallInst *V = createVectorCall(State);
2282 if (!V->getType()->isVoidTy())
2283 State.set(this, V);
2284}
2285
2288 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2289 Type *ScalarRetTy = R.getScalarType();
2290 // Skip the reverse operation cost for the mask.
2291 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2292 // by VPlanTransforms::cse before cost computation.
2293 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2294 return InstructionCost(0);
2295
2296 // Some backends analyze intrinsic arguments to determine cost. Use the
2297 // underlying value for the operand if it has one. Otherwise try to use the
2298 // operand of the underlying call instruction, if there is one. Otherwise
2299 // clear Arguments.
2300 // TODO: Rework TTI interface to be independent of concrete IR values.
2302 for (const auto &[Idx, Op] : enumerate(Operands)) {
2303 auto *V = Op->getUnderlyingValue();
2304 if (!V) {
2305 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2306 Arguments.push_back(UI->getArgOperand(Idx));
2307 continue;
2308 }
2309 Arguments.clear();
2310 break;
2311 }
2312 Arguments.push_back(V);
2313 }
2314
2315 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2316 SmallVector<Type *> ParamTys =
2317 map_to_vector(Operands, [&](const VPValue *Op) {
2318 return toVectorTy(Op->getScalarType(), VF);
2319 });
2320
2322 for (const VPValue *Op : Operands)
2323 if (isa<VPWidenRecipe>(Op) &&
2326 break;
2327 }
2328
2329 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2330 IntrinsicCostAttributes CostAttrs(
2331 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2332 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2334 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2335}
2336
2338 VPCostContext &Ctx) const {
2339 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2340}
2341
2343 return Intrinsic::getBaseName(VectorIntrinsicID);
2344}
2345
2347 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2348 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2349 auto [Idx, V] = X;
2351 Idx, nullptr);
2352 });
2353}
2354
2355#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2357 VPSlotTracker &SlotTracker) const {
2358 O << Indent << "WIDEN-INTRINSIC ";
2359 if (getScalarType()->isVoidTy()) {
2360 O << "void ";
2361 } else {
2363 O << " = ";
2364 }
2365
2366 O << "call";
2367 printFlags(O);
2368 O << getIntrinsicName() << "(";
2370 O << ")";
2371}
2372#endif
2373
2375 CallInst *MemI = createVectorCall(State);
2376 MemI->addParamAttr(
2377 0, Attribute::getWithAlignment(MemI->getContext(), Alignment));
2378 State.set(this, MemI);
2379}
2380
2382 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2383 VPCostContext &Ctx) {
2384 return Ctx.TTI.getMemIntrinsicInstrCost(
2385 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2386 Ctx.CostKind);
2387}
2388
2391 VPCostContext &Ctx) const {
2392 Type *Ty = toVectorTy(getScalarType(), VF);
2394 !match(getOperand(2), m_True()), Alignment,
2395 Ctx);
2396}
2397
2399 IRBuilderBase &Builder = State.Builder;
2400
2401 Value *Address = State.get(getOperand(0));
2402 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2403 VectorType *VTy = cast<VectorType>(Address->getType());
2404
2405 // The histogram intrinsic requires a mask even if the recipe doesn't;
2406 // if the mask operand was omitted then all lanes should be executed and
2407 // we just need to synthesize an all-true mask.
2408 Value *Mask = nullptr;
2409 if (VPValue *VPMask = getMask())
2410 Mask = State.get(VPMask);
2411 else
2412 Mask =
2413 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2414
2415 // If this is a subtract, we want to invert the increment amount. We may
2416 // add a separate intrinsic in future, but for now we'll try this.
2417 if (Opcode == Instruction::Sub)
2418 IncAmt = Builder.CreateNeg(IncAmt);
2419 else
2420 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2421
2422 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2423 Intrinsic::experimental_vector_histogram_add, {VTy, IncAmt->getType()},
2424 {Address, IncAmt, Mask});
2425 applyMetadata(*HistogramInst);
2426}
2427
2429 VPCostContext &Ctx) const {
2430 // FIXME: Take the gather and scatter into account as well. For now we're
2431 // generating the same cost as the fallback path, but we'll likely
2432 // need to create a new TTI method for determining the cost, including
2433 // whether we can use base + vec-of-smaller-indices or just
2434 // vec-of-pointers.
2435 assert(VF.isVector() && "Invalid VF for histogram cost");
2436 Type *AddressTy = getOperand(0)->getScalarType();
2437 VPValue *IncAmt = getOperand(1);
2438 Type *IncTy = IncAmt->getScalarType();
2439 VectorType *VTy = VectorType::get(IncTy, VF);
2440
2441 // Assume that a non-constant update value (or a constant != 1) requires
2442 // a multiply, and add that into the cost.
2443 InstructionCost MulCost =
2444 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2445 if (match(IncAmt, m_One()))
2446 MulCost = TTI::TCC_Free;
2447
2448 // Find the cost of the histogram operation itself.
2449 Type *PtrTy = VectorType::get(AddressTy, VF);
2450 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2451 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2452 Type::getVoidTy(Ctx.LLVMCtx),
2453 {PtrTy, IncTy, MaskTy});
2454
2455 // Add the costs together with the add/sub operation.
2456 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2457 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2458}
2459
2460#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2462 VPSlotTracker &SlotTracker) const {
2463 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2465
2466 if (Opcode == Instruction::Sub)
2467 O << ", dec: ";
2468 else {
2469 assert(Opcode == Instruction::Add);
2470 O << ", inc: ";
2471 }
2473
2474 if (VPValue *Mask = getMask()) {
2475 O << ", mask: ";
2476 Mask->printAsOperand(O, SlotTracker);
2477 }
2478}
2479#endif
2480
2481VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2482 AllowReassoc = FMF.allowReassoc();
2483 NoNaNs = FMF.noNaNs();
2484 NoInfs = FMF.noInfs();
2485 NoSignedZeros = FMF.noSignedZeros();
2486 AllowReciprocal = FMF.allowReciprocal();
2487 AllowContract = FMF.allowContract();
2488 ApproxFunc = FMF.approxFunc();
2489}
2490
2492 switch (Opcode) {
2493 case Instruction::Add:
2494 case Instruction::Sub:
2495 case Instruction::Mul:
2496 case Instruction::Shl:
2498 return WrapFlagsTy(false, false);
2499 case Instruction::Trunc:
2500 return TruncFlagsTy(false, false);
2501 case Instruction::Or:
2502 return DisjointFlagsTy(false);
2503 case Instruction::AShr:
2504 case Instruction::LShr:
2505 case Instruction::UDiv:
2506 case Instruction::SDiv:
2507 return ExactFlagsTy(false);
2508 case Instruction::GetElementPtr:
2511 return GEPNoWrapFlags::none();
2512 case Instruction::ZExt:
2513 case Instruction::UIToFP:
2514 return NonNegFlagsTy(false);
2515 case Instruction::FAdd:
2516 case Instruction::FSub:
2517 case Instruction::FMul:
2518 case Instruction::FDiv:
2519 case Instruction::FRem:
2520 case Instruction::FNeg:
2521 case Instruction::FPExt:
2522 case Instruction::FPTrunc:
2523 return FastMathFlags();
2524 case Instruction::ICmp:
2525 case Instruction::FCmp:
2527 llvm_unreachable("opcode requires explicit flags");
2528 default:
2529 return VPIRFlags();
2530 }
2531}
2532
2533#if !defined(NDEBUG)
2534bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2535 switch (OpType) {
2536 case OperationType::OverflowingBinOp:
2537 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2538 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2539 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2540 case OperationType::Trunc:
2541 return Opcode == Instruction::Trunc;
2542 case OperationType::DisjointOp:
2543 return Opcode == Instruction::Or;
2544 case OperationType::PossiblyExactOp:
2545 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2546 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2547 case OperationType::GEPOp:
2548 return Opcode == Instruction::GetElementPtr ||
2549 Opcode == VPInstruction::PtrAdd ||
2550 Opcode == VPInstruction::WidePtrAdd;
2551 case OperationType::FPMathOp:
2552 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2553 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2554 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2555 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2556 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2557 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2558 Opcode == Instruction::UIToFP ||
2559 Opcode == VPInstruction::WideIVStep ||
2561 case OperationType::FCmp:
2562 return Opcode == Instruction::FCmp;
2563 case OperationType::NonNegOp:
2564 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2565 case OperationType::Cmp:
2566 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2567 case OperationType::ReductionOp:
2569 case OperationType::Other:
2570 return true;
2571 }
2572 llvm_unreachable("Unknown OperationType enum");
2573}
2574
2575bool VPIRFlags::hasRequiredFlagsForOpcode(unsigned Opcode) const {
2576 // Handle opcodes without default flags.
2577 if (Opcode == Instruction::ICmp)
2578 return OpType == OperationType::Cmp;
2579 if (Opcode == Instruction::FCmp)
2580 return OpType == OperationType::FCmp;
2582 return OpType == OperationType::ReductionOp;
2583
2584 OperationType Required = getDefaultFlags(Opcode).OpType;
2585 return Required == OperationType::Other || Required == OpType;
2586}
2587#endif
2588
2589#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2590static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2591 switch (Kind) {
2592 case RecurKind::None:
2593 OS << "none";
2594 break;
2595 case RecurKind::Add:
2596 OS << "add";
2597 break;
2598 case RecurKind::Sub:
2599 OS << "sub";
2600 break;
2602 OS << "add-chain-with-subs";
2603 break;
2604 case RecurKind::Mul:
2605 OS << "mul";
2606 break;
2607 case RecurKind::Or:
2608 OS << "or";
2609 break;
2610 case RecurKind::And:
2611 OS << "and";
2612 break;
2613 case RecurKind::Xor:
2614 OS << "xor";
2615 break;
2616 case RecurKind::SMin:
2617 OS << "smin";
2618 break;
2619 case RecurKind::SMax:
2620 OS << "smax";
2621 break;
2622 case RecurKind::UMin:
2623 OS << "umin";
2624 break;
2625 case RecurKind::UMax:
2626 OS << "umax";
2627 break;
2628 case RecurKind::FAdd:
2629 OS << "fadd";
2630 break;
2632 OS << "fadd-chain-with-subs";
2633 break;
2634 case RecurKind::FSub:
2635 OS << "fsub";
2636 break;
2637 case RecurKind::FMul:
2638 OS << "fmul";
2639 break;
2640 case RecurKind::FMin:
2641 OS << "fmin";
2642 break;
2643 case RecurKind::FMax:
2644 OS << "fmax";
2645 break;
2646 case RecurKind::FMinNum:
2647 OS << "fminnum";
2648 break;
2649 case RecurKind::FMaxNum:
2650 OS << "fmaxnum";
2651 break;
2653 OS << "fminimum";
2654 break;
2656 OS << "fmaximum";
2657 break;
2659 OS << "fminimumnum";
2660 break;
2662 OS << "fmaximumnum";
2663 break;
2664 case RecurKind::FMulAdd:
2665 OS << "fmuladd";
2666 break;
2667 case RecurKind::AnyOf:
2668 OS << "any-of";
2669 break;
2670 case RecurKind::FindIV:
2671 OS << "find-iv";
2672 break;
2674 OS << "find-last";
2675 break;
2676 }
2677}
2678
2680 switch (OpType) {
2681 case OperationType::Cmp:
2683 break;
2684 case OperationType::FCmp:
2687 break;
2688 case OperationType::DisjointOp:
2689 if (DisjointFlags.IsDisjoint)
2690 O << " disjoint";
2691 break;
2692 case OperationType::PossiblyExactOp:
2693 if (ExactFlags.IsExact)
2694 O << " exact";
2695 break;
2696 case OperationType::OverflowingBinOp:
2697 if (WrapFlags.HasNUW)
2698 O << " nuw";
2699 if (WrapFlags.HasNSW)
2700 O << " nsw";
2701 break;
2702 case OperationType::Trunc:
2703 if (TruncFlags.HasNUW)
2704 O << " nuw";
2705 if (TruncFlags.HasNSW)
2706 O << " nsw";
2707 break;
2708 case OperationType::FPMathOp:
2710 break;
2711 case OperationType::GEPOp: {
2713 if (Flags.isInBounds())
2714 O << " inbounds";
2715 else if (Flags.hasNoUnsignedSignedWrap())
2716 O << " nusw";
2717 if (Flags.hasNoUnsignedWrap())
2718 O << " nuw";
2719 break;
2720 }
2721 case OperationType::NonNegOp:
2722 if (NonNegFlags.NonNeg)
2723 O << " nneg";
2724 break;
2725 case OperationType::ReductionOp: {
2726 O << " (";
2728 if (isReductionInLoop())
2729 O << ", in-loop";
2730 if (isReductionOrdered())
2731 O << ", ordered";
2732 O << ")";
2734 break;
2735 }
2736 case OperationType::Other:
2737 break;
2738 }
2739 O << " ";
2740}
2741#endif
2742
2744 auto &Builder = State.Builder;
2745 switch (Opcode) {
2746 case Instruction::Call:
2747 case Instruction::UncondBr:
2748 case Instruction::CondBr:
2749 case Instruction::PHI:
2750 case Instruction::GetElementPtr:
2751 llvm_unreachable("This instruction is handled by a different recipe.");
2752 case Instruction::UDiv:
2753 case Instruction::SDiv:
2754 case Instruction::SRem:
2755 case Instruction::URem:
2756 case Instruction::Add:
2757 case Instruction::FAdd:
2758 case Instruction::Sub:
2759 case Instruction::FSub:
2760 case Instruction::FNeg:
2761 case Instruction::Mul:
2762 case Instruction::FMul:
2763 case Instruction::FDiv:
2764 case Instruction::FRem:
2765 case Instruction::Shl:
2766 case Instruction::LShr:
2767 case Instruction::AShr:
2768 case Instruction::And:
2769 case Instruction::Or:
2770 case Instruction::Xor: {
2771 // Just widen unops and binops.
2773 for (VPValue *VPOp : operands())
2774 Ops.push_back(State.get(VPOp));
2775
2776 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2777
2778 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2779 applyFlags(*VecOp);
2780 applyMetadata(*VecOp);
2781 }
2782
2783 // Use this vector value for all users of the original instruction.
2784 State.set(this, V);
2785 break;
2786 }
2787 case Instruction::ExtractValue: {
2788 assert(getNumOperands() == 2 && "expected single level extractvalue");
2789 Value *Op = State.get(getOperand(0));
2790 Value *Extract = Builder.CreateExtractValue(
2791 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2792 State.set(this, Extract);
2793 break;
2794 }
2795 case Instruction::Freeze: {
2796 Value *Op = State.get(getOperand(0));
2797 Value *Freeze = Builder.CreateFreeze(Op);
2798 State.set(this, Freeze);
2799 break;
2800 }
2801 case Instruction::ICmp:
2802 case Instruction::FCmp: {
2803 // Widen compares. Generate vector compares.
2804 bool FCmp = Opcode == Instruction::FCmp;
2805 Value *A = State.get(getOperand(0));
2806 Value *B = State.get(getOperand(1));
2807 Value *C = nullptr;
2808 if (FCmp) {
2809 C = Builder.CreateFCmp(getPredicate(), A, B);
2810 } else {
2811 C = Builder.CreateICmp(getPredicate(), A, B);
2812 }
2813 if (auto *I = dyn_cast<Instruction>(C)) {
2814 applyFlags(*I);
2815 applyMetadata(*I);
2816 }
2817 State.set(this, C);
2818 break;
2819 }
2820 case Instruction::Select: {
2821 VPValue *CondOp = getOperand(0);
2822 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2823 Value *Op0 = State.get(getOperand(1));
2824 Value *Op1 = State.get(getOperand(2));
2825 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2826 State.set(this, Sel);
2827 if (auto *I = dyn_cast<Instruction>(Sel)) {
2829 applyFlags(*I);
2830 applyMetadata(*I);
2831 }
2832 break;
2833 }
2834 default:
2835 // This instruction is not vectorized by simple widening.
2836 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2837 << Instruction::getOpcodeName(Opcode));
2838 llvm_unreachable("Unhandled instruction!");
2839 } // end of switch.
2840
2841#if !defined(NDEBUG)
2842 // Verify that VPlan type inference results agree with the type of the
2843 // generated values.
2844 assert(VectorType::get(this->getScalarType(), State.VF) ==
2845 State.get(this)->getType() &&
2846 "inferred type and type from generated instructions do not match");
2847#endif
2848}
2849
2851 VPCostContext &Ctx) const {
2852 switch (Opcode) {
2853 case Instruction::UDiv:
2854 case Instruction::SDiv:
2855 case Instruction::SRem:
2856 case Instruction::URem:
2857 // If the div/rem operation isn't safe to speculate and requires
2858 // predication, then the only way we can even create a vplan is to insert
2859 // a select on the second input operand to ensure we use the value of 1
2860 // for the inactive lanes. The select will be costed separately.
2861 case Instruction::FNeg:
2862 case Instruction::Add:
2863 case Instruction::FAdd:
2864 case Instruction::Sub:
2865 case Instruction::FSub:
2866 case Instruction::Mul:
2867 case Instruction::FMul:
2868 case Instruction::FDiv:
2869 case Instruction::FRem:
2870 case Instruction::Shl:
2871 case Instruction::LShr:
2872 case Instruction::AShr:
2873 case Instruction::And:
2874 case Instruction::Or:
2875 case Instruction::Xor:
2876 case Instruction::Freeze:
2877 case Instruction::ExtractValue:
2878 case Instruction::ICmp:
2879 case Instruction::FCmp:
2880 case Instruction::Select:
2881 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2882 default:
2883 llvm_unreachable("Unsupported opcode for instruction");
2884 }
2885}
2886
2887#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2889 VPSlotTracker &SlotTracker) const {
2890 O << Indent << "WIDEN ";
2892 O << " = " << Instruction::getOpcodeName(Opcode);
2893 printFlags(O);
2895}
2896#endif
2897
2899 auto &Builder = State.Builder;
2900 /// Vectorize casts.
2901 assert(State.VF.isVector() && "Not vectorizing?");
2902 Type *DestTy = VectorType::get(getScalarType(), State.VF);
2903 VPValue *Op = getOperand(0);
2904 Value *A = State.get(Op);
2905 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2906 State.set(this, Cast);
2907 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2908 applyFlags(*CastOp);
2909 applyMetadata(*CastOp);
2910 }
2911}
2912
2917
2918#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2920 VPSlotTracker &SlotTracker) const {
2921 O << Indent << "WIDEN-CAST ";
2923 O << " = " << Instruction::getOpcodeName(Opcode);
2924 printFlags(O);
2926 O << " to " << *getScalarType();
2927}
2928#endif
2929
2931 VPCostContext &Ctx) const {
2932 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2933}
2934
2935#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2937 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2938 O << Indent;
2940 O << " = WIDEN-INDUCTION";
2941 printFlags(O);
2943
2944 if (auto *TI = getTruncInst())
2945 O << " (truncated to " << *TI->getType() << ")";
2946}
2947#endif
2948
2950 // The step may be defined by a recipe in the preheader (e.g. if it requires
2951 // SCEV expansion), but for the canonical induction the step is required to be
2952 // 1, which is represented as live-in.
2953 return match(getStartValue(), m_ZeroInt()) &&
2954 match(getStepValue(), m_One()) &&
2955 getScalarType() == getRegion()->getCanonicalIVType();
2956}
2957
2959 VPCostContext &Ctx) const {
2960 // The cost model for this is modelled on expandVPDerivedIV in
2961 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
2962 // negatively affect vectorization it takes into account any expected
2963 // simplifications that happen in simplifyRecipe.
2964 switch (getInductionKind()) {
2965 default:
2966 // TODO: Compute cost for remaining kinds.
2967 break;
2969 // There are currently no tests that expose a path where all lanes are
2970 // used, so it's better to bail out for now.
2971 if (!vputils::onlyFirstLaneUsed(this))
2972 break;
2973
2974 // Start off by assuming we need both mul and add, then refine this.
2975 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
2976
2977 // If the start value is zero the add gets folded away.
2978 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
2979 NeedsAdd = !StartC->isZero();
2980
2981 // For some values of step the arithmetic changes:
2982 // 1. A step of 1 requires no operation.
2983 // 2. A step of -1 requires a negate.
2984 // 3. A power-of-2 step will use a shl, instead of a mul.
2985 Type *StepTy = getStepValue()->getScalarType();
2987 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
2988 if (StepC->isOne())
2989 NeedsMul = false;
2990 else if (StepC->getAPInt().isAllOnes()) {
2991 // This will most likely end up as a negate in simplifyRecipe, and
2992 // the negate will be combined with the add to make a sub.
2993 // NOTE: This is perhaps an invalid assumption that the cost of an
2994 // 'add' is the same as a 'sub'.
2995 NeedsMul = false;
2996 NeedsAdd = true;
2997 } else if (StepC->getAPInt().isPowerOf2()) {
2998 // This will most likely end up as a shift-left in simplifyRecipe
2999 NeedsMul = false;
3000 NeedsShl = true;
3001 }
3002 }
3003
3004 // Add the cost of the conversion from index to step type if the index
3005 // will be used.
3006 Type *IndexTy = getIndex()->getScalarType();
3007 unsigned StepTySize = StepTy->getScalarSizeInBits();
3008 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3009 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3010 unsigned CastOpc =
3011 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::SExt;
3012 Cost += Ctx.TTI.getCastInstrCost(
3013 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3014 }
3015
3016 if (NeedsMul)
3017 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3018 Ctx.CostKind);
3019 if (NeedsShl)
3020 Cost += Ctx.TTI.getArithmeticInstrCost(
3021 Instruction::Shl, StepTy, Ctx.CostKind,
3022 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3023 {TargetTransformInfo::OK_UniformConstantValue,
3024 TargetTransformInfo::OP_None});
3025 if (NeedsAdd)
3026 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3027 Ctx.CostKind);
3028 return Cost;
3029 }
3030 }
3031
3032 return 0;
3033}
3034
3035#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3037 VPSlotTracker &SlotTracker) const {
3038 O << Indent;
3040 O << " = DERIVED-IV ";
3041 getStartValue()->printAsOperand(O, SlotTracker);
3042 O << " + ";
3043 getOperand(1)->printAsOperand(O, SlotTracker);
3044 O << " * ";
3045 getStepValue()->printAsOperand(O, SlotTracker);
3046}
3047#endif
3048
3052
3054 VPCostContext &Ctx) const {
3055 // TODO: Add costs for floating point.
3056 Type *BaseIVTy = getOperand(0)->getScalarType();
3057 if (!BaseIVTy->isIntegerTy())
3058 return 0;
3059
3060 // TODO: Add support for predicated regions. Requires scaling the cost by the
3061 // probability of entering the block.
3062 if (getRegion() && getRegion()->isReplicator())
3063 return 0;
3064
3065 // If only the first lane is used, then there won't be any code that remains
3066 // in the loop for the first unrolled part.
3068 return 0;
3069
3070 // Typically the operations are:
3071 // 1. Add the start index to each lane value.
3072 // 2. Multiply the start index by the step.
3073 // 3. Add the scaled start index to base IV.
3074 // Any code generated for 1 and 2 should be loop invariant and therefore
3075 // hoisted out of the loop. We only need to add on the cost of 3.
3076
3077 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3078 // %add1 = add i32 %iv, 0
3079 // %add2 = add i32 %iv, 1
3080 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3081 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3082 // it's very likely that these GEPs will all be rewritten to have a common
3083 // base such that what's left is just
3084 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3085 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3086 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3087 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3088 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3089 return Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3090 Ctx.CostKind);
3091}
3092
3094 // Fast-math-flags propagate from the original induction instruction.
3095 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3096 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3097
3098 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3099 /// variable on which to base the steps, \p Step is the size of the step.
3100
3101 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3102 Value *Step = State.get(getStepValue(), VPLane(0));
3103 IRBuilderBase &Builder = State.Builder;
3104
3105 // Ensure step has the same type as that of scalar IV.
3106 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3107 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3108
3109 // We build scalar steps for both integer and floating-point induction
3110 // variables. Here, we determine the kind of arithmetic we will perform.
3113 if (BaseIVTy->isIntegerTy()) {
3114 AddOp = Instruction::Add;
3115 MulOp = Instruction::Mul;
3116 } else {
3117 AddOp = InductionOpcode;
3118 MulOp = Instruction::FMul;
3119 }
3120
3121 // Determine the number of scalars we need to generate.
3122 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
3123 // Compute the scalar steps and save the results in State.
3124
3125 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
3126 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
3127 : Constant::getNullValue(BaseIVTy);
3128
3129 for (unsigned Lane = 0; Lane < EndLane; ++Lane) {
3130 // It is okay if the induction variable type cannot hold the lane number,
3131 // we expect truncation in this case.
3132 Constant *LaneValue =
3133 BaseIVTy->isIntegerTy()
3134 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
3135 /*ImplicitTrunc=*/true)
3136 : ConstantFP::get(BaseIVTy, Lane);
3137 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
3138 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
3139 "Expected StartIdx to be folded to a constant when VF is not "
3140 "scalable");
3141 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3142 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3143 State.set(this, Add, VPLane(Lane));
3144 }
3145}
3146
3147#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3149 VPSlotTracker &SlotTracker) const {
3150 O << Indent;
3152 O << " = SCALAR-STEPS ";
3154}
3155#endif
3156
3158 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3160}
3161
3163 assert(State.VF.isVector() && "not widening");
3164 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3165 return State.get(Op, vputils::isSingleScalar(Op));
3166 });
3167 auto *GEP =
3168 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3169 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3170 State.set(this, GEP, vputils::isSingleScalar(this));
3171}
3172
3173#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3175 VPSlotTracker &SlotTracker) const {
3176 O << Indent << "WIDEN-GEP ";
3178 O << " = getelementptr";
3179 printFlags(O);
3181}
3182#endif
3183
3185 assert(!getOffset() && "Unexpected offset operand");
3186 VPBuilder Builder(this);
3187 VPlan &Plan = *getParent()->getPlan();
3188 VPValue *VFVal = getVFValue();
3189 const DataLayout &DL = Plan.getDataLayout();
3190 Type *IndexTy = DL.getIndexType(this->getScalarType());
3191 VPValue *Stride =
3192 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3193 VPValue *VF =
3194 Builder.createScalarZExtOrTrunc(VFVal, IndexTy, DebugLoc::getUnknown());
3195
3196 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3197 VPInstruction *VFMinusOne =
3198 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3199 DebugLoc::getUnknown(), "", {true, true});
3200 VPInstruction *Offset0 =
3201 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3202
3203 // Offset for PartN = Offset0 + Part * Stride * VF.
3204 VPValue *PartxStride =
3205 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3206 VPValue *Offset = Builder.createAdd(
3207 Offset0,
3208 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3210}
3211
3213 auto &Builder = State.Builder;
3214 assert(getOffset() && "Expected prior materialization of offset");
3215 Value *Ptr = State.get(getPointer(), true);
3216 Value *Offset = State.get(getOffset(), true);
3217 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3219 State.set(this, ResultPtr, /*IsScalar*/ true);
3220}
3221
3222#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3224 VPSlotTracker &SlotTracker) const {
3225 O << Indent;
3227 O << " = vector-end-pointer";
3228 printFlags(O);
3230}
3231#endif
3232
3234 assert(getVFxPart() &&
3235 "Expected prior simplification of recipe without VFxPart");
3236
3237 auto &Builder = State.Builder;
3238 Value *Ptr = State.get(getOperand(0), VPLane(0));
3239 Value *Offset = State.get(getVFxPart(), true);
3240 // TODO: Expand to VPInstruction to support constant folding.
3241 if (!match(getStride(), m_One())) {
3242 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3243 Offset->getType());
3244 Offset = Builder.CreateMul(Offset, Stride);
3245 }
3246 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3248 State.set(this, ResultPtr, /*IsScalar*/ true);
3249}
3250
3251#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3253 VPSlotTracker &SlotTracker) const {
3254 O << Indent;
3256 O << " = vector-pointer";
3257 printFlags(O);
3259}
3260#endif
3261
3263 VPCostContext &Ctx) const {
3264 // A blend will be expanded to a select VPInstruction, which will generate a
3265 // scalar select if only the first lane is used.
3267 VF = ElementCount::getFixed(1);
3268
3269 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3270 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3271 return (getNumIncomingValues() - 1) *
3272 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3273 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
3274}
3275
3276#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3278 VPSlotTracker &SlotTracker) const {
3279 O << Indent << "BLEND ";
3281 O << " =";
3282 printFlags(O);
3283 if (getNumIncomingValues() == 1) {
3284 // Not a User of any mask: not really blending, this is a
3285 // single-predecessor phi.
3286 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3287 } else {
3288 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3289 if (I != 0)
3290 O << " ";
3291 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3292 if (I == 0 && isNormalized())
3293 continue;
3294 O << "/";
3295 getMask(I)->printAsOperand(O, SlotTracker);
3296 }
3297 }
3298}
3299#endif
3300
3304 "In-loop AnyOf reductions aren't currently supported");
3305 // Propagate the fast-math flags carried by the underlying instruction.
3306 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3307 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3308 Value *NewVecOp = State.get(getVecOp());
3309 if (VPValue *Cond = getCondOp()) {
3310 Value *NewCond = State.get(Cond, State.VF.isScalar());
3311 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3312 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3313
3314 Value *Start =
3316 if (State.VF.isVector())
3317 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3318
3319 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3320 NewVecOp = Select;
3321 }
3322 Value *NewRed;
3323 Value *NextInChain;
3324 if (isOrdered()) {
3325 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3326 if (State.VF.isVector())
3327 NewRed =
3328 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3329 else
3330 NewRed = State.Builder.CreateBinOp(
3332 PrevInChain, NewVecOp);
3333 PrevInChain = NewRed;
3334 NextInChain = NewRed;
3335 } else if (isPartialReduction()) {
3336 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3337 "Unexpected partial reduction kind");
3338 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
3339 NewRed = State.Builder.CreateIntrinsic(
3340 PrevInChain->getType(),
3341 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3342 : Intrinsic::vector_partial_reduce_fadd,
3343 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3344 "partial.reduce");
3345 PrevInChain = NewRed;
3346 NextInChain = NewRed;
3347 } else {
3348 assert(isInLoop() &&
3349 "The reduction must either be ordered, partial or in-loop");
3350 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3351 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3353 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3354 else
3355 NextInChain = State.Builder.CreateBinOp(
3357 PrevInChain, NewRed);
3358 }
3359 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3360}
3361
3363
3364 auto &Builder = State.Builder;
3365 // Propagate the fast-math flags carried by the underlying instruction.
3366 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3367 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3368
3370 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
3371 Value *VecOp = State.get(getVecOp());
3372 Value *EVL = State.get(getEVL(), VPLane(0));
3373
3374 Value *Mask;
3375 if (VPValue *CondOp = getCondOp())
3376 Mask = State.get(CondOp);
3377 else
3378 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3379
3380 Value *NewRed;
3381 if (isOrdered()) {
3382 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3383 } else {
3384 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3386 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3387 else
3388 NewRed = Builder.CreateBinOp(
3390 Prev);
3391 }
3392 State.set(this, NewRed, /*IsScalar*/ true);
3393}
3394
3396 VPCostContext &Ctx) const {
3397 RecurKind RdxKind = getRecurrenceKind();
3398 Type *ElementTy = this->getScalarType();
3399 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3400 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3402 std::optional<FastMathFlags> OptionalFMF =
3403 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3404
3405 if (isPartialReduction()) {
3406 InstructionCost CondCost = 0;
3407 if (isConditional()) {
3409 auto *CondTy =
3411 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3412 CondTy, Pred, Ctx.CostKind);
3413 }
3414 return CondCost + Ctx.TTI.getPartialReductionCost(
3415 Opcode, ElementTy, ElementTy, ElementTy, VF,
3416 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3417 OptionalFMF);
3418 }
3419
3420 // TODO: Support any-of reductions.
3421 assert(
3423 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
3424 "Any-of reduction not implemented in VPlan-based cost model currently.");
3425
3426 // Note that TTI should model the cost of moving result to the scalar register
3427 // and the BinOp cost in the getMinMaxReductionCost().
3430 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3431 }
3432
3433 // Note that TTI should model the cost of moving result to the scalar register
3434 // and the BinOp cost in the getArithmeticReductionCost().
3435 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3436 Ctx.CostKind);
3437}
3438
3439VPExpressionRecipe::VPExpressionRecipe(
3440 ExpressionTypes ExpressionType,
3441 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3442 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3443 cast<VPReductionRecipe>(ExpressionRecipes.back())
3444 ->getChainOp()
3445 ->getScalarType()),
3446 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3447 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3448 assert(
3449 none_of(ExpressionRecipes,
3450 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3451 "expression cannot contain recipes with side-effects");
3452
3453 // Maintain a copy of the expression recipes as a set of users.
3454 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3455 for (auto *R : ExpressionRecipes)
3456 ExpressionRecipesAsSetOfUsers.insert(R);
3457
3458 // Recipes in the expression, except the last one, must only be used by
3459 // (other) recipes inside the expression. If there are other users, external
3460 // to the expression, use a clone of the recipe for external users.
3461 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3462 if (R != ExpressionRecipes.back() &&
3463 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3464 return !ExpressionRecipesAsSetOfUsers.contains(U);
3465 })) {
3466 // There are users outside of the expression. Clone the recipe and use the
3467 // clone those external users.
3468 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3469 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
3470 VPUser &U, unsigned) {
3471 return !ExpressionRecipesAsSetOfUsers.contains(&U);
3472 });
3473 CopyForExtUsers->insertBefore(R);
3474 }
3475 if (R->getParent())
3476 R->removeFromParent();
3477 }
3478
3479 // Internalize all external operands to the expression recipes. To do so,
3480 // create new temporary VPValues for all operands defined by a recipe outside
3481 // the expression. The original operands are added as operands of the
3482 // VPExpressionRecipe itself.
3483 for (auto *R : ExpressionRecipes) {
3484 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3485 auto *Def = Op->getDefiningRecipe();
3486 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3487 continue;
3488 addOperand(Op);
3489 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3490 }
3491 }
3492
3493 // Replace each external operand with the first one created for it in
3494 // LiveInPlaceholders.
3495 for (auto *R : ExpressionRecipes)
3496 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3497 R->replaceUsesOfWith(LiveIn, Tmp);
3498}
3499
3501 for (auto *R : ExpressionRecipes)
3502 // Since the list could contain duplicates, make sure the recipe hasn't
3503 // already been inserted.
3504 if (!R->getParent())
3505 R->insertBefore(this);
3506
3507 for (const auto &[Idx, Op] : enumerate(operands()))
3508 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3509
3510 replaceAllUsesWith(ExpressionRecipes.back());
3511 ExpressionRecipes.clear();
3512}
3513
3515 VPCostContext &Ctx) const {
3516 Type *RedTy = this->getScalarType();
3517 auto *SrcVecTy =
3519 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3520 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3521 switch (ExpressionType) {
3522 case ExpressionTypes::NegatedExtendedReduction:
3523 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3524 "Unexpected opcode");
3525 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3526 [[fallthrough]];
3527 case ExpressionTypes::ExtendedReduction: {
3528 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3529 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3530
3531 if (RedR->isPartialReduction())
3532 return Ctx.TTI.getPartialReductionCost(
3533 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3535 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3536 RedTy->isFloatingPointTy()
3537 ? std::optional{RedR->getFastMathFlagsOrNone()}
3538 : std::nullopt);
3539 else if (!RedTy->isFloatingPointTy())
3540 // TTI::getExtendedReductionCost only supports integer types.
3541 return Ctx.TTI.getExtendedReductionCost(
3542 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3543 std::nullopt, Ctx.CostKind);
3544 else
3546 }
3547 case ExpressionTypes::MulAccReduction:
3548 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3549 Ctx.CostKind);
3550
3551 case ExpressionTypes::ExtNegatedMulAccReduction:
3552 switch (Opcode) {
3553 case Instruction::Add:
3554 Opcode = Instruction::Sub;
3555 break;
3556 case Instruction::FAdd:
3557 Opcode = Instruction::FSub;
3558 break;
3559 default:
3560 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3561 }
3562 [[fallthrough]];
3563 case ExpressionTypes::ExtMulAccReduction: {
3564 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3565 if (RedR->isPartialReduction()) {
3566 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3567 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3568 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3569 return Ctx.TTI.getPartialReductionCost(
3570 Opcode, getOperand(0)->getScalarType(),
3571 getOperand(1)->getScalarType(), RedTy, VF,
3573 Ext0R->getOpcode()),
3575 Ext1R->getOpcode()),
3576 Mul->getOpcode(), Ctx.CostKind,
3577 RedTy->isFloatingPointTy()
3578 ? std::optional{RedR->getFastMathFlagsOrNone()}
3579 : std::nullopt);
3580 }
3581 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3582 return Ctx.TTI.getMulAccReductionCost(
3583 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3584 Instruction::ZExt,
3585 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3586 }
3587 }
3588 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3589}
3590
3592 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3593 return R->mayReadFromMemory() || R->mayWriteToMemory();
3594 });
3595}
3596
3598 assert(
3599 none_of(ExpressionRecipes,
3600 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3601 "expression cannot contain recipes with side-effects");
3602 return false;
3603}
3604
3606 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3607 return RR && !RR->isPartialReduction();
3608}
3609
3610#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3611
3613 VPSlotTracker &SlotTracker) const {
3614 O << Indent << "EXPRESSION ";
3616 O << " = ";
3617 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3618 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3619 VPValue *RdxStart =
3620 getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1));
3621
3622 switch (ExpressionType) {
3623 case ExpressionTypes::NegatedExtendedReduction:
3624 case ExpressionTypes::ExtendedReduction: {
3625 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
3627 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3628 O << Instruction::getOpcodeName(Opcode) << " (";
3629 if (Negated)
3630 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
3632 if (Negated)
3633 O << ")";
3634 Red->printFlags(O);
3635
3636 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3637 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3638 << *Ext0->getScalarType();
3639 if (Red->isConditional()) {
3640 O << ", ";
3642 }
3643 O << ")";
3644 break;
3645 }
3646 case ExpressionTypes::ExtNegatedMulAccReduction: {
3647 RdxStart->printAsOperand(O, SlotTracker);
3648 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3650 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3651 << " (sub (0, mul";
3652 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3653 Mul->printFlags(O);
3654 O << "(";
3656 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3657 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3658 << *Ext0->getScalarType() << "), (";
3660 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3661 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3662 << *Ext1->getScalarType() << ")";
3663 if (Red->isConditional()) {
3664 O << ", ";
3666 }
3667 O << "))";
3668 break;
3669 }
3670 case ExpressionTypes::MulAccReduction:
3671 case ExpressionTypes::ExtMulAccReduction: {
3672 RdxStart->printAsOperand(O, SlotTracker);
3673 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3675 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3676 << " (";
3677 O << "mul";
3678 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3679 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3680 : ExpressionRecipes[0]);
3681 Mul->printFlags(O);
3682 if (IsExtended)
3683 O << "(";
3685 if (IsExtended) {
3686 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3687 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3688 << *Ext0->getScalarType() << "), (";
3689 } else {
3690 O << ", ";
3691 }
3693 if (IsExtended) {
3694 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3695 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3696 << *Ext1->getScalarType() << ")";
3697 }
3698 if (Red->isConditional()) {
3699 O << ", ";
3701 }
3702 O << ")";
3703 break;
3704 }
3705 }
3706}
3707
3709 VPSlotTracker &SlotTracker) const {
3710 if (isPartialReduction())
3711 O << Indent << "PARTIAL-REDUCE ";
3712 else
3713 O << Indent << "REDUCE ";
3715 O << " = ";
3717 O << " +";
3718 printFlags(O);
3719 O << " reduce.";
3721 O << " (";
3723 if (isConditional()) {
3724 O << ", ";
3726 }
3727 O << ")";
3728}
3729
3731 VPSlotTracker &SlotTracker) const {
3732 O << Indent << "REDUCE ";
3734 O << " = ";
3736 O << " +";
3737 printFlags(O);
3738 O << " vp.reduce."
3741 << " (";
3743 O << ", ";
3745 if (isConditional()) {
3746 O << ", ";
3748 }
3749 O << ")";
3750}
3751
3752#endif
3753
3755 assert(IsSingleScalar &&
3756 "VPReplicateRecipes must be unrolled before ::execute");
3757 auto *Instr = getUnderlyingInstr();
3758 Instruction *Cloned = Instr->clone();
3759 Type *ResultTy = getScalarType();
3760 if (!ResultTy->isVoidTy()) {
3761 Cloned->setName(Instr->getName() + ".cloned");
3762 // The operands of the replicate recipe may have been narrowed, resulting in
3763 // a narrower result type. Update the type of the cloned instruction to the
3764 // correct type.
3765 if (ResultTy != Cloned->getType())
3766 Cloned->mutateType(ResultTy);
3767 }
3768
3769 applyFlags(*Cloned);
3770 applyMetadata(*Cloned);
3771
3772 if (hasPredicate())
3773 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
3774
3775 // Replace the operands of the cloned instructions with their scalar
3776 // equivalents in the new loop.
3777 for (const auto &[Idx, V] : enumerate(operands()))
3778 Cloned->setOperand(Idx, State.get(V, true));
3779
3780 // Place the cloned scalar in the new loop.
3781 State.Builder.Insert(Cloned);
3782
3783 State.set(this, Cloned, true);
3784
3785 // If we just cloned a new assumption, add it the assumption cache.
3786 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3787 State.AC->registerAssumption(II);
3788}
3789
3790/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3791/// which the legacy cost model computes a SCEV expression when computing the
3792/// address cost. Computing SCEVs for VPValues is incomplete and returns
3793/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3794/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3795static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3797 const Loop *L) {
3798 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3799 if (isa<SCEVCouldNotCompute>(Addr))
3800 return Addr;
3801
3802 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3803}
3804
3806 VPCostContext &Ctx) const {
3808 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3809 // transform, avoid computing their cost multiple times for now.
3810 Ctx.SkipCostComputation.insert(UI);
3811
3812 if (VF.isScalable() && !isSingleScalar())
3814
3815 switch (UI->getOpcode()) {
3816 case Instruction::Alloca:
3817 if (VF.isScalable())
3819 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
3820 this->getScalarType(), Ctx.CostKind);
3821 case Instruction::GetElementPtr:
3822 // We mark this instruction as zero-cost because the cost of GEPs in
3823 // vectorized code depends on whether the corresponding memory instruction
3824 // is scalarized or not. Therefore, we handle GEPs with the memory
3825 // instruction cost.
3826 return 0;
3827 case Instruction::Call: {
3828 auto *CalledFn =
3830 Type *ResultTy = this->getScalarType();
3831 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
3832 isSingleScalar(), VF, Ctx);
3833 }
3834 case Instruction::Add:
3835 case Instruction::Sub:
3836 case Instruction::FAdd:
3837 case Instruction::FSub:
3838 case Instruction::Mul:
3839 case Instruction::FMul:
3840 case Instruction::FDiv:
3841 case Instruction::FRem:
3842 case Instruction::Shl:
3843 case Instruction::LShr:
3844 case Instruction::AShr:
3845 case Instruction::And:
3846 case Instruction::Or:
3847 case Instruction::Xor:
3848 case Instruction::ICmp:
3849 case Instruction::FCmp:
3851 Ctx) *
3852 (isSingleScalar() ? 1 : VF.getFixedValue());
3853 case Instruction::SDiv:
3854 case Instruction::UDiv:
3855 case Instruction::SRem:
3856 case Instruction::URem: {
3857 InstructionCost ScalarCost =
3859 if (isSingleScalar())
3860 return ScalarCost;
3861
3862 // If any of the operands is from a different replicate region and has its
3863 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3864 // model to avoid cost mis-match.
3865 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3866 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3867 if (!PredR)
3868 return false;
3869 return Ctx.skipCostComputation(
3871 PredR->getOperand(0)->getUnderlyingValue()),
3872 VF.isVector());
3873 }))
3874 break;
3875
3876 ScalarCost = ScalarCost * VF.getFixedValue() +
3877 Ctx.getScalarizationOverhead(this->getScalarType(),
3878 to_vector(operands()), VF);
3879 // If the recipe is not predicated (i.e. not in a replicate region), return
3880 // the scalar cost. Otherwise handle predicated cost.
3881 if (!getRegion()->isReplicator())
3882 return ScalarCost;
3883
3884 // Account for the phi nodes that we will create.
3885 ScalarCost += VF.getFixedValue() *
3886 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3887 // Scale the cost by the probability of executing the predicated blocks.
3888 // This assumes the predicated block for each vector lane is equally
3889 // likely.
3890 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3891 return ScalarCost;
3892 }
3893 case Instruction::Load:
3894 case Instruction::Store: {
3895 bool IsLoad = UI->getOpcode() == Instruction::Load;
3896 const VPValue *PtrOp = getOperand(!IsLoad);
3897 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3899 break;
3900
3901 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
3902 Type *ScalarPtrTy = PtrOp->getScalarType();
3903 const Align Alignment = getLoadStoreAlignment(UI);
3904 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3906 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3907 bool UsedByLoadStoreAddress =
3908 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
3909 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3910 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3911 UsedByLoadStoreAddress ? UI : nullptr);
3912
3913 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3914 InstructionCost ScalarCost =
3915 ScalarMemOpCost +
3916 Ctx.TTI.getAddressComputationCost(
3917 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3918 Ctx.CostKind);
3919 if (isSingleScalar())
3920 return ScalarCost;
3921
3922 SmallVector<const VPValue *> OpsToScalarize;
3923 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3924 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3925 // don't assign scalarization overhead in general, if the target prefers
3926 // vectorized addressing or the loaded value is used as part of an address
3927 // of another load or store.
3928 if (!UsedByLoadStoreAddress) {
3929 bool EfficientVectorLoadStore =
3930 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3931 if (!(IsLoad && !PreferVectorizedAddressing) &&
3932 !(!IsLoad && EfficientVectorLoadStore))
3933 append_range(OpsToScalarize, operands());
3934
3935 if (!EfficientVectorLoadStore)
3936 ResultTy = this->getScalarType();
3937 }
3938
3940 IsLoad ? TTI::VectorInstrContext::Load : TTI::VectorInstrContext::Store;
3942 (ScalarCost * VF.getFixedValue()) +
3943 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3944
3945 const VPRegionBlock *ParentRegion = getRegion();
3946 if (ParentRegion && ParentRegion->isReplicator()) {
3947 if (!PtrSCEV)
3948 break;
3949 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3950 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
3951
3952 auto *VecI1Ty = VectorType::get(
3953 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3954 Cost += Ctx.TTI.getScalarizationOverhead(
3955 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3956 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3957
3958 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3959 // Artificially setting to a high enough value to practically disable
3960 // vectorization with such operations.
3961 return 3000000;
3962 }
3963 }
3964 return Cost;
3965 }
3966 case Instruction::SExt:
3967 case Instruction::ZExt:
3968 case Instruction::FPToUI:
3969 case Instruction::FPToSI:
3970 case Instruction::FPExt:
3971 case Instruction::PtrToInt:
3972 case Instruction::PtrToAddr:
3973 case Instruction::IntToPtr:
3974 case Instruction::SIToFP:
3975 case Instruction::UIToFP:
3976 case Instruction::Trunc:
3977 case Instruction::FPTrunc:
3978 case Instruction::Select:
3979 case Instruction::AddrSpaceCast: {
3981 Ctx) *
3982 (isSingleScalar() ? 1 : VF.getFixedValue());
3983 }
3984 case Instruction::ExtractValue:
3985 case Instruction::InsertValue:
3986 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3987 }
3988
3989 return Ctx.getLegacyCost(UI, VF);
3990}
3991
3993 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
3994 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
3996 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
3997
3998 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
3999 auto GetIntrinsicCost = [&] {
4000 if (!IntrinID)
4002 return Ctx.TTI.getIntrinsicInstrCost(
4003 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
4004 };
4005
4006 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
4007 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
4008 return 0;
4009 }
4010
4011 InstructionCost ScalarCallCost =
4012 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4013 if (IsSingleScalar) {
4014 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4015 return ScalarCallCost;
4016 }
4017
4018 // Scalarization overhead is undefined for scalable VFs.
4019 if (VF.isScalable())
4021
4022 return ScalarCallCost * VF.getFixedValue() +
4023 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4024}
4025
4026#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4028 VPSlotTracker &SlotTracker) const {
4029 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4030
4031 if (!getScalarType()->isVoidTy()) {
4033 O << " = ";
4034 }
4035 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4036 O << "call";
4037 printFlags(O);
4038 O << "@" << CB->getCalledFunction()->getName() << "(";
4040 Op->printAsOperand(O, SlotTracker);
4041 });
4042 O << ")";
4043 } else {
4045 printFlags(O);
4047 }
4048
4049 // Find if the recipe is used by a widened recipe via an intervening
4050 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4051 if (any_of(users(), [](const VPUser *U) {
4052 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4053 return !vputils::onlyScalarValuesUsed(PredR);
4054 return false;
4055 }))
4056 O << " (S->V)";
4057}
4058#endif
4059
4061 llvm_unreachable("recipe must be removed when dissolving replicate region");
4062}
4063
4065 VPCostContext &Ctx) const {
4066 // The legacy cost model doesn't assign costs to branches for individual
4067 // replicate regions. Match the current behavior in the VPlan cost model for
4068 // now.
4069 return 0;
4070}
4071
4073 llvm_unreachable("recipe must be removed when dissolving replicate region");
4074}
4075
4076#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4078 VPSlotTracker &SlotTracker) const {
4079 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4081 O << " = ";
4083}
4084#endif
4085
4087const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4088
4091
4093const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4094
4097
4099 VPCostContext &Ctx) const {
4100 const VPRecipeBase *R = getAsRecipe();
4102 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4103 : R->getOperand(1)->getScalarType();
4104 Type *Ty = toVectorTy(ScalarTy, VF);
4105 unsigned AS =
4106 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4107 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4108
4109 if (!Consecutive) {
4110 // TODO: Using the original IR may not be accurate.
4111 // Currently, ARM will use the underlying IR to calculate gather/scatter
4112 // instruction cost.
4113 Type *PtrTy = getAddr()->getScalarType();
4114 const Value *Ptr = getAddr()->getUnderlyingValue();
4115
4116 // If the address value is uniform across all lanes, then the address can be
4117 // calculated with scalar type and broadcast.
4119 PtrTy = toVectorTy(PtrTy, VF);
4120
4121 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4122 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4123 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4124 : Intrinsic::vp_scatter;
4125 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4126 Ctx.CostKind) +
4127 Ctx.TTI.getMemIntrinsicInstrCost(
4129 &Ingredient),
4130 Ctx.CostKind);
4131 }
4132
4134 if (IsMasked) {
4135 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4136 : Intrinsic::masked_store;
4137 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4138 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4139 } else {
4140 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4142 : R->getOperand(1));
4143 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4144 OpInfo, &Ingredient);
4145 }
4146 return Cost;
4147}
4148
4150 Type *ScalarDataTy = getScalarType();
4151 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4152 bool CreateGather = !isConsecutive();
4153
4154 auto &Builder = State.Builder;
4155 Value *Mask = nullptr;
4156 if (auto *VPMask = getMask())
4157 Mask = State.get(VPMask);
4158
4159 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
4160 Value *NewLI;
4161 if (CreateGather) {
4162 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4163 "wide.masked.gather");
4164 } else if (Mask) {
4165 NewLI =
4166 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4167 PoisonValue::get(DataTy), "wide.masked.load");
4168 } else {
4169 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4170 }
4172 State.set(this, NewLI);
4173}
4174
4175#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4177 VPSlotTracker &SlotTracker) const {
4178 O << Indent << "WIDEN ";
4180 O << " = load ";
4182}
4183#endif
4184
4186 Type *ScalarDataTy = getScalarType();
4187 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4188 bool CreateGather = !isConsecutive();
4189
4190 auto &Builder = State.Builder;
4191 CallInst *NewLI;
4192 Value *EVL = State.get(getEVL(), VPLane(0));
4193 Value *Addr = State.get(getAddr(), !CreateGather);
4194 Value *Mask = nullptr;
4195 if (VPValue *VPMask = getMask())
4196 Mask = State.get(VPMask);
4197 else
4198 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4199
4200 if (CreateGather) {
4201 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4202 {Addr, Mask, EVL}, nullptr,
4203 "wide.masked.gather");
4204 } else {
4205 NewLI = Builder.CreateIntrinsicWithoutFolding(
4206 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4207 }
4208 NewLI->addParamAttr(
4210 applyMetadata(*NewLI);
4211 State.set(this, NewLI);
4212}
4213
4215 VPCostContext &Ctx) const {
4216 if (!Consecutive || IsMasked)
4217 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4218
4219 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4220 // here because the EVL recipes using EVL to replace the tail mask. But in the
4221 // legacy model, it will always calculate the cost of mask.
4222 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4223 // don't need to compare to the legacy cost model.
4224 Type *Ty = toVectorTy(getScalarType(), VF);
4225 unsigned AS =
4226 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4227 return Ctx.TTI.getMemIntrinsicInstrCost(
4228 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4229 Ctx.CostKind);
4230}
4231
4232#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4234 VPSlotTracker &SlotTracker) const {
4235 O << Indent << "WIDEN ";
4237 O << " = vp.load ";
4239}
4240#endif
4241
4243 VPValue *StoredVPValue = getStoredValue();
4244 bool CreateScatter = !isConsecutive();
4245
4246 auto &Builder = State.Builder;
4247
4248 Value *Mask = nullptr;
4249 if (auto *VPMask = getMask())
4250 Mask = State.get(VPMask);
4251
4252 Value *StoredVal = State.get(StoredVPValue);
4253 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
4254 Instruction *NewSI = nullptr;
4255 if (CreateScatter)
4256 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4257 else if (Mask)
4258 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4259 else
4260 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4261 applyMetadata(*NewSI);
4262}
4263
4264#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4266 VPSlotTracker &SlotTracker) const {
4267 O << Indent << "WIDEN store ";
4269}
4270#endif
4271
4273 VPValue *StoredValue = getStoredValue();
4274 bool CreateScatter = !isConsecutive();
4275
4276 auto &Builder = State.Builder;
4277
4278 CallInst *NewSI = nullptr;
4279 Value *StoredVal = State.get(StoredValue);
4280 Value *EVL = State.get(getEVL(), VPLane(0));
4281 Value *Mask = nullptr;
4282 if (VPValue *VPMask = getMask())
4283 Mask = State.get(VPMask);
4284 else
4285 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4286
4287 Value *Addr = State.get(getAddr(), !CreateScatter);
4288 if (CreateScatter) {
4289 NewSI = Builder.CreateIntrinsicWithoutFolding(
4290 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4291 {StoredVal, Addr, Mask, EVL});
4292 } else {
4293 NewSI = Builder.CreateIntrinsicWithoutFolding(
4294 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4295 {StoredVal, Addr, Mask, EVL});
4296 }
4297 NewSI->addParamAttr(
4299 applyMetadata(*NewSI);
4300}
4301
4303 VPCostContext &Ctx) const {
4304 if (!Consecutive || IsMasked)
4305 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4306
4307 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4308 // here because the EVL recipes using EVL to replace the tail mask. But in the
4309 // legacy model, it will always calculate the cost of mask.
4310 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4311 // don't need to compare to the legacy cost model.
4312 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4313 unsigned AS =
4314 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4315 return Ctx.TTI.getMemIntrinsicInstrCost(
4316 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4317 Ctx.CostKind);
4318}
4319
4320#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4322 VPSlotTracker &SlotTracker) const {
4323 O << Indent << "WIDEN vp.store ";
4325}
4326#endif
4327
4329 VectorType *DstVTy, const DataLayout &DL) {
4330 // Verify that V is a vector type with same number of elements as DstVTy.
4331 auto VF = DstVTy->getElementCount();
4332 auto *SrcVecTy = cast<VectorType>(V->getType());
4333 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4334 Type *SrcElemTy = SrcVecTy->getElementType();
4335 Type *DstElemTy = DstVTy->getElementType();
4336 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4337 "Vector elements must have same size");
4338
4339 // Do a direct cast if element types are castable.
4340 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4341 return Builder.CreateBitOrPointerCast(V, DstVTy);
4342 }
4343 // V cannot be directly casted to desired vector type.
4344 // May happen when V is a floating point vector but DstVTy is a vector of
4345 // pointers or vice-versa. Handle this using a two-step bitcast using an
4346 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4347 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4348 "Only one type should be a pointer type");
4349 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4350 "Only one type should be a floating point type");
4351 Type *IntTy =
4352 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4353 auto *VecIntTy = VectorType::get(IntTy, VF);
4354 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4355 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4356}
4357
4358/// Return a vector containing interleaved elements from multiple
4359/// smaller input vectors.
4361 const Twine &Name) {
4362 unsigned Factor = Vals.size();
4363 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4364
4365 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4366#ifndef NDEBUG
4367 for (Value *Val : Vals)
4368 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4369#endif
4370
4371 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4372 // must use intrinsics to interleave.
4373 if (VecTy->isScalableTy()) {
4374 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4375 return Builder.CreateVectorInterleave(Vals, Name);
4376 }
4377
4378 // Fixed length. Start by concatenating all vectors into a wide vector.
4379 Value *WideVec = concatenateVectors(Builder, Vals);
4380
4381 // Interleave the elements into the wide vector.
4382 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4383 return Builder.CreateShuffleVector(
4384 WideVec, createInterleaveMask(NumElts, Factor), Name);
4385}
4386
4387// Try to vectorize the interleave group that \p Instr belongs to.
4388//
4389// E.g. Translate following interleaved load group (factor = 3):
4390// for (i = 0; i < N; i+=3) {
4391// R = Pic[i]; // Member of index 0
4392// G = Pic[i+1]; // Member of index 1
4393// B = Pic[i+2]; // Member of index 2
4394// ... // do something to R, G, B
4395// }
4396// To:
4397// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4398// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4399// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4400// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4401//
4402// Or translate following interleaved store group (factor = 3):
4403// for (i = 0; i < N; i+=3) {
4404// ... do something to R, G, B
4405// Pic[i] = R; // Member of index 0
4406// Pic[i+1] = G; // Member of index 1
4407// Pic[i+2] = B; // Member of index 2
4408// }
4409// To:
4410// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4411// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4412// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4413// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4414// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4416 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4417 "Masking gaps for scalable vectors is not yet supported.");
4419 Instruction *Instr = Group->getInsertPos();
4420
4421 // Prepare for the vector type of the interleaved load/store.
4422 Type *ScalarTy = getLoadStoreType(Instr);
4423 unsigned InterleaveFactor = Group->getFactor();
4424 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4425
4426 VPValue *BlockInMask = getMask();
4427 VPValue *Addr = getAddr();
4428 Value *ResAddr = State.get(Addr, VPLane(0));
4429
4430 auto CreateGroupMask = [&BlockInMask, &State,
4431 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4432 if (State.VF.isScalable()) {
4433 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4434 assert(InterleaveFactor <= 8 &&
4435 "Unsupported deinterleave factor for scalable vectors");
4436 auto *ResBlockInMask = State.get(BlockInMask);
4437 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4438 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4439 }
4440
4441 if (!BlockInMask)
4442 return MaskForGaps;
4443
4444 Value *ResBlockInMask = State.get(BlockInMask);
4445 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4446 ResBlockInMask,
4447 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4448 "interleaved.mask");
4449 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4450 ShuffledMask, MaskForGaps)
4451 : ShuffledMask;
4452 };
4453
4454 const DataLayout &DL = Instr->getDataLayout();
4455 // Vectorize the interleaved load group.
4456 if (isa<LoadInst>(Instr)) {
4457 Value *MaskForGaps = nullptr;
4458 if (needsMaskForGaps()) {
4459 MaskForGaps =
4460 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4461 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4462 }
4463
4464 Instruction *NewLoad;
4465 if (BlockInMask || MaskForGaps) {
4466 Value *GroupMask = CreateGroupMask(MaskForGaps);
4467 Value *PoisonVec = PoisonValue::get(VecTy);
4468 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4469 Group->getAlign(), GroupMask,
4470 PoisonVec, "wide.masked.vec");
4471 } else
4472 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4473 Group->getAlign(), "wide.vec");
4474 applyMetadata(*NewLoad);
4475 // TODO: Also manage existing metadata using VPIRMetadata.
4476 Group->addMetadata(NewLoad);
4477
4479 if (VecTy->isScalableTy()) {
4480 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4481 // so must use intrinsics to deinterleave.
4482 assert(InterleaveFactor <= 8 &&
4483 "Unsupported deinterleave factor for scalable vectors");
4484 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4485 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4486 NewLoad->getType(), NewLoad,
4487 /*FMFSource=*/nullptr, "strided.vec");
4488 }
4489
4490 auto CreateStridedVector = [&InterleaveFactor, &State,
4491 &NewLoad](unsigned Index) -> Value * {
4492 assert(Index < InterleaveFactor && "Illegal group index");
4493 if (State.VF.isScalable())
4494 return State.Builder.CreateExtractValue(NewLoad, Index);
4495
4496 // For fixed length VF, use shuffle to extract the sub-vectors from the
4497 // wide load.
4498 auto StrideMask =
4499 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4500 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4501 "strided.vec");
4502 };
4503
4504 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4505 Instruction *Member = Group->getMember(I);
4506
4507 // Skip the gaps in the group.
4508 if (!Member)
4509 continue;
4510
4511 Value *StridedVec = CreateStridedVector(I);
4512
4513 // If this member has different type, cast the result type.
4514 if (Member->getType() != ScalarTy) {
4515 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4516 StridedVec =
4517 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4518 }
4519
4520 if (Group->isReverse())
4521 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4522
4523 State.set(VPDefs[J], StridedVec);
4524 ++J;
4525 }
4526 return;
4527 }
4528
4529 // The sub vector type for current instruction.
4530 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4531
4532 // Vectorize the interleaved store group.
4533 Value *MaskForGaps =
4534 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4535 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4536 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4537 ArrayRef<VPValue *> StoredValues = getStoredValues();
4538 // Collect the stored vector from each member.
4539 SmallVector<Value *, 4> StoredVecs;
4540 unsigned StoredIdx = 0;
4541 for (unsigned i = 0; i < InterleaveFactor; i++) {
4542 assert((Group->getMember(i) || MaskForGaps) &&
4543 "Fail to get a member from an interleaved store group");
4544 Instruction *Member = Group->getMember(i);
4545
4546 // Skip the gaps in the group.
4547 if (!Member) {
4548 Value *Undef = PoisonValue::get(SubVT);
4549 StoredVecs.push_back(Undef);
4550 continue;
4551 }
4552
4553 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4554 ++StoredIdx;
4555
4556 if (Group->isReverse())
4557 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4558
4559 // If this member has different type, cast it to a unified type.
4560
4561 if (StoredVec->getType() != SubVT)
4562 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4563
4564 StoredVecs.push_back(StoredVec);
4565 }
4566
4567 // Interleave all the smaller vectors into one wider vector.
4568 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4569 Instruction *NewStoreInstr;
4570 if (BlockInMask || MaskForGaps) {
4571 Value *GroupMask = CreateGroupMask(MaskForGaps);
4572 NewStoreInstr = State.Builder.CreateMaskedStore(
4573 IVec, ResAddr, Group->getAlign(), GroupMask);
4574 } else
4575 NewStoreInstr =
4576 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4577
4578 applyMetadata(*NewStoreInstr);
4579 // TODO: Also manage existing metadata using VPIRMetadata.
4580 Group->addMetadata(NewStoreInstr);
4581}
4582
4583#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4585 VPSlotTracker &SlotTracker) const {
4587 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4589 VPValue *Mask = getMask();
4590 if (Mask) {
4591 O << ", ";
4592 Mask->printAsOperand(O, SlotTracker);
4593 }
4594
4595 unsigned OpIdx = 0;
4596 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4597 if (!IG->getMember(i))
4598 continue;
4599 if (getNumStoreOperands() > 0) {
4600 O << "\n" << Indent << " store ";
4602 O << " to index " << i;
4603 } else {
4604 O << "\n" << Indent << " ";
4606 O << " = load from index " << i;
4607 }
4608 ++OpIdx;
4609 }
4610}
4611#endif
4612
4614 assert(State.VF.isScalable() &&
4615 "Only support scalable VF for EVL tail-folding.");
4617 "Masking gaps for scalable vectors is not yet supported.");
4619 Instruction *Instr = Group->getInsertPos();
4620
4621 // Prepare for the vector type of the interleaved load/store.
4622 Type *ScalarTy = getLoadStoreType(Instr);
4623 unsigned InterleaveFactor = Group->getFactor();
4624 assert(InterleaveFactor <= 8 &&
4625 "Unsupported deinterleave/interleave factor for scalable vectors");
4626 ElementCount WideVF = State.VF * InterleaveFactor;
4627 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4628
4629 VPValue *Addr = getAddr();
4630 Value *ResAddr = State.get(Addr, VPLane(0));
4631 Value *EVL = State.get(getEVL(), VPLane(0));
4632 Value *InterleaveEVL = State.Builder.CreateMul(
4633 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4634 /* NUW= */ true, /* NSW= */ true);
4635 LLVMContext &Ctx = State.Builder.getContext();
4636
4637 Value *GroupMask = nullptr;
4638 if (VPValue *BlockInMask = getMask()) {
4639 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4640 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4641 } else {
4642 GroupMask =
4643 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4644 }
4645
4646 // Vectorize the interleaved load group.
4647 if (isa<LoadInst>(Instr)) {
4648 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4649 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4650 "wide.vp.load");
4651 NewLoad->addParamAttr(0,
4652 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4653
4654 applyMetadata(*NewLoad);
4655 // TODO: Also manage existing metadata using VPIRMetadata.
4656 Group->addMetadata(NewLoad);
4657
4658 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4659 // so must use intrinsics to deinterleave.
4660 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4661 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4662 NewLoad->getType(), NewLoad,
4663 /*FMFSource=*/nullptr, "strided.vec");
4664
4665 const DataLayout &DL = Instr->getDataLayout();
4666 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4667 Instruction *Member = Group->getMember(I);
4668 // Skip the gaps in the group.
4669 if (!Member)
4670 continue;
4671
4672 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4673 // If this member has different type, cast the result type.
4674 if (Member->getType() != ScalarTy) {
4675 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4676 StridedVec =
4677 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4678 }
4679
4680 State.set(getVPValue(J), StridedVec);
4681 ++J;
4682 }
4683 return;
4684 } // End for interleaved load.
4685
4686 // The sub vector type for current instruction.
4687 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4688 // Vectorize the interleaved store group.
4689 ArrayRef<VPValue *> StoredValues = getStoredValues();
4690 // Collect the stored vector from each member.
4691 SmallVector<Value *, 4> StoredVecs;
4692 const DataLayout &DL = Instr->getDataLayout();
4693 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4694 Instruction *Member = Group->getMember(I);
4695 // Skip the gaps in the group.
4696 if (!Member) {
4697 StoredVecs.push_back(PoisonValue::get(SubVT));
4698 continue;
4699 }
4700
4701 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4702 // If this member has different type, cast it to a unified type.
4703 if (StoredVec->getType() != SubVT)
4704 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4705
4706 StoredVecs.push_back(StoredVec);
4707 ++StoredIdx;
4708 }
4709
4710 // Interleave all the smaller vectors into one wider vector.
4711 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4712 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
4713 Type::getVoidTy(Ctx), Intrinsic::vp_store,
4714 {IVec, ResAddr, GroupMask, InterleaveEVL});
4715
4716 NewStore->addParamAttr(1,
4717 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4718
4719 applyMetadata(*NewStore);
4720 // TODO: Also manage existing metadata using VPIRMetadata.
4721 Group->addMetadata(NewStore);
4722}
4723
4724#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4726 VPSlotTracker &SlotTracker) const {
4728 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4730 O << ", ";
4732 if (VPValue *Mask = getMask()) {
4733 O << ", ";
4734 Mask->printAsOperand(O, SlotTracker);
4735 }
4736
4737 unsigned OpIdx = 0;
4738 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4739 if (!IG->getMember(i))
4740 continue;
4741 if (getNumStoreOperands() > 0) {
4742 O << "\n" << Indent << " vp.store ";
4744 O << " to index " << i;
4745 } else {
4746 O << "\n" << Indent << " ";
4748 O << " = vp.load from index " << i;
4749 }
4750 ++OpIdx;
4751 }
4752}
4753#endif
4754
4756 VPCostContext &Ctx) const {
4757 Instruction *InsertPos = getInsertPos();
4758 // Find the VPValue index of the interleave group. We need to skip gaps.
4759 unsigned InsertPosIdx = 0;
4760 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4761 if (auto *Member = IG->getMember(Idx)) {
4762 if (Member == InsertPos)
4763 break;
4764 InsertPosIdx++;
4765 }
4766 const VPValue *ValV = getNumDefinedValues() > 0
4767 ? getVPValue(InsertPosIdx)
4768 : getStoredValues()[InsertPosIdx];
4769 Type *ValTy = ValV->getScalarType();
4770 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4771 unsigned AS =
4772 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4773
4774 unsigned InterleaveFactor = IG->getFactor();
4775 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4776
4777 // Holds the indices of existing members in the interleaved group.
4779 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4780 if (IG->getMember(IF))
4781 Indices.push_back(IF);
4782
4783 // Calculate the cost of the whole interleaved group.
4784 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4785 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4786 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4787
4788 if (!IG->isReverse())
4789 return Cost;
4790
4791 return Cost + IG->getNumMembers() *
4792 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4793 VectorTy, VectorTy, {}, Ctx.CostKind,
4794 0);
4795}
4796
4798 return vputils::onlyScalarValuesUsed(this) &&
4799 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4800}
4801
4802#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4804 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4805 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4806 "unexpected number of operands");
4807 O << Indent << "EMIT ";
4809 O << " = WIDEN-POINTER-INDUCTION ";
4811 O << ", ";
4813 O << ", ";
4815 if (getNumOperands() == 5) {
4816 O << ", ";
4818 O << ", ";
4820 }
4821}
4822
4824 VPSlotTracker &SlotTracker) const {
4825 O << Indent << "EMIT ";
4827 O << " = EXPAND SCEV " << *Expr;
4828}
4829#endif
4830
4831#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4833 VPSlotTracker &SlotTracker) const {
4834 O << Indent << "EMIT ";
4836 O << " = WIDEN-CANONICAL-INDUCTION";
4837 printFlags(O);
4839}
4840#endif
4841
4843 auto &Builder = State.Builder;
4844 // Create a vector from the initial value.
4845 auto *VectorInit = getStartValue()->getLiveInIRValue();
4846
4847 Type *VecTy = State.VF.isScalar()
4848 ? VectorInit->getType()
4849 : VectorType::get(VectorInit->getType(), State.VF);
4850
4851 BasicBlock *VectorPH =
4852 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4853 if (State.VF.isVector()) {
4854 auto *IdxTy = Builder.getInt32Ty();
4855 auto *One = ConstantInt::get(IdxTy, 1);
4856 IRBuilder<>::InsertPointGuard Guard(Builder);
4857 Builder.SetInsertPoint(VectorPH->getTerminator());
4858 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4859 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4860 VectorInit = Builder.CreateInsertElement(
4861 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4862 }
4863
4864 // Create a phi node for the new recurrence.
4865 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4866 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4867 Phi->addIncoming(VectorInit, VectorPH);
4868 State.set(this, Phi);
4869}
4870
4873 VPCostContext &Ctx) const {
4874 if (VF.isScalar())
4875 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4876
4877 return 0;
4878}
4879
4880#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4882 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4883 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4885 O << " = phi ";
4887}
4888#endif
4889
4891 // Reductions do not have to start at zero. They can start with
4892 // any loop invariant values.
4893 VPValue *StartVPV = getStartValue();
4894
4895 // In order to support recurrences we need to be able to vectorize Phi nodes.
4896 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4897 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4898 // this value when we vectorize all of the instructions that use the PHI.
4899 BasicBlock *VectorPH =
4900 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4901 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4902 Value *StartV = State.get(StartVPV, ScalarPHI);
4903 Type *VecTy = StartV->getType();
4904
4905 BasicBlock *HeaderBB = State.CFG.PrevBB;
4906 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4907 "recipe must be in the vector loop header");
4908 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4909 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4910 State.set(this, Phi, isInLoop());
4911
4912 Phi->addIncoming(StartV, VectorPH);
4913}
4914
4915#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4917 VPSlotTracker &SlotTracker) const {
4918 O << Indent << "WIDEN-REDUCTION-PHI ";
4919
4921 O << " = phi (";
4922 printRecurrenceKind(O, Kind);
4923 O << ")";
4924 printFlags(O);
4926 if (getVFScaleFactor() > 1)
4927 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4928}
4929#endif
4930
4932 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
4933 return vputils::onlyFirstLaneUsed(this);
4934}
4935
4937 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
4938}
4939
4941 VPCostContext &Ctx) const {
4942 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4943}
4944
4945#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4947 VPSlotTracker &SlotTracker) const {
4948 O << Indent << "WIDEN-PHI ";
4949
4951 O << " = phi ";
4953}
4954#endif
4955
4957 BasicBlock *VectorPH =
4958 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4959 Value *StartMask = State.get(getOperand(0));
4960 PHINode *Phi =
4961 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4962 Phi->addIncoming(StartMask, VectorPH);
4963 State.set(this, Phi);
4964}
4965
4966#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4968 VPSlotTracker &SlotTracker) const {
4969 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4970
4972 O << " = phi ";
4974}
4975#endif
4976
4977#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4979 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4980 O << Indent << "CURRENT-ITERATION-PHI ";
4981
4983 O << " = phi ";
4985}
4986#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:856
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)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
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 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:235
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
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
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_UGT
unsigned greater than
Definition InstrTypes.h:763
@ 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 the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
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:324
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
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:284
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:643
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:576
bool doesNotAccessMemory() const
Determine if the function does not access memory.
Definition Function.cpp:862
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
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:2662
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:2716
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2650
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:1216
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:2709
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:2728
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:534
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2092
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2277
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:2379
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1770
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:2509
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1854
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2375
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1154
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1439
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2121
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:1422
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:1731
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2387
Value * CreateLogicalOr(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1778
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2485
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1592
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1456
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.
@ 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
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:67
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
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:4365
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4418
iterator end()
Definition VPlan.h:4402
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4431
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:2980
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2975
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:2971
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:94
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:225
VPlan * getPlan()
Definition VPlan.cpp:211
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:4196
VPValue * getIndex() const
Definition VPlan.h:4193
VPValue * getStepValue() const
Definition VPlan.h:4194
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:4192
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.
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
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.
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:2463
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:2184
Class to record and manage LLVM IR flags.
Definition VPlan.h:695
FastMathFlagsTy FMFs
Definition VPlan.h:784
ReductionFlagsTy ReductionFlags
Definition VPlan.h:786
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode) const
Returns true if Opcode has its required flags set.
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
static VPIRFlags getDefaultFlags(unsigned Opcode)
Returns default flags for Opcode for opcodes that support it, asserts otherwise.
WrapFlagsTy WrapFlags
Definition VPlan.h:778
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:1001
bool isReductionOrdered() const
Definition VPlan.h:1062
TruncFlagsTy TruncFlags
Definition VPlan.h:779
CmpInst::Predicate getPredicate() const
Definition VPlan.h:973
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:781
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:782
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:991
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:996
DisjointFlagsTy DisjointFlags
Definition VPlan.h:780
FCmpFlagsTy FCmpFlags
Definition VPlan.h:785
NonNegFlagsTy NonNegFlags
Definition VPlan.h:783
bool isReductionInLoop() const
Definition VPlan.h:1068
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:930
uint8_t CmpPredStorage
Definition VPlan.h:777
RecurKind getRecurKind() const
Definition VPlan.h:1056
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:1719
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetadata object with MD, keeping only metadata nodes that are common to both.
VPIRMetadata()=default
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print metadata with node IDs.
void applyMetadata(Instruction &I) const
Add all metadata to I.
Type * getResultType() const
Definition VPlan.h:1580
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:1224
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:1326
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1346
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1317
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1330
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1342
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1320
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1267
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1313
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1262
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1259
@ CanonicalIVIncrementForPart
Definition VPlan.h:1243
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1270
bool hasResult() const
Definition VPlan.h:1431
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:1512
unsigned getOpcode() const
Definition VPlan.h:1410
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:1456
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:3084
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3088
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3086
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3078
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3107
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3072
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3181
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:3194
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:3144
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
static VPLane getLastLaneForVF(const ElementCount &VF)
static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset)
static VPLane getFirstLane()
Helper type to provide functions to access incoming values and blocks for phi-like recipes.
Definition VPlan.h:1599
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:1648
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1608
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const
Sets the incoming value for VPBB to V.
void execute(VPTransformState &State) override
Generates phi nodes for live-outs (from a replicate region) as needed to retain SSA form.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
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:4756
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:520
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:474
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:552
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:464
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:3352
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:2886
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2905
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:3294
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:3305
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3307
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3290
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3296
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3303
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3298
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:4590
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4666
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:3433
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:3471
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:4251
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4259
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:610
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:680
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:612
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:1519
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:1470
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:1515
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:2278
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:2275
int64_t getStride() const
Definition VPlan.h:2276
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
VPValue * getStride() const
Definition VPlan.h:2352
Type * getSourceElementType() const
Definition VPlan.h:2367
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:2354
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:2135
Function * getCalledScalarFunction() const
Definition VPlan.h:2131
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:1906
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:2232
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.
VPIRValue * getStartValue() const
Returns the start value of the induction.
Definition VPlan.h:2549
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2552
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2660
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:2020
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:3732
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3757
Instruction & Ingredient
Definition VPlan.h:3723
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3729
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3767
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3726
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3760
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:1849
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4769
const DataLayout & getDataLayout() const
Definition VPlan.h:4976
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4930
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:5078
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 LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition TypeSize.h:256
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ 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.
specific_intval< 1 > m_False()
specific_intval< 1 > m_True()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
VPInstruction_match< VPInstruction::Reverse, Op0_t > m_Reverse(const Op0_t &Op0)
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:386
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:85
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
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:578
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:374
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
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
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:1960
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:1777
PHINode & getIRPhi()
Definition VPlan.h:1790
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,...
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:1116
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.
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide load or gather.
LLVM_ABI_FOR_TEST VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3852
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:3954
LLVM_ABI_FOR_TEST void execute(VPTransformState &State) override
Generate the wide store or scatter.
LLVM_ABI_FOR_TEST VPRecipeBase * getAsRecipe() override
Return a VPRecipeBase* to the current object.
LLVM_ABI_FOR_TEST void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3957
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:3902