LLVM 23.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:
669 1;
670 case Instruction::GetElementPtr:
671 case Instruction::PHI:
672 case Instruction::Switch:
673 case Instruction::AtomicRMW:
674 case Instruction::AtomicCmpXchg:
675 case Instruction::Fence:
686 // Cannot determine the number of operands from the opcode.
687 return -1u;
688 }
689 llvm_unreachable("all cases should be handled above");
690}
691
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:
1653 default:
1654 return true;
1655 }
1656}
1657
1659 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1661 return vputils::onlyFirstLaneUsed(this);
1662
1663 switch (getOpcode()) {
1664 default:
1665 return false;
1666 case Instruction::ExtractElement:
1667 return Op == getOperand(1);
1668 case Instruction::InsertElement:
1669 return Op == getOperand(1) || Op == getOperand(2);
1670 case Instruction::PHI:
1671 return true;
1672 case Instruction::FCmp:
1673 case Instruction::ICmp:
1674 case Instruction::Select:
1675 case Instruction::Or:
1676 case Instruction::Freeze:
1677 case VPInstruction::Not:
1678 // TODO: Cover additional opcodes.
1679 return vputils::onlyFirstLaneUsed(this);
1680 case Instruction::Load:
1692 return true;
1695 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1696 // operand, after replicating its operands only the first lane is used.
1697 // Before replicating, it will have only a single operand.
1698 return getNumOperands() > 1;
1700 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1702 // WidePtrAdd supports scalar and vector base addresses.
1703 return false;
1706 return Op == getOperand(0);
1707 };
1708 llvm_unreachable("switch should return");
1709}
1710
1712 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1714 return vputils::onlyFirstPartUsed(this);
1715
1716 switch (getOpcode()) {
1717 default:
1718 return false;
1719 case Instruction::FCmp:
1720 case Instruction::ICmp:
1721 case Instruction::Select:
1722 return vputils::onlyFirstPartUsed(this);
1727 return true;
1728 };
1729 llvm_unreachable("switch should return");
1730}
1731
1732#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1734 VPSlotTracker SlotTracker(getParent()->getPlan());
1736}
1737
1739 VPSlotTracker &SlotTracker) const {
1740 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1741
1742 if (hasResult()) {
1744 O << " = ";
1745 }
1746
1747 switch (getOpcode()) {
1748 case VPInstruction::Not:
1749 O << "not";
1750 break;
1752 O << "active lane mask";
1753 break;
1755 O << "incoming-alias-mask";
1756 break;
1758 O << "EXPLICIT-VECTOR-LENGTH";
1759 break;
1761 O << "first-order splice";
1762 break;
1764 O << "branch-on-cond";
1765 break;
1767 O << "branch-on-two-conds";
1768 break;
1770 O << "TC > VF ? TC - VF : 0";
1771 break;
1773 O << "VF * Part +";
1774 break;
1776 O << "branch-on-count";
1777 break;
1779 O << "broadcast";
1780 break;
1782 O << "buildstructvector";
1783 break;
1785 O << "buildvector";
1786 break;
1788 O << "exiting-iv-value";
1789 break;
1791 O << "masked-cond";
1792 break;
1794 O << "extract-lane";
1795 break;
1797 O << "extract-last-lane";
1798 break;
1800 O << "extract-last-part";
1801 break;
1803 O << "extract-penultimate-element";
1804 break;
1806 O << "compute-reduction-result";
1807 break;
1809 O << "logical-and";
1810 break;
1812 O << "logical-or";
1813 break;
1815 O << "ptradd";
1816 break;
1818 O << "wide-ptradd";
1819 break;
1821 O << "any-of";
1822 break;
1824 O << "first-active-lane";
1825 break;
1827 O << "last-active-lane";
1828 break;
1830 O << "reduction-start-vector";
1831 break;
1833 O << "resume-for-epilogue";
1834 break;
1836 O << "reverse";
1837 break;
1839 O << "unpack";
1840 break;
1842 O << "extract-last-active";
1843 break;
1845 O << "num-active-lanes";
1846 break;
1847 default:
1849 }
1850
1851 printFlags(O);
1853}
1854#endif
1855
1857 Type *ResultTy = getResultType();
1859 Value *Op = State.get(getOperand(0), VPLane(0));
1860 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1861 Op, ResultTy);
1862 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
1863 applyFlags(*CastOp);
1864 applyMetadata(*CastOp);
1865 }
1866 State.set(this, Cast, VPLane(0));
1867 return;
1868 }
1869 switch (getOpcode()) {
1871 Value *StepVector =
1872 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1873 State.set(this, StepVector);
1874 break;
1875 }
1878 for (VPValue *Op : drop_end(operands()))
1879 Args.push_back(State.get(Op, /*IsSingleScalar=*/true));
1880 Value *Call =
1881 State.Builder.CreateIntrinsic(ResultTy, vputils::getIntrinsicID(this),
1882 Args, /*FMFSource=*/nullptr, getName());
1883 State.set(this, Call, true);
1884 break;
1885 }
1886
1887 default:
1888 llvm_unreachable("opcode not implemented yet");
1889 }
1890}
1891
1893 VPCostContext &Ctx) const {
1894 // NOTE: At the moment it seems only possible to expose this path for
1895 // the trunc, zext and sext opcodes. However, isScalarCast also covers
1896 // int<>fp conversions, bitcasts, ptr<>int conversions, etc.
1899 Ctx);
1900
1901 switch (getOpcode()) {
1903 // TODO: This isn't quite right since even if the step-vector is hoisted
1904 // out of the loop it has a non-zero cost in the middle block, etc.
1905 // Once the stepvector is correctly hoisted out of the vector loop by the
1906 // licm transform we can add the cost here so that it doesn't incorrectly
1907 // affect the choice of VF.
1908 return 0;
1910 Type *Ty = getScalarType();
1912 for (const VPValue *Op : drop_end(operands()))
1913 ArgTys.push_back(Op->getScalarType());
1914 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1915 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1916 }
1917 default:
1918 // Although VPInstructionWithType is also used for
1919 // VPInstruction::WideIVStep it isn't currently possible to expose cases
1920 // where the cost is queried.
1921 llvm_unreachable("Unhandled opcode");
1922 }
1923 return 0;
1924}
1925
1926#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1928 VPSlotTracker &SlotTracker) const {
1929 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1931 O << " = ";
1932
1933 Type *ResultTy = getResultType();
1934 switch (getOpcode()) {
1936 O << "wide-iv-step ";
1938 break;
1940 O << "step-vector " << *ResultTy;
1941 break;
1943 O << "call " << *ResultTy << " @"
1946 Op->printAsOperand(O, SlotTracker);
1947 });
1948 O << ")";
1949 break;
1950 }
1951 case Instruction::Load:
1952 O << "load ";
1954 break;
1955 default:
1956 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1958 printFlags(O);
1960 O << " to " << *ResultTy;
1961 }
1962}
1963#endif
1964
1965/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
1966/// adds incoming values, and stores the result in State. For header phis, only
1967/// the preheader incoming value is added; the backedge is fixed up later by
1968/// VPlan::execute().
1970 VPTransformState &State, bool IsScalar,
1971 const Twine &Name) {
1972 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
1973 ? 1
1974 : Phi.getNumIncoming();
1975 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
1976 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
1977 NewPhi->addIncoming(FirstInc,
1978 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
1979 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
1980 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
1981 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
1982 State.set(R, NewPhi, IsScalar);
1983}
1984
1986 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
1987}
1988
1989#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1990void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1991 VPSlotTracker &SlotTracker) const {
1992 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1994 O << " = phi";
1995 printFlags(O);
1997}
1998#endif
1999
2000VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
2001 if (auto *Phi = dyn_cast<PHINode>(&I))
2002 return new VPIRPhi(*Phi);
2003 return new VPIRInstruction(I);
2004}
2005
2007 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
2008 "PHINodes must be handled by VPIRPhi");
2009 // Advance the insert point after the wrapped IR instruction. This allows
2010 // interleaving VPIRInstructions and other recipes.
2011 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
2012}
2013
2015 VPCostContext &Ctx) const {
2016 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2017 // hence it does not contribute to the cost-modeling for the VPlan.
2018 return 0;
2019}
2020
2021#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2023 VPSlotTracker &SlotTracker) const {
2024 O << Indent << "IR " << I;
2025}
2026#endif
2027
2029 PHINode *Phi = &getIRPhi();
2030 for (const auto &[Idx, Op] : enumerate(operands())) {
2031 VPValue *ExitValue = Op;
2032 auto Lane = vputils::isSingleScalar(ExitValue)
2034 : VPLane::getLastLaneForVF(State.VF);
2035 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2036 auto *PredVPBB = Pred->getExitingBasicBlock();
2037 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2038 // Set insertion point in PredBB in case an extract needs to be generated.
2039 // TODO: Model extracts explicitly.
2040 State.Builder.SetInsertPoint(PredBB->getTerminator());
2041 Value *V = State.get(ExitValue, VPLane(Lane));
2042 // If there is no existing block for PredBB in the phi, add a new incoming
2043 // value. Otherwise update the existing incoming value for PredBB.
2044 if (Phi->getBasicBlockIndex(PredBB) == -1)
2045 Phi->addIncoming(V, PredBB);
2046 else
2047 Phi->setIncomingValueForBlock(PredBB, V);
2048 }
2049
2050 // Advance the insert point after the wrapped IR instruction. This allows
2051 // interleaving VPIRInstructions and other recipes.
2052 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
2053}
2054
2056 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2057 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2058 "Number of phi operands must match number of predecessors");
2059 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2060 R->removeOperand(Position);
2061}
2062
2063VPValue *
2065 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2066 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2067}
2068
2070 VPValue *V) const {
2071 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2072 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2073}
2074
2075#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2077 VPSlotTracker &SlotTracker) const {
2079 O << "[ ";
2080 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2081 O << ", ";
2082 std::get<1>(Op)->printAsOperand(O);
2083 O << " ]";
2084 });
2085}
2086#endif
2087
2088#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2090 VPSlotTracker &SlotTracker) const {
2092
2093 if (getNumOperands() != 0) {
2094 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2096 [&O, &SlotTracker](auto Op) {
2097 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2098 O << " from ";
2099 std::get<1>(Op)->printAsOperand(O);
2100 });
2101 O << ")";
2102 }
2103}
2104#endif
2105
2107 for (const auto &[Kind, Node] : Metadata)
2108 I.setMetadata(Kind, Node);
2109}
2110
2112 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
2113 for (const auto &[KindA, MDA] : Metadata) {
2114 for (const auto &[KindB, MDB] : Other.Metadata) {
2115 if (KindA == KindB && MDA == MDB) {
2116 MetadataIntersection.emplace_back(KindA, MDA);
2117 break;
2118 }
2119 }
2120 }
2121 Metadata = std::move(MetadataIntersection);
2122}
2123
2124#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2126 const Module *M = SlotTracker.getModule();
2127 if (Metadata.empty() || !M || !VPlanPrintMetadata)
2128 return;
2129
2130 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2131 O << " (";
2132 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2133 auto [Kind, Node] = KindNodePair;
2134 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2135 "Unexpected unnamed metadata kind");
2136 O << "!" << MDNames[Kind] << " ";
2137 Node->printAsOperand(O, M);
2138 });
2139 O << ")";
2140}
2141#endif
2142
2144 assert(State.VF.isVector() && "not widening");
2145 assert(Variant != nullptr && "Can't create vector function.");
2146
2147 FunctionType *VFTy = Variant->getFunctionType();
2148 // Add return type if intrinsic is overloaded on it.
2150 for (const auto &I : enumerate(args())) {
2151 Value *Arg;
2152 // Some vectorized function variants may also take a scalar argument,
2153 // e.g. linear parameters for pointers. This needs to be the scalar value
2154 // from the start of the respective part when interleaving.
2155 if (!VFTy->getParamType(I.index())->isVectorTy())
2156 Arg = State.get(I.value(), VPLane(0));
2157 else
2158 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2159 Args.push_back(Arg);
2160 }
2161
2164 if (CI)
2165 CI->getOperandBundlesAsDefs(OpBundles);
2166
2167 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
2168 applyFlags(*V);
2169 applyMetadata(*V);
2170 V->setCallingConv(Variant->getCallingConv());
2171
2172 if (!V->getType()->isVoidTy())
2173 State.set(this, V);
2174}
2175
2177 VPCostContext &Ctx) const {
2178 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2179 "Variant return type must match VF");
2180 return computeCallCost(Variant, Ctx);
2181}
2182
2184 VPCostContext &Ctx) {
2185 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2186 Variant->getFunctionType()->params(),
2187 Ctx.CostKind);
2188}
2189
2191 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2192 assert(Variant && "Variant not set");
2193 FunctionType *VFTy = Variant->getFunctionType();
2194 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2195 auto [Idx, V] = Arg;
2196 Type *ArgTy = VFTy->getParamType(Idx);
2197 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2198 ArgTy->isPointerTy() || ArgTy->isByteTy();
2199 });
2200}
2201
2202#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2204 VPSlotTracker &SlotTracker) const {
2205 O << Indent << "WIDEN-CALL ";
2206
2207 Function *CalledFn = getCalledScalarFunction();
2208 if (CalledFn->getReturnType()->isVoidTy())
2209 O << "void ";
2210 else {
2212 O << " = ";
2213 }
2214
2215 O << "call";
2216 printFlags(O);
2217 O << " @" << CalledFn->getName() << "(";
2218 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
2219 Op->printAsOperand(O, SlotTracker);
2220 });
2221 O << ")";
2222
2223 O << " (using library function";
2224 if (Variant->hasName())
2225 O << ": " << Variant->getName();
2226 O << ")";
2227}
2228#endif
2229
2231 assert(State.VF.isVector() && "not widening");
2232
2233 SmallVector<Type *, 2> TysForDecl;
2234 // Add return type if intrinsic is overloaded on it.
2235 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2236 State.TTI)) {
2237 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2238 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2239 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2241 Idx, State.TTI))
2242 TysForDecl.push_back(Ty);
2243 }
2244 }
2246 for (const auto &I : enumerate(operands())) {
2247 // Some intrinsics have a scalar argument - don't replace it with a
2248 // vector.
2249 Value *Arg;
2250 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2251 State.TTI))
2252 Arg = State.get(I.value(), VPLane(0));
2253 else
2254 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2255 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2256 State.TTI))
2257 TysForDecl.push_back(Arg->getType());
2258 Args.push_back(Arg);
2259 }
2260
2261 // Use vector version of the intrinsic.
2262 Module *M = State.Builder.GetInsertBlock()->getModule();
2263 Function *VectorF =
2264 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2265 assert(VectorF &&
2266 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2267
2270 if (CI)
2271 CI->getOperandBundlesAsDefs(OpBundles);
2272
2273 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
2274
2275 applyFlags(*V);
2276 applyMetadata(*V);
2277
2278 return V;
2279}
2280
2282 CallInst *V = createVectorCall(State);
2283 if (!V->getType()->isVoidTy())
2284 State.set(this, V);
2285}
2286
2289 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2290 Type *ScalarRetTy = R.getScalarType();
2291 // Skip the reverse operation cost for the mask.
2292 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2293 // by VPlanTransforms::cse before cost computation.
2294 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2295 return InstructionCost(0);
2296
2297 // Some backends analyze intrinsic arguments to determine cost. Use the
2298 // underlying value for the operand if it has one. Otherwise try to use the
2299 // operand of the underlying call instruction, if there is one. Otherwise
2300 // clear Arguments.
2301 // TODO: Rework TTI interface to be independent of concrete IR values.
2303 for (const auto &[Idx, Op] : enumerate(Operands)) {
2304 auto *V = Op->getUnderlyingValue();
2305 if (!V) {
2306 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2307 Arguments.push_back(UI->getArgOperand(Idx));
2308 continue;
2309 }
2310 Arguments.clear();
2311 break;
2312 }
2313 Arguments.push_back(V);
2314 }
2315
2316 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2317 SmallVector<Type *> ParamTys =
2318 map_to_vector(Operands, [&](const VPValue *Op) {
2319 return toVectorTy(Op->getScalarType(), VF);
2320 });
2321
2322 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2323 IntrinsicCostAttributes CostAttrs(
2324 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2325 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2327 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2328}
2329
2331 VPCostContext &Ctx) const {
2332 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2333}
2334
2336 return Intrinsic::getBaseName(VectorIntrinsicID);
2337}
2338
2340 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2341 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2342 auto [Idx, V] = X;
2344 Idx, nullptr);
2345 });
2346}
2347
2348#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2350 VPSlotTracker &SlotTracker) const {
2351 O << Indent << "WIDEN-INTRINSIC ";
2352 if (getScalarType()->isVoidTy()) {
2353 O << "void ";
2354 } else {
2356 O << " = ";
2357 }
2358
2359 O << "call";
2360 printFlags(O);
2361 O << getIntrinsicName() << "(";
2363 O << ")";
2364}
2365#endif
2366
2368 CallInst *MemI = createVectorCall(State);
2369 MemI->addParamAttr(
2370 0, Attribute::getWithAlignment(MemI->getContext(), Alignment));
2371 State.set(this, MemI);
2372}
2373
2375 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2376 VPCostContext &Ctx) {
2377 return Ctx.TTI.getMemIntrinsicInstrCost(
2378 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2379 Ctx.CostKind);
2380}
2381
2384 VPCostContext &Ctx) const {
2385 Type *Ty = toVectorTy(getScalarType(), VF);
2387 !match(getOperand(2), m_True()), Alignment,
2388 Ctx);
2389}
2390
2392 IRBuilderBase &Builder = State.Builder;
2393
2394 Value *Address = State.get(getOperand(0));
2395 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2396 VectorType *VTy = cast<VectorType>(Address->getType());
2397
2398 // The histogram intrinsic requires a mask even if the recipe doesn't;
2399 // if the mask operand was omitted then all lanes should be executed and
2400 // we just need to synthesize an all-true mask.
2401 Value *Mask = nullptr;
2402 if (VPValue *VPMask = getMask())
2403 Mask = State.get(VPMask);
2404 else
2405 Mask =
2406 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2407
2408 // If this is a subtract, we want to invert the increment amount. We may
2409 // add a separate intrinsic in future, but for now we'll try this.
2410 if (Opcode == Instruction::Sub)
2411 IncAmt = Builder.CreateNeg(IncAmt);
2412 else
2413 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2414
2415 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2416 Intrinsic::experimental_vector_histogram_add, {VTy, IncAmt->getType()},
2417 {Address, IncAmt, Mask});
2418 applyMetadata(*HistogramInst);
2419}
2420
2422 VPCostContext &Ctx) const {
2423 // FIXME: Take the gather and scatter into account as well. For now we're
2424 // generating the same cost as the fallback path, but we'll likely
2425 // need to create a new TTI method for determining the cost, including
2426 // whether we can use base + vec-of-smaller-indices or just
2427 // vec-of-pointers.
2428 assert(VF.isVector() && "Invalid VF for histogram cost");
2429 Type *AddressTy = getOperand(0)->getScalarType();
2430 VPValue *IncAmt = getOperand(1);
2431 Type *IncTy = IncAmt->getScalarType();
2432 VectorType *VTy = VectorType::get(IncTy, VF);
2433
2434 // Assume that a non-constant update value (or a constant != 1) requires
2435 // a multiply, and add that into the cost.
2436 InstructionCost MulCost =
2437 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2438 if (match(IncAmt, m_One()))
2439 MulCost = TTI::TCC_Free;
2440
2441 // Find the cost of the histogram operation itself.
2442 Type *PtrTy = VectorType::get(AddressTy, VF);
2443 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2444 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2445 Type::getVoidTy(Ctx.LLVMCtx),
2446 {PtrTy, IncTy, MaskTy});
2447
2448 // Add the costs together with the add/sub operation.
2449 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2450 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2451}
2452
2453#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2455 VPSlotTracker &SlotTracker) const {
2456 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2458
2459 if (Opcode == Instruction::Sub)
2460 O << ", dec: ";
2461 else {
2462 assert(Opcode == Instruction::Add);
2463 O << ", inc: ";
2464 }
2466
2467 if (VPValue *Mask = getMask()) {
2468 O << ", mask: ";
2469 Mask->printAsOperand(O, SlotTracker);
2470 }
2471}
2472#endif
2473
2474VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2475 AllowReassoc = FMF.allowReassoc();
2476 NoNaNs = FMF.noNaNs();
2477 NoInfs = FMF.noInfs();
2478 NoSignedZeros = FMF.noSignedZeros();
2479 AllowReciprocal = FMF.allowReciprocal();
2480 AllowContract = FMF.allowContract();
2481 ApproxFunc = FMF.approxFunc();
2482}
2483
2485 switch (Opcode) {
2486 case Instruction::Add:
2487 case Instruction::Sub:
2488 case Instruction::Mul:
2489 case Instruction::Shl:
2491 return WrapFlagsTy(false, false);
2492 case Instruction::Trunc:
2493 return TruncFlagsTy(false, false);
2494 case Instruction::Or:
2495 return DisjointFlagsTy(false);
2496 case Instruction::AShr:
2497 case Instruction::LShr:
2498 case Instruction::UDiv:
2499 case Instruction::SDiv:
2500 return ExactFlagsTy(false);
2501 case Instruction::GetElementPtr:
2504 return GEPNoWrapFlags::none();
2505 case Instruction::ZExt:
2506 case Instruction::UIToFP:
2507 return NonNegFlagsTy(false);
2508 case Instruction::FAdd:
2509 case Instruction::FSub:
2510 case Instruction::FMul:
2511 case Instruction::FDiv:
2512 case Instruction::FRem:
2513 case Instruction::FNeg:
2514 case Instruction::FPExt:
2515 case Instruction::FPTrunc:
2516 return FastMathFlags();
2517 case Instruction::ICmp:
2518 case Instruction::FCmp:
2520 llvm_unreachable("opcode requires explicit flags");
2521 default:
2522 return VPIRFlags();
2523 }
2524}
2525
2526#if !defined(NDEBUG)
2527bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2528 switch (OpType) {
2529 case OperationType::OverflowingBinOp:
2530 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2531 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2532 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2533 case OperationType::Trunc:
2534 return Opcode == Instruction::Trunc;
2535 case OperationType::DisjointOp:
2536 return Opcode == Instruction::Or;
2537 case OperationType::PossiblyExactOp:
2538 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2539 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2540 case OperationType::GEPOp:
2541 return Opcode == Instruction::GetElementPtr ||
2542 Opcode == VPInstruction::PtrAdd ||
2543 Opcode == VPInstruction::WidePtrAdd;
2544 case OperationType::FPMathOp:
2545 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2546 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2547 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2548 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2549 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2550 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2551 Opcode == Instruction::UIToFP ||
2552 Opcode == VPInstruction::WideIVStep ||
2554 case OperationType::FCmp:
2555 return Opcode == Instruction::FCmp;
2556 case OperationType::NonNegOp:
2557 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2558 case OperationType::Cmp:
2559 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2560 case OperationType::ReductionOp:
2562 case OperationType::Other:
2563 return true;
2564 }
2565 llvm_unreachable("Unknown OperationType enum");
2566}
2567
2568bool VPIRFlags::hasRequiredFlagsForOpcode(unsigned Opcode) const {
2569 // Handle opcodes without default flags.
2570 if (Opcode == Instruction::ICmp)
2571 return OpType == OperationType::Cmp;
2572 if (Opcode == Instruction::FCmp)
2573 return OpType == OperationType::FCmp;
2575 return OpType == OperationType::ReductionOp;
2576
2577 OperationType Required = getDefaultFlags(Opcode).OpType;
2578 return Required == OperationType::Other || Required == OpType;
2579}
2580#endif
2581
2582#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2583static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2584 switch (Kind) {
2585 case RecurKind::None:
2586 OS << "none";
2587 break;
2588 case RecurKind::Add:
2589 OS << "add";
2590 break;
2591 case RecurKind::Sub:
2592 OS << "sub";
2593 break;
2595 OS << "add-chain-with-subs";
2596 break;
2597 case RecurKind::Mul:
2598 OS << "mul";
2599 break;
2600 case RecurKind::Or:
2601 OS << "or";
2602 break;
2603 case RecurKind::And:
2604 OS << "and";
2605 break;
2606 case RecurKind::Xor:
2607 OS << "xor";
2608 break;
2609 case RecurKind::SMin:
2610 OS << "smin";
2611 break;
2612 case RecurKind::SMax:
2613 OS << "smax";
2614 break;
2615 case RecurKind::UMin:
2616 OS << "umin";
2617 break;
2618 case RecurKind::UMax:
2619 OS << "umax";
2620 break;
2621 case RecurKind::FAdd:
2622 OS << "fadd";
2623 break;
2625 OS << "fadd-chain-with-subs";
2626 break;
2627 case RecurKind::FSub:
2628 OS << "fsub";
2629 break;
2630 case RecurKind::FMul:
2631 OS << "fmul";
2632 break;
2633 case RecurKind::FMin:
2634 OS << "fmin";
2635 break;
2636 case RecurKind::FMax:
2637 OS << "fmax";
2638 break;
2639 case RecurKind::FMinNum:
2640 OS << "fminnum";
2641 break;
2642 case RecurKind::FMaxNum:
2643 OS << "fmaxnum";
2644 break;
2646 OS << "fminimum";
2647 break;
2649 OS << "fmaximum";
2650 break;
2652 OS << "fminimumnum";
2653 break;
2655 OS << "fmaximumnum";
2656 break;
2657 case RecurKind::FMulAdd:
2658 OS << "fmuladd";
2659 break;
2660 case RecurKind::AnyOf:
2661 OS << "any-of";
2662 break;
2663 case RecurKind::FindIV:
2664 OS << "find-iv";
2665 break;
2667 OS << "find-last";
2668 break;
2669 }
2670}
2671
2673 switch (OpType) {
2674 case OperationType::Cmp:
2676 break;
2677 case OperationType::FCmp:
2680 break;
2681 case OperationType::DisjointOp:
2682 if (DisjointFlags.IsDisjoint)
2683 O << " disjoint";
2684 break;
2685 case OperationType::PossiblyExactOp:
2686 if (ExactFlags.IsExact)
2687 O << " exact";
2688 break;
2689 case OperationType::OverflowingBinOp:
2690 if (WrapFlags.HasNUW)
2691 O << " nuw";
2692 if (WrapFlags.HasNSW)
2693 O << " nsw";
2694 break;
2695 case OperationType::Trunc:
2696 if (TruncFlags.HasNUW)
2697 O << " nuw";
2698 if (TruncFlags.HasNSW)
2699 O << " nsw";
2700 break;
2701 case OperationType::FPMathOp:
2703 break;
2704 case OperationType::GEPOp: {
2706 if (Flags.isInBounds())
2707 O << " inbounds";
2708 else if (Flags.hasNoUnsignedSignedWrap())
2709 O << " nusw";
2710 if (Flags.hasNoUnsignedWrap())
2711 O << " nuw";
2712 break;
2713 }
2714 case OperationType::NonNegOp:
2715 if (NonNegFlags.NonNeg)
2716 O << " nneg";
2717 break;
2718 case OperationType::ReductionOp: {
2719 O << " (";
2721 if (isReductionInLoop())
2722 O << ", in-loop";
2723 if (isReductionOrdered())
2724 O << ", ordered";
2725 O << ")";
2727 break;
2728 }
2729 case OperationType::Other:
2730 break;
2731 }
2732 O << " ";
2733}
2734#endif
2735
2737 auto &Builder = State.Builder;
2738 switch (Opcode) {
2739 case Instruction::Call:
2740 case Instruction::UncondBr:
2741 case Instruction::CondBr:
2742 case Instruction::PHI:
2743 case Instruction::GetElementPtr:
2744 llvm_unreachable("This instruction is handled by a different recipe.");
2745 case Instruction::UDiv:
2746 case Instruction::SDiv:
2747 case Instruction::SRem:
2748 case Instruction::URem:
2749 case Instruction::Add:
2750 case Instruction::FAdd:
2751 case Instruction::Sub:
2752 case Instruction::FSub:
2753 case Instruction::FNeg:
2754 case Instruction::Mul:
2755 case Instruction::FMul:
2756 case Instruction::FDiv:
2757 case Instruction::FRem:
2758 case Instruction::Shl:
2759 case Instruction::LShr:
2760 case Instruction::AShr:
2761 case Instruction::And:
2762 case Instruction::Or:
2763 case Instruction::Xor: {
2764 // Just widen unops and binops.
2766 for (VPValue *VPOp : operands())
2767 Ops.push_back(State.get(VPOp));
2768
2769 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2770
2771 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2772 applyFlags(*VecOp);
2773 applyMetadata(*VecOp);
2774 }
2775
2776 // Use this vector value for all users of the original instruction.
2777 State.set(this, V);
2778 break;
2779 }
2780 case Instruction::ExtractValue: {
2781 assert(getNumOperands() == 2 && "expected single level extractvalue");
2782 Value *Op = State.get(getOperand(0));
2783 Value *Extract = Builder.CreateExtractValue(
2784 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2785 State.set(this, Extract);
2786 break;
2787 }
2788 case Instruction::Freeze: {
2789 Value *Op = State.get(getOperand(0));
2790 Value *Freeze = Builder.CreateFreeze(Op);
2791 State.set(this, Freeze);
2792 break;
2793 }
2794 case Instruction::ICmp:
2795 case Instruction::FCmp: {
2796 // Widen compares. Generate vector compares.
2797 bool FCmp = Opcode == Instruction::FCmp;
2798 Value *A = State.get(getOperand(0));
2799 Value *B = State.get(getOperand(1));
2800 Value *C = nullptr;
2801 if (FCmp) {
2802 C = Builder.CreateFCmp(getPredicate(), A, B);
2803 } else {
2804 C = Builder.CreateICmp(getPredicate(), A, B);
2805 }
2806 if (auto *I = dyn_cast<Instruction>(C)) {
2807 applyFlags(*I);
2808 applyMetadata(*I);
2809 }
2810 State.set(this, C);
2811 break;
2812 }
2813 case Instruction::Select: {
2814 VPValue *CondOp = getOperand(0);
2815 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2816 Value *Op0 = State.get(getOperand(1));
2817 Value *Op1 = State.get(getOperand(2));
2818 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2819 State.set(this, Sel);
2820 if (auto *I = dyn_cast<Instruction>(Sel)) {
2822 applyFlags(*I);
2823 applyMetadata(*I);
2824 }
2825 break;
2826 }
2827 default:
2828 // This instruction is not vectorized by simple widening.
2829 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2830 << Instruction::getOpcodeName(Opcode));
2831 llvm_unreachable("Unhandled instruction!");
2832 } // end of switch.
2833
2834#if !defined(NDEBUG)
2835 // Verify that VPlan type inference results agree with the type of the
2836 // generated values.
2837 assert(VectorType::get(this->getScalarType(), State.VF) ==
2838 State.get(this)->getType() &&
2839 "inferred type and type from generated instructions do not match");
2840#endif
2841}
2842
2844 VPCostContext &Ctx) const {
2845 switch (Opcode) {
2846 case Instruction::UDiv:
2847 case Instruction::SDiv:
2848 case Instruction::SRem:
2849 case Instruction::URem:
2850 // If the div/rem operation isn't safe to speculate and requires
2851 // predication, then the only way we can even create a vplan is to insert
2852 // a select on the second input operand to ensure we use the value of 1
2853 // for the inactive lanes. The select will be costed separately.
2854 case Instruction::FNeg:
2855 case Instruction::Add:
2856 case Instruction::FAdd:
2857 case Instruction::Sub:
2858 case Instruction::FSub:
2859 case Instruction::Mul:
2860 case Instruction::FMul:
2861 case Instruction::FDiv:
2862 case Instruction::FRem:
2863 case Instruction::Shl:
2864 case Instruction::LShr:
2865 case Instruction::AShr:
2866 case Instruction::And:
2867 case Instruction::Or:
2868 case Instruction::Xor:
2869 case Instruction::Freeze:
2870 case Instruction::ExtractValue:
2871 case Instruction::ICmp:
2872 case Instruction::FCmp:
2873 case Instruction::Select:
2874 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2875 default:
2876 llvm_unreachable("Unsupported opcode for instruction");
2877 }
2878}
2879
2880#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2882 VPSlotTracker &SlotTracker) const {
2883 O << Indent << "WIDEN ";
2885 O << " = " << Instruction::getOpcodeName(Opcode);
2886 printFlags(O);
2888}
2889#endif
2890
2892 auto &Builder = State.Builder;
2893 /// Vectorize casts.
2894 assert(State.VF.isVector() && "Not vectorizing?");
2895 Type *DestTy = VectorType::get(getScalarType(), State.VF);
2896 VPValue *Op = getOperand(0);
2897 Value *A = State.get(Op);
2898 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2899 State.set(this, Cast);
2900 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2901 applyFlags(*CastOp);
2902 applyMetadata(*CastOp);
2903 }
2904}
2905
2910
2911#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2913 VPSlotTracker &SlotTracker) const {
2914 O << Indent << "WIDEN-CAST ";
2916 O << " = " << Instruction::getOpcodeName(Opcode);
2917 printFlags(O);
2919 O << " to " << *getScalarType();
2920}
2921#endif
2922
2924 VPCostContext &Ctx) const {
2925 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2926}
2927
2928#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2930 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2931 O << Indent;
2933 O << " = WIDEN-INDUCTION";
2934 printFlags(O);
2936
2937 if (auto *TI = getTruncInst())
2938 O << " (truncated to " << *TI->getType() << ")";
2939}
2940#endif
2941
2943 // The step may be defined by a recipe in the preheader (e.g. if it requires
2944 // SCEV expansion), but for the canonical induction the step is required to be
2945 // 1, which is represented as live-in.
2946 return match(getStartValue(), m_ZeroInt()) &&
2947 match(getStepValue(), m_One()) &&
2948 getScalarType() == getRegion()->getCanonicalIVType();
2949}
2950
2952 VPCostContext &Ctx) const {
2953 // The cost model for this is modelled on expandVPDerivedIV in
2954 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
2955 // negatively affect vectorization it takes into account any expected
2956 // simplifications that happen in simplifyRecipe.
2957 switch (getInductionKind()) {
2958 default:
2959 // TODO: Compute cost for remaining kinds.
2960 break;
2962 // There are currently no tests that expose a path where all lanes are
2963 // used, so it's better to bail out for now.
2964 if (!vputils::onlyFirstLaneUsed(this))
2965 break;
2966
2967 // Start off by assuming we need both mul and add, then refine this.
2968 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
2969
2970 // If the start value is zero the add gets folded away.
2971 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
2972 NeedsAdd = !StartC->isZero();
2973
2974 // For some values of step the arithmetic changes:
2975 // 1. A step of 1 requires no operation.
2976 // 2. A step of -1 requires a negate.
2977 // 3. A power-of-2 step will use a shl, instead of a mul.
2978 Type *StepTy = getStepValue()->getScalarType();
2980 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
2981 if (StepC->isOne())
2982 NeedsMul = false;
2983 else if (StepC->getAPInt().isAllOnes()) {
2984 // This will most likely end up as a negate in simplifyRecipe, and
2985 // the negate will be combined with the add to make a sub.
2986 // NOTE: This is perhaps an invalid assumption that the cost of an
2987 // 'add' is the same as a 'sub'.
2988 NeedsMul = false;
2989 NeedsAdd = true;
2990 } else if (StepC->getAPInt().isPowerOf2()) {
2991 // This will most likely end up as a shift-left in simplifyRecipe
2992 NeedsMul = false;
2993 NeedsShl = true;
2994 }
2995 }
2996
2997 // Add the cost of the conversion from index to step type if the index
2998 // will be used.
2999 Type *IndexTy = getIndex()->getScalarType();
3000 unsigned StepTySize = StepTy->getScalarSizeInBits();
3001 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
3002 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3003 unsigned CastOpc =
3004 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::SExt;
3005 Cost += Ctx.TTI.getCastInstrCost(
3006 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3007 }
3008
3009 if (NeedsMul)
3010 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3011 Ctx.CostKind);
3012 if (NeedsShl)
3013 Cost += Ctx.TTI.getArithmeticInstrCost(
3014 Instruction::Shl, StepTy, Ctx.CostKind,
3015 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3016 {TargetTransformInfo::OK_UniformConstantValue,
3017 TargetTransformInfo::OP_None});
3018 if (NeedsAdd)
3019 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3020 Ctx.CostKind);
3021 return Cost;
3022 }
3023 }
3024
3025 return 0;
3026}
3027
3028#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3030 VPSlotTracker &SlotTracker) const {
3031 O << Indent;
3033 O << " = DERIVED-IV ";
3034 getStartValue()->printAsOperand(O, SlotTracker);
3035 O << " + ";
3036 getOperand(1)->printAsOperand(O, SlotTracker);
3037 O << " * ";
3038 getStepValue()->printAsOperand(O, SlotTracker);
3039}
3040#endif
3041
3043 VPCostContext &Ctx) const {
3044 // TODO: Add costs for floating point.
3045 Type *BaseIVTy = getOperand(0)->getScalarType();
3046 if (!BaseIVTy->isIntegerTy())
3047 return 0;
3048
3049 // TODO: Add support for predicated regions. Requires scaling the cost by the
3050 // probability of entering the block.
3051 if (getRegion() && getRegion()->isReplicator())
3052 return 0;
3053
3054 // If only the first lane is used, then there won't be any code that remains
3055 // in the loop for the first unrolled part.
3057 return 0;
3058
3059 // Typically the operations are:
3060 // 1. Add the start index to each lane value.
3061 // 2. Multiply the start index by the step.
3062 // 3. Add the scaled start index to base IV.
3063 // Any code generated for 1 and 2 should be loop invariant and therefore
3064 // hoisted out of the loop. We only need to add on the cost of 3.
3065
3066 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3067 // %add1 = add i32 %iv, 0
3068 // %add2 = add i32 %iv, 1
3069 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3070 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3071 // it's very likely that these GEPs will all be rewritten to have a common
3072 // base such that what's left is just
3073 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3074 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3075 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3076 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3077 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3078 return Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3079 Ctx.CostKind);
3080}
3081
3083 // Fast-math-flags propagate from the original induction instruction.
3084 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3085 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3086
3087 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3088 /// variable on which to base the steps, \p Step is the size of the step.
3089
3090 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3091 Value *Step = State.get(getStepValue(), VPLane(0));
3092 IRBuilderBase &Builder = State.Builder;
3093
3094 // Ensure step has the same type as that of scalar IV.
3095 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3096 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3097
3098 // We build scalar steps for both integer and floating-point induction
3099 // variables. Here, we determine the kind of arithmetic we will perform.
3102 if (BaseIVTy->isIntegerTy()) {
3103 AddOp = Instruction::Add;
3104 MulOp = Instruction::Mul;
3105 } else {
3106 AddOp = InductionOpcode;
3107 MulOp = Instruction::FMul;
3108 }
3109
3110 // Determine the number of scalars we need to generate.
3111 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
3112 // Compute the scalar steps and save the results in State.
3113
3114 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
3115 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
3116 : Constant::getNullValue(BaseIVTy);
3117
3118 for (unsigned Lane = 0; Lane < EndLane; ++Lane) {
3119 // It is okay if the induction variable type cannot hold the lane number,
3120 // we expect truncation in this case.
3121 Constant *LaneValue =
3122 BaseIVTy->isIntegerTy()
3123 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
3124 /*ImplicitTrunc=*/true)
3125 : ConstantFP::get(BaseIVTy, Lane);
3126 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
3127 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
3128 "Expected StartIdx to be folded to a constant when VF is not "
3129 "scalable");
3130 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3131 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3132 State.set(this, Add, VPLane(Lane));
3133 }
3134}
3135
3136#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3138 VPSlotTracker &SlotTracker) const {
3139 O << Indent;
3141 O << " = SCALAR-STEPS ";
3143}
3144#endif
3145
3147 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3149}
3150
3152 assert(State.VF.isVector() && "not widening");
3153 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3154 return State.get(Op, vputils::isSingleScalar(Op));
3155 });
3156 auto *GEP =
3157 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3158 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3159 State.set(this, GEP, vputils::isSingleScalar(this));
3160}
3161
3162#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3164 VPSlotTracker &SlotTracker) const {
3165 O << Indent << "WIDEN-GEP ";
3167 O << " = getelementptr";
3168 printFlags(O);
3170}
3171#endif
3172
3174 assert(!getOffset() && "Unexpected offset operand");
3175 VPBuilder Builder(this);
3176 VPlan &Plan = *getParent()->getPlan();
3177 VPValue *VFVal = getVFValue();
3178 const DataLayout &DL = Plan.getDataLayout();
3179 Type *IndexTy = DL.getIndexType(this->getScalarType());
3180 VPValue *Stride =
3181 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3182 Type *VFTy = VFVal->getScalarType();
3183 VPValue *VF = Builder.createScalarZExtOrTrunc(VFVal, IndexTy, VFTy,
3185
3186 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3187 VPInstruction *VFMinusOne =
3188 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3189 DebugLoc::getUnknown(), "", {true, true});
3190 VPInstruction *Offset0 =
3191 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3192
3193 // Offset for PartN = Offset0 + Part * Stride * VF.
3194 VPValue *PartxStride =
3195 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3196 VPValue *Offset = Builder.createAdd(
3197 Offset0,
3198 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3200}
3201
3203 auto &Builder = State.Builder;
3204 assert(getOffset() && "Expected prior materialization of offset");
3205 Value *Ptr = State.get(getPointer(), true);
3206 Value *Offset = State.get(getOffset(), true);
3207 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3209 State.set(this, ResultPtr, /*IsScalar*/ true);
3210}
3211
3212#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3214 VPSlotTracker &SlotTracker) const {
3215 O << Indent;
3217 O << " = vector-end-pointer";
3218 printFlags(O);
3220}
3221#endif
3222
3224 assert(getVFxPart() &&
3225 "Expected prior simplification of recipe without VFxPart");
3226
3227 auto &Builder = State.Builder;
3228 Value *Ptr = State.get(getOperand(0), VPLane(0));
3229 Value *Offset = State.get(getVFxPart(), true);
3230 // TODO: Expand to VPInstruction to support constant folding.
3231 if (!match(getStride(), m_One())) {
3232 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3233 Offset->getType());
3234 Offset = Builder.CreateMul(Offset, Stride);
3235 }
3236 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3238 State.set(this, ResultPtr, /*IsScalar*/ true);
3239}
3240
3241#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3243 VPSlotTracker &SlotTracker) const {
3244 O << Indent;
3246 O << " = vector-pointer";
3247 printFlags(O);
3249}
3250#endif
3251
3253 VPCostContext &Ctx) const {
3254 // A blend will be expanded to a select VPInstruction, which will generate a
3255 // scalar select if only the first lane is used.
3257 VF = ElementCount::getFixed(1);
3258
3259 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3260 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3261 return (getNumIncomingValues() - 1) *
3262 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3263 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
3264}
3265
3266#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3268 VPSlotTracker &SlotTracker) const {
3269 O << Indent << "BLEND ";
3271 O << " =";
3272 printFlags(O);
3273 if (getNumIncomingValues() == 1) {
3274 // Not a User of any mask: not really blending, this is a
3275 // single-predecessor phi.
3276 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3277 } else {
3278 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3279 if (I != 0)
3280 O << " ";
3281 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3282 if (I == 0 && isNormalized())
3283 continue;
3284 O << "/";
3285 getMask(I)->printAsOperand(O, SlotTracker);
3286 }
3287 }
3288}
3289#endif
3290
3294 "In-loop AnyOf reductions aren't currently supported");
3295 // Propagate the fast-math flags carried by the underlying instruction.
3296 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3297 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3298 Value *NewVecOp = State.get(getVecOp());
3299 if (VPValue *Cond = getCondOp()) {
3300 Value *NewCond = State.get(Cond, State.VF.isScalar());
3301 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3302 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3303
3304 Value *Start =
3306 if (State.VF.isVector())
3307 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3308
3309 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3310 NewVecOp = Select;
3311 }
3312 Value *NewRed;
3313 Value *NextInChain;
3314 if (isOrdered()) {
3315 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3316 if (State.VF.isVector())
3317 NewRed =
3318 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3319 else
3320 NewRed = State.Builder.CreateBinOp(
3322 PrevInChain, NewVecOp);
3323 PrevInChain = NewRed;
3324 NextInChain = NewRed;
3325 } else if (isPartialReduction()) {
3326 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3327 "Unexpected partial reduction kind");
3328 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
3329 NewRed = State.Builder.CreateIntrinsic(
3330 PrevInChain->getType(),
3331 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3332 : Intrinsic::vector_partial_reduce_fadd,
3333 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3334 "partial.reduce");
3335 PrevInChain = NewRed;
3336 NextInChain = NewRed;
3337 } else {
3338 assert(isInLoop() &&
3339 "The reduction must either be ordered, partial or in-loop");
3340 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3341 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3343 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3344 else
3345 NextInChain = State.Builder.CreateBinOp(
3347 PrevInChain, NewRed);
3348 }
3349 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3350}
3351
3353
3354 auto &Builder = State.Builder;
3355 // Propagate the fast-math flags carried by the underlying instruction.
3356 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3357 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3358
3360 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
3361 Value *VecOp = State.get(getVecOp());
3362 Value *EVL = State.get(getEVL(), VPLane(0));
3363
3364 Value *Mask;
3365 if (VPValue *CondOp = getCondOp())
3366 Mask = State.get(CondOp);
3367 else
3368 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3369
3370 Value *NewRed;
3371 if (isOrdered()) {
3372 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3373 } else {
3374 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3376 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3377 else
3378 NewRed = Builder.CreateBinOp(
3380 Prev);
3381 }
3382 State.set(this, NewRed, /*IsScalar*/ true);
3383}
3384
3386 VPCostContext &Ctx) const {
3387 RecurKind RdxKind = getRecurrenceKind();
3388 Type *ElementTy = this->getScalarType();
3389 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3390 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3392 std::optional<FastMathFlags> OptionalFMF =
3393 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3394
3395 if (isPartialReduction()) {
3396 InstructionCost CondCost = 0;
3397 if (isConditional()) {
3399 auto *CondTy =
3401 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3402 CondTy, Pred, Ctx.CostKind);
3403 }
3404 return CondCost + Ctx.TTI.getPartialReductionCost(
3405 Opcode, ElementTy, ElementTy, ElementTy, VF,
3406 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3407 OptionalFMF);
3408 }
3409
3410 // TODO: Support any-of reductions.
3411 assert(
3413 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
3414 "Any-of reduction not implemented in VPlan-based cost model currently.");
3415
3416 // Note that TTI should model the cost of moving result to the scalar register
3417 // and the BinOp cost in the getMinMaxReductionCost().
3420 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3421 }
3422
3423 // Note that TTI should model the cost of moving result to the scalar register
3424 // and the BinOp cost in the getArithmeticReductionCost().
3425 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3426 Ctx.CostKind);
3427}
3428
3429VPExpressionRecipe::VPExpressionRecipe(
3430 ExpressionTypes ExpressionType,
3431 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3432 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3433 cast<VPReductionRecipe>(ExpressionRecipes.back())
3434 ->getChainOp()
3435 ->getScalarType()),
3436 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3437 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3438 assert(
3439 none_of(ExpressionRecipes,
3440 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3441 "expression cannot contain recipes with side-effects");
3442
3443 // Maintain a copy of the expression recipes as a set of users.
3444 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3445 for (auto *R : ExpressionRecipes)
3446 ExpressionRecipesAsSetOfUsers.insert(R);
3447
3448 // Recipes in the expression, except the last one, must only be used by
3449 // (other) recipes inside the expression. If there are other users, external
3450 // to the expression, use a clone of the recipe for external users.
3451 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3452 if (R != ExpressionRecipes.back() &&
3453 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3454 return !ExpressionRecipesAsSetOfUsers.contains(U);
3455 })) {
3456 // There are users outside of the expression. Clone the recipe and use the
3457 // clone those external users.
3458 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3459 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
3460 VPUser &U, unsigned) {
3461 return !ExpressionRecipesAsSetOfUsers.contains(&U);
3462 });
3463 CopyForExtUsers->insertBefore(R);
3464 }
3465 if (R->getParent())
3466 R->removeFromParent();
3467 }
3468
3469 // Internalize all external operands to the expression recipes. To do so,
3470 // create new temporary VPValues for all operands defined by a recipe outside
3471 // the expression. The original operands are added as operands of the
3472 // VPExpressionRecipe itself.
3473 for (auto *R : ExpressionRecipes) {
3474 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3475 auto *Def = Op->getDefiningRecipe();
3476 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3477 continue;
3478 addOperand(Op);
3479 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3480 }
3481 }
3482
3483 // Replace each external operand with the first one created for it in
3484 // LiveInPlaceholders.
3485 for (auto *R : ExpressionRecipes)
3486 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3487 R->replaceUsesOfWith(LiveIn, Tmp);
3488}
3489
3491 for (auto *R : ExpressionRecipes)
3492 // Since the list could contain duplicates, make sure the recipe hasn't
3493 // already been inserted.
3494 if (!R->getParent())
3495 R->insertBefore(this);
3496
3497 for (const auto &[Idx, Op] : enumerate(operands()))
3498 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3499
3500 replaceAllUsesWith(ExpressionRecipes.back());
3501 ExpressionRecipes.clear();
3502}
3503
3505 VPCostContext &Ctx) const {
3506 Type *RedTy = this->getScalarType();
3507 auto *SrcVecTy =
3509 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3510 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3511 switch (ExpressionType) {
3512 case ExpressionTypes::NegatedExtendedReduction:
3513 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3514 "Unexpected opcode");
3515 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3516 [[fallthrough]];
3517 case ExpressionTypes::ExtendedReduction: {
3518 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3519 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3520
3521 if (RedR->isPartialReduction())
3522 return Ctx.TTI.getPartialReductionCost(
3523 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3525 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3526 RedTy->isFloatingPointTy()
3527 ? std::optional{RedR->getFastMathFlagsOrNone()}
3528 : std::nullopt);
3529 else if (!RedTy->isFloatingPointTy())
3530 // TTI::getExtendedReductionCost only supports integer types.
3531 return Ctx.TTI.getExtendedReductionCost(
3532 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3533 std::nullopt, Ctx.CostKind);
3534 else
3536 }
3537 case ExpressionTypes::MulAccReduction:
3538 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3539 Ctx.CostKind);
3540
3541 case ExpressionTypes::ExtNegatedMulAccReduction:
3542 switch (Opcode) {
3543 case Instruction::Add:
3544 Opcode = Instruction::Sub;
3545 break;
3546 case Instruction::FAdd:
3547 Opcode = Instruction::FSub;
3548 break;
3549 default:
3550 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3551 }
3552 [[fallthrough]];
3553 case ExpressionTypes::ExtMulAccReduction: {
3554 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3555 if (RedR->isPartialReduction()) {
3556 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3557 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3558 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3559 return Ctx.TTI.getPartialReductionCost(
3560 Opcode, getOperand(0)->getScalarType(),
3561 getOperand(1)->getScalarType(), RedTy, VF,
3563 Ext0R->getOpcode()),
3565 Ext1R->getOpcode()),
3566 Mul->getOpcode(), Ctx.CostKind,
3567 RedTy->isFloatingPointTy()
3568 ? std::optional{RedR->getFastMathFlagsOrNone()}
3569 : std::nullopt);
3570 }
3571 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3572 return Ctx.TTI.getMulAccReductionCost(
3573 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3574 Instruction::ZExt,
3575 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3576 }
3577 }
3578 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3579}
3580
3582 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3583 return R->mayReadFromMemory() || R->mayWriteToMemory();
3584 });
3585}
3586
3588 assert(
3589 none_of(ExpressionRecipes,
3590 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3591 "expression cannot contain recipes with side-effects");
3592 return false;
3593}
3594
3596 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3597 return RR && !RR->isPartialReduction();
3598}
3599
3600#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3601
3603 VPSlotTracker &SlotTracker) const {
3604 O << Indent << "EXPRESSION ";
3606 O << " = ";
3607 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3608 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3609 VPValue *RdxStart =
3610 getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1));
3611
3612 switch (ExpressionType) {
3613 case ExpressionTypes::NegatedExtendedReduction:
3614 case ExpressionTypes::ExtendedReduction: {
3615 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
3617 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3618 O << Instruction::getOpcodeName(Opcode) << " (";
3619 if (Negated)
3620 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
3622 if (Negated)
3623 O << ")";
3624 Red->printFlags(O);
3625
3626 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3627 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3628 << *Ext0->getScalarType();
3629 if (Red->isConditional()) {
3630 O << ", ";
3632 }
3633 O << ")";
3634 break;
3635 }
3636 case ExpressionTypes::ExtNegatedMulAccReduction: {
3637 RdxStart->printAsOperand(O, SlotTracker);
3638 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3640 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3641 << " (sub (0, mul";
3642 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3643 Mul->printFlags(O);
3644 O << "(";
3646 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3647 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3648 << *Ext0->getScalarType() << "), (";
3650 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3651 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3652 << *Ext1->getScalarType() << ")";
3653 if (Red->isConditional()) {
3654 O << ", ";
3656 }
3657 O << "))";
3658 break;
3659 }
3660 case ExpressionTypes::MulAccReduction:
3661 case ExpressionTypes::ExtMulAccReduction: {
3662 RdxStart->printAsOperand(O, SlotTracker);
3663 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3665 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3666 << " (";
3667 O << "mul";
3668 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3669 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3670 : ExpressionRecipes[0]);
3671 Mul->printFlags(O);
3672 if (IsExtended)
3673 O << "(";
3675 if (IsExtended) {
3676 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3677 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3678 << *Ext0->getScalarType() << "), (";
3679 } else {
3680 O << ", ";
3681 }
3683 if (IsExtended) {
3684 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3685 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3686 << *Ext1->getScalarType() << ")";
3687 }
3688 if (Red->isConditional()) {
3689 O << ", ";
3691 }
3692 O << ")";
3693 break;
3694 }
3695 }
3696}
3697
3699 VPSlotTracker &SlotTracker) const {
3700 if (isPartialReduction())
3701 O << Indent << "PARTIAL-REDUCE ";
3702 else
3703 O << Indent << "REDUCE ";
3705 O << " = ";
3707 O << " +";
3708 printFlags(O);
3709 O << " reduce.";
3711 O << " (";
3713 if (isConditional()) {
3714 O << ", ";
3716 }
3717 O << ")";
3718}
3719
3721 VPSlotTracker &SlotTracker) const {
3722 O << Indent << "REDUCE ";
3724 O << " = ";
3726 O << " +";
3727 printFlags(O);
3728 O << " vp.reduce."
3731 << " (";
3733 O << ", ";
3735 if (isConditional()) {
3736 O << ", ";
3738 }
3739 O << ")";
3740}
3741
3742#endif
3743
3745 assert(IsSingleScalar &&
3746 "VPReplicateRecipes must be unrolled before ::execute");
3747 auto *Instr = getUnderlyingInstr();
3748 Instruction *Cloned = Instr->clone();
3749 Type *ResultTy = getScalarType();
3750 if (!ResultTy->isVoidTy()) {
3751 Cloned->setName(Instr->getName() + ".cloned");
3752 // The operands of the replicate recipe may have been narrowed, resulting in
3753 // a narrower result type. Update the type of the cloned instruction to the
3754 // correct type.
3755 if (ResultTy != Cloned->getType())
3756 Cloned->mutateType(ResultTy);
3757 }
3758
3759 applyFlags(*Cloned);
3760 applyMetadata(*Cloned);
3761
3762 if (hasPredicate())
3763 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
3764
3765 // Replace the operands of the cloned instructions with their scalar
3766 // equivalents in the new loop.
3767 for (const auto &[Idx, V] : enumerate(operands()))
3768 Cloned->setOperand(Idx, State.get(V, true));
3769
3770 // Place the cloned scalar in the new loop.
3771 State.Builder.Insert(Cloned);
3772
3773 State.set(this, Cloned, true);
3774
3775 // If we just cloned a new assumption, add it the assumption cache.
3776 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3777 State.AC->registerAssumption(II);
3778}
3779
3780/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3781/// which the legacy cost model computes a SCEV expression when computing the
3782/// address cost. Computing SCEVs for VPValues is incomplete and returns
3783/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3784/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3785static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3787 const Loop *L) {
3788 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3789 if (isa<SCEVCouldNotCompute>(Addr))
3790 return Addr;
3791
3792 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3793}
3794
3796 VPCostContext &Ctx) const {
3798 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3799 // transform, avoid computing their cost multiple times for now.
3800 Ctx.SkipCostComputation.insert(UI);
3801
3802 if (VF.isScalable() && !isSingleScalar())
3804
3805 switch (UI->getOpcode()) {
3806 case Instruction::Alloca:
3807 if (VF.isScalable())
3809 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
3810 this->getScalarType(), Ctx.CostKind);
3811 case Instruction::GetElementPtr:
3812 // We mark this instruction as zero-cost because the cost of GEPs in
3813 // vectorized code depends on whether the corresponding memory instruction
3814 // is scalarized or not. Therefore, we handle GEPs with the memory
3815 // instruction cost.
3816 return 0;
3817 case Instruction::Call: {
3818 auto *CalledFn =
3820 Type *ResultTy = this->getScalarType();
3821 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
3822 isSingleScalar(), VF, Ctx);
3823 }
3824 case Instruction::Add:
3825 case Instruction::Sub:
3826 case Instruction::FAdd:
3827 case Instruction::FSub:
3828 case Instruction::Mul:
3829 case Instruction::FMul:
3830 case Instruction::FDiv:
3831 case Instruction::FRem:
3832 case Instruction::Shl:
3833 case Instruction::LShr:
3834 case Instruction::AShr:
3835 case Instruction::And:
3836 case Instruction::Or:
3837 case Instruction::Xor:
3838 case Instruction::ICmp:
3839 case Instruction::FCmp:
3841 Ctx) *
3842 (isSingleScalar() ? 1 : VF.getFixedValue());
3843 case Instruction::SDiv:
3844 case Instruction::UDiv:
3845 case Instruction::SRem:
3846 case Instruction::URem: {
3847 InstructionCost ScalarCost =
3849 if (isSingleScalar())
3850 return ScalarCost;
3851
3852 // If any of the operands is from a different replicate region and has its
3853 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3854 // model to avoid cost mis-match.
3855 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3856 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3857 if (!PredR)
3858 return false;
3859 return Ctx.skipCostComputation(
3861 PredR->getOperand(0)->getUnderlyingValue()),
3862 VF.isVector());
3863 }))
3864 break;
3865
3866 ScalarCost = ScalarCost * VF.getFixedValue() +
3867 Ctx.getScalarizationOverhead(this->getScalarType(),
3868 to_vector(operands()), VF);
3869 // If the recipe is not predicated (i.e. not in a replicate region), return
3870 // the scalar cost. Otherwise handle predicated cost.
3871 if (!getRegion()->isReplicator())
3872 return ScalarCost;
3873
3874 // Account for the phi nodes that we will create.
3875 ScalarCost += VF.getFixedValue() *
3876 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3877 // Scale the cost by the probability of executing the predicated blocks.
3878 // This assumes the predicated block for each vector lane is equally
3879 // likely.
3880 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3881 return ScalarCost;
3882 }
3883 case Instruction::Load:
3884 case Instruction::Store: {
3885 bool IsLoad = UI->getOpcode() == Instruction::Load;
3886 const VPValue *PtrOp = getOperand(!IsLoad);
3887 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3889 break;
3890
3891 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
3892 Type *ScalarPtrTy = PtrOp->getScalarType();
3893 const Align Alignment = getLoadStoreAlignment(UI);
3894 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3896 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3897 bool UsedByLoadStoreAddress =
3898 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
3899 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3900 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3901 UsedByLoadStoreAddress ? UI : nullptr);
3902
3903 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3904 InstructionCost ScalarCost =
3905 ScalarMemOpCost +
3906 Ctx.TTI.getAddressComputationCost(
3907 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3908 Ctx.CostKind);
3909 if (isSingleScalar())
3910 return ScalarCost;
3911
3912 SmallVector<const VPValue *> OpsToScalarize;
3913 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3914 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3915 // don't assign scalarization overhead in general, if the target prefers
3916 // vectorized addressing or the loaded value is used as part of an address
3917 // of another load or store.
3918 if (!UsedByLoadStoreAddress) {
3919 bool EfficientVectorLoadStore =
3920 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3921 if (!(IsLoad && !PreferVectorizedAddressing) &&
3922 !(!IsLoad && EfficientVectorLoadStore))
3923 append_range(OpsToScalarize, operands());
3924
3925 if (!EfficientVectorLoadStore)
3926 ResultTy = this->getScalarType();
3927 }
3928
3932 (ScalarCost * VF.getFixedValue()) +
3933 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3934
3935 const VPRegionBlock *ParentRegion = getRegion();
3936 if (ParentRegion && ParentRegion->isReplicator()) {
3937 if (!PtrSCEV)
3938 break;
3939 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3940 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
3941
3942 auto *VecI1Ty = VectorType::get(
3943 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3944 Cost += Ctx.TTI.getScalarizationOverhead(
3945 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3946 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3947
3948 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3949 // Artificially setting to a high enough value to practically disable
3950 // vectorization with such operations.
3951 return 3000000;
3952 }
3953 }
3954 return Cost;
3955 }
3956 case Instruction::SExt:
3957 case Instruction::ZExt:
3958 case Instruction::FPToUI:
3959 case Instruction::FPToSI:
3960 case Instruction::FPExt:
3961 case Instruction::PtrToInt:
3962 case Instruction::PtrToAddr:
3963 case Instruction::IntToPtr:
3964 case Instruction::SIToFP:
3965 case Instruction::UIToFP:
3966 case Instruction::Trunc:
3967 case Instruction::FPTrunc:
3968 case Instruction::Select:
3969 case Instruction::AddrSpaceCast: {
3971 Ctx) *
3972 (isSingleScalar() ? 1 : VF.getFixedValue());
3973 }
3974 case Instruction::ExtractValue:
3975 case Instruction::InsertValue:
3976 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3977 }
3978
3979 return Ctx.getLegacyCost(UI, VF);
3980}
3981
3983 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
3984 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
3986 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
3987
3988 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
3989 auto GetIntrinsicCost = [&] {
3990 if (!IntrinID)
3992 return Ctx.TTI.getIntrinsicInstrCost(
3993 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
3994 };
3995
3996 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
3997 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
3998 return 0;
3999 }
4000
4001 InstructionCost ScalarCallCost =
4002 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4003 if (IsSingleScalar) {
4004 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4005 return ScalarCallCost;
4006 }
4007
4008 // Scalarization overhead is undefined for scalable VFs.
4009 if (VF.isScalable())
4011
4012 return ScalarCallCost * VF.getFixedValue() +
4013 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4014}
4015
4016#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4018 VPSlotTracker &SlotTracker) const {
4019 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4020
4021 if (!getScalarType()->isVoidTy()) {
4023 O << " = ";
4024 }
4025 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4026 O << "call";
4027 printFlags(O);
4028 O << "@" << CB->getCalledFunction()->getName() << "(";
4030 Op->printAsOperand(O, SlotTracker);
4031 });
4032 O << ")";
4033 } else {
4035 printFlags(O);
4037 }
4038
4039 // Find if the recipe is used by a widened recipe via an intervening
4040 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4041 if (any_of(users(), [](const VPUser *U) {
4042 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4043 return !vputils::onlyScalarValuesUsed(PredR);
4044 return false;
4045 }))
4046 O << " (S->V)";
4047}
4048#endif
4049
4051 llvm_unreachable("recipe must be removed when dissolving replicate region");
4052}
4053
4055 VPCostContext &Ctx) const {
4056 // The legacy cost model doesn't assign costs to branches for individual
4057 // replicate regions. Match the current behavior in the VPlan cost model for
4058 // now.
4059 return 0;
4060}
4061
4063 llvm_unreachable("recipe must be removed when dissolving replicate region");
4064}
4065
4066#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4068 VPSlotTracker &SlotTracker) const {
4069 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4071 O << " = ";
4073}
4074#endif
4075
4077const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4078
4081
4083const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4084
4087
4089 VPCostContext &Ctx) const {
4090 const VPRecipeBase *R = getAsRecipe();
4092 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4093 : R->getOperand(1)->getScalarType();
4094 Type *Ty = toVectorTy(ScalarTy, VF);
4095 unsigned AS =
4096 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4097 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4098
4099 if (!Consecutive) {
4100 // TODO: Using the original IR may not be accurate.
4101 // Currently, ARM will use the underlying IR to calculate gather/scatter
4102 // instruction cost.
4103 Type *PtrTy = getAddr()->getScalarType();
4104 const Value *Ptr = getAddr()->getUnderlyingValue();
4105
4106 // If the address value is uniform across all lanes, then the address can be
4107 // calculated with scalar type and broadcast.
4109 PtrTy = toVectorTy(PtrTy, VF);
4110
4111 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4112 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4113 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4114 : Intrinsic::vp_scatter;
4115 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4116 Ctx.CostKind) +
4117 Ctx.TTI.getMemIntrinsicInstrCost(
4119 &Ingredient),
4120 Ctx.CostKind);
4121 }
4122
4124 if (IsMasked) {
4125 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4126 : Intrinsic::masked_store;
4127 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4128 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4129 } else {
4130 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4132 : R->getOperand(1));
4133 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4134 OpInfo, &Ingredient);
4135 }
4136 return Cost;
4137}
4138
4140 Type *ScalarDataTy = getScalarType();
4141 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4142 bool CreateGather = !isConsecutive();
4143
4144 auto &Builder = State.Builder;
4145 Value *Mask = nullptr;
4146 if (auto *VPMask = getMask())
4147 Mask = State.get(VPMask);
4148
4149 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
4150 Value *NewLI;
4151 if (CreateGather) {
4152 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4153 "wide.masked.gather");
4154 } else if (Mask) {
4155 NewLI =
4156 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4157 PoisonValue::get(DataTy), "wide.masked.load");
4158 } else {
4159 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4160 }
4162 State.set(this, NewLI);
4163}
4164
4165#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4167 VPSlotTracker &SlotTracker) const {
4168 O << Indent << "WIDEN ";
4170 O << " = load ";
4172}
4173#endif
4174
4176 Type *ScalarDataTy = getScalarType();
4177 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4178 bool CreateGather = !isConsecutive();
4179
4180 auto &Builder = State.Builder;
4181 CallInst *NewLI;
4182 Value *EVL = State.get(getEVL(), VPLane(0));
4183 Value *Addr = State.get(getAddr(), !CreateGather);
4184 Value *Mask = nullptr;
4185 if (VPValue *VPMask = getMask())
4186 Mask = State.get(VPMask);
4187 else
4188 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4189
4190 if (CreateGather) {
4191 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4192 {Addr, Mask, EVL}, nullptr,
4193 "wide.masked.gather");
4194 } else {
4195 NewLI = Builder.CreateIntrinsicWithoutFolding(
4196 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4197 }
4198 NewLI->addParamAttr(
4200 applyMetadata(*NewLI);
4201 State.set(this, NewLI);
4202}
4203
4205 VPCostContext &Ctx) const {
4206 if (!Consecutive || IsMasked)
4207 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4208
4209 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4210 // here because the EVL recipes using EVL to replace the tail mask. But in the
4211 // legacy model, it will always calculate the cost of mask.
4212 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4213 // don't need to compare to the legacy cost model.
4214 Type *Ty = toVectorTy(getScalarType(), VF);
4215 unsigned AS =
4216 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4217 return Ctx.TTI.getMemIntrinsicInstrCost(
4218 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4219 Ctx.CostKind);
4220}
4221
4222#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4224 VPSlotTracker &SlotTracker) const {
4225 O << Indent << "WIDEN ";
4227 O << " = vp.load ";
4229}
4230#endif
4231
4233 VPValue *StoredVPValue = getStoredValue();
4234 bool CreateScatter = !isConsecutive();
4235
4236 auto &Builder = State.Builder;
4237
4238 Value *Mask = nullptr;
4239 if (auto *VPMask = getMask())
4240 Mask = State.get(VPMask);
4241
4242 Value *StoredVal = State.get(StoredVPValue);
4243 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
4244 Instruction *NewSI = nullptr;
4245 if (CreateScatter)
4246 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4247 else if (Mask)
4248 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4249 else
4250 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4251 applyMetadata(*NewSI);
4252}
4253
4254#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4256 VPSlotTracker &SlotTracker) const {
4257 O << Indent << "WIDEN store ";
4259}
4260#endif
4261
4263 VPValue *StoredValue = getStoredValue();
4264 bool CreateScatter = !isConsecutive();
4265
4266 auto &Builder = State.Builder;
4267
4268 CallInst *NewSI = nullptr;
4269 Value *StoredVal = State.get(StoredValue);
4270 Value *EVL = State.get(getEVL(), VPLane(0));
4271 Value *Mask = nullptr;
4272 if (VPValue *VPMask = getMask())
4273 Mask = State.get(VPMask);
4274 else
4275 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4276
4277 Value *Addr = State.get(getAddr(), !CreateScatter);
4278 if (CreateScatter) {
4279 NewSI = Builder.CreateIntrinsicWithoutFolding(
4280 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4281 {StoredVal, Addr, Mask, EVL});
4282 } else {
4283 NewSI = Builder.CreateIntrinsicWithoutFolding(
4284 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4285 {StoredVal, Addr, Mask, EVL});
4286 }
4287 NewSI->addParamAttr(
4289 applyMetadata(*NewSI);
4290}
4291
4293 VPCostContext &Ctx) const {
4294 if (!Consecutive || IsMasked)
4295 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4296
4297 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4298 // here because the EVL recipes using EVL to replace the tail mask. But in the
4299 // legacy model, it will always calculate the cost of mask.
4300 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4301 // don't need to compare to the legacy cost model.
4302 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4303 unsigned AS =
4304 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4305 return Ctx.TTI.getMemIntrinsicInstrCost(
4306 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4307 Ctx.CostKind);
4308}
4309
4310#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4312 VPSlotTracker &SlotTracker) const {
4313 O << Indent << "WIDEN vp.store ";
4315}
4316#endif
4317
4319 VectorType *DstVTy, const DataLayout &DL) {
4320 // Verify that V is a vector type with same number of elements as DstVTy.
4321 auto VF = DstVTy->getElementCount();
4322 auto *SrcVecTy = cast<VectorType>(V->getType());
4323 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4324 Type *SrcElemTy = SrcVecTy->getElementType();
4325 Type *DstElemTy = DstVTy->getElementType();
4326 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4327 "Vector elements must have same size");
4328
4329 // Do a direct cast if element types are castable.
4330 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4331 return Builder.CreateBitOrPointerCast(V, DstVTy);
4332 }
4333 // V cannot be directly casted to desired vector type.
4334 // May happen when V is a floating point vector but DstVTy is a vector of
4335 // pointers or vice-versa. Handle this using a two-step bitcast using an
4336 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4337 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4338 "Only one type should be a pointer type");
4339 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4340 "Only one type should be a floating point type");
4341 Type *IntTy =
4342 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4343 auto *VecIntTy = VectorType::get(IntTy, VF);
4344 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4345 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4346}
4347
4348/// Return a vector containing interleaved elements from multiple
4349/// smaller input vectors.
4351 const Twine &Name) {
4352 unsigned Factor = Vals.size();
4353 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4354
4355 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4356#ifndef NDEBUG
4357 for (Value *Val : Vals)
4358 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4359#endif
4360
4361 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4362 // must use intrinsics to interleave.
4363 if (VecTy->isScalableTy()) {
4364 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4365 return Builder.CreateVectorInterleave(Vals, Name);
4366 }
4367
4368 // Fixed length. Start by concatenating all vectors into a wide vector.
4369 Value *WideVec = concatenateVectors(Builder, Vals);
4370
4371 // Interleave the elements into the wide vector.
4372 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4373 return Builder.CreateShuffleVector(
4374 WideVec, createInterleaveMask(NumElts, Factor), Name);
4375}
4376
4377// Try to vectorize the interleave group that \p Instr belongs to.
4378//
4379// E.g. Translate following interleaved load group (factor = 3):
4380// for (i = 0; i < N; i+=3) {
4381// R = Pic[i]; // Member of index 0
4382// G = Pic[i+1]; // Member of index 1
4383// B = Pic[i+2]; // Member of index 2
4384// ... // do something to R, G, B
4385// }
4386// To:
4387// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4388// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4389// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4390// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4391//
4392// Or translate following interleaved store group (factor = 3):
4393// for (i = 0; i < N; i+=3) {
4394// ... do something to R, G, B
4395// Pic[i] = R; // Member of index 0
4396// Pic[i+1] = G; // Member of index 1
4397// Pic[i+2] = B; // Member of index 2
4398// }
4399// To:
4400// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4401// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4402// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4403// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4404// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4406 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4407 "Masking gaps for scalable vectors is not yet supported.");
4409 Instruction *Instr = Group->getInsertPos();
4410
4411 // Prepare for the vector type of the interleaved load/store.
4412 Type *ScalarTy = getLoadStoreType(Instr);
4413 unsigned InterleaveFactor = Group->getFactor();
4414 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4415
4416 VPValue *BlockInMask = getMask();
4417 VPValue *Addr = getAddr();
4418 Value *ResAddr = State.get(Addr, VPLane(0));
4419
4420 auto CreateGroupMask = [&BlockInMask, &State,
4421 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4422 if (State.VF.isScalable()) {
4423 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4424 assert(InterleaveFactor <= 8 &&
4425 "Unsupported deinterleave factor for scalable vectors");
4426 auto *ResBlockInMask = State.get(BlockInMask);
4427 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4428 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4429 }
4430
4431 if (!BlockInMask)
4432 return MaskForGaps;
4433
4434 Value *ResBlockInMask = State.get(BlockInMask);
4435 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4436 ResBlockInMask,
4437 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4438 "interleaved.mask");
4439 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4440 ShuffledMask, MaskForGaps)
4441 : ShuffledMask;
4442 };
4443
4444 const DataLayout &DL = Instr->getDataLayout();
4445 // Vectorize the interleaved load group.
4446 if (isa<LoadInst>(Instr)) {
4447 Value *MaskForGaps = nullptr;
4448 if (needsMaskForGaps()) {
4449 MaskForGaps =
4450 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4451 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4452 }
4453
4454 Instruction *NewLoad;
4455 if (BlockInMask || MaskForGaps) {
4456 Value *GroupMask = CreateGroupMask(MaskForGaps);
4457 Value *PoisonVec = PoisonValue::get(VecTy);
4458 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4459 Group->getAlign(), GroupMask,
4460 PoisonVec, "wide.masked.vec");
4461 } else
4462 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4463 Group->getAlign(), "wide.vec");
4464 applyMetadata(*NewLoad);
4465 // TODO: Also manage existing metadata using VPIRMetadata.
4466 Group->addMetadata(NewLoad);
4467
4469 if (VecTy->isScalableTy()) {
4470 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4471 // so must use intrinsics to deinterleave.
4472 assert(InterleaveFactor <= 8 &&
4473 "Unsupported deinterleave factor for scalable vectors");
4474 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4475 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4476 NewLoad->getType(), NewLoad,
4477 /*FMFSource=*/nullptr, "strided.vec");
4478 }
4479
4480 auto CreateStridedVector = [&InterleaveFactor, &State,
4481 &NewLoad](unsigned Index) -> Value * {
4482 assert(Index < InterleaveFactor && "Illegal group index");
4483 if (State.VF.isScalable())
4484 return State.Builder.CreateExtractValue(NewLoad, Index);
4485
4486 // For fixed length VF, use shuffle to extract the sub-vectors from the
4487 // wide load.
4488 auto StrideMask =
4489 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4490 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4491 "strided.vec");
4492 };
4493
4494 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4495 Instruction *Member = Group->getMember(I);
4496
4497 // Skip the gaps in the group.
4498 if (!Member)
4499 continue;
4500
4501 Value *StridedVec = CreateStridedVector(I);
4502
4503 // If this member has different type, cast the result type.
4504 if (Member->getType() != ScalarTy) {
4505 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4506 StridedVec =
4507 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4508 }
4509
4510 if (Group->isReverse())
4511 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4512
4513 State.set(VPDefs[J], StridedVec);
4514 ++J;
4515 }
4516 return;
4517 }
4518
4519 // The sub vector type for current instruction.
4520 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4521
4522 // Vectorize the interleaved store group.
4523 Value *MaskForGaps =
4524 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4525 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4526 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4527 ArrayRef<VPValue *> StoredValues = getStoredValues();
4528 // Collect the stored vector from each member.
4529 SmallVector<Value *, 4> StoredVecs;
4530 unsigned StoredIdx = 0;
4531 for (unsigned i = 0; i < InterleaveFactor; i++) {
4532 assert((Group->getMember(i) || MaskForGaps) &&
4533 "Fail to get a member from an interleaved store group");
4534 Instruction *Member = Group->getMember(i);
4535
4536 // Skip the gaps in the group.
4537 if (!Member) {
4538 Value *Undef = PoisonValue::get(SubVT);
4539 StoredVecs.push_back(Undef);
4540 continue;
4541 }
4542
4543 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4544 ++StoredIdx;
4545
4546 if (Group->isReverse())
4547 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4548
4549 // If this member has different type, cast it to a unified type.
4550
4551 if (StoredVec->getType() != SubVT)
4552 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4553
4554 StoredVecs.push_back(StoredVec);
4555 }
4556
4557 // Interleave all the smaller vectors into one wider vector.
4558 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4559 Instruction *NewStoreInstr;
4560 if (BlockInMask || MaskForGaps) {
4561 Value *GroupMask = CreateGroupMask(MaskForGaps);
4562 NewStoreInstr = State.Builder.CreateMaskedStore(
4563 IVec, ResAddr, Group->getAlign(), GroupMask);
4564 } else
4565 NewStoreInstr =
4566 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4567
4568 applyMetadata(*NewStoreInstr);
4569 // TODO: Also manage existing metadata using VPIRMetadata.
4570 Group->addMetadata(NewStoreInstr);
4571}
4572
4573#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4575 VPSlotTracker &SlotTracker) const {
4577 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4579 VPValue *Mask = getMask();
4580 if (Mask) {
4581 O << ", ";
4582 Mask->printAsOperand(O, SlotTracker);
4583 }
4584
4585 unsigned OpIdx = 0;
4586 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4587 if (!IG->getMember(i))
4588 continue;
4589 if (getNumStoreOperands() > 0) {
4590 O << "\n" << Indent << " store ";
4592 O << " to index " << i;
4593 } else {
4594 O << "\n" << Indent << " ";
4596 O << " = load from index " << i;
4597 }
4598 ++OpIdx;
4599 }
4600}
4601#endif
4602
4604 assert(State.VF.isScalable() &&
4605 "Only support scalable VF for EVL tail-folding.");
4607 "Masking gaps for scalable vectors is not yet supported.");
4609 Instruction *Instr = Group->getInsertPos();
4610
4611 // Prepare for the vector type of the interleaved load/store.
4612 Type *ScalarTy = getLoadStoreType(Instr);
4613 unsigned InterleaveFactor = Group->getFactor();
4614 assert(InterleaveFactor <= 8 &&
4615 "Unsupported deinterleave/interleave factor for scalable vectors");
4616 ElementCount WideVF = State.VF * InterleaveFactor;
4617 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4618
4619 VPValue *Addr = getAddr();
4620 Value *ResAddr = State.get(Addr, VPLane(0));
4621 Value *EVL = State.get(getEVL(), VPLane(0));
4622 Value *InterleaveEVL = State.Builder.CreateMul(
4623 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4624 /* NUW= */ true, /* NSW= */ true);
4625 LLVMContext &Ctx = State.Builder.getContext();
4626
4627 Value *GroupMask = nullptr;
4628 if (VPValue *BlockInMask = getMask()) {
4629 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4630 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4631 } else {
4632 GroupMask =
4633 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4634 }
4635
4636 // Vectorize the interleaved load group.
4637 if (isa<LoadInst>(Instr)) {
4638 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4639 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4640 "wide.vp.load");
4641 NewLoad->addParamAttr(0,
4642 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4643
4644 applyMetadata(*NewLoad);
4645 // TODO: Also manage existing metadata using VPIRMetadata.
4646 Group->addMetadata(NewLoad);
4647
4648 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4649 // so must use intrinsics to deinterleave.
4650 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4651 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4652 NewLoad->getType(), NewLoad,
4653 /*FMFSource=*/nullptr, "strided.vec");
4654
4655 const DataLayout &DL = Instr->getDataLayout();
4656 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4657 Instruction *Member = Group->getMember(I);
4658 // Skip the gaps in the group.
4659 if (!Member)
4660 continue;
4661
4662 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4663 // If this member has different type, cast the result type.
4664 if (Member->getType() != ScalarTy) {
4665 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4666 StridedVec =
4667 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4668 }
4669
4670 State.set(getVPValue(J), StridedVec);
4671 ++J;
4672 }
4673 return;
4674 } // End for interleaved load.
4675
4676 // The sub vector type for current instruction.
4677 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4678 // Vectorize the interleaved store group.
4679 ArrayRef<VPValue *> StoredValues = getStoredValues();
4680 // Collect the stored vector from each member.
4681 SmallVector<Value *, 4> StoredVecs;
4682 const DataLayout &DL = Instr->getDataLayout();
4683 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4684 Instruction *Member = Group->getMember(I);
4685 // Skip the gaps in the group.
4686 if (!Member) {
4687 StoredVecs.push_back(PoisonValue::get(SubVT));
4688 continue;
4689 }
4690
4691 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4692 // If this member has different type, cast it to a unified type.
4693 if (StoredVec->getType() != SubVT)
4694 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4695
4696 StoredVecs.push_back(StoredVec);
4697 ++StoredIdx;
4698 }
4699
4700 // Interleave all the smaller vectors into one wider vector.
4701 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4702 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
4703 Type::getVoidTy(Ctx), Intrinsic::vp_store,
4704 {IVec, ResAddr, GroupMask, InterleaveEVL});
4705
4706 NewStore->addParamAttr(1,
4707 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4708
4709 applyMetadata(*NewStore);
4710 // TODO: Also manage existing metadata using VPIRMetadata.
4711 Group->addMetadata(NewStore);
4712}
4713
4714#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4716 VPSlotTracker &SlotTracker) const {
4718 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4720 O << ", ";
4722 if (VPValue *Mask = getMask()) {
4723 O << ", ";
4724 Mask->printAsOperand(O, SlotTracker);
4725 }
4726
4727 unsigned OpIdx = 0;
4728 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4729 if (!IG->getMember(i))
4730 continue;
4731 if (getNumStoreOperands() > 0) {
4732 O << "\n" << Indent << " vp.store ";
4734 O << " to index " << i;
4735 } else {
4736 O << "\n" << Indent << " ";
4738 O << " = vp.load from index " << i;
4739 }
4740 ++OpIdx;
4741 }
4742}
4743#endif
4744
4746 VPCostContext &Ctx) const {
4747 Instruction *InsertPos = getInsertPos();
4748 // Find the VPValue index of the interleave group. We need to skip gaps.
4749 unsigned InsertPosIdx = 0;
4750 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4751 if (auto *Member = IG->getMember(Idx)) {
4752 if (Member == InsertPos)
4753 break;
4754 InsertPosIdx++;
4755 }
4756 const VPValue *ValV = getNumDefinedValues() > 0
4757 ? getVPValue(InsertPosIdx)
4758 : getStoredValues()[InsertPosIdx];
4759 Type *ValTy = ValV->getScalarType();
4760 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4761 unsigned AS =
4762 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4763
4764 unsigned InterleaveFactor = IG->getFactor();
4765 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4766
4767 // Holds the indices of existing members in the interleaved group.
4769 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4770 if (IG->getMember(IF))
4771 Indices.push_back(IF);
4772
4773 // Calculate the cost of the whole interleaved group.
4774 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4775 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4776 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4777
4778 if (!IG->isReverse())
4779 return Cost;
4780
4781 return Cost + IG->getNumMembers() *
4782 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4783 VectorTy, VectorTy, {}, Ctx.CostKind,
4784 0);
4785}
4786
4788 return vputils::onlyScalarValuesUsed(this) &&
4789 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4790}
4791
4792#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4794 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4795 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4796 "unexpected number of operands");
4797 O << Indent << "EMIT ";
4799 O << " = WIDEN-POINTER-INDUCTION ";
4801 O << ", ";
4803 O << ", ";
4805 if (getNumOperands() == 5) {
4806 O << ", ";
4808 O << ", ";
4810 }
4811}
4812
4814 VPSlotTracker &SlotTracker) const {
4815 O << Indent << "EMIT ";
4817 O << " = EXPAND SCEV " << *Expr;
4818}
4819#endif
4820
4821#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4823 VPSlotTracker &SlotTracker) const {
4824 O << Indent << "EMIT ";
4826 O << " = WIDEN-CANONICAL-INDUCTION";
4827 printFlags(O);
4829}
4830#endif
4831
4833 auto &Builder = State.Builder;
4834 // Create a vector from the initial value.
4835 auto *VectorInit = getStartValue()->getLiveInIRValue();
4836
4837 Type *VecTy = State.VF.isScalar()
4838 ? VectorInit->getType()
4839 : VectorType::get(VectorInit->getType(), State.VF);
4840
4841 BasicBlock *VectorPH =
4842 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4843 if (State.VF.isVector()) {
4844 auto *IdxTy = Builder.getInt32Ty();
4845 auto *One = ConstantInt::get(IdxTy, 1);
4846 IRBuilder<>::InsertPointGuard Guard(Builder);
4847 Builder.SetInsertPoint(VectorPH->getTerminator());
4848 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4849 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4850 VectorInit = Builder.CreateInsertElement(
4851 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4852 }
4853
4854 // Create a phi node for the new recurrence.
4855 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4856 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4857 Phi->addIncoming(VectorInit, VectorPH);
4858 State.set(this, Phi);
4859}
4860
4863 VPCostContext &Ctx) const {
4864 if (VF.isScalar())
4865 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4866
4867 return 0;
4868}
4869
4870#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4872 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4873 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4875 O << " = phi ";
4877}
4878#endif
4879
4881 // Reductions do not have to start at zero. They can start with
4882 // any loop invariant values.
4883 VPValue *StartVPV = getStartValue();
4884
4885 // In order to support recurrences we need to be able to vectorize Phi nodes.
4886 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4887 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4888 // this value when we vectorize all of the instructions that use the PHI.
4889 BasicBlock *VectorPH =
4890 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4891 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4892 Value *StartV = State.get(StartVPV, ScalarPHI);
4893 Type *VecTy = StartV->getType();
4894
4895 BasicBlock *HeaderBB = State.CFG.PrevBB;
4896 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4897 "recipe must be in the vector loop header");
4898 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4899 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4900 State.set(this, Phi, isInLoop());
4901
4902 Phi->addIncoming(StartV, VectorPH);
4903}
4904
4905#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4907 VPSlotTracker &SlotTracker) const {
4908 O << Indent << "WIDEN-REDUCTION-PHI ";
4909
4911 O << " = phi (";
4912 printRecurrenceKind(O, Kind);
4913 O << ")";
4914 printFlags(O);
4916 if (getVFScaleFactor() > 1)
4917 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4918}
4919#endif
4920
4922 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
4923 return vputils::onlyFirstLaneUsed(this);
4924}
4925
4927 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
4928}
4929
4931 VPCostContext &Ctx) const {
4932 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4933}
4934
4935#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4937 VPSlotTracker &SlotTracker) const {
4938 O << Indent << "WIDEN-PHI ";
4939
4941 O << " = phi ";
4943}
4944#endif
4945
4947 BasicBlock *VectorPH =
4948 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4949 Value *StartMask = State.get(getOperand(0));
4950 PHINode *Phi =
4951 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4952 Phi->addIncoming(StartMask, VectorPH);
4953 State.set(this, Phi);
4954}
4955
4956#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4958 VPSlotTracker &SlotTracker) const {
4959 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4960
4962 O << " = phi ";
4964}
4965#endif
4966
4967#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4969 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4970 O << Indent << "CURRENT-ITERATION-PHI ";
4971
4973 O << " = phi ";
4975}
4976#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
VectorInstrContext
Represents a hint about the context in which an insert/extract is used.
@ None
The insert/extract is not used with a load/store.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
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.
@ TCC_Free
Expected to fold away in lowering.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Reverse
Reverse the order of the vector.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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:4357
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4410
iterator end()
Definition VPlan.h:4394
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4423
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:2977
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2972
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:2968
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:94
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:222
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:576
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:549
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:561
ArrayRef< VPRecipeValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:571
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4191
VPValue * getIndex() const
Definition VPlan.h:4188
VPValue * getStepValue() const
Definition VPlan.h:4189
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:4187
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:689
FastMathFlagsTy FMFs
Definition VPlan.h:777
ReductionFlagsTy ReductionFlags
Definition VPlan.h:779
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:771
void printFlags(raw_ostream &O) const
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:994
bool isReductionOrdered() const
Definition VPlan.h:1055
TruncFlagsTy TruncFlags
Definition VPlan.h:772
CmpInst::Predicate getPredicate() const
Definition VPlan.h:966
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
ExactFlagsTy ExactFlags
Definition VPlan.h:774
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
uint8_t GEPFlagsStorage
Definition VPlan.h:775
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:984
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:989
DisjointFlagsTy DisjointFlags
Definition VPlan.h:773
FCmpFlagsTy FCmpFlags
Definition VPlan.h:778
NonNegFlagsTy NonNegFlags
Definition VPlan.h:776
bool isReductionInLoop() const
Definition VPlan.h:1061
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:923
uint8_t CmpPredStorage
Definition VPlan.h:770
RecurKind getRecurKind() const
Definition VPlan.h:1049
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:1718
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:1579
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:1217
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 VPInstruction generates scalar values for all lanes.
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1319
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1339
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1310
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1323
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1335
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1313
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1260
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1306
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1255
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1252
@ CanonicalIVIncrementForPart
Definition VPlan.h:1236
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1263
bool hasResult() const
Definition VPlan.h:1429
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:1511
unsigned getOpcode() const
Definition VPlan.h:1408
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 this VPInstruction's operands are single scalars and the result is also a single scal...
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:1454
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:3082
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:3086
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3084
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3076
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3105
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3070
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3179
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:3192
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:3142
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:1598
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:1647
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1607
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:396
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:4748
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.
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:471
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:549
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.
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.
unsigned getVPRecipeID() const
Definition VPlan.h:517
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:461
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:352
friend class VPValue
Definition VPlanValue.h:331
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:3351
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:2883
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2902
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:3293
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:3304
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3306
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3289
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3295
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3302
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3297
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:4582
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4658
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:3431
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:3466
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPScalarIVStepsRecipe.
VPValue * getStepValue() const
Definition VPlan.h:4246
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4254
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:603
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:674
LLVM_ABI_FOR_TEST LLVM_DUMP_METHOD void dump() const
Print this VPSingleDefRecipe to dbgs() (for debugging).
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:605
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:399
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1514
operand_range operands()
Definition VPlanValue.h:472
unsigned getNumOperands() const
Definition VPlanValue.h:439
operand_iterator op_end()
Definition VPlanValue.h:470
operand_iterator op_begin()
Definition VPlanValue.h:468
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:440
void addOperand(VPValue *Operand)
Definition VPlanValue.h:425
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:1465
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:1510
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:1905
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:3727
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3752
Instruction & Ingredient
Definition VPlan.h:3718
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3724
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3762
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3721
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3755
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:1848
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4761
const DataLayout & getDataLayout() const
Definition VPlan.h:4968
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4922
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:5070
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:81
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:573
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
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:1955
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:1776
PHINode & getIRPhi()
Definition VPlan.h:1789
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.
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
VPRecipeWithIRFlags(const unsigned char SC, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1109
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:313
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:3847
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:3949
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:3952
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:3897