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:
683 // Cannot determine the number of operands from the opcode.
684 return -1u;
685 }
686 llvm_unreachable("all cases should be handled above");
687}
688
692
693bool VPInstruction::canGenerateScalarForFirstLane() const {
695 return true;
697 return true;
698 switch (Opcode) {
699 case Instruction::Freeze:
700 case Instruction::ICmp:
701 case Instruction::PHI:
702 case Instruction::Select:
712 return true;
713 default:
714 return false;
715 }
716}
717
719 if (Kind == RecurKind::Sub)
720 return Instruction::Add;
721 if (Kind == RecurKind::FSub)
722 return Instruction::FAdd;
723 llvm_unreachable("RecurKind should be Sub/FSub.");
724}
725
726Value *VPInstruction::generate(VPTransformState &State) {
727 IRBuilderBase &Builder = State.Builder;
728
730 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
731 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
732 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
733 auto *Res =
734 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
735 if (auto *I = dyn_cast<Instruction>(Res))
736 applyFlags(*I);
737 return Res;
738 }
739
740 switch (getOpcode()) {
741 case VPInstruction::Not: {
742 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
743 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
744 return Builder.CreateNot(A, Name);
745 }
746 case Instruction::ExtractElement: {
747 assert(State.VF.isVector() && "Only extract elements from vectors");
748 if (auto *Idx = dyn_cast<VPConstantInt>(getOperand(1)))
749 return State.get(getOperand(0), VPLane(Idx->getZExtValue()));
750 Value *Vec = State.get(getOperand(0));
751 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
752 return Builder.CreateExtractElement(Vec, Idx, Name);
753 }
754 case Instruction::InsertElement: {
755 assert(State.VF.isVector() && "Can only insert elements into vectors");
756 Value *Vec = State.get(getOperand(0), /*IsScalar=*/false);
757 Value *Elt = State.get(getOperand(1), /*IsScalar=*/true);
758 Value *Idx = State.get(getOperand(2), /*IsScalar=*/true);
759 return Builder.CreateInsertElement(Vec, Elt, Idx, Name);
760 }
761 case Instruction::Freeze: {
763 return Builder.CreateFreeze(Op, Name);
764 }
765 case Instruction::FCmp:
766 case Instruction::ICmp: {
767 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
768 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
769 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
770 return Builder.CreateCmp(getPredicate(), A, B, Name);
771 }
772 case Instruction::PHI: {
773 llvm_unreachable("should be handled by VPPhi::execute");
774 }
775 case Instruction::Select: {
776 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
777 Value *Cond =
778 State.get(getOperand(0),
779 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
780 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
781 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
782 return Builder.CreateSelectFMF(Cond, Op1, Op2, getFastMathFlagsOrNone(),
783 Name);
784 }
786 // Get first lane of vector induction variable.
787 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
788 // Get the original loop tripcount.
789 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
790
791 // If this part of the active lane mask is scalar, generate the CMP directly
792 // to avoid unnecessary extracts.
793 if (State.VF.isScalar())
794 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
795 Name);
796
797 ElementCount EC = State.VF.multiplyCoefficientBy(
798 cast<VPConstantInt>(getOperand(2))->getZExtValue());
799 auto *PredTy = VectorType::get(Builder.getInt1Ty(), EC);
800 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
801 {PredTy, ScalarTC->getType()},
802 {VIVElem0, ScalarTC}, nullptr, Name);
803 }
805 Value *Op = State.get(getOperand(0));
806 auto *VecTy = cast<VectorType>(Op->getType());
807 assert(VecTy->getScalarSizeInBits() == 1 &&
808 "NumActiveLanes only implemented for i1 vectors");
809
810 Type *Ty = getScalarType();
811 Value *ZExt = Builder.CreateCast(
812 Instruction::ZExt, Op, VectorType::get(Ty, VecTy->getElementCount()));
813 Value *NumActive =
814 Builder.CreateUnaryIntrinsic(Intrinsic::vector_reduce_add, ZExt);
815 return NumActive;
816 }
818 // Generate code to combine the previous and current values in vector v3.
819 //
820 // vector.ph:
821 // v_init = vector(..., ..., ..., a[-1])
822 // br vector.body
823 //
824 // vector.body
825 // i = phi [0, vector.ph], [i+4, vector.body]
826 // v1 = phi [v_init, vector.ph], [v2, vector.body]
827 // v2 = a[i, i+1, i+2, i+3];
828 // v3 = vector(v1(3), v2(0, 1, 2))
829
830 auto *V1 = State.get(getOperand(0));
831 if (!V1->getType()->isVectorTy())
832 return V1;
833 Value *V2 = State.get(getOperand(1));
834 return Builder.CreateVectorSpliceRight(V1, V2, 1, Name);
835 }
837 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
838 Value *VFxUF = State.get(getOperand(1), VPLane(0));
839 Value *Sub = Builder.CreateSub(ScalarTC, VFxUF);
840 Value *Cmp =
841 Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, VFxUF);
843 return Builder.CreateSelect(Cmp, Sub, Zero);
844 }
846 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
847 // be outside of the main loop.
848 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
849 // Compute EVL
850 assert(AVL->getType()->isIntegerTy() &&
851 "Requested vector length should be an integer.");
852
853 assert(State.VF.isScalable() && "Expected scalable vector factor.");
854 Value *VFArg = Builder.getInt32(State.VF.getKnownMinValue());
855
856 Value *EVL = Builder.CreateIntrinsic(
857 Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
858 {AVL, VFArg, Builder.getTrue()});
859 return EVL;
860 }
862 Value *Cond = State.get(getOperand(0), VPLane(0));
863 // Replace the temporary unreachable terminator with a new conditional
864 // branch, hooking it up to backward destination for latch blocks now, and
865 // to forward destination(s) later when they are created.
866 // Second successor may be backwards - iff it is already in VPBB2IRBB.
867 VPBasicBlock *SecondVPSucc =
868 cast<VPBasicBlock>(getParent()->getSuccessors()[1]);
869 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
870 BasicBlock *IRBB = State.CFG.VPBB2IRBB[getParent()];
871 auto *Br = Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
872 // First successor is always forward, reset it to nullptr.
873 Br->setSuccessor(0, nullptr);
875 applyMetadata(*Br);
876 return Br;
877 }
879 return Builder.CreateVectorSplat(
880 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
881 }
883 // For struct types, we need to build a new 'wide' struct type, where each
884 // element is widened, i.e., we create a struct of vectors.
885 auto *StructTy = cast<StructType>(getOperand(0)->getScalarType());
886 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
887 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
888 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
889 FieldIndex++) {
890 Value *ScalarValue =
891 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
892 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
893 VectorValue =
894 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
895 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
896 }
897 }
898 return Res;
899 }
901 auto *ScalarTy = getOperand(0)->getScalarType();
902 auto NumOfElements = ElementCount::getFixed(getNumOperands());
903 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
904 for (const auto &[Idx, Op] : enumerate(operands()))
905 Res = Builder.CreateInsertElement(Res, State.get(Op, true),
906 Builder.getInt32(Idx));
907 return Res;
908 }
910 if (State.VF.isScalar())
911 return State.get(getOperand(0), true);
912 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
914 // If this start vector is scaled then it should produce a vector with fewer
915 // elements than the VF.
916 ElementCount VF = State.VF.divideCoefficientBy(
917 cast<VPConstantInt>(getOperand(2))->getZExtValue());
918 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
919 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
920 Builder.getInt32(0));
921 }
923 RecurKind RK = getRecurKind();
924 bool IsOrdered = isReductionOrdered();
925 bool IsInLoop = isReductionInLoop();
927 "FindIV should use min/max reduction kinds");
928
929 // The recipe may have multiple operands to be reduced together.
930 unsigned NumOperandsToReduce = getNumOperands();
931 VectorParts RdxParts(NumOperandsToReduce);
932 for (unsigned Part = 0; Part < NumOperandsToReduce; ++Part)
933 RdxParts[Part] = State.get(getOperand(Part), IsInLoop);
934
935 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
937
938 // Reduce multiple operands into one.
939 Value *ReducedPartRdx = RdxParts[0];
940 if (IsOrdered) {
941 ReducedPartRdx = RdxParts[NumOperandsToReduce - 1];
942 } else {
943 // Floating-point operations should have some FMF to enable the reduction.
944 for (unsigned Part = 1; Part < NumOperandsToReduce; ++Part) {
945 Value *RdxPart = RdxParts[Part];
947 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
948 else {
949 // For sub-recurrences, each part's reduction variable is already
950 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
954 : (Instruction::BinaryOps)RecurrenceDescriptor::getOpcode(RK);
955 ReducedPartRdx =
956 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
957 }
958 }
959 }
960
961 // Create the reduction after the loop. Note that inloop reductions create
962 // the target reduction in the loop using a Reduction recipe.
963 if (State.VF.isVector() && !IsInLoop) {
964 // TODO: Support in-order reductions based on the recurrence descriptor.
965 // All ops in the reduction inherit fast-math-flags from the recurrence
966 // descriptor.
967 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
968 }
969
970 return ReducedPartRdx;
971 }
974 unsigned Offset =
976 Value *Res;
977 if (State.VF.isVector()) {
978 assert(Offset <= State.VF.getKnownMinValue() &&
979 "invalid offset to extract from");
980 // Extract lane VF - Offset from the operand.
981 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
982 } else {
983 // TODO: Remove ExtractLastLane for scalar VFs.
984 assert(Offset <= 1 && "invalid offset to extract from");
985 Res = State.get(getOperand(0));
986 }
988 Res->setName(Name);
989 return Res;
990 }
992 Value *A = State.get(getOperand(0));
993 Value *B = State.get(getOperand(1));
994 return Builder.CreateLogicalAnd(A, B, Name);
995 }
997 Value *A = State.get(getOperand(0));
998 Value *B = State.get(getOperand(1));
999 return Builder.CreateLogicalOr(A, B, Name);
1000 }
1001 case VPInstruction::PtrAdd: {
1002 assert((State.VF.isScalar() || vputils::onlyFirstLaneUsed(this)) &&
1003 "can only generate first lane for PtrAdd");
1004 Value *Ptr = State.get(getOperand(0), VPLane(0));
1005 Value *Addend = State.get(getOperand(1), VPLane(0));
1006 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1007 }
1009 Value *Ptr =
1011 Value *Addend = State.get(getOperand(1));
1012 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
1013 }
1014 case VPInstruction::AnyOf: {
1015 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
1016 for (VPValue *Op : drop_begin(operands()))
1017 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
1018 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
1019 }
1021 assert(getNumOperands() != 2 && "ExtractLane from single source should be "
1022 "simplified to ExtractElement.");
1023 Value *LaneToExtract = State.get(getOperand(0), true);
1024 Type *IdxTy = getOperand(0)->getScalarType();
1025 Value *Res = nullptr;
1026 Value *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1027
1028 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
1029 Value *VectorStart =
1030 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
1031 Value *VectorIdx = Idx == 1
1032 ? LaneToExtract
1033 : Builder.CreateSub(LaneToExtract, VectorStart);
1034 Value *Ext = State.VF.isScalar()
1035 ? State.get(getOperand(Idx))
1036 : Builder.CreateExtractElement(
1037 State.get(getOperand(Idx)), VectorIdx);
1038 if (Res) {
1039 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
1040 Res = Builder.CreateSelect(Cmp, Ext, Res);
1041 } else {
1042 Res = Ext;
1043 }
1044 }
1045 return Res;
1046 }
1048 Type *Ty = this->getScalarType();
1049 if (getNumOperands() == 1) {
1050 Value *Mask = State.get(getOperand(0));
1051 return Builder.CreateCountTrailingZeroElems(Ty, Mask,
1052 /*ZeroIsPoison=*/false, Name);
1053 }
1054 // If there are multiple operands, create a chain of selects to pick the
1055 // first operand with an active lane and add the number of lanes of the
1056 // preceding operands.
1057 Value *RuntimeVF = getRuntimeVF(Builder, Ty, State.VF);
1058 unsigned LastOpIdx = getNumOperands() - 1;
1059 Value *Res = nullptr;
1060 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
1061 Value *TrailingZeros =
1062 State.VF.isScalar()
1063 ? Builder.CreateZExt(
1064 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
1065 Builder.getFalse()),
1066 Ty)
1068 Ty, State.get(getOperand(Idx)),
1069 /*ZeroIsPoison=*/false, Name);
1070 Value *Current = Builder.CreateAdd(
1071 Builder.CreateMul(RuntimeVF, ConstantInt::get(Ty, Idx)),
1072 TrailingZeros);
1073 if (Res) {
1074 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
1075 Res = Builder.CreateSelect(Cmp, Current, Res);
1076 } else {
1077 Res = Current;
1078 }
1079 }
1080
1081 return Res;
1082 }
1084 return State.get(getOperand(0), true);
1086 return Builder.CreateVectorReverse(State.get(getOperand(0)), "reverse");
1088 Value *Result = State.get(getOperand(0), /*IsScalar=*/true);
1089 for (unsigned Idx = 1; Idx < getNumOperands(); Idx += 2) {
1090 Value *Data = State.get(getOperand(Idx));
1091 Value *Mask = State.get(getOperand(Idx + 1));
1092 Type *VTy = Data->getType();
1093
1094 if (State.VF.isScalar())
1095 Result = Builder.CreateSelect(Mask, Data, Result);
1096 else
1097 Result = Builder.CreateIntrinsic(
1098 Intrinsic::experimental_vector_extract_last_active, {VTy},
1099 {Data, Mask, Result});
1100 }
1101
1102 return Result;
1103 }
1104 default:
1105 llvm_unreachable("Unsupported opcode for instruction");
1106 }
1107}
1108
1110 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
1111 Type *ScalarTy = this->getScalarType();
1112 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
1113 switch (Opcode) {
1114 case Instruction::FNeg:
1115 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
1116 case Instruction::UDiv:
1117 case Instruction::SDiv:
1118 case Instruction::SRem:
1119 case Instruction::URem:
1120 case Instruction::Add:
1121 case Instruction::FAdd:
1122 case Instruction::Sub:
1123 case Instruction::FSub:
1124 case Instruction::Mul:
1125 case Instruction::FMul:
1126 case Instruction::FDiv:
1127 case Instruction::FRem:
1128 case Instruction::Shl:
1129 case Instruction::LShr:
1130 case Instruction::AShr:
1131 case Instruction::And:
1132 case Instruction::Or:
1133 case Instruction::Xor: {
1134 // Certain instructions can be cheaper if they have a constant second
1135 // operand. One example of this are shifts on x86.
1136 VPValue *RHS = getOperand(1);
1137 TargetTransformInfo::OperandValueInfo RHSInfo = Ctx.getOperandInfo(RHS);
1138
1139 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
1142
1145 if (CtxI)
1146 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
1147 return Ctx.TTI.getArithmeticInstrCost(
1148 Opcode, ResultTy, Ctx.CostKind,
1149 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1150 RHSInfo, Operands, CtxI, &Ctx.TLI);
1151 }
1152 case Instruction::Freeze:
1153 // NOTE: The only way to ask for the cost is via getInstructionCost, which
1154 // requires the actual vector instruction. Instead, both here and in the
1155 // LoopVectorizationCostModel::getInstructionCost the costs mirror the
1156 // current behaviour in llvm/Analysis/TargetTransformInfoImpl.h to keep
1157 // them in sync.
1158 return TTI::TCC_Free;
1159 case Instruction::ExtractValue:
1160 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
1161 Ctx.CostKind);
1162 case Instruction::ICmp:
1163 case Instruction::FCmp: {
1164 Type *ScalarOpTy = getOperand(0)->getScalarType();
1165 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
1167 return Ctx.TTI.getCmpSelInstrCost(
1169 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
1170 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
1171 }
1172 case Instruction::BitCast: {
1173 Type *ScalarTy = this->getScalarType();
1174 if (ScalarTy->isPointerTy())
1175 return 0;
1176 [[fallthrough]];
1177 }
1178 case Instruction::SExt:
1179 case Instruction::ZExt:
1180 case Instruction::FPToUI:
1181 case Instruction::FPToSI:
1182 case Instruction::FPExt:
1183 case Instruction::PtrToInt:
1184 case Instruction::PtrToAddr:
1185 case Instruction::IntToPtr:
1186 case Instruction::SIToFP:
1187 case Instruction::UIToFP:
1188 case Instruction::Trunc:
1189 case Instruction::FPTrunc:
1190 case Instruction::AddrSpaceCast: {
1191 // Computes the CastContextHint from a recipe that may access memory.
1192 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
1193 if (isa<VPInterleaveBase>(R))
1195 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R)) {
1196 // Only compute CCH for memory operations, matching the legacy model
1197 // which only considers loads/stores for cast context hints.
1198 auto *UI = cast<Instruction>(ReplicateRecipe->getUnderlyingValue());
1199 if (!isa<LoadInst, StoreInst>(UI))
1201 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
1203 }
1204 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
1205 if (WidenMemoryRecipe == nullptr)
1207 if (VF.isScalar())
1209 if (!WidenMemoryRecipe->isConsecutive())
1211 if (WidenMemoryRecipe->isMasked())
1214 };
1215
1216 VPValue *Operand = getOperand(0);
1218 bool IsReverse = false;
1219 // For Trunc/FPTrunc, get the context from the only user.
1220 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
1221 if (auto *Recipe = cast_or_null<VPRecipeBase>(getSingleUser())) {
1222 if (match(Recipe,
1226 IsReverse = true;
1228 Recipe->getVPSingleValue()->getSingleUser());
1229 }
1230 if (Recipe)
1231 CCH = ComputeCCH(Recipe);
1232 }
1233 }
1234 // For Z/Sext, get the context from the operand.
1235 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
1236 Opcode == Instruction::FPExt) {
1237 if (auto *Recipe = Operand->getDefiningRecipe()) {
1238 VPValue *ReverseOp;
1239 if (match(Recipe,
1240 m_CombineOr(m_Reverse(m_VPValue(ReverseOp)),
1242 m_VPValue(ReverseOp))))) {
1243 Recipe = ReverseOp->getDefiningRecipe();
1244 IsReverse = true;
1245 }
1246 if (Recipe)
1247 CCH = ComputeCCH(Recipe);
1248 }
1249 }
1250 if (IsReverse && CCH != TTI::CastContextHint::None)
1252
1253 auto *ScalarSrcTy = Operand->getScalarType();
1254 Type *SrcTy = VF.isVector() ? toVectorTy(ScalarSrcTy, VF) : ScalarSrcTy;
1255 // Arm TTI will use the underlying instruction to determine the cost.
1256 return Ctx.TTI.getCastInstrCost(
1257 Opcode, ResultTy, SrcTy, CCH, Ctx.CostKind,
1259 }
1260 case Instruction::Select: {
1262 bool IsScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1263 Type *ScalarTy = this->getScalarType();
1264
1265 VPValue *Op0, *Op1;
1266 bool IsLogicalAnd =
1267 match(this, m_c_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1)));
1268 bool IsLogicalOr =
1269 match(this, m_c_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1270 // Also match the inverted forms:
1271 // select x, false, y --> !x & y (still AND)
1272 // select x, y, true --> !x | y (still OR)
1273 IsLogicalAnd |=
1274 match(this, m_Select(m_VPValue(Op0), m_False(), m_VPValue(Op1)));
1275 IsLogicalOr |=
1276 match(this, m_Select(m_VPValue(Op0), m_VPValue(Op1), m_True()));
1277
1278 if (!IsScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1279 (IsLogicalAnd || IsLogicalOr)) {
1280 // select x, y, false --> x & y
1281 // select x, true, y --> x | y
1282 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1283 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1284
1286 if (SI && all_of(operands(),
1287 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1288 append_range(Operands, SI->operands());
1289 return Ctx.TTI.getArithmeticInstrCost(
1290 IsLogicalOr ? Instruction::Or : Instruction::And, ResultTy,
1291 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1292 }
1293
1294 Type *CondTy = getOperand(0)->getScalarType();
1295 if (!IsScalarCond && VF.isVector())
1296 CondTy = VectorType::get(CondTy, VF);
1297
1298 llvm::CmpPredicate Pred;
1299 if (!match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue())))
1300 if (auto *CondIRV = dyn_cast<VPIRValue>(getOperand(0)))
1301 if (auto *Cmp = dyn_cast<CmpInst>(CondIRV->getValue()))
1302 Pred = Cmp->getPredicate();
1303 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1304 return Ctx.TTI.getCmpSelInstrCost(
1305 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1306 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1307 }
1308 }
1309 llvm_unreachable("called for unsupported opcode");
1310}
1311
1313 VPCostContext &Ctx) const {
1315 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1316 // TODO: Compute cost for VPInstructions without underlying values once
1317 // the legacy cost model has been retired.
1318 return 0;
1319 }
1320
1322 "Should only generate a vector value or single scalar, not scalars "
1323 "for all lanes.");
1325 getOpcode(),
1327 }
1328
1329 switch (getOpcode()) {
1330 case Instruction::Select: {
1332 match(getOperand(0), m_Cmp(Pred, m_VPValue(), m_VPValue()));
1333 auto *CondTy = getOperand(0)->getScalarType();
1334 auto *VecTy = getOperand(1)->getScalarType();
1335 if (!vputils::onlyFirstLaneUsed(this)) {
1336 CondTy = toVectorTy(CondTy, VF);
1337 VecTy = toVectorTy(VecTy, VF);
1338 }
1339 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1340 Ctx.CostKind);
1341 }
1342 case Instruction::ExtractElement:
1344 if (VF.isScalar()) {
1345 // ExtractLane with VF=1 takes care of handling extracting across multiple
1346 // parts.
1347 return 0;
1348 }
1349
1350 // Add on the cost of extracting the element.
1351 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1352 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1353 Ctx.CostKind);
1354 }
1355 case VPInstruction::AnyOf: {
1356 auto *VecTy = toVectorTy(this->getScalarType(), VF);
1357 return Ctx.TTI.getArithmeticReductionCost(
1358 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1359 }
1361 Type *Ty = this->getScalarType();
1362 Type *ScalarTy = getOperand(0)->getScalarType();
1363 if (VF.isScalar())
1364 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1366 CmpInst::ICMP_EQ, Ctx.CostKind);
1367 // Calculate the cost of determining the lane index.
1368 auto *PredTy = toVectorTy(ScalarTy, VF);
1369 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1370 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1371 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1372 }
1374 Type *Ty = this->getScalarType();
1375 Type *ScalarTy = getOperand(0)->getScalarType();
1376 if (VF.isScalar())
1377 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1379 CmpInst::ICMP_EQ, Ctx.CostKind);
1380 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1381 auto *PredTy = toVectorTy(ScalarTy, VF);
1382 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts, Ty,
1383 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1384 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1385 // Add cost of NOT operation on the predicate.
1386 Cost += Ctx.TTI.getArithmeticInstrCost(
1387 Instruction::Xor, PredTy, Ctx.CostKind,
1388 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1389 {TargetTransformInfo::OK_UniformConstantValue,
1390 TargetTransformInfo::OP_None});
1391 // Add cost of SUB operation on the index.
1392 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Sub, Ty, Ctx.CostKind);
1393 return Cost;
1394 }
1396 Type *ScalarTy = this->getScalarType();
1397 Type *VecTy = toVectorTy(ScalarTy, VF);
1398 Type *MaskTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1400 Intrinsic::experimental_vector_extract_last_active, ScalarTy,
1401 {VecTy, MaskTy, ScalarTy});
1402 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind);
1403 }
1405 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1406 Type *VectorTy = toVectorTy(this->getScalarType(), VF);
1407 return Ctx.TTI.getShuffleCost(
1409 cast<VectorType>(VectorTy), {}, Ctx.CostKind, -1);
1410 }
1412 Type *ArgTy = getOperand(0)->getScalarType();
1413 unsigned Multiplier = cast<VPConstantInt>(getOperand(2))->getZExtValue();
1414 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1415 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1416 {ArgTy, ArgTy});
1417 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1418 }
1420 Type *Arg0Ty = getOperand(0)->getScalarType();
1421 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1422 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1423 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1424 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1425 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1426 }
1428 assert(VF.isVector() && "Reverse operation must be vector type");
1429 Type *EltTy = this->getScalarType();
1430 // Skip the reverse operation cost for the mask.
1431 // FIXME: Remove this once redundant mask reverse operations can be
1432 // eliminated by VPlanTransforms::cse before cost computation.
1433 if (EltTy->isIntegerTy(1))
1434 return 0;
1435 auto *VectorTy = cast<VectorType>(toVectorTy(EltTy, VF));
1436 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
1437 VectorTy, /*Mask=*/{}, Ctx.CostKind,
1438 /*Index=*/0);
1439 }
1441 // Add on the cost of extracting the element.
1442 auto *VecTy = toVectorTy(getOperand(0)->getScalarType(), VF);
1443 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1444 VecTy, Ctx.CostKind, 0);
1445 }
1446 case VPInstruction::Not: {
1447 Type *ValTy = this->getScalarType();
1448 // InstCombine will fold `xor` to the conditional branch.
1449 if (auto *U = const_cast<VPUser *>(getSingleUser()))
1450 if (match(U, m_BranchOnCond(m_VPValue())))
1451 return 0;
1452 if (!vputils::onlyFirstLaneUsed(this))
1453 ValTy = toVectorTy(ValTy, VF);
1454 return Ctx.TTI.getArithmeticInstrCost(Instruction::Xor, ValTy,
1455 Ctx.CostKind);
1456 }
1458 // If TC <= VF then this is just a branch.
1459 // FIXME: Removing the branch happens in simplifyBranchConditionForVFAndUF
1460 // where it checks TC <= VF * UF, but we don't know UF yet. This means in
1461 // some cases we get a cost that's too high due to counting a cmp that
1462 // later gets removed.
1463 // FIXME: The compare could also be removed if TC = M * vscale,
1464 // VF = N * vscale, and M <= N. Detecting that would require having the
1465 // trip count as a SCEV though.
1468 if (TCConst && TCConst->getValue().ule(VF.getKnownMinValue()))
1469 return 0;
1470 // Otherwise BranchOnCount generates ICmpEQ followed by a branch.
1471 Type *ValTy = getOperand(0)->getScalarType();
1472 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ValTy,
1474 CmpInst::ICMP_EQ, Ctx.CostKind);
1475 }
1476 case Instruction::FCmp:
1477 case Instruction::ICmp:
1479 getOpcode(),
1482 if (VF == ElementCount::getScalable(1))
1484 [[fallthrough]];
1485 default:
1486 // TODO: Compute cost other VPInstructions once the legacy cost model has
1487 // been retired.
1489 "unexpected VPInstruction witht underlying value");
1490 return 0;
1491 }
1492}
1493
1506
1508 switch (getOpcode()) {
1509 case Instruction::Load:
1510 case Instruction::PHI:
1514 return true;
1515 default:
1517 }
1518}
1519
1521#ifndef NDEBUG
1522 Type *Ty = Op->getScalarType();
1523 switch (getOpcode()) {
1527 assert(Ty == getOperand(0)->getScalarType() &&
1528 "types of operand 0 and new operand must match");
1529 break;
1533 assert(Ty == getOperand(0)->getScalarType() &&
1534 "appended operand must match operand 0's scalar type");
1535 break;
1537 assert(Ty == getOperand(1)->getScalarType() &&
1538 "appended operand must match operand 1's scalar type");
1539 break;
1541 // The recipe is constructed with 3 operands (result, data, mask). Extra
1542 // operands beyond that are appended in (data, mask) pairs.
1543 constexpr unsigned NumInitialOperands = 3;
1544 assert(getNumOperands() >= NumInitialOperands &&
1545 "ExtractLastActive must have at least the initial 3 operands");
1546 bool IsMaskSlot = ((getNumOperands() - NumInitialOperands) & 1u) == 1u;
1547 assert((IsMaskSlot ? Ty->isIntegerTy(1)
1548 : Ty == getOperand(1)->getScalarType()) &&
1549 "ExtractLastActive expects alternating data/mask operands "
1550 "matching operand 1's type and i1, respectively");
1551 break;
1552 }
1553 default:
1554 llvm_unreachable("opcode does not support growing the operand list "
1555 "outside of construction");
1556 }
1557#endif
1559}
1560
1562 assert(!isMasked() && "cannot execute masked VPInstruction");
1563 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1565 "Set flags not supported for the provided opcode");
1567 "Opcode requires specific flags to be set");
1568 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
1569 Value *GeneratedValue = generate(State);
1570 if (!hasResult())
1571 return;
1572 assert(GeneratedValue && "generate must produce a value");
1573 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1576 assert((((GeneratedValue->getType()->isVectorTy() ||
1577 GeneratedValue->getType()->isStructTy()) ==
1578 !GeneratesPerFirstLaneOnly) ||
1579 State.VF.isScalar()) &&
1580 "scalar value but not only first lane defined");
1581 State.set(this, GeneratedValue,
1582 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1584 getOpcode() == Instruction::Freeze) {
1585 // FIXME: This is a workaround to enable reliable updates of the scalar loop
1586 // resume phis, and to let epilogue vectorization recover the frozen
1587 // reduction start from the main plan. Must be removed once epilogue
1588 // vectorization explicitly connects VPlans.
1589 setUnderlyingValue(GeneratedValue);
1590 }
1591}
1592
1596 return false;
1597 switch (getOpcode()) {
1598 case Instruction::ExtractValue:
1599 case Instruction::InsertValue:
1600 case Instruction::GetElementPtr:
1601 case Instruction::ExtractElement:
1602 case Instruction::InsertElement:
1603 case Instruction::Freeze:
1604 case Instruction::FCmp:
1605 case Instruction::ICmp:
1606 case Instruction::Select:
1607 case Instruction::PHI:
1632 case VPInstruction::Not:
1640 return false;
1643 AttributeSet Attrs =
1645 return !Attrs.getMemoryEffects().doesNotAccessMemory();
1646 }
1647 case Instruction::Call:
1650 default:
1651 return true;
1652 }
1653}
1654
1656 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1658 return vputils::onlyFirstLaneUsed(this);
1659
1660 switch (getOpcode()) {
1661 default:
1662 return false;
1663 case Instruction::ExtractElement:
1664 return Op == getOperand(1);
1665 case Instruction::InsertElement:
1666 return Op == getOperand(1) || Op == getOperand(2);
1667 case Instruction::PHI:
1668 return true;
1669 case Instruction::FCmp:
1670 case Instruction::ICmp:
1671 case Instruction::Select:
1672 case Instruction::Or:
1673 case Instruction::Freeze:
1674 case VPInstruction::Not:
1675 // TODO: Cover additional opcodes.
1676 return vputils::onlyFirstLaneUsed(this);
1677 case Instruction::Load:
1689 return true;
1692 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1693 // operand, after replicating its operands only the first lane is used.
1694 // Before replicating, it will have only a single operand.
1695 return getNumOperands() > 1;
1697 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1699 // WidePtrAdd supports scalar and vector base addresses.
1700 return false;
1703 return Op == getOperand(0);
1704 };
1705 llvm_unreachable("switch should return");
1706}
1707
1709 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1711 return vputils::onlyFirstPartUsed(this);
1712
1713 switch (getOpcode()) {
1714 default:
1715 return false;
1716 case Instruction::FCmp:
1717 case Instruction::ICmp:
1718 case Instruction::Select:
1719 return vputils::onlyFirstPartUsed(this);
1724 return true;
1725 };
1726 llvm_unreachable("switch should return");
1727}
1728
1729#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1731 VPSlotTracker SlotTracker(getParent()->getPlan());
1733}
1734
1736 VPSlotTracker &SlotTracker) const {
1737 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1738
1739 if (hasResult()) {
1741 O << " = ";
1742 }
1743
1744 switch (getOpcode()) {
1745 case VPInstruction::Not:
1746 O << "not";
1747 break;
1749 O << "active lane mask";
1750 break;
1752 O << "incoming-alias-mask";
1753 break;
1755 O << "EXPLICIT-VECTOR-LENGTH";
1756 break;
1758 O << "first-order splice";
1759 break;
1761 O << "branch-on-cond";
1762 break;
1764 O << "branch-on-two-conds";
1765 break;
1767 O << "TC > VF ? TC - VF : 0";
1768 break;
1770 O << "VF * Part +";
1771 break;
1773 O << "branch-on-count";
1774 break;
1776 O << "broadcast";
1777 break;
1779 O << "buildstructvector";
1780 break;
1782 O << "buildvector";
1783 break;
1785 O << "exiting-iv-value";
1786 break;
1788 O << "masked-cond";
1789 break;
1791 O << "extract-lane";
1792 break;
1794 O << "extract-last-lane";
1795 break;
1797 O << "extract-last-part";
1798 break;
1800 O << "extract-penultimate-element";
1801 break;
1803 O << "compute-reduction-result";
1804 break;
1806 O << "logical-and";
1807 break;
1809 O << "logical-or";
1810 break;
1812 O << "ptradd";
1813 break;
1815 O << "wide-ptradd";
1816 break;
1818 O << "any-of";
1819 break;
1821 O << "first-active-lane";
1822 break;
1824 O << "last-active-lane";
1825 break;
1827 O << "reduction-start-vector";
1828 break;
1830 O << "resume-for-epilogue";
1831 break;
1833 O << "reverse";
1834 break;
1836 O << "unpack";
1837 break;
1839 O << "extract-last-active";
1840 break;
1842 O << "num-active-lanes";
1843 break;
1844 default:
1846 }
1847
1848 printFlags(O);
1850}
1851#endif
1852
1854 Type *ResultTy = getResultType();
1856 Value *Op = State.get(getOperand(0), VPLane(0));
1857 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1858 Op, ResultTy);
1859 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
1860 applyFlags(*CastOp);
1861 applyMetadata(*CastOp);
1862 }
1863 State.set(this, Cast, VPLane(0));
1864 return;
1865 }
1866 switch (getOpcode()) {
1868 Value *StepVector =
1869 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1870 State.set(this, StepVector);
1871 break;
1872 }
1875 for (VPValue *Op : drop_end(operands()))
1876 Args.push_back(State.get(Op, /*IsSingleScalar=*/true));
1877 Value *Call =
1878 State.Builder.CreateIntrinsic(ResultTy, vputils::getIntrinsicID(this),
1879 Args, /*FMFSource=*/nullptr, getName());
1880 State.set(this, Call, true);
1881 break;
1882 }
1883
1884 default:
1885 llvm_unreachable("opcode not implemented yet");
1886 }
1887}
1888
1890 VPCostContext &Ctx) const {
1891 // NOTE: At the moment it seems only possible to expose this path for
1892 // the trunc, zext and sext opcodes. However, isScalarCast also covers
1893 // int<>fp conversions, bitcasts, ptr<>int conversions, etc.
1896 Ctx);
1897
1898 switch (getOpcode()) {
1900 // TODO: This isn't quite right since even if the step-vector is hoisted
1901 // out of the loop it has a non-zero cost in the middle block, etc.
1902 // Once the stepvector is correctly hoisted out of the vector loop by the
1903 // licm transform we can add the cost here so that it doesn't incorrectly
1904 // affect the choice of VF.
1905 return 0;
1907 Type *Ty = getScalarType();
1909 for (const VPValue *Op : drop_end(operands()))
1910 ArgTys.push_back(Op->getScalarType());
1911 IntrinsicCostAttributes Attrs(vputils::getIntrinsicID(this), Ty, ArgTys);
1912 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1913 }
1914 default:
1915 // Although VPInstructionWithType is also used for
1916 // VPInstruction::WideIVStep it isn't currently possible to expose cases
1917 // where the cost is queried.
1918 llvm_unreachable("Unhandled opcode");
1919 }
1920 return 0;
1921}
1922
1923#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1925 VPSlotTracker &SlotTracker) const {
1926 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1928 O << " = ";
1929
1930 Type *ResultTy = getResultType();
1931 switch (getOpcode()) {
1933 O << "wide-iv-step ";
1935 break;
1937 O << "step-vector " << *ResultTy;
1938 break;
1940 O << "call " << *ResultTy << " @"
1943 Op->printAsOperand(O, SlotTracker);
1944 });
1945 O << ")";
1946 break;
1947 }
1948 case Instruction::Load:
1949 O << "load ";
1951 break;
1952 default:
1953 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1955 printFlags(O);
1957 O << " to " << *ResultTy;
1958 }
1959}
1960#endif
1961
1962/// Shared execute logic for VPPhi and VPWidenPHIRecipe. Creates a PHI node,
1963/// adds incoming values, and stores the result in State. For header phis, only
1964/// the preheader incoming value is added; the backedge is fixed up later by
1965/// VPlan::execute().
1967 VPTransformState &State, bool IsScalar,
1968 const Twine &Name) {
1969 unsigned NumIncoming = VPBlockUtils::isHeader(R->getParent(), State.VPDT)
1970 ? 1
1971 : Phi.getNumIncoming();
1972 Value *FirstInc = State.get(Phi.getIncomingValue(0), IsScalar);
1973 PHINode *NewPhi = State.Builder.CreatePHI(FirstInc->getType(), 2, Name);
1974 NewPhi->addIncoming(FirstInc,
1975 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(0)));
1976 for (unsigned Idx = 1; Idx != NumIncoming; ++Idx)
1977 NewPhi->addIncoming(State.get(Phi.getIncomingValue(Idx), IsScalar),
1978 State.CFG.VPBB2IRBB.at(Phi.getIncomingBlock(Idx)));
1979 State.set(R, NewPhi, IsScalar);
1980}
1981
1983 executePhiRecipe(this, *this, State, /*IsScalar=*/true, getName());
1984}
1985
1986#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1987void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1988 VPSlotTracker &SlotTracker) const {
1989 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1991 O << " = phi";
1992 printFlags(O);
1994}
1995#endif
1996
1997VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1998 if (auto *Phi = dyn_cast<PHINode>(&I))
1999 return new VPIRPhi(*Phi);
2000 return new VPIRInstruction(I);
2001}
2002
2004 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
2005 "PHINodes must be handled by VPIRPhi");
2006 // Advance the insert point after the wrapped IR instruction. This allows
2007 // interleaving VPIRInstructions and other recipes.
2008 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
2009}
2010
2012 VPCostContext &Ctx) const {
2013 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
2014 // hence it does not contribute to the cost-modeling for the VPlan.
2015 return 0;
2016}
2017
2018#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2020 VPSlotTracker &SlotTracker) const {
2021 O << Indent << "IR " << I;
2022}
2023#endif
2024
2026 PHINode *Phi = &getIRPhi();
2027 for (const auto &[Idx, Op] : enumerate(operands())) {
2028 VPValue *ExitValue = Op;
2029 auto Lane = vputils::isSingleScalar(ExitValue)
2031 : VPLane::getLastLaneForVF(State.VF);
2032 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
2033 auto *PredVPBB = Pred->getExitingBasicBlock();
2034 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
2035 // Set insertion point in PredBB in case an extract needs to be generated.
2036 // TODO: Model extracts explicitly.
2037 State.Builder.SetInsertPoint(PredBB->getTerminator());
2038 Value *V = State.get(ExitValue, VPLane(Lane));
2039 // If there is no existing block for PredBB in the phi, add a new incoming
2040 // value. Otherwise update the existing incoming value for PredBB.
2041 if (Phi->getBasicBlockIndex(PredBB) == -1)
2042 Phi->addIncoming(V, PredBB);
2043 else
2044 Phi->setIncomingValueForBlock(PredBB, V);
2045 }
2046
2047 // Advance the insert point after the wrapped IR instruction. This allows
2048 // interleaving VPIRInstructions and other recipes.
2049 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
2050}
2051
2053 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2054 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
2055 "Number of phi operands must match number of predecessors");
2056 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
2057 R->removeOperand(Position);
2058}
2059
2060VPValue *
2062 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2063 return getIncomingValue(R->getParent()->getIndexForPredecessor(VPBB));
2064}
2065
2067 VPValue *V) const {
2068 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
2069 R->setOperand(R->getParent()->getIndexForPredecessor(VPBB), V);
2070}
2071
2072#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2074 VPSlotTracker &SlotTracker) const {
2076 O << "[ ";
2077 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2078 O << ", ";
2079 std::get<1>(Op)->printAsOperand(O);
2080 O << " ]";
2081 });
2082}
2083#endif
2084
2085#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2087 VPSlotTracker &SlotTracker) const {
2089
2090 if (getNumOperands() != 0) {
2091 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
2093 [&O, &SlotTracker](auto Op) {
2094 std::get<0>(Op)->printAsOperand(O, SlotTracker);
2095 O << " from ";
2096 std::get<1>(Op)->printAsOperand(O);
2097 });
2098 O << ")";
2099 }
2100}
2101#endif
2102
2104 for (const auto &[Kind, Node] : Metadata)
2105 I.setMetadata(Kind, Node);
2106}
2107
2109 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
2110 for (const auto &[KindA, MDA] : Metadata) {
2111 for (const auto &[KindB, MDB] : Other.Metadata) {
2112 if (KindA == KindB && MDA == MDB) {
2113 MetadataIntersection.emplace_back(KindA, MDA);
2114 break;
2115 }
2116 }
2117 }
2118 Metadata = std::move(MetadataIntersection);
2119}
2120
2121#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2123 const Module *M = SlotTracker.getModule();
2124 if (Metadata.empty() || !M || !VPlanPrintMetadata)
2125 return;
2126
2127 ArrayRef<StringRef> MDNames = SlotTracker.getMDNames();
2128 O << " (";
2129 interleaveComma(Metadata, O, [&](const auto &KindNodePair) {
2130 auto [Kind, Node] = KindNodePair;
2131 assert(Kind < MDNames.size() && !MDNames[Kind].empty() &&
2132 "Unexpected unnamed metadata kind");
2133 O << "!" << MDNames[Kind] << " ";
2134 Node->printAsOperand(O, M);
2135 });
2136 O << ")";
2137}
2138#endif
2139
2141 assert(State.VF.isVector() && "not widening");
2142 assert(Variant != nullptr && "Can't create vector function.");
2143
2144 FunctionType *VFTy = Variant->getFunctionType();
2145 // Add return type if intrinsic is overloaded on it.
2147 for (const auto &I : enumerate(args())) {
2148 Value *Arg;
2149 // Some vectorized function variants may also take a scalar argument,
2150 // e.g. linear parameters for pointers. This needs to be the scalar value
2151 // from the start of the respective part when interleaving.
2152 if (!VFTy->getParamType(I.index())->isVectorTy())
2153 Arg = State.get(I.value(), VPLane(0));
2154 else
2155 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2156 Args.push_back(Arg);
2157 }
2158
2161 if (CI)
2162 CI->getOperandBundlesAsDefs(OpBundles);
2163
2164 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
2165 applyFlags(*V);
2166 applyMetadata(*V);
2167 V->setCallingConv(Variant->getCallingConv());
2168
2169 if (!V->getType()->isVoidTy())
2170 State.set(this, V);
2171}
2172
2174 VPCostContext &Ctx) const {
2175 assert(getVectorizedTypeVF(Variant->getReturnType()) == VF &&
2176 "Variant return type must match VF");
2177 return computeCallCost(Variant, Ctx);
2178}
2179
2181 VPCostContext &Ctx) {
2182 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
2183 Variant->getFunctionType()->params(),
2184 Ctx.CostKind);
2185}
2186
2188 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2189 assert(Variant && "Variant not set");
2190 FunctionType *VFTy = Variant->getFunctionType();
2191 return all_of(enumerate(args()), [VFTy, &Op](const auto &Arg) {
2192 auto [Idx, V] = Arg;
2193 Type *ArgTy = VFTy->getParamType(Idx);
2194 return V != Op || ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy() ||
2195 ArgTy->isPointerTy() || ArgTy->isByteTy();
2196 });
2197}
2198
2199#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2201 VPSlotTracker &SlotTracker) const {
2202 O << Indent << "WIDEN-CALL ";
2203
2204 Function *CalledFn = getCalledScalarFunction();
2205 if (CalledFn->getReturnType()->isVoidTy())
2206 O << "void ";
2207 else {
2209 O << " = ";
2210 }
2211
2212 O << "call";
2213 printFlags(O);
2214 O << " @" << CalledFn->getName() << "(";
2215 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
2216 Op->printAsOperand(O, SlotTracker);
2217 });
2218 O << ")";
2219
2220 O << " (using library function";
2221 if (Variant->hasName())
2222 O << ": " << Variant->getName();
2223 O << ")";
2224}
2225#endif
2226
2228 assert(State.VF.isVector() && "not widening");
2229
2230 SmallVector<Type *, 2> TysForDecl;
2231 // Add return type if intrinsic is overloaded on it.
2232 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1,
2233 State.TTI)) {
2234 Type *RetTy = toVectorizedTy(getScalarType(), State.VF);
2235 ArrayRef<Type *> ContainedTys = getContainedTypes(RetTy);
2236 for (auto [Idx, Ty] : enumerate(ContainedTys)) {
2238 Idx, State.TTI))
2239 TysForDecl.push_back(Ty);
2240 }
2241 }
2243 for (const auto &I : enumerate(operands())) {
2244 // Some intrinsics have a scalar argument - don't replace it with a
2245 // vector.
2246 Value *Arg;
2247 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
2248 State.TTI))
2249 Arg = State.get(I.value(), VPLane(0));
2250 else
2251 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
2252 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
2253 State.TTI))
2254 TysForDecl.push_back(Arg->getType());
2255 Args.push_back(Arg);
2256 }
2257
2258 // Use vector version of the intrinsic.
2259 Module *M = State.Builder.GetInsertBlock()->getModule();
2260 Function *VectorF =
2261 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
2262 assert(VectorF &&
2263 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
2264
2267 if (CI)
2268 CI->getOperandBundlesAsDefs(OpBundles);
2269
2270 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
2271
2272 applyFlags(*V);
2273 applyMetadata(*V);
2274
2275 return V;
2276}
2277
2279 CallInst *V = createVectorCall(State);
2280 if (!V->getType()->isVoidTy())
2281 State.set(this, V);
2282}
2283
2286 const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx) {
2287 Type *ScalarRetTy = R.getScalarType();
2288 // Skip the reverse operation cost for the mask.
2289 // FIXME: Remove this once redundant mask reverse operations can be eliminated
2290 // by VPlanTransforms::cse before cost computation.
2291 if (ID == Intrinsic::experimental_vp_reverse && ScalarRetTy->isIntegerTy(1))
2292 return InstructionCost(0);
2293
2294 // Some backends analyze intrinsic arguments to determine cost. Use the
2295 // underlying value for the operand if it has one. Otherwise try to use the
2296 // operand of the underlying call instruction, if there is one. Otherwise
2297 // clear Arguments.
2298 // TODO: Rework TTI interface to be independent of concrete IR values.
2300 for (const auto &[Idx, Op] : enumerate(Operands)) {
2301 auto *V = Op->getUnderlyingValue();
2302 if (!V) {
2303 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
2304 Arguments.push_back(UI->getArgOperand(Idx));
2305 continue;
2306 }
2307 Arguments.clear();
2308 break;
2309 }
2310 Arguments.push_back(V);
2311 }
2312
2313 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
2314 SmallVector<Type *> ParamTys =
2315 map_to_vector(Operands, [&](const VPValue *Op) {
2316 return toVectorTy(Op->getScalarType(), VF);
2317 });
2318
2319 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
2320 IntrinsicCostAttributes CostAttrs(
2321 ID, RetTy, Arguments, ParamTys, R.getFastMathFlagsOrNone(),
2322 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
2324 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
2325}
2326
2328 VPCostContext &Ctx) const {
2329 return computeCallCost(VectorIntrinsicID, operands(), *this, VF, Ctx);
2330}
2331
2333 return Intrinsic::getBaseName(VectorIntrinsicID);
2334}
2335
2337 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2338 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
2339 auto [Idx, V] = X;
2341 Idx, nullptr);
2342 });
2343}
2344
2345#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2347 VPSlotTracker &SlotTracker) const {
2348 O << Indent << "WIDEN-INTRINSIC ";
2349 if (getScalarType()->isVoidTy()) {
2350 O << "void ";
2351 } else {
2353 O << " = ";
2354 }
2355
2356 O << "call";
2357 printFlags(O);
2358 O << getIntrinsicName() << "(";
2360 O << ")";
2361}
2362#endif
2363
2365 CallInst *MemI = createVectorCall(State);
2366 MemI->addParamAttr(
2367 0, Attribute::getWithAlignment(MemI->getContext(), Alignment));
2368 State.set(this, MemI);
2369}
2370
2372 Intrinsic::ID IID, Type *Ty, bool IsMasked, Align Alignment,
2373 VPCostContext &Ctx) {
2374 return Ctx.TTI.getMemIntrinsicInstrCost(
2375 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr, IsMasked, Alignment),
2376 Ctx.CostKind);
2377}
2378
2381 VPCostContext &Ctx) const {
2382 Type *Ty = toVectorTy(getScalarType(), VF);
2384 !match(getOperand(2), m_True()), Alignment,
2385 Ctx);
2386}
2387
2389 IRBuilderBase &Builder = State.Builder;
2390
2391 Value *Address = State.get(getOperand(0));
2392 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
2393 VectorType *VTy = cast<VectorType>(Address->getType());
2394
2395 // The histogram intrinsic requires a mask even if the recipe doesn't;
2396 // if the mask operand was omitted then all lanes should be executed and
2397 // we just need to synthesize an all-true mask.
2398 Value *Mask = nullptr;
2399 if (VPValue *VPMask = getMask())
2400 Mask = State.get(VPMask);
2401 else
2402 Mask =
2403 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
2404
2405 // If this is a subtract, we want to invert the increment amount. We may
2406 // add a separate intrinsic in future, but for now we'll try this.
2407 if (Opcode == Instruction::Sub)
2408 IncAmt = Builder.CreateNeg(IncAmt);
2409 else
2410 assert(Opcode == Instruction::Add && "only add or sub supported for now");
2411
2412 Instruction *HistogramInst = State.Builder.CreateIntrinsicWithoutFolding(
2413 Intrinsic::experimental_vector_histogram_add, {VTy, IncAmt->getType()},
2414 {Address, IncAmt, Mask});
2415 applyMetadata(*HistogramInst);
2416}
2417
2419 VPCostContext &Ctx) const {
2420 // FIXME: Take the gather and scatter into account as well. For now we're
2421 // generating the same cost as the fallback path, but we'll likely
2422 // need to create a new TTI method for determining the cost, including
2423 // whether we can use base + vec-of-smaller-indices or just
2424 // vec-of-pointers.
2425 assert(VF.isVector() && "Invalid VF for histogram cost");
2426 Type *AddressTy = getOperand(0)->getScalarType();
2427 VPValue *IncAmt = getOperand(1);
2428 Type *IncTy = IncAmt->getScalarType();
2429 VectorType *VTy = VectorType::get(IncTy, VF);
2430
2431 // Assume that a non-constant update value (or a constant != 1) requires
2432 // a multiply, and add that into the cost.
2433 InstructionCost MulCost =
2434 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
2435 if (match(IncAmt, m_One()))
2436 MulCost = TTI::TCC_Free;
2437
2438 // Find the cost of the histogram operation itself.
2439 Type *PtrTy = VectorType::get(AddressTy, VF);
2440 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
2441 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
2442 Type::getVoidTy(Ctx.LLVMCtx),
2443 {PtrTy, IncTy, MaskTy});
2444
2445 // Add the costs together with the add/sub operation.
2446 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
2447 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
2448}
2449
2450#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2452 VPSlotTracker &SlotTracker) const {
2453 O << Indent << "WIDEN-HISTOGRAM buckets: ";
2455
2456 if (Opcode == Instruction::Sub)
2457 O << ", dec: ";
2458 else {
2459 assert(Opcode == Instruction::Add);
2460 O << ", inc: ";
2461 }
2463
2464 if (VPValue *Mask = getMask()) {
2465 O << ", mask: ";
2466 Mask->printAsOperand(O, SlotTracker);
2467 }
2468}
2469#endif
2470
2471VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
2472 AllowReassoc = FMF.allowReassoc();
2473 NoNaNs = FMF.noNaNs();
2474 NoInfs = FMF.noInfs();
2475 NoSignedZeros = FMF.noSignedZeros();
2476 AllowReciprocal = FMF.allowReciprocal();
2477 AllowContract = FMF.allowContract();
2478 ApproxFunc = FMF.approxFunc();
2479}
2480
2482 switch (Opcode) {
2483 case Instruction::Add:
2484 case Instruction::Sub:
2485 case Instruction::Mul:
2486 case Instruction::Shl:
2488 return WrapFlagsTy(false, false);
2489 case Instruction::Trunc:
2490 return TruncFlagsTy(false, false);
2491 case Instruction::Or:
2492 return DisjointFlagsTy(false);
2493 case Instruction::AShr:
2494 case Instruction::LShr:
2495 case Instruction::UDiv:
2496 case Instruction::SDiv:
2497 return ExactFlagsTy(false);
2498 case Instruction::GetElementPtr:
2501 return GEPNoWrapFlags::none();
2502 case Instruction::ZExt:
2503 case Instruction::UIToFP:
2504 return NonNegFlagsTy(false);
2505 case Instruction::FAdd:
2506 case Instruction::FSub:
2507 case Instruction::FMul:
2508 case Instruction::FDiv:
2509 case Instruction::FRem:
2510 case Instruction::FNeg:
2511 case Instruction::FPExt:
2512 case Instruction::FPTrunc:
2513 return FastMathFlags();
2514 case Instruction::ICmp:
2515 case Instruction::FCmp:
2517 llvm_unreachable("opcode requires explicit flags");
2518 default:
2519 return VPIRFlags();
2520 }
2521}
2522
2523#if !defined(NDEBUG)
2524bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
2525 switch (OpType) {
2526 case OperationType::OverflowingBinOp:
2527 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
2528 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
2529 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
2530 case OperationType::Trunc:
2531 return Opcode == Instruction::Trunc;
2532 case OperationType::DisjointOp:
2533 return Opcode == Instruction::Or;
2534 case OperationType::PossiblyExactOp:
2535 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
2536 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
2537 case OperationType::GEPOp:
2538 return Opcode == Instruction::GetElementPtr ||
2539 Opcode == VPInstruction::PtrAdd ||
2540 Opcode == VPInstruction::WidePtrAdd;
2541 case OperationType::FPMathOp:
2542 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
2543 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
2544 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
2545 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
2546 Opcode == Instruction::FPTrunc || Opcode == Instruction::PHI ||
2547 Opcode == Instruction::Select || Opcode == Instruction::SIToFP ||
2548 Opcode == Instruction::UIToFP ||
2549 Opcode == VPInstruction::WideIVStep ||
2551 case OperationType::FCmp:
2552 return Opcode == Instruction::FCmp;
2553 case OperationType::NonNegOp:
2554 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2555 case OperationType::Cmp:
2556 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2557 case OperationType::ReductionOp:
2559 case OperationType::Other:
2560 return true;
2561 }
2562 llvm_unreachable("Unknown OperationType enum");
2563}
2564
2565bool VPIRFlags::hasRequiredFlagsForOpcode(unsigned Opcode) const {
2566 // Handle opcodes without default flags.
2567 if (Opcode == Instruction::ICmp)
2568 return OpType == OperationType::Cmp;
2569 if (Opcode == Instruction::FCmp)
2570 return OpType == OperationType::FCmp;
2572 return OpType == OperationType::ReductionOp;
2573
2574 OperationType Required = getDefaultFlags(Opcode).OpType;
2575 return Required == OperationType::Other || Required == OpType;
2576}
2577#endif
2578
2579#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2580static void printRecurrenceKind(raw_ostream &OS, const RecurKind &Kind) {
2581 switch (Kind) {
2582 case RecurKind::None:
2583 OS << "none";
2584 break;
2585 case RecurKind::Add:
2586 OS << "add";
2587 break;
2588 case RecurKind::Sub:
2589 OS << "sub";
2590 break;
2592 OS << "add-chain-with-subs";
2593 break;
2594 case RecurKind::Mul:
2595 OS << "mul";
2596 break;
2597 case RecurKind::Or:
2598 OS << "or";
2599 break;
2600 case RecurKind::And:
2601 OS << "and";
2602 break;
2603 case RecurKind::Xor:
2604 OS << "xor";
2605 break;
2606 case RecurKind::SMin:
2607 OS << "smin";
2608 break;
2609 case RecurKind::SMax:
2610 OS << "smax";
2611 break;
2612 case RecurKind::UMin:
2613 OS << "umin";
2614 break;
2615 case RecurKind::UMax:
2616 OS << "umax";
2617 break;
2618 case RecurKind::FAdd:
2619 OS << "fadd";
2620 break;
2622 OS << "fadd-chain-with-subs";
2623 break;
2624 case RecurKind::FSub:
2625 OS << "fsub";
2626 break;
2627 case RecurKind::FMul:
2628 OS << "fmul";
2629 break;
2630 case RecurKind::FMin:
2631 OS << "fmin";
2632 break;
2633 case RecurKind::FMax:
2634 OS << "fmax";
2635 break;
2636 case RecurKind::FMinNum:
2637 OS << "fminnum";
2638 break;
2639 case RecurKind::FMaxNum:
2640 OS << "fmaxnum";
2641 break;
2643 OS << "fminimum";
2644 break;
2646 OS << "fmaximum";
2647 break;
2649 OS << "fminimumnum";
2650 break;
2652 OS << "fmaximumnum";
2653 break;
2654 case RecurKind::FMulAdd:
2655 OS << "fmuladd";
2656 break;
2657 case RecurKind::AnyOf:
2658 OS << "any-of";
2659 break;
2660 case RecurKind::FindIV:
2661 OS << "find-iv";
2662 break;
2664 OS << "find-last";
2665 break;
2666 }
2667}
2668
2670 switch (OpType) {
2671 case OperationType::Cmp:
2673 break;
2674 case OperationType::FCmp:
2677 break;
2678 case OperationType::DisjointOp:
2679 if (DisjointFlags.IsDisjoint)
2680 O << " disjoint";
2681 break;
2682 case OperationType::PossiblyExactOp:
2683 if (ExactFlags.IsExact)
2684 O << " exact";
2685 break;
2686 case OperationType::OverflowingBinOp:
2687 if (WrapFlags.HasNUW)
2688 O << " nuw";
2689 if (WrapFlags.HasNSW)
2690 O << " nsw";
2691 break;
2692 case OperationType::Trunc:
2693 if (TruncFlags.HasNUW)
2694 O << " nuw";
2695 if (TruncFlags.HasNSW)
2696 O << " nsw";
2697 break;
2698 case OperationType::FPMathOp:
2700 break;
2701 case OperationType::GEPOp: {
2703 if (Flags.isInBounds())
2704 O << " inbounds";
2705 else if (Flags.hasNoUnsignedSignedWrap())
2706 O << " nusw";
2707 if (Flags.hasNoUnsignedWrap())
2708 O << " nuw";
2709 break;
2710 }
2711 case OperationType::NonNegOp:
2712 if (NonNegFlags.NonNeg)
2713 O << " nneg";
2714 break;
2715 case OperationType::ReductionOp: {
2716 O << " (";
2718 if (isReductionInLoop())
2719 O << ", in-loop";
2720 if (isReductionOrdered())
2721 O << ", ordered";
2722 O << ")";
2724 break;
2725 }
2726 case OperationType::Other:
2727 break;
2728 }
2729 O << " ";
2730}
2731#endif
2732
2734 auto &Builder = State.Builder;
2735 switch (Opcode) {
2736 case Instruction::Call:
2737 case Instruction::UncondBr:
2738 case Instruction::CondBr:
2739 case Instruction::PHI:
2740 case Instruction::GetElementPtr:
2741 llvm_unreachable("This instruction is handled by a different recipe.");
2742 case Instruction::UDiv:
2743 case Instruction::SDiv:
2744 case Instruction::SRem:
2745 case Instruction::URem:
2746 case Instruction::Add:
2747 case Instruction::FAdd:
2748 case Instruction::Sub:
2749 case Instruction::FSub:
2750 case Instruction::FNeg:
2751 case Instruction::Mul:
2752 case Instruction::FMul:
2753 case Instruction::FDiv:
2754 case Instruction::FRem:
2755 case Instruction::Shl:
2756 case Instruction::LShr:
2757 case Instruction::AShr:
2758 case Instruction::And:
2759 case Instruction::Or:
2760 case Instruction::Xor: {
2761 // Just widen unops and binops.
2763 for (VPValue *VPOp : operands())
2764 Ops.push_back(State.get(VPOp));
2765
2766 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2767
2768 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2769 applyFlags(*VecOp);
2770 applyMetadata(*VecOp);
2771 }
2772
2773 // Use this vector value for all users of the original instruction.
2774 State.set(this, V);
2775 break;
2776 }
2777 case Instruction::ExtractValue: {
2778 assert(getNumOperands() == 2 && "expected single level extractvalue");
2779 Value *Op = State.get(getOperand(0));
2780 Value *Extract = Builder.CreateExtractValue(
2781 Op, cast<VPConstantInt>(getOperand(1))->getZExtValue());
2782 State.set(this, Extract);
2783 break;
2784 }
2785 case Instruction::Freeze: {
2786 Value *Op = State.get(getOperand(0));
2787 Value *Freeze = Builder.CreateFreeze(Op);
2788 State.set(this, Freeze);
2789 break;
2790 }
2791 case Instruction::ICmp:
2792 case Instruction::FCmp: {
2793 // Widen compares. Generate vector compares.
2794 bool FCmp = Opcode == Instruction::FCmp;
2795 Value *A = State.get(getOperand(0));
2796 Value *B = State.get(getOperand(1));
2797 Value *C = nullptr;
2798 if (FCmp) {
2799 C = Builder.CreateFCmp(getPredicate(), A, B);
2800 } else {
2801 C = Builder.CreateICmp(getPredicate(), A, B);
2802 }
2803 if (auto *I = dyn_cast<Instruction>(C)) {
2804 applyFlags(*I);
2805 applyMetadata(*I);
2806 }
2807 State.set(this, C);
2808 break;
2809 }
2810 case Instruction::Select: {
2811 VPValue *CondOp = getOperand(0);
2812 Value *Cond = State.get(CondOp, vputils::isSingleScalar(CondOp));
2813 Value *Op0 = State.get(getOperand(1));
2814 Value *Op1 = State.get(getOperand(2));
2815 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
2816 State.set(this, Sel);
2817 if (auto *I = dyn_cast<Instruction>(Sel)) {
2819 applyFlags(*I);
2820 applyMetadata(*I);
2821 }
2822 break;
2823 }
2824 default:
2825 // This instruction is not vectorized by simple widening.
2826 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2827 << Instruction::getOpcodeName(Opcode));
2828 llvm_unreachable("Unhandled instruction!");
2829 } // end of switch.
2830
2831#if !defined(NDEBUG)
2832 // Verify that VPlan type inference results agree with the type of the
2833 // generated values.
2834 assert(VectorType::get(this->getScalarType(), State.VF) ==
2835 State.get(this)->getType() &&
2836 "inferred type and type from generated instructions do not match");
2837#endif
2838}
2839
2841 VPCostContext &Ctx) const {
2842 switch (Opcode) {
2843 case Instruction::UDiv:
2844 case Instruction::SDiv:
2845 case Instruction::SRem:
2846 case Instruction::URem:
2847 // If the div/rem operation isn't safe to speculate and requires
2848 // predication, then the only way we can even create a vplan is to insert
2849 // a select on the second input operand to ensure we use the value of 1
2850 // for the inactive lanes. The select will be costed separately.
2851 case Instruction::FNeg:
2852 case Instruction::Add:
2853 case Instruction::FAdd:
2854 case Instruction::Sub:
2855 case Instruction::FSub:
2856 case Instruction::Mul:
2857 case Instruction::FMul:
2858 case Instruction::FDiv:
2859 case Instruction::FRem:
2860 case Instruction::Shl:
2861 case Instruction::LShr:
2862 case Instruction::AShr:
2863 case Instruction::And:
2864 case Instruction::Or:
2865 case Instruction::Xor:
2866 case Instruction::Freeze:
2867 case Instruction::ExtractValue:
2868 case Instruction::ICmp:
2869 case Instruction::FCmp:
2870 case Instruction::Select:
2871 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2872 default:
2873 llvm_unreachable("Unsupported opcode for instruction");
2874 }
2875}
2876
2877#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2879 VPSlotTracker &SlotTracker) const {
2880 O << Indent << "WIDEN ";
2882 O << " = " << Instruction::getOpcodeName(Opcode);
2883 printFlags(O);
2885}
2886#endif
2887
2889 auto &Builder = State.Builder;
2890 /// Vectorize casts.
2891 assert(State.VF.isVector() && "Not vectorizing?");
2892 Type *DestTy = VectorType::get(getScalarType(), State.VF);
2893 VPValue *Op = getOperand(0);
2894 Value *A = State.get(Op);
2895 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2896 State.set(this, Cast);
2897 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2898 applyFlags(*CastOp);
2899 applyMetadata(*CastOp);
2900 }
2901}
2902
2907
2908#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2910 VPSlotTracker &SlotTracker) const {
2911 O << Indent << "WIDEN-CAST ";
2913 O << " = " << Instruction::getOpcodeName(Opcode);
2914 printFlags(O);
2916 O << " to " << *getScalarType();
2917}
2918#endif
2919
2921 VPCostContext &Ctx) const {
2922 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2923}
2924
2925#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2927 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2928 O << Indent;
2930 O << " = WIDEN-INDUCTION";
2931 printFlags(O);
2933
2934 if (auto *TI = getTruncInst())
2935 O << " (truncated to " << *TI->getType() << ")";
2936}
2937#endif
2938
2940 // The step may be defined by a recipe in the preheader (e.g. if it requires
2941 // SCEV expansion), but for the canonical induction the step is required to be
2942 // 1, which is represented as live-in.
2943 return match(getStartValue(), m_ZeroInt()) &&
2944 match(getStepValue(), m_One()) &&
2945 getScalarType() == getRegion()->getCanonicalIVType();
2946}
2947
2949 VPCostContext &Ctx) const {
2950 // The cost model for this is modelled on expandVPDerivedIV in
2951 // VPlanTransforms.cpp. In order to avoid overly pessimistic costs that can
2952 // negatively affect vectorization it takes into account any expected
2953 // simplifications that happen in simplifyRecipe.
2954 switch (getInductionKind()) {
2955 default:
2956 // TODO: Compute cost for remaining kinds.
2957 break;
2959 // There are currently no tests that expose a path where all lanes are
2960 // used, so it's better to bail out for now.
2961 if (!vputils::onlyFirstLaneUsed(this))
2962 break;
2963
2964 // Start off by assuming we need both mul and add, then refine this.
2965 bool NeedsMul = true, NeedsAdd = true, NeedsShl = false;
2966
2967 // If the start value is zero the add gets folded away.
2968 if (auto *StartC = dyn_cast<VPConstantInt>(getStartValue()))
2969 NeedsAdd = !StartC->isZero();
2970
2971 // For some values of step the arithmetic changes:
2972 // 1. A step of 1 requires no operation.
2973 // 2. A step of -1 requires a negate.
2974 // 3. A power-of-2 step will use a shl, instead of a mul.
2975 Type *StepTy = getStepValue()->getScalarType();
2977 if (auto *StepC = dyn_cast<VPConstantInt>(getStepValue())) {
2978 if (StepC->isOne())
2979 NeedsMul = false;
2980 else if (StepC->getAPInt().isAllOnes()) {
2981 // This will most likely end up as a negate in simplifyRecipe, and
2982 // the negate will be combined with the add to make a sub.
2983 // NOTE: This is perhaps an invalid assumption that the cost of an
2984 // 'add' is the same as a 'sub'.
2985 NeedsMul = false;
2986 NeedsAdd = true;
2987 } else if (StepC->getAPInt().isPowerOf2()) {
2988 // This will most likely end up as a shift-left in simplifyRecipe
2989 NeedsMul = false;
2990 NeedsShl = true;
2991 }
2992 }
2993
2994 // Add the cost of the conversion from index to step type if the index
2995 // will be used.
2996 Type *IndexTy = getIndex()->getScalarType();
2997 unsigned StepTySize = StepTy->getScalarSizeInBits();
2998 unsigned IndexTySize = IndexTy->getScalarSizeInBits();
2999 if ((NeedsAdd || NeedsMul || NeedsShl) && StepTySize != IndexTySize) {
3000 unsigned CastOpc =
3001 StepTySize < IndexTySize ? Instruction::Trunc : Instruction::SExt;
3002 Cost += Ctx.TTI.getCastInstrCost(
3003 CastOpc, StepTy, IndexTy, TTI::CastContextHint::None, Ctx.CostKind);
3004 }
3005
3006 if (NeedsMul)
3007 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, StepTy,
3008 Ctx.CostKind);
3009 if (NeedsShl)
3010 Cost += Ctx.TTI.getArithmeticInstrCost(
3011 Instruction::Shl, StepTy, Ctx.CostKind,
3012 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
3013 {TargetTransformInfo::OK_UniformConstantValue,
3014 TargetTransformInfo::OP_None});
3015 if (NeedsAdd)
3016 Cost += Ctx.TTI.getArithmeticInstrCost(Instruction::Add, StepTy,
3017 Ctx.CostKind);
3018 return Cost;
3019 }
3020 }
3021
3022 return 0;
3023}
3024
3025#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3027 VPSlotTracker &SlotTracker) const {
3028 O << Indent;
3030 O << " = DERIVED-IV ";
3031 getStartValue()->printAsOperand(O, SlotTracker);
3032 O << " + ";
3033 getOperand(1)->printAsOperand(O, SlotTracker);
3034 O << " * ";
3035 getStepValue()->printAsOperand(O, SlotTracker);
3036}
3037#endif
3038
3040 VPCostContext &Ctx) const {
3041 // TODO: Add costs for floating point.
3042 Type *BaseIVTy = getOperand(0)->getScalarType();
3043 if (!BaseIVTy->isIntegerTy())
3044 return 0;
3045
3046 // TODO: Add support for predicated regions. Requires scaling the cost by the
3047 // probability of entering the block.
3048 if (getRegion() && getRegion()->isReplicator())
3049 return 0;
3050
3051 // If only the first lane is used, then there won't be any code that remains
3052 // in the loop for the first unrolled part.
3054 return 0;
3055
3056 // Typically the operations are:
3057 // 1. Add the start index to each lane value.
3058 // 2. Multiply the start index by the step.
3059 // 3. Add the scaled start index to base IV.
3060 // Any code generated for 1 and 2 should be loop invariant and therefore
3061 // hoisted out of the loop. We only need to add on the cost of 3.
3062
3063 // Given the users of VPScalarIVStepsRecipe tend to be scalarized GEPs, i.e.
3064 // %add1 = add i32 %iv, 0
3065 // %add2 = add i32 %iv, 1
3066 // %gep1 = getelementptr i8, ptr %p, i32 %add1
3067 // %gep2 = getelementptr i8, ptr %p, i32 %add2
3068 // it's very likely that these GEPs will all be rewritten to have a common
3069 // base such that what's left is just
3070 // %base_gep = getelementptr i8, ptr %p, i32 %iv
3071 // %gep1 = getelementptr i8, ptr %base_gep, i32 0
3072 // %gep2 = getelementptr i8, ptr %base_gep, i32 1
3073 // Therefore, in reality the cost is somewhere betwen 1*AddCost and
3074 // (NumLanes - 1) * AddCost. For now, assume the cost of a single add.
3075 return Ctx.TTI.getArithmeticInstrCost(Instruction::Add, BaseIVTy,
3076 Ctx.CostKind);
3077}
3078
3080 // Fast-math-flags propagate from the original induction instruction.
3081 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
3082 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3083
3084 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
3085 /// variable on which to base the steps, \p Step is the size of the step.
3086
3087 Value *BaseIV = State.get(getOperand(0), VPLane(0));
3088 Value *Step = State.get(getStepValue(), VPLane(0));
3089 IRBuilderBase &Builder = State.Builder;
3090
3091 // Ensure step has the same type as that of scalar IV.
3092 Type *BaseIVTy = BaseIV->getType()->getScalarType();
3093 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
3094
3095 // We build scalar steps for both integer and floating-point induction
3096 // variables. Here, we determine the kind of arithmetic we will perform.
3099 if (BaseIVTy->isIntegerTy()) {
3100 AddOp = Instruction::Add;
3101 MulOp = Instruction::Mul;
3102 } else {
3103 AddOp = InductionOpcode;
3104 MulOp = Instruction::FMul;
3105 }
3106
3107 // Determine the number of scalars we need to generate.
3108 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
3109 // Compute the scalar steps and save the results in State.
3110
3111 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
3112 Value *StartIdx0 = getStartIndex() ? State.get(getStartIndex(), true)
3113 : Constant::getNullValue(BaseIVTy);
3114
3115 for (unsigned Lane = 0; Lane < EndLane; ++Lane) {
3116 // It is okay if the induction variable type cannot hold the lane number,
3117 // we expect truncation in this case.
3118 Constant *LaneValue =
3119 BaseIVTy->isIntegerTy()
3120 ? ConstantInt::get(BaseIVTy, Lane, /*IsSigned=*/false,
3121 /*ImplicitTrunc=*/true)
3122 : ConstantFP::get(BaseIVTy, Lane);
3123 Value *StartIdx = Builder.CreateBinOp(AddOp, StartIdx0, LaneValue);
3124 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
3125 "Expected StartIdx to be folded to a constant when VF is not "
3126 "scalable");
3127 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
3128 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
3129 State.set(this, Add, VPLane(Lane));
3130 }
3131}
3132
3133#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3135 VPSlotTracker &SlotTracker) const {
3136 O << Indent;
3138 O << " = SCALAR-STEPS ";
3140}
3141#endif
3142
3144 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
3146}
3147
3149 assert(State.VF.isVector() && "not widening");
3150 auto Ops = map_to_vector(operands(), [&](VPValue *Op) {
3151 return State.get(Op, vputils::isSingleScalar(Op));
3152 });
3153 auto *GEP =
3154 State.Builder.CreateGEP(getSourceElementType(), Ops.front(),
3155 drop_begin(Ops), "wide.gep", getGEPNoWrapFlags());
3156 State.set(this, GEP, vputils::isSingleScalar(this));
3157}
3158
3159#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3161 VPSlotTracker &SlotTracker) const {
3162 O << Indent << "WIDEN-GEP ";
3164 O << " = getelementptr";
3165 printFlags(O);
3167}
3168#endif
3169
3171 assert(!getOffset() && "Unexpected offset operand");
3172 VPBuilder Builder(this);
3173 VPlan &Plan = *getParent()->getPlan();
3174 VPValue *VFVal = getVFValue();
3175 const DataLayout &DL = Plan.getDataLayout();
3176 Type *IndexTy = DL.getIndexType(this->getScalarType());
3177 VPValue *Stride =
3178 Plan.getConstantInt(IndexTy, getStride(), /*IsSigned=*/true);
3179 Type *VFTy = VFVal->getScalarType();
3180 VPValue *VF = Builder.createScalarZExtOrTrunc(VFVal, IndexTy, VFTy,
3182
3183 // Offset for Part0 = Offset0 = Stride * (VF - 1).
3184 VPInstruction *VFMinusOne =
3185 Builder.createSub(VF, Plan.getConstantInt(IndexTy, 1u),
3186 DebugLoc::getUnknown(), "", {true, true});
3187 VPInstruction *Offset0 =
3188 Builder.createOverflowingOp(Instruction::Mul, {VFMinusOne, Stride});
3189
3190 // Offset for PartN = Offset0 + Part * Stride * VF.
3191 VPValue *PartxStride =
3192 Plan.getConstantInt(IndexTy, Part * getStride(), /*IsSigned=*/true);
3193 VPValue *Offset = Builder.createAdd(
3194 Offset0,
3195 Builder.createOverflowingOp(Instruction::Mul, {PartxStride, VF}));
3197}
3198
3200 auto &Builder = State.Builder;
3201 assert(getOffset() && "Expected prior materialization of offset");
3202 Value *Ptr = State.get(getPointer(), true);
3203 Value *Offset = State.get(getOffset(), true);
3204 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3206 State.set(this, ResultPtr, /*IsScalar*/ true);
3207}
3208
3209#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3211 VPSlotTracker &SlotTracker) const {
3212 O << Indent;
3214 O << " = vector-end-pointer";
3215 printFlags(O);
3217}
3218#endif
3219
3221 assert(getVFxPart() &&
3222 "Expected prior simplification of recipe without VFxPart");
3223
3224 auto &Builder = State.Builder;
3225 Value *Ptr = State.get(getOperand(0), VPLane(0));
3226 Value *Offset = State.get(getVFxPart(), true);
3227 // TODO: Expand to VPInstruction to support constant folding.
3228 if (!match(getStride(), m_One())) {
3229 Value *Stride = Builder.CreateZExtOrTrunc(State.get(getStride(), true),
3230 Offset->getType());
3231 Offset = Builder.CreateMul(Offset, Stride);
3232 }
3233 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Offset, "",
3235 State.set(this, ResultPtr, /*IsScalar*/ true);
3236}
3237
3238#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3240 VPSlotTracker &SlotTracker) const {
3241 O << Indent;
3243 O << " = vector-pointer";
3244 printFlags(O);
3246}
3247#endif
3248
3250 VPCostContext &Ctx) const {
3251 // A blend will be expanded to a select VPInstruction, which will generate a
3252 // scalar select if only the first lane is used.
3254 VF = ElementCount::getFixed(1);
3255
3256 Type *ResultTy = toVectorTy(this->getScalarType(), VF);
3257 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF);
3258 return (getNumIncomingValues() - 1) *
3259 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
3260 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
3261}
3262
3263#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3265 VPSlotTracker &SlotTracker) const {
3266 O << Indent << "BLEND ";
3268 O << " =";
3269 printFlags(O);
3270 if (getNumIncomingValues() == 1) {
3271 // Not a User of any mask: not really blending, this is a
3272 // single-predecessor phi.
3273 getIncomingValue(0)->printAsOperand(O, SlotTracker);
3274 } else {
3275 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
3276 if (I != 0)
3277 O << " ";
3278 getIncomingValue(I)->printAsOperand(O, SlotTracker);
3279 if (I == 0 && isNormalized())
3280 continue;
3281 O << "/";
3282 getMask(I)->printAsOperand(O, SlotTracker);
3283 }
3284 }
3285}
3286#endif
3287
3291 "In-loop AnyOf reductions aren't currently supported");
3292 // Propagate the fast-math flags carried by the underlying instruction.
3293 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
3294 State.Builder.setFastMathFlags(getFastMathFlagsOrNone());
3295 Value *NewVecOp = State.get(getVecOp());
3296 if (VPValue *Cond = getCondOp()) {
3297 Value *NewCond = State.get(Cond, State.VF.isScalar());
3298 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
3299 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
3300
3301 Value *Start =
3303 if (State.VF.isVector())
3304 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
3305
3306 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
3307 NewVecOp = Select;
3308 }
3309 Value *NewRed;
3310 Value *NextInChain;
3311 if (isOrdered()) {
3312 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3313 if (State.VF.isVector())
3314 NewRed =
3315 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
3316 else
3317 NewRed = State.Builder.CreateBinOp(
3319 PrevInChain, NewVecOp);
3320 PrevInChain = NewRed;
3321 NextInChain = NewRed;
3322 } else if (isPartialReduction()) {
3323 assert((Kind == RecurKind::Add || Kind == RecurKind::FAdd) &&
3324 "Unexpected partial reduction kind");
3325 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
3326 NewRed = State.Builder.CreateIntrinsic(
3327 PrevInChain->getType(),
3328 Kind == RecurKind::Add ? Intrinsic::vector_partial_reduce_add
3329 : Intrinsic::vector_partial_reduce_fadd,
3330 {PrevInChain, NewVecOp}, State.Builder.getFastMathFlags(),
3331 "partial.reduce");
3332 PrevInChain = NewRed;
3333 NextInChain = NewRed;
3334 } else {
3335 assert(isInLoop() &&
3336 "The reduction must either be ordered, partial or in-loop");
3337 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
3338 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
3340 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
3341 else
3342 NextInChain = State.Builder.CreateBinOp(
3344 PrevInChain, NewRed);
3345 }
3346 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
3347}
3348
3350
3351 auto &Builder = State.Builder;
3352 // Propagate the fast-math flags carried by the underlying instruction.
3353 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
3354 Builder.setFastMathFlags(getFastMathFlagsOrNone());
3355
3357 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
3358 Value *VecOp = State.get(getVecOp());
3359 Value *EVL = State.get(getEVL(), VPLane(0));
3360
3361 Value *Mask;
3362 if (VPValue *CondOp = getCondOp())
3363 Mask = State.get(CondOp);
3364 else
3365 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3366
3367 Value *NewRed;
3368 if (isOrdered()) {
3369 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
3370 } else {
3371 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
3373 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
3374 else
3375 NewRed = Builder.CreateBinOp(
3377 Prev);
3378 }
3379 State.set(this, NewRed, /*IsScalar*/ true);
3380}
3381
3383 VPCostContext &Ctx) const {
3384 RecurKind RdxKind = getRecurrenceKind();
3385 Type *ElementTy = this->getScalarType();
3386 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
3387 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
3389 std::optional<FastMathFlags> OptionalFMF =
3390 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
3391
3392 if (isPartialReduction()) {
3393 InstructionCost CondCost = 0;
3394 if (isConditional()) {
3396 auto *CondTy =
3398 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
3399 CondTy, Pred, Ctx.CostKind);
3400 }
3401 return CondCost + Ctx.TTI.getPartialReductionCost(
3402 Opcode, ElementTy, ElementTy, ElementTy, VF,
3403 TTI::PR_None, TTI::PR_None, {}, Ctx.CostKind,
3404 OptionalFMF);
3405 }
3406
3407 // TODO: Support any-of reductions.
3408 assert(
3410 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
3411 "Any-of reduction not implemented in VPlan-based cost model currently.");
3412
3413 // Note that TTI should model the cost of moving result to the scalar register
3414 // and the BinOp cost in the getMinMaxReductionCost().
3417 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
3418 }
3419
3420 // Note that TTI should model the cost of moving result to the scalar register
3421 // and the BinOp cost in the getArithmeticReductionCost().
3422 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
3423 Ctx.CostKind);
3424}
3425
3426VPExpressionRecipe::VPExpressionRecipe(
3427 ExpressionTypes ExpressionType,
3428 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
3429 : VPSingleDefRecipe(VPRecipeBase::VPExpressionSC, {},
3430 cast<VPReductionRecipe>(ExpressionRecipes.back())
3431 ->getChainOp()
3432 ->getScalarType()),
3433 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
3434 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
3435 assert(
3436 none_of(ExpressionRecipes,
3437 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3438 "expression cannot contain recipes with side-effects");
3439
3440 // Maintain a copy of the expression recipes as a set of users.
3441 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
3442 for (auto *R : ExpressionRecipes)
3443 ExpressionRecipesAsSetOfUsers.insert(R);
3444
3445 // Recipes in the expression, except the last one, must only be used by
3446 // (other) recipes inside the expression. If there are other users, external
3447 // to the expression, use a clone of the recipe for external users.
3448 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
3449 if (R != ExpressionRecipes.back() &&
3450 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
3451 return !ExpressionRecipesAsSetOfUsers.contains(U);
3452 })) {
3453 // There are users outside of the expression. Clone the recipe and use the
3454 // clone those external users.
3455 VPSingleDefRecipe *CopyForExtUsers = R->clone();
3456 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
3457 VPUser &U, unsigned) {
3458 return !ExpressionRecipesAsSetOfUsers.contains(&U);
3459 });
3460 CopyForExtUsers->insertBefore(R);
3461 }
3462 if (R->getParent())
3463 R->removeFromParent();
3464 }
3465
3466 // Internalize all external operands to the expression recipes. To do so,
3467 // create new temporary VPValues for all operands defined by a recipe outside
3468 // the expression. The original operands are added as operands of the
3469 // VPExpressionRecipe itself.
3470 for (auto *R : ExpressionRecipes) {
3471 for (const auto &[Idx, Op] : enumerate(R->operands())) {
3472 auto *Def = Op->getDefiningRecipe();
3473 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
3474 continue;
3475 addOperand(Op);
3476 LiveInPlaceholders.push_back(new VPSymbolicValue(Op->getScalarType()));
3477 }
3478 }
3479
3480 // Replace each external operand with the first one created for it in
3481 // LiveInPlaceholders.
3482 for (auto *R : ExpressionRecipes)
3483 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
3484 R->replaceUsesOfWith(LiveIn, Tmp);
3485}
3486
3488 for (auto *R : ExpressionRecipes)
3489 // Since the list could contain duplicates, make sure the recipe hasn't
3490 // already been inserted.
3491 if (!R->getParent())
3492 R->insertBefore(this);
3493
3494 for (const auto &[Idx, Op] : enumerate(operands()))
3495 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
3496
3497 replaceAllUsesWith(ExpressionRecipes.back());
3498 ExpressionRecipes.clear();
3499}
3500
3502 VPCostContext &Ctx) const {
3503 Type *RedTy = this->getScalarType();
3504 auto *SrcVecTy =
3506 unsigned Opcode = RecurrenceDescriptor::getOpcode(
3507 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
3508 switch (ExpressionType) {
3509 case ExpressionTypes::NegatedExtendedReduction:
3510 assert((Opcode == Instruction::Add || Opcode == Instruction::FAdd) &&
3511 "Unexpected opcode");
3512 Opcode = Opcode == Instruction::Add ? Instruction::Sub : Instruction::FSub;
3513 [[fallthrough]];
3514 case ExpressionTypes::ExtendedReduction: {
3515 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3516 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3517
3518 if (RedR->isPartialReduction())
3519 return Ctx.TTI.getPartialReductionCost(
3520 Opcode, getOperand(0)->getScalarType(), nullptr, RedTy, VF,
3522 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind,
3523 RedTy->isFloatingPointTy()
3524 ? std::optional{RedR->getFastMathFlagsOrNone()}
3525 : std::nullopt);
3526 else if (!RedTy->isFloatingPointTy())
3527 // TTI::getExtendedReductionCost only supports integer types.
3528 return Ctx.TTI.getExtendedReductionCost(
3529 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy, SrcVecTy,
3530 std::nullopt, Ctx.CostKind);
3531 else
3533 }
3534 case ExpressionTypes::MulAccReduction:
3535 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
3536 Ctx.CostKind);
3537
3538 case ExpressionTypes::ExtNegatedMulAccReduction:
3539 switch (Opcode) {
3540 case Instruction::Add:
3541 Opcode = Instruction::Sub;
3542 break;
3543 case Instruction::FAdd:
3544 Opcode = Instruction::FSub;
3545 break;
3546 default:
3547 llvm_unreachable("Unsupported opcode for ExtNegatedMulAccReduction");
3548 }
3549 [[fallthrough]];
3550 case ExpressionTypes::ExtMulAccReduction: {
3551 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
3552 if (RedR->isPartialReduction()) {
3553 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3554 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3555 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3556 return Ctx.TTI.getPartialReductionCost(
3557 Opcode, getOperand(0)->getScalarType(),
3558 getOperand(1)->getScalarType(), RedTy, VF,
3560 Ext0R->getOpcode()),
3562 Ext1R->getOpcode()),
3563 Mul->getOpcode(), Ctx.CostKind,
3564 RedTy->isFloatingPointTy()
3565 ? std::optional{RedR->getFastMathFlagsOrNone()}
3566 : std::nullopt);
3567 }
3568 assert(Opcode != Instruction::FSub && "Only integer types are supported");
3569 return Ctx.TTI.getMulAccReductionCost(
3570 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
3571 Instruction::ZExt,
3572 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
3573 }
3574 }
3575 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
3576}
3577
3579 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
3580 return R->mayReadFromMemory() || R->mayWriteToMemory();
3581 });
3582}
3583
3585 assert(
3586 none_of(ExpressionRecipes,
3587 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
3588 "expression cannot contain recipes with side-effects");
3589 return false;
3590}
3591
3593 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3594 return RR && !RR->isPartialReduction();
3595}
3596
3597#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3598
3600 VPSlotTracker &SlotTracker) const {
3601 O << Indent << "EXPRESSION ";
3603 O << " = ";
3604 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
3605 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
3606 VPValue *RdxStart =
3607 getOperand(getNumOperands() - (Red->isConditional() ? 2 : 1));
3608
3609 switch (ExpressionType) {
3610 case ExpressionTypes::NegatedExtendedReduction:
3611 case ExpressionTypes::ExtendedReduction: {
3612 bool Negated = ExpressionType == ExpressionTypes::NegatedExtendedReduction;
3614 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3615 O << Instruction::getOpcodeName(Opcode) << " (";
3616 if (Negated)
3617 O << (Opcode == Instruction::Add ? "sub (0, " : "fneg(");
3619 if (Negated)
3620 O << ")";
3621 Red->printFlags(O);
3622
3623 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3624 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3625 << *Ext0->getScalarType();
3626 if (Red->isConditional()) {
3627 O << ", ";
3629 }
3630 O << ")";
3631 break;
3632 }
3633 case ExpressionTypes::ExtNegatedMulAccReduction: {
3634 RdxStart->printAsOperand(O, SlotTracker);
3635 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3637 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3638 << " (sub (0, mul";
3639 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
3640 Mul->printFlags(O);
3641 O << "(";
3643 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3644 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3645 << *Ext0->getScalarType() << "), (";
3647 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3648 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3649 << *Ext1->getScalarType() << ")";
3650 if (Red->isConditional()) {
3651 O << ", ";
3653 }
3654 O << "))";
3655 break;
3656 }
3657 case ExpressionTypes::MulAccReduction:
3658 case ExpressionTypes::ExtMulAccReduction: {
3659 RdxStart->printAsOperand(O, SlotTracker);
3660 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
3662 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
3663 << " (";
3664 O << "mul";
3665 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
3666 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
3667 : ExpressionRecipes[0]);
3668 Mul->printFlags(O);
3669 if (IsExtended)
3670 O << "(";
3672 if (IsExtended) {
3673 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
3674 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
3675 << *Ext0->getScalarType() << "), (";
3676 } else {
3677 O << ", ";
3678 }
3680 if (IsExtended) {
3681 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
3682 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
3683 << *Ext1->getScalarType() << ")";
3684 }
3685 if (Red->isConditional()) {
3686 O << ", ";
3688 }
3689 O << ")";
3690 break;
3691 }
3692 }
3693}
3694
3696 VPSlotTracker &SlotTracker) const {
3697 if (isPartialReduction())
3698 O << Indent << "PARTIAL-REDUCE ";
3699 else
3700 O << Indent << "REDUCE ";
3702 O << " = ";
3704 O << " +";
3705 printFlags(O);
3706 O << " reduce.";
3708 O << " (";
3710 if (isConditional()) {
3711 O << ", ";
3713 }
3714 O << ")";
3715}
3716
3718 VPSlotTracker &SlotTracker) const {
3719 O << Indent << "REDUCE ";
3721 O << " = ";
3723 O << " +";
3724 printFlags(O);
3725 O << " vp.reduce."
3728 << " (";
3730 O << ", ";
3732 if (isConditional()) {
3733 O << ", ";
3735 }
3736 O << ")";
3737}
3738
3739#endif
3740
3742 assert(IsSingleScalar &&
3743 "VPReplicateRecipes must be unrolled before ::execute");
3744 auto *Instr = getUnderlyingInstr();
3745 Instruction *Cloned = Instr->clone();
3746 Type *ResultTy = getScalarType();
3747 if (!ResultTy->isVoidTy()) {
3748 Cloned->setName(Instr->getName() + ".cloned");
3749 // The operands of the replicate recipe may have been narrowed, resulting in
3750 // a narrower result type. Update the type of the cloned instruction to the
3751 // correct type.
3752 if (ResultTy != Cloned->getType())
3753 Cloned->mutateType(ResultTy);
3754 }
3755
3756 applyFlags(*Cloned);
3757 applyMetadata(*Cloned);
3758
3759 if (hasPredicate())
3760 cast<CmpInst>(Cloned)->setPredicate(getPredicate());
3761
3762 // Replace the operands of the cloned instructions with their scalar
3763 // equivalents in the new loop.
3764 for (const auto &[Idx, V] : enumerate(operands()))
3765 Cloned->setOperand(Idx, State.get(V, true));
3766
3767 // Place the cloned scalar in the new loop.
3768 State.Builder.Insert(Cloned);
3769
3770 State.set(this, Cloned, true);
3771
3772 // If we just cloned a new assumption, add it the assumption cache.
3773 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3774 State.AC->registerAssumption(II);
3775}
3776
3777/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3778/// which the legacy cost model computes a SCEV expression when computing the
3779/// address cost. Computing SCEVs for VPValues is incomplete and returns
3780/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3781/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3782static const SCEV *getAddressAccessSCEV(const VPValue *Ptr,
3784 const Loop *L) {
3785 const SCEV *Addr = vputils::getSCEVExprForVPValue(Ptr, PSE, L);
3786 if (isa<SCEVCouldNotCompute>(Addr))
3787 return Addr;
3788
3789 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), L) ? Addr : nullptr;
3790}
3791
3793 VPCostContext &Ctx) const {
3795 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3796 // transform, avoid computing their cost multiple times for now.
3797 Ctx.SkipCostComputation.insert(UI);
3798
3799 if (VF.isScalable() && !isSingleScalar())
3801
3802 switch (UI->getOpcode()) {
3803 case Instruction::Alloca:
3804 if (VF.isScalable())
3806 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul,
3807 this->getScalarType(), Ctx.CostKind);
3808 case Instruction::GetElementPtr:
3809 // We mark this instruction as zero-cost because the cost of GEPs in
3810 // vectorized code depends on whether the corresponding memory instruction
3811 // is scalarized or not. Therefore, we handle GEPs with the memory
3812 // instruction cost.
3813 return 0;
3814 case Instruction::Call: {
3815 auto *CalledFn =
3817 Type *ResultTy = this->getScalarType();
3818 return computeCallCost(CalledFn, ResultTy, drop_end(operands()),
3819 isSingleScalar(), VF, Ctx);
3820 }
3821 case Instruction::Add:
3822 case Instruction::Sub:
3823 case Instruction::FAdd:
3824 case Instruction::FSub:
3825 case Instruction::Mul:
3826 case Instruction::FMul:
3827 case Instruction::FDiv:
3828 case Instruction::FRem:
3829 case Instruction::Shl:
3830 case Instruction::LShr:
3831 case Instruction::AShr:
3832 case Instruction::And:
3833 case Instruction::Or:
3834 case Instruction::Xor:
3835 case Instruction::ICmp:
3836 case Instruction::FCmp:
3838 Ctx) *
3839 (isSingleScalar() ? 1 : VF.getFixedValue());
3840 case Instruction::SDiv:
3841 case Instruction::UDiv:
3842 case Instruction::SRem:
3843 case Instruction::URem: {
3844 InstructionCost ScalarCost =
3846 if (isSingleScalar())
3847 return ScalarCost;
3848
3849 // If any of the operands is from a different replicate region and has its
3850 // cost skipped, it may have been forced to scalar. Fall back to legacy cost
3851 // model to avoid cost mis-match.
3852 if (any_of(operands(), [&Ctx, VF](VPValue *Op) {
3853 auto *PredR = dyn_cast<VPPredInstPHIRecipe>(Op);
3854 if (!PredR)
3855 return false;
3856 return Ctx.skipCostComputation(
3858 PredR->getOperand(0)->getUnderlyingValue()),
3859 VF.isVector());
3860 }))
3861 break;
3862
3863 ScalarCost = ScalarCost * VF.getFixedValue() +
3864 Ctx.getScalarizationOverhead(this->getScalarType(),
3865 to_vector(operands()), VF);
3866 // If the recipe is not predicated (i.e. not in a replicate region), return
3867 // the scalar cost. Otherwise handle predicated cost.
3868 if (!getRegion()->isReplicator())
3869 return ScalarCost;
3870
3871 // Account for the phi nodes that we will create.
3872 ScalarCost += VF.getFixedValue() *
3873 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3874 // Scale the cost by the probability of executing the predicated blocks.
3875 // This assumes the predicated block for each vector lane is equally
3876 // likely.
3877 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3878 return ScalarCost;
3879 }
3880 case Instruction::Load:
3881 case Instruction::Store: {
3882 bool IsLoad = UI->getOpcode() == Instruction::Load;
3883 const VPValue *PtrOp = getOperand(!IsLoad);
3884 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.PSE, Ctx.L);
3886 break;
3887
3888 Type *ValTy = (IsLoad ? this : getOperand(0))->getScalarType();
3889 Type *ScalarPtrTy = PtrOp->getScalarType();
3890 const Align Alignment = getLoadStoreAlignment(UI);
3891 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3893 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3894 bool UsedByLoadStoreAddress =
3895 !PreferVectorizedAddressing && vputils::isUsedByLoadStoreAddress(this);
3896 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3897 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo,
3898 UsedByLoadStoreAddress ? UI : nullptr);
3899
3900 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3901 InstructionCost ScalarCost =
3902 ScalarMemOpCost +
3903 Ctx.TTI.getAddressComputationCost(
3904 PtrTy, UsedByLoadStoreAddress ? nullptr : Ctx.PSE.getSE(), PtrSCEV,
3905 Ctx.CostKind);
3906 if (isSingleScalar())
3907 return ScalarCost;
3908
3909 SmallVector<const VPValue *> OpsToScalarize;
3910 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3911 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3912 // don't assign scalarization overhead in general, if the target prefers
3913 // vectorized addressing or the loaded value is used as part of an address
3914 // of another load or store.
3915 if (!UsedByLoadStoreAddress) {
3916 bool EfficientVectorLoadStore =
3917 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3918 if (!(IsLoad && !PreferVectorizedAddressing) &&
3919 !(!IsLoad && EfficientVectorLoadStore))
3920 append_range(OpsToScalarize, operands());
3921
3922 if (!EfficientVectorLoadStore)
3923 ResultTy = this->getScalarType();
3924 }
3925
3929 (ScalarCost * VF.getFixedValue()) +
3930 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, VIC, true);
3931
3932 const VPRegionBlock *ParentRegion = getRegion();
3933 if (ParentRegion && ParentRegion->isReplicator()) {
3934 if (!PtrSCEV)
3935 break;
3936 Cost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3937 Cost += Ctx.TTI.getCFInstrCost(Instruction::CondBr, Ctx.CostKind);
3938
3939 auto *VecI1Ty = VectorType::get(
3940 IntegerType::getInt1Ty(Ctx.L->getHeader()->getContext()), VF);
3941 Cost += Ctx.TTI.getScalarizationOverhead(
3942 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3943 /*Insert=*/false, /*Extract=*/true, Ctx.CostKind);
3944
3945 if (Ctx.useEmulatedMaskMemRefHack(this, VF)) {
3946 // Artificially setting to a high enough value to practically disable
3947 // vectorization with such operations.
3948 return 3000000;
3949 }
3950 }
3951 return Cost;
3952 }
3953 case Instruction::SExt:
3954 case Instruction::ZExt:
3955 case Instruction::FPToUI:
3956 case Instruction::FPToSI:
3957 case Instruction::FPExt:
3958 case Instruction::PtrToInt:
3959 case Instruction::PtrToAddr:
3960 case Instruction::IntToPtr:
3961 case Instruction::SIToFP:
3962 case Instruction::UIToFP:
3963 case Instruction::Trunc:
3964 case Instruction::FPTrunc:
3965 case Instruction::Select:
3966 case Instruction::AddrSpaceCast: {
3968 Ctx) *
3969 (isSingleScalar() ? 1 : VF.getFixedValue());
3970 }
3971 case Instruction::ExtractValue:
3972 case Instruction::InsertValue:
3973 return Ctx.TTI.getInsertExtractValueCost(getOpcode(), Ctx.CostKind);
3974 }
3975
3976 return Ctx.getLegacyCost(UI, VF);
3977}
3978
3980 Function *CalledFn, Type *ResultTy, ArrayRef<const VPValue *> ArgOps,
3981 bool IsSingleScalar, ElementCount VF, VPCostContext &Ctx) {
3983 ArgOps, [&](const VPValue *Op) { return Op->getScalarType(); });
3984
3985 Intrinsic::ID IntrinID = CalledFn->getIntrinsicID();
3986 auto GetIntrinsicCost = [&] {
3987 if (!IntrinID)
3989 return Ctx.TTI.getIntrinsicInstrCost(
3990 IntrinsicCostAttributes(IntrinID, ResultTy, Tys), Ctx.CostKind);
3991 };
3992
3993 if (IntrinID && VPCostContext::isFreeScalarIntrinsic(IntrinID)) {
3994 assert(GetIntrinsicCost() == 0 && "scalarizing intrinsic should be free");
3995 return 0;
3996 }
3997
3998 InstructionCost ScalarCallCost =
3999 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
4000 if (IsSingleScalar) {
4001 ScalarCallCost = std::min(ScalarCallCost, GetIntrinsicCost());
4002 return ScalarCallCost;
4003 }
4004
4005 // Scalarization overhead is undefined for scalable VFs.
4006 if (VF.isScalable())
4008
4009 return ScalarCallCost * VF.getFixedValue() +
4010 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
4011}
4012
4013#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4015 VPSlotTracker &SlotTracker) const {
4016 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
4017
4018 if (!getScalarType()->isVoidTy()) {
4020 O << " = ";
4021 }
4022 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
4023 O << "call";
4024 printFlags(O);
4025 O << "@" << CB->getCalledFunction()->getName() << "(";
4027 Op->printAsOperand(O, SlotTracker);
4028 });
4029 O << ")";
4030 } else {
4032 printFlags(O);
4034 }
4035
4036 // Find if the recipe is used by a widened recipe via an intervening
4037 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
4038 if (any_of(users(), [](const VPUser *U) {
4039 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
4040 return !vputils::onlyScalarValuesUsed(PredR);
4041 return false;
4042 }))
4043 O << " (S->V)";
4044}
4045#endif
4046
4048 llvm_unreachable("recipe must be removed when dissolving replicate region");
4049}
4050
4052 VPCostContext &Ctx) const {
4053 // The legacy cost model doesn't assign costs to branches for individual
4054 // replicate regions. Match the current behavior in the VPlan cost model for
4055 // now.
4056 return 0;
4057}
4058
4060 llvm_unreachable("recipe must be removed when dissolving replicate region");
4061}
4062
4063#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4065 VPSlotTracker &SlotTracker) const {
4066 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
4068 O << " = ";
4070}
4071#endif
4072
4074const VPRecipeBase *VPWidenLoadRecipe::getAsRecipe() const { return this; }
4075
4078
4080const VPRecipeBase *VPWidenStoreRecipe::getAsRecipe() const { return this; }
4081
4084
4086 VPCostContext &Ctx) const {
4087 const VPRecipeBase *R = getAsRecipe();
4089 Type *ScalarTy = IsLoad ? cast<VPSingleDefRecipe>(R)->getScalarType()
4090 : R->getOperand(1)->getScalarType();
4091 Type *Ty = toVectorTy(ScalarTy, VF);
4092 unsigned AS =
4093 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4094 unsigned Opcode = IsLoad ? Instruction::Load : Instruction::Store;
4095
4096 if (!Consecutive) {
4097 // TODO: Using the original IR may not be accurate.
4098 // Currently, ARM will use the underlying IR to calculate gather/scatter
4099 // instruction cost.
4100 Type *PtrTy = getAddr()->getScalarType();
4101 const Value *Ptr = getAddr()->getUnderlyingValue();
4102
4103 // If the address value is uniform across all lanes, then the address can be
4104 // calculated with scalar type and broadcast.
4106 PtrTy = toVectorTy(PtrTy, VF);
4107
4108 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_gather
4109 : isa<VPWidenStoreRecipe>(R) ? Intrinsic::masked_scatter
4110 : isa<VPWidenLoadEVLRecipe>(R) ? Intrinsic::vp_gather
4111 : Intrinsic::vp_scatter;
4112 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4113 Ctx.CostKind) +
4114 Ctx.TTI.getMemIntrinsicInstrCost(
4116 &Ingredient),
4117 Ctx.CostKind);
4118 }
4119
4121 if (IsMasked) {
4122 unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
4123 : Intrinsic::masked_store;
4124 Cost += Ctx.TTI.getMemIntrinsicInstrCost(
4125 MemIntrinsicCostAttributes(IID, Ty, Alignment, AS), Ctx.CostKind);
4126 } else {
4127 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
4129 : R->getOperand(1));
4130 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
4131 OpInfo, &Ingredient);
4132 }
4133 return Cost;
4134}
4135
4137 Type *ScalarDataTy = getScalarType();
4138 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4139 bool CreateGather = !isConsecutive();
4140
4141 auto &Builder = State.Builder;
4142 Value *Mask = nullptr;
4143 if (auto *VPMask = getMask())
4144 Mask = State.get(VPMask);
4145
4146 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
4147 Value *NewLI;
4148 if (CreateGather) {
4149 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
4150 "wide.masked.gather");
4151 } else if (Mask) {
4152 NewLI =
4153 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
4154 PoisonValue::get(DataTy), "wide.masked.load");
4155 } else {
4156 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
4157 }
4159 State.set(this, NewLI);
4160}
4161
4162#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4164 VPSlotTracker &SlotTracker) const {
4165 O << Indent << "WIDEN ";
4167 O << " = load ";
4169}
4170#endif
4171
4173 Type *ScalarDataTy = getScalarType();
4174 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
4175 bool CreateGather = !isConsecutive();
4176
4177 auto &Builder = State.Builder;
4178 CallInst *NewLI;
4179 Value *EVL = State.get(getEVL(), VPLane(0));
4180 Value *Addr = State.get(getAddr(), !CreateGather);
4181 Value *Mask = nullptr;
4182 if (VPValue *VPMask = getMask())
4183 Mask = State.get(VPMask);
4184 else
4185 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4186
4187 if (CreateGather) {
4188 NewLI = Builder.CreateIntrinsicWithoutFolding(DataTy, Intrinsic::vp_gather,
4189 {Addr, Mask, EVL}, nullptr,
4190 "wide.masked.gather");
4191 } else {
4192 NewLI = Builder.CreateIntrinsicWithoutFolding(
4193 DataTy, Intrinsic::vp_load, {Addr, Mask, EVL}, nullptr, "vp.op.load");
4194 }
4195 NewLI->addParamAttr(
4197 applyMetadata(*NewLI);
4198 State.set(this, NewLI);
4199}
4200
4202 VPCostContext &Ctx) const {
4203 if (!Consecutive || IsMasked)
4204 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4205
4206 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4207 // here because the EVL recipes using EVL to replace the tail mask. But in the
4208 // legacy model, it will always calculate the cost of mask.
4209 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4210 // don't need to compare to the legacy cost model.
4211 Type *Ty = toVectorTy(getScalarType(), VF);
4212 unsigned AS =
4213 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4214 return Ctx.TTI.getMemIntrinsicInstrCost(
4215 MemIntrinsicCostAttributes(Intrinsic::vp_load, Ty, Alignment, AS),
4216 Ctx.CostKind);
4217}
4218
4219#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4221 VPSlotTracker &SlotTracker) const {
4222 O << Indent << "WIDEN ";
4224 O << " = vp.load ";
4226}
4227#endif
4228
4230 VPValue *StoredVPValue = getStoredValue();
4231 bool CreateScatter = !isConsecutive();
4232
4233 auto &Builder = State.Builder;
4234
4235 Value *Mask = nullptr;
4236 if (auto *VPMask = getMask())
4237 Mask = State.get(VPMask);
4238
4239 Value *StoredVal = State.get(StoredVPValue);
4240 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
4241 Instruction *NewSI = nullptr;
4242 if (CreateScatter)
4243 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
4244 else if (Mask)
4245 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
4246 else
4247 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
4248 applyMetadata(*NewSI);
4249}
4250
4251#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4253 VPSlotTracker &SlotTracker) const {
4254 O << Indent << "WIDEN store ";
4256}
4257#endif
4258
4260 VPValue *StoredValue = getStoredValue();
4261 bool CreateScatter = !isConsecutive();
4262
4263 auto &Builder = State.Builder;
4264
4265 CallInst *NewSI = nullptr;
4266 Value *StoredVal = State.get(StoredValue);
4267 Value *EVL = State.get(getEVL(), VPLane(0));
4268 Value *Mask = nullptr;
4269 if (VPValue *VPMask = getMask())
4270 Mask = State.get(VPMask);
4271 else
4272 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
4273
4274 Value *Addr = State.get(getAddr(), !CreateScatter);
4275 if (CreateScatter) {
4276 NewSI = Builder.CreateIntrinsicWithoutFolding(
4277 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_scatter,
4278 {StoredVal, Addr, Mask, EVL});
4279 } else {
4280 NewSI = Builder.CreateIntrinsicWithoutFolding(
4281 Type::getVoidTy(EVL->getContext()), Intrinsic::vp_store,
4282 {StoredVal, Addr, Mask, EVL});
4283 }
4284 NewSI->addParamAttr(
4286 applyMetadata(*NewSI);
4287}
4288
4290 VPCostContext &Ctx) const {
4291 if (!Consecutive || IsMasked)
4292 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4293
4294 // We need to use the getMemIntrinsicInstrCost() instead of getMemoryOpCost()
4295 // here because the EVL recipes using EVL to replace the tail mask. But in the
4296 // legacy model, it will always calculate the cost of mask.
4297 // TODO: Using getMemoryOpCost() instead of getMemIntrinsicInstrCost when we
4298 // don't need to compare to the legacy cost model.
4299 Type *Ty = toVectorTy(getStoredValue()->getScalarType(), VF);
4300 unsigned AS =
4301 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4302 return Ctx.TTI.getMemIntrinsicInstrCost(
4303 MemIntrinsicCostAttributes(Intrinsic::vp_store, Ty, Alignment, AS),
4304 Ctx.CostKind);
4305}
4306
4307#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4309 VPSlotTracker &SlotTracker) const {
4310 O << Indent << "WIDEN vp.store ";
4312}
4313#endif
4314
4316 VectorType *DstVTy, const DataLayout &DL) {
4317 // Verify that V is a vector type with same number of elements as DstVTy.
4318 auto VF = DstVTy->getElementCount();
4319 auto *SrcVecTy = cast<VectorType>(V->getType());
4320 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
4321 Type *SrcElemTy = SrcVecTy->getElementType();
4322 Type *DstElemTy = DstVTy->getElementType();
4323 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
4324 "Vector elements must have same size");
4325
4326 // Do a direct cast if element types are castable.
4327 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
4328 return Builder.CreateBitOrPointerCast(V, DstVTy);
4329 }
4330 // V cannot be directly casted to desired vector type.
4331 // May happen when V is a floating point vector but DstVTy is a vector of
4332 // pointers or vice-versa. Handle this using a two-step bitcast using an
4333 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
4334 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
4335 "Only one type should be a pointer type");
4336 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
4337 "Only one type should be a floating point type");
4338 Type *IntTy =
4339 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
4340 auto *VecIntTy = VectorType::get(IntTy, VF);
4341 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
4342 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
4343}
4344
4345/// Return a vector containing interleaved elements from multiple
4346/// smaller input vectors.
4348 const Twine &Name) {
4349 unsigned Factor = Vals.size();
4350 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
4351
4352 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
4353#ifndef NDEBUG
4354 for (Value *Val : Vals)
4355 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
4356#endif
4357
4358 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
4359 // must use intrinsics to interleave.
4360 if (VecTy->isScalableTy()) {
4361 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
4362 return Builder.CreateVectorInterleave(Vals, Name);
4363 }
4364
4365 // Fixed length. Start by concatenating all vectors into a wide vector.
4366 Value *WideVec = concatenateVectors(Builder, Vals);
4367
4368 // Interleave the elements into the wide vector.
4369 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
4370 return Builder.CreateShuffleVector(
4371 WideVec, createInterleaveMask(NumElts, Factor), Name);
4372}
4373
4374// Try to vectorize the interleave group that \p Instr belongs to.
4375//
4376// E.g. Translate following interleaved load group (factor = 3):
4377// for (i = 0; i < N; i+=3) {
4378// R = Pic[i]; // Member of index 0
4379// G = Pic[i+1]; // Member of index 1
4380// B = Pic[i+2]; // Member of index 2
4381// ... // do something to R, G, B
4382// }
4383// To:
4384// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
4385// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
4386// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
4387// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
4388//
4389// Or translate following interleaved store group (factor = 3):
4390// for (i = 0; i < N; i+=3) {
4391// ... do something to R, G, B
4392// Pic[i] = R; // Member of index 0
4393// Pic[i+1] = G; // Member of index 1
4394// Pic[i+2] = B; // Member of index 2
4395// }
4396// To:
4397// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
4398// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
4399// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
4400// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
4401// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
4403 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
4404 "Masking gaps for scalable vectors is not yet supported.");
4406 Instruction *Instr = Group->getInsertPos();
4407
4408 // Prepare for the vector type of the interleaved load/store.
4409 Type *ScalarTy = getLoadStoreType(Instr);
4410 unsigned InterleaveFactor = Group->getFactor();
4411 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
4412
4413 VPValue *BlockInMask = getMask();
4414 VPValue *Addr = getAddr();
4415 Value *ResAddr = State.get(Addr, VPLane(0));
4416
4417 auto CreateGroupMask = [&BlockInMask, &State,
4418 &InterleaveFactor](Value *MaskForGaps) -> Value * {
4419 if (State.VF.isScalable()) {
4420 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
4421 assert(InterleaveFactor <= 8 &&
4422 "Unsupported deinterleave factor for scalable vectors");
4423 auto *ResBlockInMask = State.get(BlockInMask);
4424 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
4425 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
4426 }
4427
4428 if (!BlockInMask)
4429 return MaskForGaps;
4430
4431 Value *ResBlockInMask = State.get(BlockInMask);
4432 Value *ShuffledMask = State.Builder.CreateShuffleVector(
4433 ResBlockInMask,
4434 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
4435 "interleaved.mask");
4436 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
4437 ShuffledMask, MaskForGaps)
4438 : ShuffledMask;
4439 };
4440
4441 const DataLayout &DL = Instr->getDataLayout();
4442 // Vectorize the interleaved load group.
4443 if (isa<LoadInst>(Instr)) {
4444 Value *MaskForGaps = nullptr;
4445 if (needsMaskForGaps()) {
4446 MaskForGaps =
4447 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
4448 assert(MaskForGaps && "Mask for Gaps is required but it is null");
4449 }
4450
4451 Instruction *NewLoad;
4452 if (BlockInMask || MaskForGaps) {
4453 Value *GroupMask = CreateGroupMask(MaskForGaps);
4454 Value *PoisonVec = PoisonValue::get(VecTy);
4455 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
4456 Group->getAlign(), GroupMask,
4457 PoisonVec, "wide.masked.vec");
4458 } else
4459 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
4460 Group->getAlign(), "wide.vec");
4461 applyMetadata(*NewLoad);
4462 // TODO: Also manage existing metadata using VPIRMetadata.
4463 Group->addMetadata(NewLoad);
4464
4466 if (VecTy->isScalableTy()) {
4467 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4468 // so must use intrinsics to deinterleave.
4469 assert(InterleaveFactor <= 8 &&
4470 "Unsupported deinterleave factor for scalable vectors");
4471 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4472 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4473 NewLoad->getType(), NewLoad,
4474 /*FMFSource=*/nullptr, "strided.vec");
4475 }
4476
4477 auto CreateStridedVector = [&InterleaveFactor, &State,
4478 &NewLoad](unsigned Index) -> Value * {
4479 assert(Index < InterleaveFactor && "Illegal group index");
4480 if (State.VF.isScalable())
4481 return State.Builder.CreateExtractValue(NewLoad, Index);
4482
4483 // For fixed length VF, use shuffle to extract the sub-vectors from the
4484 // wide load.
4485 auto StrideMask =
4486 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
4487 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
4488 "strided.vec");
4489 };
4490
4491 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4492 Instruction *Member = Group->getMember(I);
4493
4494 // Skip the gaps in the group.
4495 if (!Member)
4496 continue;
4497
4498 Value *StridedVec = CreateStridedVector(I);
4499
4500 // If this member has different type, cast the result type.
4501 if (Member->getType() != ScalarTy) {
4502 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4503 StridedVec =
4504 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4505 }
4506
4507 if (Group->isReverse())
4508 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
4509
4510 State.set(VPDefs[J], StridedVec);
4511 ++J;
4512 }
4513 return;
4514 }
4515
4516 // The sub vector type for current instruction.
4517 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4518
4519 // Vectorize the interleaved store group.
4520 Value *MaskForGaps =
4521 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
4522 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
4523 "Mismatch between NeedsMaskForGaps and MaskForGaps");
4524 ArrayRef<VPValue *> StoredValues = getStoredValues();
4525 // Collect the stored vector from each member.
4526 SmallVector<Value *, 4> StoredVecs;
4527 unsigned StoredIdx = 0;
4528 for (unsigned i = 0; i < InterleaveFactor; i++) {
4529 assert((Group->getMember(i) || MaskForGaps) &&
4530 "Fail to get a member from an interleaved store group");
4531 Instruction *Member = Group->getMember(i);
4532
4533 // Skip the gaps in the group.
4534 if (!Member) {
4535 Value *Undef = PoisonValue::get(SubVT);
4536 StoredVecs.push_back(Undef);
4537 continue;
4538 }
4539
4540 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4541 ++StoredIdx;
4542
4543 if (Group->isReverse())
4544 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
4545
4546 // If this member has different type, cast it to a unified type.
4547
4548 if (StoredVec->getType() != SubVT)
4549 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4550
4551 StoredVecs.push_back(StoredVec);
4552 }
4553
4554 // Interleave all the smaller vectors into one wider vector.
4555 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4556 Instruction *NewStoreInstr;
4557 if (BlockInMask || MaskForGaps) {
4558 Value *GroupMask = CreateGroupMask(MaskForGaps);
4559 NewStoreInstr = State.Builder.CreateMaskedStore(
4560 IVec, ResAddr, Group->getAlign(), GroupMask);
4561 } else
4562 NewStoreInstr =
4563 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4564
4565 applyMetadata(*NewStoreInstr);
4566 // TODO: Also manage existing metadata using VPIRMetadata.
4567 Group->addMetadata(NewStoreInstr);
4568}
4569
4570#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4572 VPSlotTracker &SlotTracker) const {
4574 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4576 VPValue *Mask = getMask();
4577 if (Mask) {
4578 O << ", ";
4579 Mask->printAsOperand(O, SlotTracker);
4580 }
4581
4582 unsigned OpIdx = 0;
4583 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4584 if (!IG->getMember(i))
4585 continue;
4586 if (getNumStoreOperands() > 0) {
4587 O << "\n" << Indent << " store ";
4589 O << " to index " << i;
4590 } else {
4591 O << "\n" << Indent << " ";
4593 O << " = load from index " << i;
4594 }
4595 ++OpIdx;
4596 }
4597}
4598#endif
4599
4601 assert(State.VF.isScalable() &&
4602 "Only support scalable VF for EVL tail-folding.");
4604 "Masking gaps for scalable vectors is not yet supported.");
4606 Instruction *Instr = Group->getInsertPos();
4607
4608 // Prepare for the vector type of the interleaved load/store.
4609 Type *ScalarTy = getLoadStoreType(Instr);
4610 unsigned InterleaveFactor = Group->getFactor();
4611 assert(InterleaveFactor <= 8 &&
4612 "Unsupported deinterleave/interleave factor for scalable vectors");
4613 ElementCount WideVF = State.VF * InterleaveFactor;
4614 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4615
4616 VPValue *Addr = getAddr();
4617 Value *ResAddr = State.get(Addr, VPLane(0));
4618 Value *EVL = State.get(getEVL(), VPLane(0));
4619 Value *InterleaveEVL = State.Builder.CreateMul(
4620 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4621 /* NUW= */ true, /* NSW= */ true);
4622 LLVMContext &Ctx = State.Builder.getContext();
4623
4624 Value *GroupMask = nullptr;
4625 if (VPValue *BlockInMask = getMask()) {
4626 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4627 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4628 } else {
4629 GroupMask =
4630 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4631 }
4632
4633 // Vectorize the interleaved load group.
4634 if (isa<LoadInst>(Instr)) {
4635 CallInst *NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4636 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4637 "wide.vp.load");
4638 NewLoad->addParamAttr(0,
4639 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4640
4641 applyMetadata(*NewLoad);
4642 // TODO: Also manage existing metadata using VPIRMetadata.
4643 Group->addMetadata(NewLoad);
4644
4645 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4646 // so must use intrinsics to deinterleave.
4647 NewLoad = State.Builder.CreateIntrinsicWithoutFolding(
4648 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4649 NewLoad->getType(), NewLoad,
4650 /*FMFSource=*/nullptr, "strided.vec");
4651
4652 const DataLayout &DL = Instr->getDataLayout();
4653 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4654 Instruction *Member = Group->getMember(I);
4655 // Skip the gaps in the group.
4656 if (!Member)
4657 continue;
4658
4659 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4660 // If this member has different type, cast the result type.
4661 if (Member->getType() != ScalarTy) {
4662 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4663 StridedVec =
4664 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4665 }
4666
4667 State.set(getVPValue(J), StridedVec);
4668 ++J;
4669 }
4670 return;
4671 } // End for interleaved load.
4672
4673 // The sub vector type for current instruction.
4674 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4675 // Vectorize the interleaved store group.
4676 ArrayRef<VPValue *> StoredValues = getStoredValues();
4677 // Collect the stored vector from each member.
4678 SmallVector<Value *, 4> StoredVecs;
4679 const DataLayout &DL = Instr->getDataLayout();
4680 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4681 Instruction *Member = Group->getMember(I);
4682 // Skip the gaps in the group.
4683 if (!Member) {
4684 StoredVecs.push_back(PoisonValue::get(SubVT));
4685 continue;
4686 }
4687
4688 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4689 // If this member has different type, cast it to a unified type.
4690 if (StoredVec->getType() != SubVT)
4691 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4692
4693 StoredVecs.push_back(StoredVec);
4694 ++StoredIdx;
4695 }
4696
4697 // Interleave all the smaller vectors into one wider vector.
4698 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4699 CallInst *NewStore = State.Builder.CreateIntrinsicWithoutFolding(
4700 Type::getVoidTy(Ctx), Intrinsic::vp_store,
4701 {IVec, ResAddr, GroupMask, InterleaveEVL});
4702
4703 NewStore->addParamAttr(1,
4704 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4705
4706 applyMetadata(*NewStore);
4707 // TODO: Also manage existing metadata using VPIRMetadata.
4708 Group->addMetadata(NewStore);
4709}
4710
4711#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4713 VPSlotTracker &SlotTracker) const {
4715 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << ", ";
4717 O << ", ";
4719 if (VPValue *Mask = getMask()) {
4720 O << ", ";
4721 Mask->printAsOperand(O, SlotTracker);
4722 }
4723
4724 unsigned OpIdx = 0;
4725 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4726 if (!IG->getMember(i))
4727 continue;
4728 if (getNumStoreOperands() > 0) {
4729 O << "\n" << Indent << " vp.store ";
4731 O << " to index " << i;
4732 } else {
4733 O << "\n" << Indent << " ";
4735 O << " = vp.load from index " << i;
4736 }
4737 ++OpIdx;
4738 }
4739}
4740#endif
4741
4743 VPCostContext &Ctx) const {
4744 Instruction *InsertPos = getInsertPos();
4745 // Find the VPValue index of the interleave group. We need to skip gaps.
4746 unsigned InsertPosIdx = 0;
4747 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4748 if (auto *Member = IG->getMember(Idx)) {
4749 if (Member == InsertPos)
4750 break;
4751 InsertPosIdx++;
4752 }
4753 const VPValue *ValV = getNumDefinedValues() > 0
4754 ? getVPValue(InsertPosIdx)
4755 : getStoredValues()[InsertPosIdx];
4756 Type *ValTy = ValV->getScalarType();
4757 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4758 unsigned AS =
4759 cast<PointerType>(getAddr()->getScalarType())->getAddressSpace();
4760
4761 unsigned InterleaveFactor = IG->getFactor();
4762 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4763
4764 // Holds the indices of existing members in the interleaved group.
4766 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4767 if (IG->getMember(IF))
4768 Indices.push_back(IF);
4769
4770 // Calculate the cost of the whole interleaved group.
4771 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4772 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4773 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4774
4775 if (!IG->isReverse())
4776 return Cost;
4777
4778 return Cost + IG->getNumMembers() *
4779 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4780 VectorTy, VectorTy, {}, Ctx.CostKind,
4781 0);
4782}
4783
4785 return vputils::onlyScalarValuesUsed(this) &&
4786 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4787}
4788
4789#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4791 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4792 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4793 "unexpected number of operands");
4794 O << Indent << "EMIT ";
4796 O << " = WIDEN-POINTER-INDUCTION ";
4798 O << ", ";
4800 O << ", ";
4802 if (getNumOperands() == 5) {
4803 O << ", ";
4805 O << ", ";
4807 }
4808}
4809
4811 VPSlotTracker &SlotTracker) const {
4812 O << Indent << "EMIT ";
4814 O << " = EXPAND SCEV " << *Expr;
4815}
4816#endif
4817
4818#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4820 VPSlotTracker &SlotTracker) const {
4821 O << Indent << "EMIT ";
4823 O << " = WIDEN-CANONICAL-INDUCTION";
4824 printFlags(O);
4826}
4827#endif
4828
4830 auto &Builder = State.Builder;
4831 // Create a vector from the initial value.
4832 auto *VectorInit = getStartValue()->getLiveInIRValue();
4833
4834 Type *VecTy = State.VF.isScalar()
4835 ? VectorInit->getType()
4836 : VectorType::get(VectorInit->getType(), State.VF);
4837
4838 BasicBlock *VectorPH =
4839 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4840 if (State.VF.isVector()) {
4841 auto *IdxTy = Builder.getInt32Ty();
4842 auto *One = ConstantInt::get(IdxTy, 1);
4843 IRBuilder<>::InsertPointGuard Guard(Builder);
4844 Builder.SetInsertPoint(VectorPH->getTerminator());
4845 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4846 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4847 VectorInit = Builder.CreateInsertElement(
4848 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4849 }
4850
4851 // Create a phi node for the new recurrence.
4852 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4853 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4854 Phi->addIncoming(VectorInit, VectorPH);
4855 State.set(this, Phi);
4856}
4857
4860 VPCostContext &Ctx) const {
4861 if (VF.isScalar())
4862 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4863
4864 return 0;
4865}
4866
4867#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4869 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4870 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4872 O << " = phi ";
4874}
4875#endif
4876
4878 // Reductions do not have to start at zero. They can start with
4879 // any loop invariant values.
4880 VPValue *StartVPV = getStartValue();
4881
4882 // In order to support recurrences we need to be able to vectorize Phi nodes.
4883 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4884 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4885 // this value when we vectorize all of the instructions that use the PHI.
4886 BasicBlock *VectorPH =
4887 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4888 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4889 Value *StartV = State.get(StartVPV, ScalarPHI);
4890 Type *VecTy = StartV->getType();
4891
4892 BasicBlock *HeaderBB = State.CFG.PrevBB;
4893 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4894 "recipe must be in the vector loop header");
4895 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4896 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4897 State.set(this, Phi, isInLoop());
4898
4899 Phi->addIncoming(StartV, VectorPH);
4900}
4901
4902#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4904 VPSlotTracker &SlotTracker) const {
4905 O << Indent << "WIDEN-REDUCTION-PHI ";
4906
4908 O << " = phi (";
4909 printRecurrenceKind(O, Kind);
4910 O << ")";
4911 printFlags(O);
4913 if (getVFScaleFactor() > 1)
4914 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4915}
4916#endif
4917
4919 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
4920 return vputils::onlyFirstLaneUsed(this);
4921}
4922
4924 executePhiRecipe(this, *this, State, /*IsScalar=*/false, Name);
4925}
4926
4928 VPCostContext &Ctx) const {
4929 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4930}
4931
4932#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4934 VPSlotTracker &SlotTracker) const {
4935 O << Indent << "WIDEN-PHI ";
4936
4938 O << " = phi ";
4940}
4941#endif
4942
4944 BasicBlock *VectorPH =
4945 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4946 Value *StartMask = State.get(getOperand(0));
4947 PHINode *Phi =
4948 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4949 Phi->addIncoming(StartMask, VectorPH);
4950 State.set(this, Phi);
4951}
4952
4953#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4955 VPSlotTracker &SlotTracker) const {
4956 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4957
4959 O << " = phi ";
4961}
4962#endif
4963
4964#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4966 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4967 O << Indent << "CURRENT-ITERATION-PHI ";
4968
4970 O << " = phi ";
4972}
4973#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