LLVM 22.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 "VPlanAnalysis.h"
17#include "VPlanHelpers.h"
18#include "VPlanPatternMatch.h"
19#include "VPlanUtils.h"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Twine.h"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Type.h"
32#include "llvm/IR/Value.h"
35#include "llvm/Support/Debug.h"
39#include <cassert>
40
41using namespace llvm;
42using namespace llvm::VPlanPatternMatch;
43
45
46#define LV_NAME "loop-vectorize"
47#define DEBUG_TYPE LV_NAME
48
50 switch (getVPDefID()) {
51 case VPExpressionSC:
52 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
53 case VPInstructionSC: {
54 auto *VPI = cast<VPInstruction>(this);
55 // Loads read from memory but don't write to memory.
56 if (VPI->getOpcode() == Instruction::Load)
57 return false;
58 return VPI->opcodeMayReadOrWriteFromMemory();
59 }
60 case VPInterleaveEVLSC:
61 case VPInterleaveSC:
62 return cast<VPInterleaveBase>(this)->getNumStoreOperands() > 0;
63 case VPWidenStoreEVLSC:
64 case VPWidenStoreSC:
65 return true;
66 case VPReplicateSC:
67 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
68 ->mayWriteToMemory();
69 case VPWidenCallSC:
70 return !cast<VPWidenCallRecipe>(this)
71 ->getCalledScalarFunction()
72 ->onlyReadsMemory();
73 case VPWidenIntrinsicSC:
74 return cast<VPWidenIntrinsicRecipe>(this)->mayWriteToMemory();
75 case VPCanonicalIVPHISC:
76 case VPBranchOnMaskSC:
77 case VPDerivedIVSC:
78 case VPFirstOrderRecurrencePHISC:
79 case VPReductionPHISC:
80 case VPScalarIVStepsSC:
81 case VPPredInstPHISC:
82 return false;
83 case VPBlendSC:
84 case VPReductionEVLSC:
85 case VPReductionSC:
86 case VPVectorPointerSC:
87 case VPWidenCanonicalIVSC:
88 case VPWidenCastSC:
89 case VPWidenGEPSC:
90 case VPWidenIntOrFpInductionSC:
91 case VPWidenLoadEVLSC:
92 case VPWidenLoadSC:
93 case VPWidenPHISC:
94 case VPWidenPointerInductionSC:
95 case VPWidenSC:
96 case VPWidenSelectSC: {
97 const Instruction *I =
98 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
99 (void)I;
100 assert((!I || !I->mayWriteToMemory()) &&
101 "underlying instruction may write to memory");
102 return false;
103 }
104 default:
105 return true;
106 }
107}
108
110 switch (getVPDefID()) {
111 case VPExpressionSC:
112 return cast<VPExpressionRecipe>(this)->mayReadOrWriteMemory();
113 case VPInstructionSC:
114 return cast<VPInstruction>(this)->opcodeMayReadOrWriteFromMemory();
115 case VPWidenLoadEVLSC:
116 case VPWidenLoadSC:
117 return true;
118 case VPReplicateSC:
119 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
120 ->mayReadFromMemory();
121 case VPWidenCallSC:
122 return !cast<VPWidenCallRecipe>(this)
123 ->getCalledScalarFunction()
124 ->onlyWritesMemory();
125 case VPWidenIntrinsicSC:
126 return cast<VPWidenIntrinsicRecipe>(this)->mayReadFromMemory();
127 case VPBranchOnMaskSC:
128 case VPDerivedIVSC:
129 case VPFirstOrderRecurrencePHISC:
130 case VPPredInstPHISC:
131 case VPScalarIVStepsSC:
132 case VPWidenStoreEVLSC:
133 case VPWidenStoreSC:
134 return false;
135 case VPBlendSC:
136 case VPReductionEVLSC:
137 case VPReductionSC:
138 case VPVectorPointerSC:
139 case VPWidenCanonicalIVSC:
140 case VPWidenCastSC:
141 case VPWidenGEPSC:
142 case VPWidenIntOrFpInductionSC:
143 case VPWidenPHISC:
144 case VPWidenPointerInductionSC:
145 case VPWidenSC:
146 case VPWidenSelectSC: {
147 const Instruction *I =
148 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
149 (void)I;
150 assert((!I || !I->mayReadFromMemory()) &&
151 "underlying instruction may read from memory");
152 return false;
153 }
154 default:
155 // FIXME: Return false if the recipe represents an interleaved store.
156 return true;
157 }
158}
159
161 switch (getVPDefID()) {
162 case VPExpressionSC:
163 return cast<VPExpressionRecipe>(this)->mayHaveSideEffects();
164 case VPDerivedIVSC:
165 case VPFirstOrderRecurrencePHISC:
166 case VPPredInstPHISC:
167 case VPVectorEndPointerSC:
168 return false;
169 case VPInstructionSC: {
170 auto *VPI = cast<VPInstruction>(this);
171 return mayWriteToMemory() ||
172 VPI->getOpcode() == VPInstruction::BranchOnCount ||
173 VPI->getOpcode() == VPInstruction::BranchOnCond;
174 }
175 case VPWidenCallSC: {
176 Function *Fn = cast<VPWidenCallRecipe>(this)->getCalledScalarFunction();
177 return mayWriteToMemory() || !Fn->doesNotThrow() || !Fn->willReturn();
178 }
179 case VPWidenIntrinsicSC:
180 return cast<VPWidenIntrinsicRecipe>(this)->mayHaveSideEffects();
181 case VPBlendSC:
182 case VPReductionEVLSC:
183 case VPReductionSC:
184 case VPScalarIVStepsSC:
185 case VPVectorPointerSC:
186 case VPWidenCanonicalIVSC:
187 case VPWidenCastSC:
188 case VPWidenGEPSC:
189 case VPWidenIntOrFpInductionSC:
190 case VPWidenPHISC:
191 case VPWidenPointerInductionSC:
192 case VPWidenSC:
193 case VPWidenSelectSC: {
194 const Instruction *I =
195 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
196 (void)I;
197 assert((!I || !I->mayHaveSideEffects()) &&
198 "underlying instruction has side-effects");
199 return false;
200 }
201 case VPInterleaveEVLSC:
202 case VPInterleaveSC:
203 return mayWriteToMemory();
204 case VPWidenLoadEVLSC:
205 case VPWidenLoadSC:
206 case VPWidenStoreEVLSC:
207 case VPWidenStoreSC:
208 assert(
209 cast<VPWidenMemoryRecipe>(this)->getIngredient().mayHaveSideEffects() ==
211 "mayHaveSideffects result for ingredient differs from this "
212 "implementation");
213 return mayWriteToMemory();
214 case VPReplicateSC: {
215 auto *R = cast<VPReplicateRecipe>(this);
216 return R->getUnderlyingInstr()->mayHaveSideEffects();
217 }
218 default:
219 return true;
220 }
221}
222
224 assert(!Parent && "Recipe already in some VPBasicBlock");
225 assert(InsertPos->getParent() &&
226 "Insertion position not in any VPBasicBlock");
227 InsertPos->getParent()->insert(this, InsertPos->getIterator());
228}
229
230void VPRecipeBase::insertBefore(VPBasicBlock &BB,
232 assert(!Parent && "Recipe already in some VPBasicBlock");
233 assert(I == BB.end() || I->getParent() == &BB);
234 BB.insert(this, I);
235}
236
238 assert(!Parent && "Recipe already in some VPBasicBlock");
239 assert(InsertPos->getParent() &&
240 "Insertion position not in any VPBasicBlock");
241 InsertPos->getParent()->insert(this, std::next(InsertPos->getIterator()));
242}
243
245 assert(getParent() && "Recipe not in any VPBasicBlock");
247 Parent = nullptr;
248}
249
251 assert(getParent() && "Recipe not in any VPBasicBlock");
253}
254
257 insertAfter(InsertPos);
258}
259
265
267 // Get the underlying instruction for the recipe, if there is one. It is used
268 // to
269 // * decide if cost computation should be skipped for this recipe,
270 // * apply forced target instruction cost.
271 Instruction *UI = nullptr;
272 if (auto *S = dyn_cast<VPSingleDefRecipe>(this))
273 UI = dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
274 else if (auto *IG = dyn_cast<VPInterleaveBase>(this))
275 UI = IG->getInsertPos();
276 else if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(this))
277 UI = &WidenMem->getIngredient();
278
279 InstructionCost RecipeCost;
280 if (UI && Ctx.skipCostComputation(UI, VF.isVector())) {
281 RecipeCost = 0;
282 } else {
283 RecipeCost = computeCost(VF, Ctx);
284 RecipeCost = computeCost(VF, Ctx);
285 if (ForceTargetInstructionCost.getNumOccurrences() > 0 &&
286 RecipeCost.isValid()) {
287 if (UI)
289 else
290 RecipeCost = InstructionCost(0);
291 }
292 }
293
294 LLVM_DEBUG({
295 dbgs() << "Cost of " << RecipeCost << " for VF " << VF << ": ";
296 dump();
297 });
298 return RecipeCost;
299}
300
302 VPCostContext &Ctx) const {
303 llvm_unreachable("subclasses should implement computeCost");
304}
305
307 return (getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC) ||
309}
310
312 auto *VPI = dyn_cast<VPInstruction>(this);
313 return VPI && Instruction::isCast(VPI->getOpcode());
314}
315
317 assert(OpType == Other.OpType && "OpType must match");
318 switch (OpType) {
319 case OperationType::OverflowingBinOp:
320 WrapFlags.HasNUW &= Other.WrapFlags.HasNUW;
321 WrapFlags.HasNSW &= Other.WrapFlags.HasNSW;
322 break;
323 case OperationType::Trunc:
324 TruncFlags.HasNUW &= Other.TruncFlags.HasNUW;
325 TruncFlags.HasNSW &= Other.TruncFlags.HasNSW;
326 break;
327 case OperationType::DisjointOp:
328 DisjointFlags.IsDisjoint &= Other.DisjointFlags.IsDisjoint;
329 break;
330 case OperationType::PossiblyExactOp:
331 ExactFlags.IsExact &= Other.ExactFlags.IsExact;
332 break;
333 case OperationType::GEPOp:
334 GEPFlags &= Other.GEPFlags;
335 break;
336 case OperationType::FPMathOp:
337 case OperationType::FCmp:
338 assert((OpType != OperationType::FCmp ||
339 FCmpFlags.Pred == Other.FCmpFlags.Pred) &&
340 "Cannot drop CmpPredicate");
341 getFMFsRef().NoNaNs &= Other.getFMFsRef().NoNaNs;
342 getFMFsRef().NoInfs &= Other.getFMFsRef().NoInfs;
343 break;
344 case OperationType::NonNegOp:
345 NonNegFlags.NonNeg &= Other.NonNegFlags.NonNeg;
346 break;
347 case OperationType::Cmp:
348 assert(CmpPredicate == Other.CmpPredicate && "Cannot drop CmpPredicate");
349 break;
350 case OperationType::Other:
351 assert(AllFlags == Other.AllFlags && "Cannot drop other flags");
352 break;
353 }
354}
355
357 assert((OpType == OperationType::FPMathOp || OpType == OperationType::FCmp) &&
358 "recipe doesn't have fast math flags");
359 const FastMathFlagsTy &F = getFMFsRef();
360 FastMathFlags Res;
361 Res.setAllowReassoc(F.AllowReassoc);
362 Res.setNoNaNs(F.NoNaNs);
363 Res.setNoInfs(F.NoInfs);
364 Res.setNoSignedZeros(F.NoSignedZeros);
365 Res.setAllowReciprocal(F.AllowReciprocal);
366 Res.setAllowContract(F.AllowContract);
367 Res.setApproxFunc(F.ApproxFunc);
368 return Res;
369}
370
371#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
373
374void VPRecipeBase::print(raw_ostream &O, const Twine &Indent,
375 VPSlotTracker &SlotTracker) const {
376 printRecipe(O, Indent, SlotTracker);
377 if (auto DL = getDebugLoc()) {
378 O << ", !dbg ";
379 DL.print(O);
380 }
381}
382#endif
383
384template <unsigned PartOpIdx>
385VPValue *
387 if (U.getNumOperands() == PartOpIdx + 1)
388 return U.getOperand(PartOpIdx);
389 return nullptr;
390}
391
392template <unsigned PartOpIdx>
394 if (auto *UnrollPartOp = getUnrollPartOperand(U))
395 return cast<ConstantInt>(UnrollPartOp->getLiveInIRValue())->getZExtValue();
396 return 0;
397}
398
399namespace llvm {
400template class VPUnrollPartAccessor<1>;
401template class VPUnrollPartAccessor<2>;
402template class VPUnrollPartAccessor<3>;
403}
404
406 const VPIRFlags &Flags, const VPIRMetadata &MD,
407 DebugLoc DL, const Twine &Name)
408 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, Flags, DL),
409 VPIRMetadata(MD), Opcode(Opcode), Name(Name.str()) {
411 "Set flags not supported for the provided opcode");
412 assert((getNumOperandsForOpcode(Opcode) == -1u ||
413 getNumOperandsForOpcode(Opcode) == getNumOperands()) &&
414 "number of operands does not match opcode");
415}
416
417#ifndef NDEBUG
418unsigned VPInstruction::getNumOperandsForOpcode(unsigned Opcode) {
419 if (Instruction::isUnaryOp(Opcode) || Instruction::isCast(Opcode))
420 return 1;
421
422 if (Instruction::isBinaryOp(Opcode))
423 return 2;
424
425 switch (Opcode) {
428 return 0;
429 case Instruction::Alloca:
430 case Instruction::ExtractValue:
431 case Instruction::Freeze:
432 case Instruction::Load:
446 return 1;
447 case Instruction::ICmp:
448 case Instruction::FCmp:
449 case Instruction::ExtractElement:
450 case Instruction::Store:
459 return 2;
460 case Instruction::Select:
464 return 3;
466 return 4;
467 case Instruction::Call:
468 case Instruction::GetElementPtr:
469 case Instruction::PHI:
470 case Instruction::Switch:
476 // Cannot determine the number of operands from the opcode.
477 return -1u;
478 }
479 llvm_unreachable("all cases should be handled above");
480}
481#endif
482
486
487bool VPInstruction::canGenerateScalarForFirstLane() const {
489 return true;
491 return true;
492 switch (Opcode) {
493 case Instruction::Freeze:
494 case Instruction::ICmp:
495 case Instruction::PHI:
496 case Instruction::Select:
505 return true;
506 default:
507 return false;
508 }
509}
510
511/// Create a conditional branch using \p Cond branching to the successors of \p
512/// VPBB. Note that the first successor is always forward (i.e. not created yet)
513/// while the second successor may already have been created (if it is a header
514/// block and VPBB is a latch).
516 VPTransformState &State) {
517 // Replace the temporary unreachable terminator with a new conditional
518 // branch, hooking it up to backward destination (header) for latch blocks
519 // now, and to forward destination(s) later when they are created.
520 // Second successor may be backwards - iff it is already in VPBB2IRBB.
521 VPBasicBlock *SecondVPSucc = cast<VPBasicBlock>(VPBB->getSuccessors()[1]);
522 BasicBlock *SecondIRSucc = State.CFG.VPBB2IRBB.lookup(SecondVPSucc);
523 BasicBlock *IRBB = State.CFG.VPBB2IRBB[VPBB];
524 BranchInst *CondBr = State.Builder.CreateCondBr(Cond, IRBB, SecondIRSucc);
525 // First successor is always forward, reset it to nullptr
526 CondBr->setSuccessor(0, nullptr);
528 return CondBr;
529}
530
531Value *VPInstruction::generate(VPTransformState &State) {
532 IRBuilderBase &Builder = State.Builder;
533
535 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
536 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
537 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
538 auto *Res =
539 Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B, Name);
540 if (auto *I = dyn_cast<Instruction>(Res))
541 applyFlags(*I);
542 return Res;
543 }
544
545 switch (getOpcode()) {
546 case VPInstruction::Not: {
547 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
548 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
549 return Builder.CreateNot(A, Name);
550 }
551 case Instruction::ExtractElement: {
552 assert(State.VF.isVector() && "Only extract elements from vectors");
553 if (getOperand(1)->isLiveIn()) {
554 unsigned IdxToExtract =
555 cast<ConstantInt>(getOperand(1)->getLiveInIRValue())->getZExtValue();
556 return State.get(getOperand(0), VPLane(IdxToExtract));
557 }
558 Value *Vec = State.get(getOperand(0));
559 Value *Idx = State.get(getOperand(1), /*IsScalar=*/true);
560 return Builder.CreateExtractElement(Vec, Idx, Name);
561 }
562 case Instruction::Freeze: {
564 return Builder.CreateFreeze(Op, Name);
565 }
566 case Instruction::FCmp:
567 case Instruction::ICmp: {
568 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
569 Value *A = State.get(getOperand(0), OnlyFirstLaneUsed);
570 Value *B = State.get(getOperand(1), OnlyFirstLaneUsed);
571 return Builder.CreateCmp(getPredicate(), A, B, Name);
572 }
573 case Instruction::PHI: {
574 llvm_unreachable("should be handled by VPPhi::execute");
575 }
576 case Instruction::Select: {
577 bool OnlyFirstLaneUsed = vputils::onlyFirstLaneUsed(this);
578 Value *Cond =
579 State.get(getOperand(0),
580 OnlyFirstLaneUsed || vputils::isSingleScalar(getOperand(0)));
581 Value *Op1 = State.get(getOperand(1), OnlyFirstLaneUsed);
582 Value *Op2 = State.get(getOperand(2), OnlyFirstLaneUsed);
583 return Builder.CreateSelect(Cond, Op1, Op2, Name);
584 }
586 // Get first lane of vector induction variable.
587 Value *VIVElem0 = State.get(getOperand(0), VPLane(0));
588 // Get the original loop tripcount.
589 Value *ScalarTC = State.get(getOperand(1), VPLane(0));
590
591 // If this part of the active lane mask is scalar, generate the CMP directly
592 // to avoid unnecessary extracts.
593 if (State.VF.isScalar())
594 return Builder.CreateCmp(CmpInst::Predicate::ICMP_ULT, VIVElem0, ScalarTC,
595 Name);
596
597 auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
598 auto PredTy = VectorType::get(
599 Int1Ty, State.VF * cast<ConstantInt>(getOperand(2)->getLiveInIRValue())
600 ->getZExtValue());
601 return Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
602 {PredTy, ScalarTC->getType()},
603 {VIVElem0, ScalarTC}, nullptr, Name);
604 }
606 // Generate code to combine the previous and current values in vector v3.
607 //
608 // vector.ph:
609 // v_init = vector(..., ..., ..., a[-1])
610 // br vector.body
611 //
612 // vector.body
613 // i = phi [0, vector.ph], [i+4, vector.body]
614 // v1 = phi [v_init, vector.ph], [v2, vector.body]
615 // v2 = a[i, i+1, i+2, i+3];
616 // v3 = vector(v1(3), v2(0, 1, 2))
617
618 auto *V1 = State.get(getOperand(0));
619 if (!V1->getType()->isVectorTy())
620 return V1;
621 Value *V2 = State.get(getOperand(1));
622 return Builder.CreateVectorSplice(V1, V2, -1, Name);
623 }
625 unsigned UF = getParent()->getPlan()->getUF();
626 Value *ScalarTC = State.get(getOperand(0), VPLane(0));
627 Value *Step = createStepForVF(Builder, ScalarTC->getType(), State.VF, UF);
628 Value *Sub = Builder.CreateSub(ScalarTC, Step);
629 Value *Cmp = Builder.CreateICmp(CmpInst::Predicate::ICMP_UGT, ScalarTC, Step);
630 Value *Zero = ConstantInt::get(ScalarTC->getType(), 0);
631 return Builder.CreateSelect(Cmp, Sub, Zero);
632 }
634 // TODO: Restructure this code with an explicit remainder loop, vsetvli can
635 // be outside of the main loop.
636 Value *AVL = State.get(getOperand(0), /*IsScalar*/ true);
637 // Compute EVL
638 assert(AVL->getType()->isIntegerTy() &&
639 "Requested vector length should be an integer.");
640
641 assert(State.VF.isScalable() && "Expected scalable vector factor.");
642 Value *VFArg = State.Builder.getInt32(State.VF.getKnownMinValue());
643
644 Value *EVL = State.Builder.CreateIntrinsic(
645 State.Builder.getInt32Ty(), Intrinsic::experimental_get_vector_length,
646 {AVL, VFArg, State.Builder.getTrue()});
647 return EVL;
648 }
650 unsigned Part = getUnrollPart(*this);
651 auto *IV = State.get(getOperand(0), VPLane(0));
652 assert(Part != 0 && "Must have a positive part");
653 // The canonical IV is incremented by the vectorization factor (num of
654 // SIMD elements) times the unroll part.
655 Value *Step = createStepForVF(Builder, IV->getType(), State.VF, Part);
656 return Builder.CreateAdd(IV, Step, Name, hasNoUnsignedWrap(),
658 }
660 Value *Cond = State.get(getOperand(0), VPLane(0));
661 auto *Br = createCondBranch(Cond, getParent(), State);
662 applyMetadata(*Br);
663 return Br;
664 }
666 // First create the compare.
667 Value *IV = State.get(getOperand(0), /*IsScalar*/ true);
668 Value *TC = State.get(getOperand(1), /*IsScalar*/ true);
669 Value *Cond = Builder.CreateICmpEQ(IV, TC);
670 return createCondBranch(Cond, getParent(), State);
671 }
673 return Builder.CreateVectorSplat(
674 State.VF, State.get(getOperand(0), /*IsScalar*/ true), "broadcast");
675 }
677 // For struct types, we need to build a new 'wide' struct type, where each
678 // element is widened, i.e., we create a struct of vectors.
679 auto *StructTy =
681 Value *Res = PoisonValue::get(toVectorizedTy(StructTy, State.VF));
682 for (const auto &[LaneIndex, Op] : enumerate(operands())) {
683 for (unsigned FieldIndex = 0; FieldIndex != StructTy->getNumElements();
684 FieldIndex++) {
685 Value *ScalarValue =
686 Builder.CreateExtractValue(State.get(Op, true), FieldIndex);
687 Value *VectorValue = Builder.CreateExtractValue(Res, FieldIndex);
688 VectorValue =
689 Builder.CreateInsertElement(VectorValue, ScalarValue, LaneIndex);
690 Res = Builder.CreateInsertValue(Res, VectorValue, FieldIndex);
691 }
692 }
693 return Res;
694 }
696 auto *ScalarTy = State.TypeAnalysis.inferScalarType(getOperand(0));
697 auto NumOfElements = ElementCount::getFixed(getNumOperands());
698 Value *Res = PoisonValue::get(toVectorizedTy(ScalarTy, NumOfElements));
699 for (const auto &[Idx, Op] : enumerate(operands()))
700 Res = State.Builder.CreateInsertElement(Res, State.get(Op, true),
701 State.Builder.getInt32(Idx));
702 return Res;
703 }
705 if (State.VF.isScalar())
706 return State.get(getOperand(0), true);
707 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
709 // If this start vector is scaled then it should produce a vector with fewer
710 // elements than the VF.
711 ElementCount VF = State.VF.divideCoefficientBy(
712 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue());
713 auto *Iden = Builder.CreateVectorSplat(VF, State.get(getOperand(1), true));
714 Constant *Zero = Builder.getInt32(0);
715 return Builder.CreateInsertElement(Iden, State.get(getOperand(0), true),
716 Zero);
717 }
719 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
720 // and will be removed by breaking up the recipe further.
721 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
722 auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
723 Value *ReducedPartRdx = State.get(getOperand(2));
724 for (unsigned Idx = 3; Idx < getNumOperands(); ++Idx)
725 ReducedPartRdx =
726 Builder.CreateBinOp(Instruction::Or, State.get(getOperand(Idx)),
727 ReducedPartRdx, "bin.rdx");
728 return createAnyOfReduction(Builder, ReducedPartRdx,
729 State.get(getOperand(1), VPLane(0)), OrigPhi);
730 }
732 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
733 // and will be removed by breaking up the recipe further.
734 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
735 // Get its reduction variable descriptor.
736 RecurKind RK = PhiR->getRecurrenceKind();
738 "Unexpected reduction kind");
739 assert(!PhiR->isInLoop() &&
740 "In-loop FindLastIV reduction is not supported yet");
741
742 // The recipe's operands are the reduction phi, the start value, the
743 // sentinel value, followed by one operand for each part of the reduction.
744 unsigned UF = getNumOperands() - 3;
745 Value *ReducedPartRdx = State.get(getOperand(3));
746 RecurKind MinMaxKind;
749 MinMaxKind = IsSigned ? RecurKind::SMax : RecurKind::UMax;
750 else
751 MinMaxKind = IsSigned ? RecurKind::SMin : RecurKind::UMin;
752 for (unsigned Part = 1; Part < UF; ++Part)
753 ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
754 State.get(getOperand(3 + Part)));
755
756 Value *Start = State.get(getOperand(1), true);
758 return createFindLastIVReduction(Builder, ReducedPartRdx, RK, Start,
759 Sentinel);
760 }
762 // FIXME: The cross-recipe dependency on VPReductionPHIRecipe is temporary
763 // and will be removed by breaking up the recipe further.
764 auto *PhiR = cast<VPReductionPHIRecipe>(getOperand(0));
765 // Get its reduction variable descriptor.
766
767 RecurKind RK = PhiR->getRecurrenceKind();
769 "should be handled by ComputeFindIVResult");
770
771 // The recipe's operands are the reduction phi, followed by one operand for
772 // each part of the reduction.
773 unsigned UF = getNumOperands() - 1;
774 VectorParts RdxParts(UF);
775 for (unsigned Part = 0; Part < UF; ++Part)
776 RdxParts[Part] = State.get(getOperand(1 + Part), PhiR->isInLoop());
777
778 IRBuilderBase::FastMathFlagGuard FMFG(Builder);
779 if (hasFastMathFlags())
781
782 // Reduce all of the unrolled parts into a single vector.
783 Value *ReducedPartRdx = RdxParts[0];
784 if (PhiR->isOrdered()) {
785 ReducedPartRdx = RdxParts[UF - 1];
786 } else {
787 // Floating-point operations should have some FMF to enable the reduction.
788 for (unsigned Part = 1; Part < UF; ++Part) {
789 Value *RdxPart = RdxParts[Part];
791 ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
792 else {
794 // For sub-recurrences, each UF's reduction variable is already
795 // negative, we need to do: reduce.add(-acc_uf0 + -acc_uf1)
796 if (RK == RecurKind::Sub)
797 Opcode = Instruction::Add;
798 else
799 Opcode =
801 ReducedPartRdx =
802 Builder.CreateBinOp(Opcode, RdxPart, ReducedPartRdx, "bin.rdx");
803 }
804 }
805 }
806
807 // Create the reduction after the loop. Note that inloop reductions create
808 // the target reduction in the loop using a Reduction recipe.
809 if (State.VF.isVector() && !PhiR->isInLoop()) {
810 // TODO: Support in-order reductions based on the recurrence descriptor.
811 // All ops in the reduction inherit fast-math-flags from the recurrence
812 // descriptor.
813 ReducedPartRdx = createSimpleReduction(Builder, ReducedPartRdx, RK);
814 }
815
816 return ReducedPartRdx;
817 }
821 unsigned Offset =
823 Value *Res;
824 if (State.VF.isVector()) {
825 assert(Offset <= State.VF.getKnownMinValue() &&
826 "invalid offset to extract from");
827 // Extract lane VF - Offset from the operand.
828 Res = State.get(getOperand(0), VPLane::getLaneFromEnd(State.VF, Offset));
829 } else {
830 assert(Offset <= 1 && "invalid offset to extract from");
831 Res = State.get(getOperand(0));
832 }
834 Res->setName(Name);
835 return Res;
836 }
838 Value *A = State.get(getOperand(0));
839 Value *B = State.get(getOperand(1));
840 return Builder.CreateLogicalAnd(A, B, Name);
841 }
844 "can only generate first lane for PtrAdd");
845 Value *Ptr = State.get(getOperand(0), VPLane(0));
846 Value *Addend = State.get(getOperand(1), VPLane(0));
847 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
848 }
850 Value *Ptr =
852 Value *Addend = State.get(getOperand(1));
853 return Builder.CreatePtrAdd(Ptr, Addend, Name, getGEPNoWrapFlags());
854 }
856 Value *Res = Builder.CreateFreeze(State.get(getOperand(0)));
857 for (VPValue *Op : drop_begin(operands()))
858 Res = Builder.CreateOr(Res, Builder.CreateFreeze(State.get(Op)));
859 return State.VF.isScalar() ? Res : Builder.CreateOrReduce(Res);
860 }
862 Value *LaneToExtract = State.get(getOperand(0), true);
863 Type *IdxTy = State.TypeAnalysis.inferScalarType(getOperand(0));
864 Value *Res = nullptr;
865 Value *RuntimeVF = getRuntimeVF(State.Builder, IdxTy, State.VF);
866
867 for (unsigned Idx = 1; Idx != getNumOperands(); ++Idx) {
868 Value *VectorStart =
869 Builder.CreateMul(RuntimeVF, ConstantInt::get(IdxTy, Idx - 1));
870 Value *VectorIdx = Idx == 1
871 ? LaneToExtract
872 : Builder.CreateSub(LaneToExtract, VectorStart);
873 Value *Ext = State.VF.isScalar()
874 ? State.get(getOperand(Idx))
875 : Builder.CreateExtractElement(
876 State.get(getOperand(Idx)), VectorIdx);
877 if (Res) {
878 Value *Cmp = Builder.CreateICmpUGE(LaneToExtract, VectorStart);
879 Res = Builder.CreateSelect(Cmp, Ext, Res);
880 } else {
881 Res = Ext;
882 }
883 }
884 return Res;
885 }
887 if (getNumOperands() == 1) {
888 Value *Mask = State.get(getOperand(0));
889 return Builder.CreateCountTrailingZeroElems(Builder.getInt64Ty(), Mask,
890 /*ZeroIsPoison=*/false, Name);
891 }
892 // If there are multiple operands, create a chain of selects to pick the
893 // first operand with an active lane and add the number of lanes of the
894 // preceding operands.
895 Value *RuntimeVF =
896 getRuntimeVF(State.Builder, State.Builder.getInt64Ty(), State.VF);
897 unsigned LastOpIdx = getNumOperands() - 1;
898 Value *Res = nullptr;
899 for (int Idx = LastOpIdx; Idx >= 0; --Idx) {
900 Value *TrailingZeros =
901 State.VF.isScalar()
902 ? Builder.CreateZExt(
903 Builder.CreateICmpEQ(State.get(getOperand(Idx)),
904 Builder.getFalse()),
905 Builder.getInt64Ty())
907 Builder.getInt64Ty(), State.get(getOperand(Idx)),
908 /*ZeroIsPoison=*/false, Name);
909 Value *Current = Builder.CreateAdd(
910 Builder.CreateMul(RuntimeVF, Builder.getInt64(Idx)), TrailingZeros);
911 if (Res) {
912 Value *Cmp = Builder.CreateICmpNE(TrailingZeros, RuntimeVF);
913 Res = Builder.CreateSelect(Cmp, Current, Res);
914 } else {
915 Res = Current;
916 }
917 }
918
919 return Res;
920 }
922 return State.get(getOperand(0), true);
923 default:
924 llvm_unreachable("Unsupported opcode for instruction");
925 }
926}
927
929 unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const {
930 Type *ScalarTy = Ctx.Types.inferScalarType(this);
931 Type *ResultTy = VF.isVector() ? toVectorTy(ScalarTy, VF) : ScalarTy;
932 switch (Opcode) {
933 case Instruction::FNeg:
934 return Ctx.TTI.getArithmeticInstrCost(Opcode, ResultTy, Ctx.CostKind);
935 case Instruction::UDiv:
936 case Instruction::SDiv:
937 case Instruction::SRem:
938 case Instruction::URem:
939 case Instruction::Add:
940 case Instruction::FAdd:
941 case Instruction::Sub:
942 case Instruction::FSub:
943 case Instruction::Mul:
944 case Instruction::FMul:
945 case Instruction::FDiv:
946 case Instruction::FRem:
947 case Instruction::Shl:
948 case Instruction::LShr:
949 case Instruction::AShr:
950 case Instruction::And:
951 case Instruction::Or:
952 case Instruction::Xor: {
955
956 if (VF.isVector()) {
957 // Certain instructions can be cheaper to vectorize if they have a
958 // constant second vector operand. One example of this are shifts on x86.
959 VPValue *RHS = getOperand(1);
960 RHSInfo = Ctx.getOperandInfo(RHS);
961
962 if (RHSInfo.Kind == TargetTransformInfo::OK_AnyValue &&
965 }
966
969 if (CtxI)
970 Operands.append(CtxI->value_op_begin(), CtxI->value_op_end());
971 return Ctx.TTI.getArithmeticInstrCost(
972 Opcode, ResultTy, Ctx.CostKind,
973 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
974 RHSInfo, Operands, CtxI, &Ctx.TLI);
975 }
976 case Instruction::Freeze:
977 // This opcode is unknown. Assume that it is the same as 'mul'.
978 return Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, ResultTy,
979 Ctx.CostKind);
980 case Instruction::ExtractValue:
981 return Ctx.TTI.getInsertExtractValueCost(Instruction::ExtractValue,
982 Ctx.CostKind);
983 case Instruction::ICmp:
984 case Instruction::FCmp: {
985 Type *ScalarOpTy = Ctx.Types.inferScalarType(getOperand(0));
986 Type *OpTy = VF.isVector() ? toVectorTy(ScalarOpTy, VF) : ScalarOpTy;
988 return Ctx.TTI.getCmpSelInstrCost(
989 Opcode, OpTy, CmpInst::makeCmpResultType(OpTy), getPredicate(),
990 Ctx.CostKind, {TTI::OK_AnyValue, TTI::OP_None},
991 {TTI::OK_AnyValue, TTI::OP_None}, CtxI);
992 }
993 }
994 llvm_unreachable("called for unsupported opcode");
995}
996
998 VPCostContext &Ctx) const {
1000 if (!getUnderlyingValue() && getOpcode() != Instruction::FMul) {
1001 // TODO: Compute cost for VPInstructions without underlying values once
1002 // the legacy cost model has been retired.
1003 return 0;
1004 }
1005
1007 "Should only generate a vector value or single scalar, not scalars "
1008 "for all lanes.");
1010 getOpcode(),
1012 }
1013
1014 switch (getOpcode()) {
1015 case Instruction::Select: {
1016 // TODO: It may be possible to improve this by analyzing where the
1017 // condition operand comes from.
1019 auto *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1020 auto *VecTy = Ctx.Types.inferScalarType(getOperand(1));
1021 if (!vputils::onlyFirstLaneUsed(this)) {
1022 CondTy = toVectorTy(CondTy, VF);
1023 VecTy = toVectorTy(VecTy, VF);
1024 }
1025 return Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CondTy, Pred,
1026 Ctx.CostKind);
1027 }
1028 case Instruction::ExtractElement:
1030 if (VF.isScalar()) {
1031 // ExtractLane with VF=1 takes care of handling extracting across multiple
1032 // parts.
1033 return 0;
1034 }
1035
1036 // Add on the cost of extracting the element.
1037 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1038 return Ctx.TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy,
1039 Ctx.CostKind);
1040 }
1041 case VPInstruction::AnyOf: {
1042 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1043 return Ctx.TTI.getArithmeticReductionCost(
1044 Instruction::Or, cast<VectorType>(VecTy), std::nullopt, Ctx.CostKind);
1045 }
1047 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1048 if (VF.isScalar())
1049 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1051 CmpInst::ICMP_EQ, Ctx.CostKind);
1052 // Calculate the cost of determining the lane index.
1053 auto *PredTy = toVectorTy(ScalarTy, VF);
1054 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1055 Type::getInt64Ty(Ctx.LLVMCtx),
1056 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1057 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1058 }
1060 Type *ScalarTy = Ctx.Types.inferScalarType(getOperand(0));
1061 if (VF.isScalar())
1062 return Ctx.TTI.getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
1064 CmpInst::ICMP_EQ, Ctx.CostKind);
1065 // Calculate the cost of determining the lane index: NOT + cttz_elts + SUB.
1066 auto *PredTy = toVectorTy(ScalarTy, VF);
1067 IntrinsicCostAttributes Attrs(Intrinsic::experimental_cttz_elts,
1068 Type::getInt64Ty(Ctx.LLVMCtx),
1069 {PredTy, Type::getInt1Ty(Ctx.LLVMCtx)});
1070 InstructionCost Cost = Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1071 // Add cost of NOT operation on the predicate.
1072 Cost += Ctx.TTI.getArithmeticInstrCost(
1073 Instruction::Xor, PredTy, Ctx.CostKind,
1074 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
1075 {TargetTransformInfo::OK_UniformConstantValue,
1076 TargetTransformInfo::OP_None});
1077 // Add cost of SUB operation on the index.
1078 Cost += Ctx.TTI.getArithmeticInstrCost(
1079 Instruction::Sub, Type::getInt64Ty(Ctx.LLVMCtx), Ctx.CostKind);
1080 return Cost;
1081 }
1083 assert(VF.isVector() && "Scalar FirstOrderRecurrenceSplice?");
1085 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
1086 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1087
1088 return Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
1089 cast<VectorType>(VectorTy),
1090 cast<VectorType>(VectorTy), Mask,
1091 Ctx.CostKind, VF.getKnownMinValue() - 1);
1092 }
1094 Type *ArgTy = Ctx.Types.inferScalarType(getOperand(0));
1095 unsigned Multiplier =
1096 cast<ConstantInt>(getOperand(2)->getLiveInIRValue())->getZExtValue();
1097 Type *RetTy = toVectorTy(Type::getInt1Ty(Ctx.LLVMCtx), VF * Multiplier);
1098 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
1099 {ArgTy, ArgTy});
1100 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1101 }
1103 Type *Arg0Ty = Ctx.Types.inferScalarType(getOperand(0));
1104 Type *I32Ty = Type::getInt32Ty(Ctx.LLVMCtx);
1105 Type *I1Ty = Type::getInt1Ty(Ctx.LLVMCtx);
1106 IntrinsicCostAttributes Attrs(Intrinsic::experimental_get_vector_length,
1107 I32Ty, {Arg0Ty, I32Ty, I1Ty});
1108 return Ctx.TTI.getIntrinsicInstrCost(Attrs, Ctx.CostKind);
1109 }
1111 // Add on the cost of extracting the element.
1112 auto *VecTy = toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF);
1113 return Ctx.TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
1114 VecTy, Ctx.CostKind, 0);
1115 }
1117 if (VF == ElementCount::getScalable(1))
1119 [[fallthrough]];
1120 default:
1121 // TODO: Compute cost other VPInstructions once the legacy cost model has
1122 // been retired.
1124 "unexpected VPInstruction witht underlying value");
1125 return 0;
1126 }
1127}
1128
1142
1144 switch (getOpcode()) {
1145 case Instruction::PHI:
1149 return true;
1150 default:
1151 return isScalarCast();
1152 }
1153}
1154
1156 assert(!State.Lane && "VPInstruction executing an Lane");
1157 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
1159 "Set flags not supported for the provided opcode");
1160 if (hasFastMathFlags())
1161 State.Builder.setFastMathFlags(getFastMathFlags());
1162 Value *GeneratedValue = generate(State);
1163 if (!hasResult())
1164 return;
1165 assert(GeneratedValue && "generate must produce a value");
1166 bool GeneratesPerFirstLaneOnly = canGenerateScalarForFirstLane() &&
1169 assert((((GeneratedValue->getType()->isVectorTy() ||
1170 GeneratedValue->getType()->isStructTy()) ==
1171 !GeneratesPerFirstLaneOnly) ||
1172 State.VF.isScalar()) &&
1173 "scalar value but not only first lane defined");
1174 State.set(this, GeneratedValue,
1175 /*IsScalar*/ GeneratesPerFirstLaneOnly);
1176}
1177
1180 return false;
1181 switch (getOpcode()) {
1182 case Instruction::GetElementPtr:
1183 case Instruction::ExtractElement:
1184 case Instruction::Freeze:
1185 case Instruction::FCmp:
1186 case Instruction::ICmp:
1187 case Instruction::Select:
1188 case Instruction::PHI:
1207 case VPInstruction::Not:
1215 return false;
1216 default:
1217 return true;
1218 }
1219}
1220
1222 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1224 return vputils::onlyFirstLaneUsed(this);
1225
1226 switch (getOpcode()) {
1227 default:
1228 return false;
1229 case Instruction::ExtractElement:
1230 return Op == getOperand(1);
1231 case Instruction::PHI:
1232 return true;
1233 case Instruction::FCmp:
1234 case Instruction::ICmp:
1235 case Instruction::Select:
1236 case Instruction::Or:
1237 case Instruction::Freeze:
1238 case VPInstruction::Not:
1239 // TODO: Cover additional opcodes.
1240 return vputils::onlyFirstLaneUsed(this);
1249 return true;
1252 // Before replicating by VF, Build(Struct)Vector uses all lanes of the
1253 // operand, after replicating its operands only the first lane is used.
1254 // Before replicating, it will have only a single operand.
1255 return getNumOperands() > 1;
1257 return Op == getOperand(0) || vputils::onlyFirstLaneUsed(this);
1259 // WidePtrAdd supports scalar and vector base addresses.
1260 return false;
1263 return Op == getOperand(1);
1265 return Op == getOperand(0);
1266 };
1267 llvm_unreachable("switch should return");
1268}
1269
1271 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1273 return vputils::onlyFirstPartUsed(this);
1274
1275 switch (getOpcode()) {
1276 default:
1277 return false;
1278 case Instruction::FCmp:
1279 case Instruction::ICmp:
1280 case Instruction::Select:
1281 return vputils::onlyFirstPartUsed(this);
1285 return true;
1286 };
1287 llvm_unreachable("switch should return");
1288}
1289
1290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1292 VPSlotTracker SlotTracker(getParent()->getPlan());
1294}
1295
1297 VPSlotTracker &SlotTracker) const {
1298 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1299
1300 if (hasResult()) {
1302 O << " = ";
1303 }
1304
1305 switch (getOpcode()) {
1306 case VPInstruction::Not:
1307 O << "not";
1308 break;
1310 O << "combined load";
1311 break;
1313 O << "combined store";
1314 break;
1316 O << "active lane mask";
1317 break;
1319 O << "EXPLICIT-VECTOR-LENGTH";
1320 break;
1322 O << "first-order splice";
1323 break;
1325 O << "branch-on-cond";
1326 break;
1328 O << "TC > VF ? TC - VF : 0";
1329 break;
1331 O << "VF * Part +";
1332 break;
1334 O << "branch-on-count";
1335 break;
1337 O << "broadcast";
1338 break;
1340 O << "buildstructvector";
1341 break;
1343 O << "buildvector";
1344 break;
1346 O << "extract-lane";
1347 break;
1349 O << "extract-last-element";
1350 break;
1352 O << "extract-last-lane-per-part";
1353 break;
1355 O << "extract-penultimate-element";
1356 break;
1358 O << "compute-anyof-result";
1359 break;
1361 O << "compute-find-iv-result";
1362 break;
1364 O << "compute-reduction-result";
1365 break;
1367 O << "logical-and";
1368 break;
1370 O << "ptradd";
1371 break;
1373 O << "wide-ptradd";
1374 break;
1376 O << "any-of";
1377 break;
1379 O << "first-active-lane";
1380 break;
1382 O << "last-active-lane";
1383 break;
1385 O << "reduction-start-vector";
1386 break;
1388 O << "resume-for-epilogue";
1389 break;
1391 O << "unpack";
1392 break;
1393 default:
1395 }
1396
1397 printFlags(O);
1399}
1400#endif
1401
1403 State.setDebugLocFrom(getDebugLoc());
1404 if (isScalarCast()) {
1405 Value *Op = State.get(getOperand(0), VPLane(0));
1406 Value *Cast = State.Builder.CreateCast(Instruction::CastOps(getOpcode()),
1407 Op, ResultTy);
1408 State.set(this, Cast, VPLane(0));
1409 return;
1410 }
1411 switch (getOpcode()) {
1413 Value *StepVector =
1414 State.Builder.CreateStepVector(VectorType::get(ResultTy, State.VF));
1415 State.set(this, StepVector);
1416 break;
1417 }
1418 case VPInstruction::VScale: {
1419 Value *VScale = State.Builder.CreateVScale(ResultTy);
1420 State.set(this, VScale, true);
1421 break;
1422 }
1423
1424 default:
1425 llvm_unreachable("opcode not implemented yet");
1426 }
1427}
1428
1429#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1431 VPSlotTracker &SlotTracker) const {
1432 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1434 O << " = ";
1435
1436 switch (getOpcode()) {
1438 O << "wide-iv-step ";
1440 break;
1442 O << "step-vector " << *ResultTy;
1443 break;
1445 O << "vscale " << *ResultTy;
1446 break;
1447 default:
1448 assert(Instruction::isCast(getOpcode()) && "unhandled opcode");
1451 O << " to " << *ResultTy;
1452 }
1453}
1454#endif
1455
1457 State.setDebugLocFrom(getDebugLoc());
1458 PHINode *NewPhi = State.Builder.CreatePHI(
1459 State.TypeAnalysis.inferScalarType(this), 2, getName());
1460 unsigned NumIncoming = getNumIncoming();
1461 if (getParent() != getParent()->getPlan()->getScalarPreheader()) {
1462 // TODO: Fixup all incoming values of header phis once recipes defining them
1463 // are introduced.
1464 NumIncoming = 1;
1465 }
1466 for (unsigned Idx = 0; Idx != NumIncoming; ++Idx) {
1467 Value *IncV = State.get(getIncomingValue(Idx), VPLane(0));
1468 BasicBlock *PredBB = State.CFG.VPBB2IRBB.at(getIncomingBlock(Idx));
1469 NewPhi->addIncoming(IncV, PredBB);
1470 }
1471 State.set(this, NewPhi, VPLane(0));
1472}
1473
1474#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1475void VPPhi::printRecipe(raw_ostream &O, const Twine &Indent,
1476 VPSlotTracker &SlotTracker) const {
1477 O << Indent << "EMIT" << (isSingleScalar() ? "-SCALAR" : "") << " ";
1479 O << " = phi ";
1481}
1482#endif
1483
1484VPIRInstruction *VPIRInstruction ::create(Instruction &I) {
1485 if (auto *Phi = dyn_cast<PHINode>(&I))
1486 return new VPIRPhi(*Phi);
1487 return new VPIRInstruction(I);
1488}
1489
1491 assert(!isa<VPIRPhi>(this) && getNumOperands() == 0 &&
1492 "PHINodes must be handled by VPIRPhi");
1493 // Advance the insert point after the wrapped IR instruction. This allows
1494 // interleaving VPIRInstructions and other recipes.
1495 State.Builder.SetInsertPoint(I.getParent(), std::next(I.getIterator()));
1496}
1497
1499 VPCostContext &Ctx) const {
1500 // The recipe wraps an existing IR instruction on the border of VPlan's scope,
1501 // hence it does not contribute to the cost-modeling for the VPlan.
1502 return 0;
1503}
1504
1507 "can only update exiting operands to phi nodes");
1508 assert(getNumOperands() > 0 && "must have at least one operand");
1509 VPValue *Exiting = getOperand(0);
1510 if (Exiting->isLiveIn())
1511 return;
1512
1513 Exiting = Builder.createNaryOp(VPInstruction::ExtractLastElement, {Exiting});
1514 setOperand(0, Exiting);
1515}
1516
1517#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1519 VPSlotTracker &SlotTracker) const {
1520 O << Indent << "IR " << I;
1521}
1522#endif
1523
1525 PHINode *Phi = &getIRPhi();
1526 for (const auto &[Idx, Op] : enumerate(operands())) {
1527 VPValue *ExitValue = Op;
1528 auto Lane = vputils::isSingleScalar(ExitValue)
1530 : VPLane::getLastLaneForVF(State.VF);
1531 VPBlockBase *Pred = getParent()->getPredecessors()[Idx];
1532 auto *PredVPBB = Pred->getExitingBasicBlock();
1533 BasicBlock *PredBB = State.CFG.VPBB2IRBB[PredVPBB];
1534 // Set insertion point in PredBB in case an extract needs to be generated.
1535 // TODO: Model extracts explicitly.
1536 State.Builder.SetInsertPoint(PredBB, PredBB->getFirstNonPHIIt());
1537 Value *V = State.get(ExitValue, VPLane(Lane));
1538 // If there is no existing block for PredBB in the phi, add a new incoming
1539 // value. Otherwise update the existing incoming value for PredBB.
1540 if (Phi->getBasicBlockIndex(PredBB) == -1)
1541 Phi->addIncoming(V, PredBB);
1542 else
1543 Phi->setIncomingValueForBlock(PredBB, V);
1544 }
1545
1546 // Advance the insert point after the wrapped IR instruction. This allows
1547 // interleaving VPIRInstructions and other recipes.
1548 State.Builder.SetInsertPoint(Phi->getParent(), std::next(Phi->getIterator()));
1549}
1550
1552 VPRecipeBase *R = const_cast<VPRecipeBase *>(getAsRecipe());
1553 assert(R->getNumOperands() == R->getParent()->getNumPredecessors() &&
1554 "Number of phi operands must match number of predecessors");
1555 unsigned Position = R->getParent()->getIndexForPredecessor(IncomingBlock);
1556 R->removeOperand(Position);
1557}
1558
1559#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1561 VPSlotTracker &SlotTracker) const {
1562 interleaveComma(enumerate(getAsRecipe()->operands()), O,
1563 [this, &O, &SlotTracker](auto Op) {
1564 O << "[ ";
1565 Op.value()->printAsOperand(O, SlotTracker);
1566 O << ", ";
1567 getIncomingBlock(Op.index())->printAsOperand(O);
1568 O << " ]";
1569 });
1570}
1571#endif
1572
1573#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1575 VPSlotTracker &SlotTracker) const {
1577
1578 if (getNumOperands() != 0) {
1579 O << " (extra operand" << (getNumOperands() > 1 ? "s" : "") << ": ";
1581 [&O, &SlotTracker](auto Op) {
1582 std::get<0>(Op)->printAsOperand(O, SlotTracker);
1583 O << " from ";
1584 std::get<1>(Op)->printAsOperand(O);
1585 });
1586 O << ")";
1587 }
1588}
1589#endif
1590
1592 for (const auto &[Kind, Node] : Metadata)
1593 I.setMetadata(Kind, Node);
1594}
1595
1597 SmallVector<std::pair<unsigned, MDNode *>> MetadataIntersection;
1598 for (const auto &[KindA, MDA] : Metadata) {
1599 for (const auto &[KindB, MDB] : Other.Metadata) {
1600 if (KindA == KindB && MDA == MDB) {
1601 MetadataIntersection.emplace_back(KindA, MDA);
1602 break;
1603 }
1604 }
1605 }
1606 Metadata = std::move(MetadataIntersection);
1607}
1608
1610 assert(State.VF.isVector() && "not widening");
1611 assert(Variant != nullptr && "Can't create vector function.");
1612
1613 FunctionType *VFTy = Variant->getFunctionType();
1614 // Add return type if intrinsic is overloaded on it.
1616 for (const auto &I : enumerate(args())) {
1617 Value *Arg;
1618 // Some vectorized function variants may also take a scalar argument,
1619 // e.g. linear parameters for pointers. This needs to be the scalar value
1620 // from the start of the respective part when interleaving.
1621 if (!VFTy->getParamType(I.index())->isVectorTy())
1622 Arg = State.get(I.value(), VPLane(0));
1623 else
1624 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1625 Args.push_back(Arg);
1626 }
1627
1630 if (CI)
1631 CI->getOperandBundlesAsDefs(OpBundles);
1632
1633 CallInst *V = State.Builder.CreateCall(Variant, Args, OpBundles);
1634 applyFlags(*V);
1635 applyMetadata(*V);
1636 V->setCallingConv(Variant->getCallingConv());
1637
1638 if (!V->getType()->isVoidTy())
1639 State.set(this, V);
1640}
1641
1643 VPCostContext &Ctx) const {
1644 return Ctx.TTI.getCallInstrCost(nullptr, Variant->getReturnType(),
1645 Variant->getFunctionType()->params(),
1646 Ctx.CostKind);
1647}
1648
1649#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1651 VPSlotTracker &SlotTracker) const {
1652 O << Indent << "WIDEN-CALL ";
1653
1654 Function *CalledFn = getCalledScalarFunction();
1655 if (CalledFn->getReturnType()->isVoidTy())
1656 O << "void ";
1657 else {
1659 O << " = ";
1660 }
1661
1662 O << "call";
1663 printFlags(O);
1664 O << " @" << CalledFn->getName() << "(";
1665 interleaveComma(args(), O, [&O, &SlotTracker](VPValue *Op) {
1666 Op->printAsOperand(O, SlotTracker);
1667 });
1668 O << ")";
1669
1670 O << " (using library function";
1671 if (Variant->hasName())
1672 O << ": " << Variant->getName();
1673 O << ")";
1674}
1675#endif
1676
1678 assert(State.VF.isVector() && "not widening");
1679
1680 SmallVector<Type *, 2> TysForDecl;
1681 // Add return type if intrinsic is overloaded on it.
1682 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, -1, State.TTI))
1683 TysForDecl.push_back(VectorType::get(getResultType(), State.VF));
1685 for (const auto &I : enumerate(operands())) {
1686 // Some intrinsics have a scalar argument - don't replace it with a
1687 // vector.
1688 Value *Arg;
1689 if (isVectorIntrinsicWithScalarOpAtArg(VectorIntrinsicID, I.index(),
1690 State.TTI))
1691 Arg = State.get(I.value(), VPLane(0));
1692 else
1693 Arg = State.get(I.value(), usesFirstLaneOnly(I.value()));
1694 if (isVectorIntrinsicWithOverloadTypeAtArg(VectorIntrinsicID, I.index(),
1695 State.TTI))
1696 TysForDecl.push_back(Arg->getType());
1697 Args.push_back(Arg);
1698 }
1699
1700 // Use vector version of the intrinsic.
1701 Module *M = State.Builder.GetInsertBlock()->getModule();
1702 Function *VectorF =
1703 Intrinsic::getOrInsertDeclaration(M, VectorIntrinsicID, TysForDecl);
1704 assert(VectorF &&
1705 "Can't retrieve vector intrinsic or vector-predication intrinsics.");
1706
1709 if (CI)
1710 CI->getOperandBundlesAsDefs(OpBundles);
1711
1712 CallInst *V = State.Builder.CreateCall(VectorF, Args, OpBundles);
1713
1714 applyFlags(*V);
1715 applyMetadata(*V);
1716
1717 if (!V->getType()->isVoidTy())
1718 State.set(this, V);
1719}
1720
1721/// Compute the cost for the intrinsic \p ID with \p Operands, produced by \p R.
1724 const VPRecipeWithIRFlags &R,
1725 ElementCount VF,
1726 VPCostContext &Ctx) {
1727 // Some backends analyze intrinsic arguments to determine cost. Use the
1728 // underlying value for the operand if it has one. Otherwise try to use the
1729 // operand of the underlying call instruction, if there is one. Otherwise
1730 // clear Arguments.
1731 // TODO: Rework TTI interface to be independent of concrete IR values.
1733 for (const auto &[Idx, Op] : enumerate(Operands)) {
1734 auto *V = Op->getUnderlyingValue();
1735 if (!V) {
1736 if (auto *UI = dyn_cast_or_null<CallBase>(R.getUnderlyingValue())) {
1737 Arguments.push_back(UI->getArgOperand(Idx));
1738 continue;
1739 }
1740 Arguments.clear();
1741 break;
1742 }
1743 Arguments.push_back(V);
1744 }
1745
1746 Type *ScalarRetTy = Ctx.Types.inferScalarType(&R);
1747 Type *RetTy = VF.isVector() ? toVectorizedTy(ScalarRetTy, VF) : ScalarRetTy;
1748 SmallVector<Type *> ParamTys;
1749 for (const VPValue *Op : Operands) {
1750 ParamTys.push_back(VF.isVector()
1751 ? toVectorTy(Ctx.Types.inferScalarType(Op), VF)
1752 : Ctx.Types.inferScalarType(Op));
1753 }
1754
1755 // TODO: Rework TTI interface to avoid reliance on underlying IntrinsicInst.
1756 FastMathFlags FMF =
1757 R.hasFastMathFlags() ? R.getFastMathFlags() : FastMathFlags();
1758 IntrinsicCostAttributes CostAttrs(
1759 ID, RetTy, Arguments, ParamTys, FMF,
1760 dyn_cast_or_null<IntrinsicInst>(R.getUnderlyingValue()),
1761 InstructionCost::getInvalid(), &Ctx.TLI);
1762 return Ctx.TTI.getIntrinsicInstrCost(CostAttrs, Ctx.CostKind);
1763}
1764
1766 VPCostContext &Ctx) const {
1768 return getCostForIntrinsics(VectorIntrinsicID, ArgOps, *this, VF, Ctx);
1769}
1770
1772 return Intrinsic::getBaseName(VectorIntrinsicID);
1773}
1774
1776 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
1777 return all_of(enumerate(operands()), [this, &Op](const auto &X) {
1778 auto [Idx, V] = X;
1780 Idx, nullptr);
1781 });
1782}
1783
1784#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1786 VPSlotTracker &SlotTracker) const {
1787 O << Indent << "WIDEN-INTRINSIC ";
1788 if (ResultTy->isVoidTy()) {
1789 O << "void ";
1790 } else {
1792 O << " = ";
1793 }
1794
1795 O << "call";
1796 printFlags(O);
1797 O << getIntrinsicName() << "(";
1798
1800 Op->printAsOperand(O, SlotTracker);
1801 });
1802 O << ")";
1803}
1804#endif
1805
1807 IRBuilderBase &Builder = State.Builder;
1808
1809 Value *Address = State.get(getOperand(0));
1810 Value *IncAmt = State.get(getOperand(1), /*IsScalar=*/true);
1811 VectorType *VTy = cast<VectorType>(Address->getType());
1812
1813 // The histogram intrinsic requires a mask even if the recipe doesn't;
1814 // if the mask operand was omitted then all lanes should be executed and
1815 // we just need to synthesize an all-true mask.
1816 Value *Mask = nullptr;
1817 if (VPValue *VPMask = getMask())
1818 Mask = State.get(VPMask);
1819 else
1820 Mask =
1821 Builder.CreateVectorSplat(VTy->getElementCount(), Builder.getInt1(1));
1822
1823 // If this is a subtract, we want to invert the increment amount. We may
1824 // add a separate intrinsic in future, but for now we'll try this.
1825 if (Opcode == Instruction::Sub)
1826 IncAmt = Builder.CreateNeg(IncAmt);
1827 else
1828 assert(Opcode == Instruction::Add && "only add or sub supported for now");
1829
1830 State.Builder.CreateIntrinsic(Intrinsic::experimental_vector_histogram_add,
1831 {VTy, IncAmt->getType()},
1832 {Address, IncAmt, Mask});
1833}
1834
1836 VPCostContext &Ctx) const {
1837 // FIXME: Take the gather and scatter into account as well. For now we're
1838 // generating the same cost as the fallback path, but we'll likely
1839 // need to create a new TTI method for determining the cost, including
1840 // whether we can use base + vec-of-smaller-indices or just
1841 // vec-of-pointers.
1842 assert(VF.isVector() && "Invalid VF for histogram cost");
1843 Type *AddressTy = Ctx.Types.inferScalarType(getOperand(0));
1844 VPValue *IncAmt = getOperand(1);
1845 Type *IncTy = Ctx.Types.inferScalarType(IncAmt);
1846 VectorType *VTy = VectorType::get(IncTy, VF);
1847
1848 // Assume that a non-constant update value (or a constant != 1) requires
1849 // a multiply, and add that into the cost.
1850 InstructionCost MulCost =
1851 Ctx.TTI.getArithmeticInstrCost(Instruction::Mul, VTy, Ctx.CostKind);
1852 if (IncAmt->isLiveIn()) {
1854
1855 if (CI && CI->getZExtValue() == 1)
1856 MulCost = TTI::TCC_Free;
1857 }
1858
1859 // Find the cost of the histogram operation itself.
1860 Type *PtrTy = VectorType::get(AddressTy, VF);
1861 Type *MaskTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
1862 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
1863 Type::getVoidTy(Ctx.LLVMCtx),
1864 {PtrTy, IncTy, MaskTy});
1865
1866 // Add the costs together with the add/sub operation.
1867 return Ctx.TTI.getIntrinsicInstrCost(ICA, Ctx.CostKind) + MulCost +
1868 Ctx.TTI.getArithmeticInstrCost(Opcode, VTy, Ctx.CostKind);
1869}
1870
1871#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1873 VPSlotTracker &SlotTracker) const {
1874 O << Indent << "WIDEN-HISTOGRAM buckets: ";
1876
1877 if (Opcode == Instruction::Sub)
1878 O << ", dec: ";
1879 else {
1880 assert(Opcode == Instruction::Add);
1881 O << ", inc: ";
1882 }
1884
1885 if (VPValue *Mask = getMask()) {
1886 O << ", mask: ";
1887 Mask->printAsOperand(O, SlotTracker);
1888 }
1889}
1890
1892 VPSlotTracker &SlotTracker) const {
1893 O << Indent << "WIDEN-SELECT ";
1895 O << " = select ";
1896 printFlags(O);
1898 O << ", ";
1900 O << ", ";
1902 O << (vputils::isSingleScalar(getCond()) ? " (condition is single-scalar)"
1903 : "");
1904}
1905#endif
1906
1908 Value *Cond = State.get(getCond(), vputils::isSingleScalar(getCond()));
1909
1910 Value *Op0 = State.get(getOperand(1));
1911 Value *Op1 = State.get(getOperand(2));
1912 Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
1913 State.set(this, Sel);
1914 if (auto *I = dyn_cast<Instruction>(Sel)) {
1916 applyFlags(*I);
1917 applyMetadata(*I);
1918 }
1919}
1920
1922 VPCostContext &Ctx) const {
1924 bool ScalarCond = getOperand(0)->isDefinedOutsideLoopRegions();
1925 Type *ScalarTy = Ctx.Types.inferScalarType(this);
1926 Type *VectorTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
1927
1928 VPValue *Op0, *Op1;
1929 if (!ScalarCond && ScalarTy->getScalarSizeInBits() == 1 &&
1930 (match(this, m_LogicalAnd(m_VPValue(Op0), m_VPValue(Op1))) ||
1931 match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1))))) {
1932 // select x, y, false --> x & y
1933 // select x, true, y --> x | y
1934 const auto [Op1VK, Op1VP] = Ctx.getOperandInfo(Op0);
1935 const auto [Op2VK, Op2VP] = Ctx.getOperandInfo(Op1);
1936
1938 if (all_of(operands(),
1939 [](VPValue *Op) { return Op->getUnderlyingValue(); }))
1940 Operands.append(SI->op_begin(), SI->op_end());
1941 bool IsLogicalOr = match(this, m_LogicalOr(m_VPValue(Op0), m_VPValue(Op1)));
1942 return Ctx.TTI.getArithmeticInstrCost(
1943 IsLogicalOr ? Instruction::Or : Instruction::And, VectorTy,
1944 Ctx.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, SI);
1945 }
1946
1947 Type *CondTy = Ctx.Types.inferScalarType(getOperand(0));
1948 if (!ScalarCond)
1949 CondTy = VectorType::get(CondTy, VF);
1950
1952 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
1953 Pred = Cmp->getPredicate();
1954 return Ctx.TTI.getCmpSelInstrCost(
1955 Instruction::Select, VectorTy, CondTy, Pred, Ctx.CostKind,
1956 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, SI);
1957}
1958
1959VPIRFlags::FastMathFlagsTy::FastMathFlagsTy(const FastMathFlags &FMF) {
1960 AllowReassoc = FMF.allowReassoc();
1961 NoNaNs = FMF.noNaNs();
1962 NoInfs = FMF.noInfs();
1963 NoSignedZeros = FMF.noSignedZeros();
1964 AllowReciprocal = FMF.allowReciprocal();
1965 AllowContract = FMF.allowContract();
1966 ApproxFunc = FMF.approxFunc();
1967}
1968
1969#if !defined(NDEBUG)
1970bool VPIRFlags::flagsValidForOpcode(unsigned Opcode) const {
1971 switch (OpType) {
1972 case OperationType::OverflowingBinOp:
1973 return Opcode == Instruction::Add || Opcode == Instruction::Sub ||
1974 Opcode == Instruction::Mul || Opcode == Instruction::Shl ||
1975 Opcode == VPInstruction::VPInstruction::CanonicalIVIncrementForPart;
1976 case OperationType::Trunc:
1977 return Opcode == Instruction::Trunc;
1978 case OperationType::DisjointOp:
1979 return Opcode == Instruction::Or;
1980 case OperationType::PossiblyExactOp:
1981 return Opcode == Instruction::AShr || Opcode == Instruction::LShr ||
1982 Opcode == Instruction::UDiv || Opcode == Instruction::SDiv;
1983 case OperationType::GEPOp:
1984 return Opcode == Instruction::GetElementPtr ||
1985 Opcode == VPInstruction::PtrAdd ||
1986 Opcode == VPInstruction::WidePtrAdd;
1987 case OperationType::FPMathOp:
1988 return Opcode == Instruction::Call || Opcode == Instruction::FAdd ||
1989 Opcode == Instruction::FMul || Opcode == Instruction::FSub ||
1990 Opcode == Instruction::FNeg || Opcode == Instruction::FDiv ||
1991 Opcode == Instruction::FRem || Opcode == Instruction::FPExt ||
1992 Opcode == Instruction::FPTrunc || Opcode == Instruction::Select ||
1993 Opcode == VPInstruction::WideIVStep ||
1996 case OperationType::FCmp:
1997 return Opcode == Instruction::FCmp;
1998 case OperationType::NonNegOp:
1999 return Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP;
2000 case OperationType::Cmp:
2001 return Opcode == Instruction::FCmp || Opcode == Instruction::ICmp;
2002 case OperationType::Other:
2003 return true;
2004 }
2005 llvm_unreachable("Unknown OperationType enum");
2006}
2007#endif
2008
2009#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2011 switch (OpType) {
2012 case OperationType::Cmp:
2014 break;
2015 case OperationType::FCmp:
2018 break;
2019 case OperationType::DisjointOp:
2020 if (DisjointFlags.IsDisjoint)
2021 O << " disjoint";
2022 break;
2023 case OperationType::PossiblyExactOp:
2024 if (ExactFlags.IsExact)
2025 O << " exact";
2026 break;
2027 case OperationType::OverflowingBinOp:
2028 if (WrapFlags.HasNUW)
2029 O << " nuw";
2030 if (WrapFlags.HasNSW)
2031 O << " nsw";
2032 break;
2033 case OperationType::Trunc:
2034 if (TruncFlags.HasNUW)
2035 O << " nuw";
2036 if (TruncFlags.HasNSW)
2037 O << " nsw";
2038 break;
2039 case OperationType::FPMathOp:
2041 break;
2042 case OperationType::GEPOp:
2043 if (GEPFlags.isInBounds())
2044 O << " inbounds";
2045 else if (GEPFlags.hasNoUnsignedSignedWrap())
2046 O << " nusw";
2047 if (GEPFlags.hasNoUnsignedWrap())
2048 O << " nuw";
2049 break;
2050 case OperationType::NonNegOp:
2051 if (NonNegFlags.NonNeg)
2052 O << " nneg";
2053 break;
2054 case OperationType::Other:
2055 break;
2056 }
2057 O << " ";
2058}
2059#endif
2060
2062 auto &Builder = State.Builder;
2063 switch (Opcode) {
2064 case Instruction::Call:
2065 case Instruction::Br:
2066 case Instruction::PHI:
2067 case Instruction::GetElementPtr:
2068 case Instruction::Select:
2069 llvm_unreachable("This instruction is handled by a different recipe.");
2070 case Instruction::UDiv:
2071 case Instruction::SDiv:
2072 case Instruction::SRem:
2073 case Instruction::URem:
2074 case Instruction::Add:
2075 case Instruction::FAdd:
2076 case Instruction::Sub:
2077 case Instruction::FSub:
2078 case Instruction::FNeg:
2079 case Instruction::Mul:
2080 case Instruction::FMul:
2081 case Instruction::FDiv:
2082 case Instruction::FRem:
2083 case Instruction::Shl:
2084 case Instruction::LShr:
2085 case Instruction::AShr:
2086 case Instruction::And:
2087 case Instruction::Or:
2088 case Instruction::Xor: {
2089 // Just widen unops and binops.
2091 for (VPValue *VPOp : operands())
2092 Ops.push_back(State.get(VPOp));
2093
2094 Value *V = Builder.CreateNAryOp(Opcode, Ops);
2095
2096 if (auto *VecOp = dyn_cast<Instruction>(V)) {
2097 applyFlags(*VecOp);
2098 applyMetadata(*VecOp);
2099 }
2100
2101 // Use this vector value for all users of the original instruction.
2102 State.set(this, V);
2103 break;
2104 }
2105 case Instruction::ExtractValue: {
2106 assert(getNumOperands() == 2 && "expected single level extractvalue");
2107 Value *Op = State.get(getOperand(0));
2109 Value *Extract = Builder.CreateExtractValue(Op, CI->getZExtValue());
2110 State.set(this, Extract);
2111 break;
2112 }
2113 case Instruction::Freeze: {
2114 Value *Op = State.get(getOperand(0));
2115 Value *Freeze = Builder.CreateFreeze(Op);
2116 State.set(this, Freeze);
2117 break;
2118 }
2119 case Instruction::ICmp:
2120 case Instruction::FCmp: {
2121 // Widen compares. Generate vector compares.
2122 bool FCmp = Opcode == Instruction::FCmp;
2123 Value *A = State.get(getOperand(0));
2124 Value *B = State.get(getOperand(1));
2125 Value *C = nullptr;
2126 if (FCmp) {
2127 C = Builder.CreateFCmp(getPredicate(), A, B);
2128 } else {
2129 C = Builder.CreateICmp(getPredicate(), A, B);
2130 }
2131 if (auto *I = dyn_cast<Instruction>(C)) {
2132 applyFlags(*I);
2133 applyMetadata(*I);
2134 }
2135 State.set(this, C);
2136 break;
2137 }
2138 default:
2139 // This instruction is not vectorized by simple widening.
2140 LLVM_DEBUG(dbgs() << "LV: Found an unhandled opcode : "
2141 << Instruction::getOpcodeName(Opcode));
2142 llvm_unreachable("Unhandled instruction!");
2143 } // end of switch.
2144
2145#if !defined(NDEBUG)
2146 // Verify that VPlan type inference results agree with the type of the
2147 // generated values.
2148 assert(VectorType::get(State.TypeAnalysis.inferScalarType(this), State.VF) ==
2149 State.get(this)->getType() &&
2150 "inferred type and type from generated instructions do not match");
2151#endif
2152}
2153
2155 VPCostContext &Ctx) const {
2156 switch (Opcode) {
2157 case Instruction::UDiv:
2158 case Instruction::SDiv:
2159 case Instruction::SRem:
2160 case Instruction::URem:
2161 // If the div/rem operation isn't safe to speculate and requires
2162 // predication, then the only way we can even create a vplan is to insert
2163 // a select on the second input operand to ensure we use the value of 1
2164 // for the inactive lanes. The select will be costed separately.
2165 case Instruction::FNeg:
2166 case Instruction::Add:
2167 case Instruction::FAdd:
2168 case Instruction::Sub:
2169 case Instruction::FSub:
2170 case Instruction::Mul:
2171 case Instruction::FMul:
2172 case Instruction::FDiv:
2173 case Instruction::FRem:
2174 case Instruction::Shl:
2175 case Instruction::LShr:
2176 case Instruction::AShr:
2177 case Instruction::And:
2178 case Instruction::Or:
2179 case Instruction::Xor:
2180 case Instruction::Freeze:
2181 case Instruction::ExtractValue:
2182 case Instruction::ICmp:
2183 case Instruction::FCmp:
2184 return getCostForRecipeWithOpcode(getOpcode(), VF, Ctx);
2185 default:
2186 llvm_unreachable("Unsupported opcode for instruction");
2187 }
2188}
2189
2190#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2192 VPSlotTracker &SlotTracker) const {
2193 O << Indent << "WIDEN ";
2195 O << " = " << Instruction::getOpcodeName(Opcode);
2196 printFlags(O);
2198}
2199#endif
2200
2202 auto &Builder = State.Builder;
2203 /// Vectorize casts.
2204 assert(State.VF.isVector() && "Not vectorizing?");
2205 Type *DestTy = VectorType::get(getResultType(), State.VF);
2206 VPValue *Op = getOperand(0);
2207 Value *A = State.get(Op);
2208 Value *Cast = Builder.CreateCast(Instruction::CastOps(Opcode), A, DestTy);
2209 State.set(this, Cast);
2210 if (auto *CastOp = dyn_cast<Instruction>(Cast)) {
2211 applyFlags(*CastOp);
2212 applyMetadata(*CastOp);
2213 }
2214}
2215
2217 VPCostContext &Ctx) const {
2218 // TODO: In some cases, VPWidenCastRecipes are created but not considered in
2219 // the legacy cost model, including truncates/extends when evaluating a
2220 // reduction in a smaller type.
2221 if (!getUnderlyingValue())
2222 return 0;
2223 // Computes the CastContextHint from a recipes that may access memory.
2224 auto ComputeCCH = [&](const VPRecipeBase *R) -> TTI::CastContextHint {
2225 if (VF.isScalar())
2227 if (isa<VPInterleaveBase>(R))
2229 if (const auto *ReplicateRecipe = dyn_cast<VPReplicateRecipe>(R))
2230 return ReplicateRecipe->isPredicated() ? TTI::CastContextHint::Masked
2232 const auto *WidenMemoryRecipe = dyn_cast<VPWidenMemoryRecipe>(R);
2233 if (WidenMemoryRecipe == nullptr)
2235 if (!WidenMemoryRecipe->isConsecutive())
2237 if (WidenMemoryRecipe->isReverse())
2239 if (WidenMemoryRecipe->isMasked())
2242 };
2243
2244 VPValue *Operand = getOperand(0);
2246 // For Trunc/FPTrunc, get the context from the only user.
2247 if ((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
2249 if (auto *StoreRecipe = dyn_cast<VPRecipeBase>(*user_begin()))
2250 CCH = ComputeCCH(StoreRecipe);
2251 }
2252 // For Z/Sext, get the context from the operand.
2253 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
2254 Opcode == Instruction::FPExt) {
2255 if (Operand->isLiveIn())
2257 else if (Operand->getDefiningRecipe())
2258 CCH = ComputeCCH(Operand->getDefiningRecipe());
2259 }
2260
2261 auto *SrcTy =
2262 cast<VectorType>(toVectorTy(Ctx.Types.inferScalarType(Operand), VF));
2263 auto *DestTy = cast<VectorType>(toVectorTy(getResultType(), VF));
2264 // Arm TTI will use the underlying instruction to determine the cost.
2265 return Ctx.TTI.getCastInstrCost(
2266 Opcode, DestTy, SrcTy, CCH, Ctx.CostKind,
2268}
2269
2270#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2272 VPSlotTracker &SlotTracker) const {
2273 O << Indent << "WIDEN-CAST ";
2275 O << " = " << Instruction::getOpcodeName(Opcode);
2276 printFlags(O);
2278 O << " to " << *getResultType();
2279}
2280#endif
2281
2283 VPCostContext &Ctx) const {
2284 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2285}
2286
2287/// A helper function that returns an integer or floating-point constant with
2288/// value C.
2290 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
2291 : ConstantFP::get(Ty, C);
2292}
2293
2294#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2296 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
2297 O << Indent;
2299 O << " = WIDEN-INDUCTION";
2300 printFlags(O);
2301 O << " ";
2303
2304 if (auto *TI = getTruncInst())
2305 O << " (truncated to " << *TI->getType() << ")";
2306}
2307#endif
2308
2310 // The step may be defined by a recipe in the preheader (e.g. if it requires
2311 // SCEV expansion), but for the canonical induction the step is required to be
2312 // 1, which is represented as live-in.
2314 return false;
2317 return StartC && StartC->isZero() && StepC && StepC->isOne() &&
2318 getScalarType() == getRegion()->getCanonicalIVType();
2319}
2320
2321#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2323 VPSlotTracker &SlotTracker) const {
2324 O << Indent;
2326 O << " = DERIVED-IV ";
2327 getStartValue()->printAsOperand(O, SlotTracker);
2328 O << " + ";
2329 getOperand(1)->printAsOperand(O, SlotTracker);
2330 O << " * ";
2331 getStepValue()->printAsOperand(O, SlotTracker);
2332}
2333#endif
2334
2336 // Fast-math-flags propagate from the original induction instruction.
2337 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
2338 if (hasFastMathFlags())
2339 State.Builder.setFastMathFlags(getFastMathFlags());
2340
2341 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2342 /// variable on which to base the steps, \p Step is the size of the step.
2343
2344 Value *BaseIV = State.get(getOperand(0), VPLane(0));
2345 Value *Step = State.get(getStepValue(), VPLane(0));
2346 IRBuilderBase &Builder = State.Builder;
2347
2348 // Ensure step has the same type as that of scalar IV.
2349 Type *BaseIVTy = BaseIV->getType()->getScalarType();
2350 assert(BaseIVTy == Step->getType() && "Types of BaseIV and Step must match!");
2351
2352 // We build scalar steps for both integer and floating-point induction
2353 // variables. Here, we determine the kind of arithmetic we will perform.
2356 if (BaseIVTy->isIntegerTy()) {
2357 AddOp = Instruction::Add;
2358 MulOp = Instruction::Mul;
2359 } else {
2360 AddOp = InductionOpcode;
2361 MulOp = Instruction::FMul;
2362 }
2363
2364 // Determine the number of scalars we need to generate for each unroll
2365 // iteration.
2366 bool FirstLaneOnly = vputils::onlyFirstLaneUsed(this);
2367 // Compute the scalar steps and save the results in State.
2368 Type *IntStepTy =
2369 IntegerType::get(BaseIVTy->getContext(), BaseIVTy->getScalarSizeInBits());
2370 Type *VecIVTy = nullptr;
2371 Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2372 if (!FirstLaneOnly && State.VF.isScalable()) {
2373 VecIVTy = VectorType::get(BaseIVTy, State.VF);
2374 UnitStepVec =
2375 Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2376 SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2377 SplatIV = Builder.CreateVectorSplat(State.VF, BaseIV);
2378 }
2379
2380 unsigned StartLane = 0;
2381 unsigned EndLane = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2382 if (State.Lane) {
2383 StartLane = State.Lane->getKnownLane();
2384 EndLane = StartLane + 1;
2385 }
2386 Value *StartIdx0;
2387 if (getUnrollPart(*this) == 0)
2388 StartIdx0 = ConstantInt::get(IntStepTy, 0);
2389 else {
2390 StartIdx0 = State.get(getOperand(2), true);
2391 if (getUnrollPart(*this) != 1) {
2392 StartIdx0 =
2393 Builder.CreateMul(StartIdx0, ConstantInt::get(StartIdx0->getType(),
2394 getUnrollPart(*this)));
2395 }
2396 StartIdx0 = Builder.CreateSExtOrTrunc(StartIdx0, IntStepTy);
2397 }
2398
2399 if (!FirstLaneOnly && State.VF.isScalable()) {
2400 auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2401 auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2402 if (BaseIVTy->isFloatingPointTy())
2403 InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2404 auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2405 auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2406 State.set(this, Add);
2407 // It's useful to record the lane values too for the known minimum number
2408 // of elements so we do those below. This improves the code quality when
2409 // trying to extract the first element, for example.
2410 }
2411
2412 if (BaseIVTy->isFloatingPointTy())
2413 StartIdx0 = Builder.CreateSIToFP(StartIdx0, BaseIVTy);
2414
2415 for (unsigned Lane = StartLane; Lane < EndLane; ++Lane) {
2416 Value *StartIdx = Builder.CreateBinOp(
2417 AddOp, StartIdx0, getSignedIntOrFpConstant(BaseIVTy, Lane));
2418 // The step returned by `createStepForVF` is a runtime-evaluated value
2419 // when VF is scalable. Otherwise, it should be folded into a Constant.
2420 assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2421 "Expected StartIdx to be folded to a constant when VF is not "
2422 "scalable");
2423 auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2424 auto *Add = Builder.CreateBinOp(AddOp, BaseIV, Mul);
2425 State.set(this, Add, VPLane(Lane));
2426 }
2427}
2428
2429#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2431 VPSlotTracker &SlotTracker) const {
2432 O << Indent;
2434 O << " = SCALAR-STEPS ";
2436}
2437#endif
2438
2440 assert(is_contained(operands(), Op) && "Op must be an operand of the recipe");
2442}
2443
2445 assert(State.VF.isVector() && "not widening");
2446 // Construct a vector GEP by widening the operands of the scalar GEP as
2447 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
2448 // results in a vector of pointers when at least one operand of the GEP
2449 // is vector-typed. Thus, to keep the representation compact, we only use
2450 // vector-typed operands for loop-varying values.
2451
2452 assert(
2453 any_of(operands(),
2454 [](VPValue *Op) { return !Op->isDefinedOutsideLoopRegions(); }) &&
2455 "Expected at least one loop-variant operand");
2456
2457 // If the GEP has at least one loop-varying operand, we are sure to
2458 // produce a vector of pointers unless VF is scalar.
2459 // The pointer operand of the new GEP. If it's loop-invariant, we
2460 // won't broadcast it.
2461 auto *Ptr = State.get(getOperand(0), isPointerLoopInvariant());
2462
2463 // Collect all the indices for the new GEP. If any index is
2464 // loop-invariant, we won't broadcast it.
2466 for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
2467 VPValue *Operand = getOperand(I);
2468 Indices.push_back(State.get(Operand, isIndexLoopInvariant(I - 1)));
2469 }
2470
2471 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
2472 // but it should be a vector, otherwise.
2473 auto *NewGEP = State.Builder.CreateGEP(getSourceElementType(), Ptr, Indices,
2474 "", getGEPNoWrapFlags());
2475 assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
2476 "NewGEP is not a pointer vector");
2477 State.set(this, NewGEP);
2478}
2479
2480#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2482 VPSlotTracker &SlotTracker) const {
2483 O << Indent << "WIDEN-GEP ";
2484 O << (isPointerLoopInvariant() ? "Inv" : "Var");
2485 for (size_t I = 0; I < getNumOperands() - 1; ++I)
2486 O << "[" << (isIndexLoopInvariant(I) ? "Inv" : "Var") << "]";
2487
2488 O << " ";
2490 O << " = getelementptr";
2491 printFlags(O);
2493}
2494#endif
2495
2497 auto &Builder = State.Builder;
2498 unsigned CurrentPart = getUnrollPart(*this);
2499 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2500 Type *IndexTy = DL.getIndexType(State.TypeAnalysis.inferScalarType(this));
2501
2502 // The wide store needs to start at the last vector element.
2503 Value *RunTimeVF = State.get(getVFValue(), VPLane(0));
2504 if (IndexTy != RunTimeVF->getType())
2505 RunTimeVF = Builder.CreateZExtOrTrunc(RunTimeVF, IndexTy);
2506 // NumElt = Stride * CurrentPart * RunTimeVF
2507 Value *NumElt = Builder.CreateMul(
2508 ConstantInt::get(IndexTy, Stride * (int64_t)CurrentPart), RunTimeVF);
2509 // LastLane = Stride * (RunTimeVF - 1)
2510 Value *LastLane = Builder.CreateSub(RunTimeVF, ConstantInt::get(IndexTy, 1));
2511 if (Stride != 1)
2512 LastLane = Builder.CreateMul(ConstantInt::get(IndexTy, Stride), LastLane);
2513 Value *Ptr = State.get(getOperand(0), VPLane(0));
2514 Value *ResultPtr =
2515 Builder.CreateGEP(IndexedTy, Ptr, NumElt, "", getGEPNoWrapFlags());
2516 ResultPtr = Builder.CreateGEP(IndexedTy, ResultPtr, LastLane, "",
2518
2519 State.set(this, ResultPtr, /*IsScalar*/ true);
2520}
2521
2522#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2524 VPSlotTracker &SlotTracker) const {
2525 O << Indent;
2527 O << " = vector-end-pointer";
2528 printFlags(O);
2530}
2531#endif
2532
2534 auto &Builder = State.Builder;
2535 unsigned CurrentPart = getUnrollPart(*this);
2536 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
2537 Type *IndexTy = DL.getIndexType(State.TypeAnalysis.inferScalarType(this));
2538 Value *Ptr = State.get(getOperand(0), VPLane(0));
2539
2540 Value *Increment = createStepForVF(Builder, IndexTy, State.VF, CurrentPart);
2541 Value *ResultPtr = Builder.CreateGEP(getSourceElementType(), Ptr, Increment,
2542 "", getGEPNoWrapFlags());
2543
2544 State.set(this, ResultPtr, /*IsScalar*/ true);
2545}
2546
2547#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2549 VPSlotTracker &SlotTracker) const {
2550 O << Indent;
2552 O << " = vector-pointer ";
2553 printFlags(O);
2555}
2556#endif
2557
2559 VPCostContext &Ctx) const {
2560 // Handle cases where only the first lane is used the same way as the legacy
2561 // cost model.
2563 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
2564
2565 Type *ResultTy = toVectorTy(Ctx.Types.inferScalarType(this), VF);
2566 Type *CmpTy = toVectorTy(Type::getInt1Ty(Ctx.Types.getContext()), VF);
2567 return (getNumIncomingValues() - 1) *
2568 Ctx.TTI.getCmpSelInstrCost(Instruction::Select, ResultTy, CmpTy,
2569 CmpInst::BAD_ICMP_PREDICATE, Ctx.CostKind);
2570}
2571
2572#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2574 VPSlotTracker &SlotTracker) const {
2575 O << Indent << "BLEND ";
2577 O << " =";
2578 if (getNumIncomingValues() == 1) {
2579 // Not a User of any mask: not really blending, this is a
2580 // single-predecessor phi.
2581 O << " ";
2582 getIncomingValue(0)->printAsOperand(O, SlotTracker);
2583 } else {
2584 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
2585 O << " ";
2586 getIncomingValue(I)->printAsOperand(O, SlotTracker);
2587 if (I == 0)
2588 continue;
2589 O << "/";
2590 getMask(I)->printAsOperand(O, SlotTracker);
2591 }
2592 }
2593}
2594#endif
2595
2597 assert(!State.Lane && "Reduction being replicated.");
2600 "In-loop AnyOf reductions aren't currently supported");
2601 // Propagate the fast-math flags carried by the underlying instruction.
2602 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
2603 State.Builder.setFastMathFlags(getFastMathFlags());
2604 Value *NewVecOp = State.get(getVecOp());
2605 if (VPValue *Cond = getCondOp()) {
2606 Value *NewCond = State.get(Cond, State.VF.isScalar());
2607 VectorType *VecTy = dyn_cast<VectorType>(NewVecOp->getType());
2608 Type *ElementTy = VecTy ? VecTy->getElementType() : NewVecOp->getType();
2609
2610 Value *Start = getRecurrenceIdentity(Kind, ElementTy, getFastMathFlags());
2611 if (State.VF.isVector())
2612 Start = State.Builder.CreateVectorSplat(VecTy->getElementCount(), Start);
2613
2614 Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, Start);
2615 NewVecOp = Select;
2616 }
2617 Value *NewRed;
2618 Value *NextInChain;
2619 if (isOrdered()) {
2620 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2621 if (State.VF.isVector())
2622 NewRed =
2623 createOrderedReduction(State.Builder, Kind, NewVecOp, PrevInChain);
2624 else
2625 NewRed = State.Builder.CreateBinOp(
2627 PrevInChain, NewVecOp);
2628 PrevInChain = NewRed;
2629 NextInChain = NewRed;
2630 } else if (isPartialReduction()) {
2631 assert(Kind == RecurKind::Add && "Unexpected partial reduction kind");
2632 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ false);
2633 NewRed = State.Builder.CreateIntrinsic(
2634 PrevInChain->getType(), Intrinsic::vector_partial_reduce_add,
2635 {PrevInChain, NewVecOp}, nullptr, "partial.reduce");
2636 PrevInChain = NewRed;
2637 NextInChain = NewRed;
2638 } else {
2639 assert(isInLoop() &&
2640 "The reduction must either be ordered, partial or in-loop");
2641 Value *PrevInChain = State.get(getChainOp(), /*IsScalar*/ true);
2642 NewRed = createSimpleReduction(State.Builder, NewVecOp, Kind);
2644 NextInChain = createMinMaxOp(State.Builder, Kind, NewRed, PrevInChain);
2645 else
2646 NextInChain = State.Builder.CreateBinOp(
2648 PrevInChain, NewRed);
2649 }
2650 State.set(this, NextInChain, /*IsScalar*/ !isPartialReduction());
2651}
2652
2654 assert(!State.Lane && "Reduction being replicated.");
2655
2656 auto &Builder = State.Builder;
2657 // Propagate the fast-math flags carried by the underlying instruction.
2658 IRBuilderBase::FastMathFlagGuard FMFGuard(Builder);
2659 Builder.setFastMathFlags(getFastMathFlags());
2660
2662 Value *Prev = State.get(getChainOp(), /*IsScalar*/ true);
2663 Value *VecOp = State.get(getVecOp());
2664 Value *EVL = State.get(getEVL(), VPLane(0));
2665
2666 Value *Mask;
2667 if (VPValue *CondOp = getCondOp())
2668 Mask = State.get(CondOp);
2669 else
2670 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
2671
2672 Value *NewRed;
2673 if (isOrdered()) {
2674 NewRed = createOrderedReduction(Builder, Kind, VecOp, Prev, Mask, EVL);
2675 } else {
2676 NewRed = createSimpleReduction(Builder, VecOp, Kind, Mask, EVL);
2678 NewRed = createMinMaxOp(Builder, Kind, NewRed, Prev);
2679 else
2680 NewRed = Builder.CreateBinOp(
2682 Prev);
2683 }
2684 State.set(this, NewRed, /*IsScalar*/ true);
2685}
2686
2688 VPCostContext &Ctx) const {
2689 RecurKind RdxKind = getRecurrenceKind();
2690 Type *ElementTy = Ctx.Types.inferScalarType(this);
2691 auto *VectorTy = cast<VectorType>(toVectorTy(ElementTy, VF));
2692 unsigned Opcode = RecurrenceDescriptor::getOpcode(RdxKind);
2694 std::optional<FastMathFlags> OptionalFMF =
2695 ElementTy->isFloatingPointTy() ? std::make_optional(FMFs) : std::nullopt;
2696
2697 if (isPartialReduction()) {
2698 InstructionCost CondCost = 0;
2699 if (isConditional()) {
2701 auto *CondTy = cast<VectorType>(
2702 toVectorTy(Ctx.Types.inferScalarType(getCondOp()), VF));
2703 CondCost = Ctx.TTI.getCmpSelInstrCost(Instruction::Select, VectorTy,
2704 CondTy, Pred, Ctx.CostKind);
2705 }
2706 return CondCost + Ctx.TTI.getPartialReductionCost(
2707 Opcode, ElementTy, ElementTy, ElementTy, VF,
2709 TargetTransformInfo::PR_None, std::nullopt,
2710 Ctx.CostKind);
2711 }
2712
2713 // TODO: Support any-of reductions.
2714 assert(
2716 ForceTargetInstructionCost.getNumOccurrences() > 0) &&
2717 "Any-of reduction not implemented in VPlan-based cost model currently.");
2718
2719 // Note that TTI should model the cost of moving result to the scalar register
2720 // and the BinOp cost in the getMinMaxReductionCost().
2723 return Ctx.TTI.getMinMaxReductionCost(Id, VectorTy, FMFs, Ctx.CostKind);
2724 }
2725
2726 // Note that TTI should model the cost of moving result to the scalar register
2727 // and the BinOp cost in the getArithmeticReductionCost().
2728 return Ctx.TTI.getArithmeticReductionCost(Opcode, VectorTy, OptionalFMF,
2729 Ctx.CostKind);
2730}
2731
2733 ExpressionTypes ExpressionType,
2734 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes)
2735 : VPSingleDefRecipe(VPDef::VPExpressionSC, {}, {}),
2736 ExpressionRecipes(ExpressionRecipes), ExpressionType(ExpressionType) {
2737 assert(!ExpressionRecipes.empty() && "Nothing to combine?");
2738 assert(
2739 none_of(ExpressionRecipes,
2740 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2741 "expression cannot contain recipes with side-effects");
2742
2743 // Maintain a copy of the expression recipes as a set of users.
2744 SmallPtrSet<VPUser *, 4> ExpressionRecipesAsSetOfUsers;
2745 for (auto *R : ExpressionRecipes)
2746 ExpressionRecipesAsSetOfUsers.insert(R);
2747
2748 // Recipes in the expression, except the last one, must only be used by
2749 // (other) recipes inside the expression. If there are other users, external
2750 // to the expression, use a clone of the recipe for external users.
2751 for (VPSingleDefRecipe *R : reverse(ExpressionRecipes)) {
2752 if (R != ExpressionRecipes.back() &&
2753 any_of(R->users(), [&ExpressionRecipesAsSetOfUsers](VPUser *U) {
2754 return !ExpressionRecipesAsSetOfUsers.contains(U);
2755 })) {
2756 // There are users outside of the expression. Clone the recipe and use the
2757 // clone those external users.
2758 VPSingleDefRecipe *CopyForExtUsers = R->clone();
2759 R->replaceUsesWithIf(CopyForExtUsers, [&ExpressionRecipesAsSetOfUsers](
2760 VPUser &U, unsigned) {
2761 return !ExpressionRecipesAsSetOfUsers.contains(&U);
2762 });
2763 CopyForExtUsers->insertBefore(R);
2764 }
2765 if (R->getParent())
2766 R->removeFromParent();
2767 }
2768
2769 // Internalize all external operands to the expression recipes. To do so,
2770 // create new temporary VPValues for all operands defined by a recipe outside
2771 // the expression. The original operands are added as operands of the
2772 // VPExpressionRecipe itself.
2773 for (auto *R : ExpressionRecipes) {
2774 for (const auto &[Idx, Op] : enumerate(R->operands())) {
2775 auto *Def = Op->getDefiningRecipe();
2776 if (Def && ExpressionRecipesAsSetOfUsers.contains(Def))
2777 continue;
2778 addOperand(Op);
2779 LiveInPlaceholders.push_back(new VPValue());
2780 }
2781 }
2782
2783 // Replace each external operand with the first one created for it in
2784 // LiveInPlaceholders.
2785 for (auto *R : ExpressionRecipes)
2786 for (auto const &[LiveIn, Tmp] : zip(operands(), LiveInPlaceholders))
2787 R->replaceUsesOfWith(LiveIn, Tmp);
2788}
2789
2791 for (auto *R : ExpressionRecipes)
2792 // Since the list could contain duplicates, make sure the recipe hasn't
2793 // already been inserted.
2794 if (!R->getParent())
2795 R->insertBefore(this);
2796
2797 for (const auto &[Idx, Op] : enumerate(operands()))
2798 LiveInPlaceholders[Idx]->replaceAllUsesWith(Op);
2799
2800 replaceAllUsesWith(ExpressionRecipes.back());
2801 ExpressionRecipes.clear();
2802}
2803
2805 VPCostContext &Ctx) const {
2806 Type *RedTy = Ctx.Types.inferScalarType(this);
2807 auto *SrcVecTy = cast<VectorType>(
2808 toVectorTy(Ctx.Types.inferScalarType(getOperand(0)), VF));
2809 assert(RedTy->isIntegerTy() &&
2810 "VPExpressionRecipe only supports integer types currently.");
2811 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2812 cast<VPReductionRecipe>(ExpressionRecipes.back())->getRecurrenceKind());
2813 switch (ExpressionType) {
2814 case ExpressionTypes::ExtendedReduction: {
2815 unsigned Opcode = RecurrenceDescriptor::getOpcode(
2816 cast<VPReductionRecipe>(ExpressionRecipes[1])->getRecurrenceKind());
2817 auto *ExtR = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2818
2819 return cast<VPReductionRecipe>(ExpressionRecipes.back())
2820 ->isPartialReduction()
2821 ? Ctx.TTI.getPartialReductionCost(
2822 Opcode, Ctx.Types.inferScalarType(getOperand(0)), nullptr,
2823 RedTy, VF,
2825 ExtR->getOpcode()),
2826 TargetTransformInfo::PR_None, std::nullopt, Ctx.CostKind)
2827 : Ctx.TTI.getExtendedReductionCost(
2828 Opcode, ExtR->getOpcode() == Instruction::ZExt, RedTy,
2829 SrcVecTy, std::nullopt, Ctx.CostKind);
2830 }
2831 case ExpressionTypes::MulAccReduction:
2832 return Ctx.TTI.getMulAccReductionCost(false, Opcode, RedTy, SrcVecTy,
2833 Ctx.CostKind);
2834
2835 case ExpressionTypes::ExtNegatedMulAccReduction:
2836 assert(Opcode == Instruction::Add && "Unexpected opcode");
2837 Opcode = Instruction::Sub;
2838 [[fallthrough]];
2839 case ExpressionTypes::ExtMulAccReduction: {
2840 auto *RedR = cast<VPReductionRecipe>(ExpressionRecipes.back());
2841 if (RedR->isPartialReduction()) {
2842 auto *Ext0R = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2843 auto *Ext1R = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2844 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2845 return Ctx.TTI.getPartialReductionCost(
2846 Opcode, Ctx.Types.inferScalarType(getOperand(0)),
2847 Ctx.Types.inferScalarType(getOperand(1)), RedTy, VF,
2849 Ext0R->getOpcode()),
2851 Ext1R->getOpcode()),
2852 Mul->getOpcode(), Ctx.CostKind);
2853 }
2854 return Ctx.TTI.getMulAccReductionCost(
2855 cast<VPWidenCastRecipe>(ExpressionRecipes.front())->getOpcode() ==
2856 Instruction::ZExt,
2857 Opcode, RedTy, SrcVecTy, Ctx.CostKind);
2858 }
2859 }
2860 llvm_unreachable("Unknown VPExpressionRecipe::ExpressionTypes enum");
2861}
2862
2864 return any_of(ExpressionRecipes, [](VPSingleDefRecipe *R) {
2865 return R->mayReadFromMemory() || R->mayWriteToMemory();
2866 });
2867}
2868
2870 assert(
2871 none_of(ExpressionRecipes,
2872 [](VPSingleDefRecipe *R) { return R->mayHaveSideEffects(); }) &&
2873 "expression cannot contain recipes with side-effects");
2874 return false;
2875}
2876
2878 // Cannot use vputils::isSingleScalar(), because all external operands
2879 // of the expression will be live-ins while bundled.
2880 auto *RR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
2881 return RR && !RR->isPartialReduction();
2882}
2883
2884#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2885
2887 VPSlotTracker &SlotTracker) const {
2888 O << Indent << "EXPRESSION ";
2890 O << " = ";
2891 auto *Red = cast<VPReductionRecipe>(ExpressionRecipes.back());
2892 unsigned Opcode = RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind());
2893
2894 switch (ExpressionType) {
2895 case ExpressionTypes::ExtendedReduction: {
2897 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
2898 O << Instruction::getOpcodeName(Opcode) << " (";
2900 Red->printFlags(O);
2901
2902 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2903 O << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2904 << *Ext0->getResultType();
2905 if (Red->isConditional()) {
2906 O << ", ";
2907 Red->getCondOp()->printAsOperand(O, SlotTracker);
2908 }
2909 O << ")";
2910 break;
2911 }
2912 case ExpressionTypes::ExtNegatedMulAccReduction: {
2914 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
2916 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
2917 << " (sub (0, mul";
2918 auto *Mul = cast<VPWidenRecipe>(ExpressionRecipes[2]);
2919 Mul->printFlags(O);
2920 O << "(";
2922 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2923 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2924 << *Ext0->getResultType() << "), (";
2926 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2927 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
2928 << *Ext1->getResultType() << ")";
2929 if (Red->isConditional()) {
2930 O << ", ";
2931 Red->getCondOp()->printAsOperand(O, SlotTracker);
2932 }
2933 O << "))";
2934 break;
2935 }
2936 case ExpressionTypes::MulAccReduction:
2937 case ExpressionTypes::ExtMulAccReduction: {
2939 O << " + " << (Red->isPartialReduction() ? "partial." : "") << "reduce.";
2941 RecurrenceDescriptor::getOpcode(Red->getRecurrenceKind()))
2942 << " (";
2943 O << "mul";
2944 bool IsExtended = ExpressionType == ExpressionTypes::ExtMulAccReduction;
2945 auto *Mul = cast<VPWidenRecipe>(IsExtended ? ExpressionRecipes[2]
2946 : ExpressionRecipes[0]);
2947 Mul->printFlags(O);
2948 if (IsExtended)
2949 O << "(";
2951 if (IsExtended) {
2952 auto *Ext0 = cast<VPWidenCastRecipe>(ExpressionRecipes[0]);
2953 O << " " << Instruction::getOpcodeName(Ext0->getOpcode()) << " to "
2954 << *Ext0->getResultType() << "), (";
2955 } else {
2956 O << ", ";
2957 }
2959 if (IsExtended) {
2960 auto *Ext1 = cast<VPWidenCastRecipe>(ExpressionRecipes[1]);
2961 O << " " << Instruction::getOpcodeName(Ext1->getOpcode()) << " to "
2962 << *Ext1->getResultType() << ")";
2963 }
2964 if (Red->isConditional()) {
2965 O << ", ";
2966 Red->getCondOp()->printAsOperand(O, SlotTracker);
2967 }
2968 O << ")";
2969 break;
2970 }
2971 }
2972}
2973
2975 VPSlotTracker &SlotTracker) const {
2976 if (isPartialReduction())
2977 O << Indent << "PARTIAL-REDUCE ";
2978 else
2979 O << Indent << "REDUCE ";
2981 O << " = ";
2983 O << " +";
2984 printFlags(O);
2985 O << " reduce."
2988 << " (";
2990 if (isConditional()) {
2991 O << ", ";
2993 }
2994 O << ")";
2995}
2996
2998 VPSlotTracker &SlotTracker) const {
2999 O << Indent << "REDUCE ";
3001 O << " = ";
3003 O << " +";
3004 printFlags(O);
3005 O << " vp.reduce."
3008 << " (";
3010 O << ", ";
3012 if (isConditional()) {
3013 O << ", ";
3015 }
3016 O << ")";
3017}
3018
3019#endif
3020
3021/// A helper function to scalarize a single Instruction in the innermost loop.
3022/// Generates a sequence of scalar instances for lane \p Lane. Uses the VPValue
3023/// operands from \p RepRecipe instead of \p Instr's operands.
3024static void scalarizeInstruction(const Instruction *Instr,
3025 VPReplicateRecipe *RepRecipe,
3026 const VPLane &Lane, VPTransformState &State) {
3027 assert((!Instr->getType()->isAggregateType() ||
3028 canVectorizeTy(Instr->getType())) &&
3029 "Expected vectorizable or non-aggregate type.");
3030
3031 // Does this instruction return a value ?
3032 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3033
3034 Instruction *Cloned = Instr->clone();
3035 if (!IsVoidRetTy) {
3036 Cloned->setName(Instr->getName() + ".cloned");
3037 Type *ResultTy = State.TypeAnalysis.inferScalarType(RepRecipe);
3038 // The operands of the replicate recipe may have been narrowed, resulting in
3039 // a narrower result type. Update the type of the cloned instruction to the
3040 // correct type.
3041 if (ResultTy != Cloned->getType())
3042 Cloned->mutateType(ResultTy);
3043 }
3044
3045 RepRecipe->applyFlags(*Cloned);
3046 RepRecipe->applyMetadata(*Cloned);
3047
3048 if (RepRecipe->hasPredicate())
3049 cast<CmpInst>(Cloned)->setPredicate(RepRecipe->getPredicate());
3050
3051 if (auto DL = RepRecipe->getDebugLoc())
3052 State.setDebugLocFrom(DL);
3053
3054 // Replace the operands of the cloned instructions with their scalar
3055 // equivalents in the new loop.
3056 for (const auto &I : enumerate(RepRecipe->operands())) {
3057 auto InputLane = Lane;
3058 VPValue *Operand = I.value();
3059 if (vputils::isSingleScalar(Operand))
3060 InputLane = VPLane::getFirstLane();
3061 Cloned->setOperand(I.index(), State.get(Operand, InputLane));
3062 }
3063
3064 // Place the cloned scalar in the new loop.
3065 State.Builder.Insert(Cloned);
3066
3067 State.set(RepRecipe, Cloned, Lane);
3068
3069 // If we just cloned a new assumption, add it the assumption cache.
3070 if (auto *II = dyn_cast<AssumeInst>(Cloned))
3071 State.AC->registerAssumption(II);
3072
3073 assert(
3074 (RepRecipe->getRegion() ||
3075 !RepRecipe->getParent()->getPlan()->getVectorLoopRegion() ||
3076 all_of(RepRecipe->operands(),
3077 [](VPValue *Op) { return Op->isDefinedOutsideLoopRegions(); })) &&
3078 "Expected a recipe is either within a region or all of its operands "
3079 "are defined outside the vectorized region.");
3080}
3081
3084
3085 if (!State.Lane) {
3086 assert(IsSingleScalar && "VPReplicateRecipes outside replicate regions "
3087 "must have already been unrolled");
3088 scalarizeInstruction(UI, this, VPLane(0), State);
3089 return;
3090 }
3091
3092 assert((State.VF.isScalar() || !isSingleScalar()) &&
3093 "uniform recipe shouldn't be predicated");
3094 assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
3095 scalarizeInstruction(UI, this, *State.Lane, State);
3096 // Insert scalar instance packing it into a vector.
3097 if (State.VF.isVector() && shouldPack()) {
3098 Value *WideValue =
3099 State.Lane->isFirstLane()
3100 ? PoisonValue::get(toVectorizedTy(UI->getType(), State.VF))
3101 : State.get(this);
3102 State.set(this, State.packScalarIntoVectorizedValue(this, WideValue,
3103 *State.Lane));
3104 }
3105}
3106
3108 // Find if the recipe is used by a widened recipe via an intervening
3109 // VPPredInstPHIRecipe. In this case, also pack the scalar values in a vector.
3110 return any_of(users(), [](const VPUser *U) {
3111 if (auto *PredR = dyn_cast<VPPredInstPHIRecipe>(U))
3112 return !vputils::onlyScalarValuesUsed(PredR);
3113 return false;
3114 });
3115}
3116
3117/// Returns a SCEV expression for \p Ptr if it is a pointer computation for
3118/// which the legacy cost model computes a SCEV expression when computing the
3119/// address cost. Computing SCEVs for VPValues is incomplete and returns
3120/// SCEVCouldNotCompute in cases the legacy cost model can compute SCEVs. In
3121/// those cases we fall back to the legacy cost model. Otherwise return nullptr.
3122static const SCEV *getAddressAccessSCEV(const VPValue *Ptr, ScalarEvolution &SE,
3123 const Loop *L) {
3124 auto *PtrR = Ptr->getDefiningRecipe();
3125 if (!PtrR || !((isa<VPReplicateRecipe>(Ptr) &&
3127 Instruction::GetElementPtr) ||
3128 isa<VPWidenGEPRecipe>(Ptr) ||
3130 return nullptr;
3131
3132 // We are looking for a GEP where all indices are either loop invariant or
3133 // inductions.
3134 for (VPValue *Opd : drop_begin(PtrR->operands())) {
3135 if (!Opd->isDefinedOutsideLoopRegions() &&
3137 return nullptr;
3138 }
3139
3140 return vputils::getSCEVExprForVPValue(Ptr, SE, L);
3141}
3142
3143/// Returns true if \p V is used as part of the address of another load or
3144/// store.
3145static bool isUsedByLoadStoreAddress(const VPUser *V) {
3147 SmallVector<const VPUser *> WorkList = {V};
3148
3149 while (!WorkList.empty()) {
3150 auto *Cur = dyn_cast<VPSingleDefRecipe>(WorkList.pop_back_val());
3151 if (!Cur || !Seen.insert(Cur).second)
3152 continue;
3153
3154 auto *Blend = dyn_cast<VPBlendRecipe>(Cur);
3155 // Skip blends that use V only through a compare by checking if any incoming
3156 // value was already visited.
3157 if (Blend && none_of(seq<unsigned>(0, Blend->getNumIncomingValues()),
3158 [&](unsigned I) {
3159 return Seen.contains(
3160 Blend->getIncomingValue(I)->getDefiningRecipe());
3161 }))
3162 continue;
3163
3164 for (VPUser *U : Cur->users()) {
3165 if (auto *InterleaveR = dyn_cast<VPInterleaveBase>(U))
3166 if (InterleaveR->getAddr() == Cur)
3167 return true;
3168 if (auto *RepR = dyn_cast<VPReplicateRecipe>(U)) {
3169 if (RepR->getOpcode() == Instruction::Load &&
3170 RepR->getOperand(0) == Cur)
3171 return true;
3172 if (RepR->getOpcode() == Instruction::Store &&
3173 RepR->getOperand(1) == Cur)
3174 return true;
3175 }
3176 if (auto *MemR = dyn_cast<VPWidenMemoryRecipe>(U)) {
3177 if (MemR->getAddr() == Cur && MemR->isConsecutive())
3178 return true;
3179 }
3180 }
3181
3182 // The legacy cost model only supports scalarization loads/stores with phi
3183 // addresses, if the phi is directly used as load/store address. Don't
3184 // traverse further for Blends.
3185 if (Blend)
3186 continue;
3187
3188 append_range(WorkList, Cur->users());
3189 }
3190 return false;
3191}
3192
3194 VPCostContext &Ctx) const {
3196 // VPReplicateRecipe may be cloned as part of an existing VPlan-to-VPlan
3197 // transform, avoid computing their cost multiple times for now.
3198 Ctx.SkipCostComputation.insert(UI);
3199
3200 if (VF.isScalable() && !isSingleScalar())
3202
3203 switch (UI->getOpcode()) {
3204 case Instruction::GetElementPtr:
3205 // We mark this instruction as zero-cost because the cost of GEPs in
3206 // vectorized code depends on whether the corresponding memory instruction
3207 // is scalarized or not. Therefore, we handle GEPs with the memory
3208 // instruction cost.
3209 return 0;
3210 case Instruction::Call: {
3211 auto *CalledFn =
3213
3216 for (const VPValue *ArgOp : ArgOps)
3217 Tys.push_back(Ctx.Types.inferScalarType(ArgOp));
3218
3219 if (CalledFn->isIntrinsic())
3220 // Various pseudo-intrinsics with costs of 0 are scalarized instead of
3221 // vectorized via VPWidenIntrinsicRecipe. Return 0 for them early.
3222 switch (CalledFn->getIntrinsicID()) {
3223 case Intrinsic::assume:
3224 case Intrinsic::lifetime_end:
3225 case Intrinsic::lifetime_start:
3226 case Intrinsic::sideeffect:
3227 case Intrinsic::pseudoprobe:
3228 case Intrinsic::experimental_noalias_scope_decl: {
3229 assert(getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3230 ElementCount::getFixed(1), Ctx) == 0 &&
3231 "scalarizing intrinsic should be free");
3232 return InstructionCost(0);
3233 }
3234 default:
3235 break;
3236 }
3237
3238 Type *ResultTy = Ctx.Types.inferScalarType(this);
3239 InstructionCost ScalarCallCost =
3240 Ctx.TTI.getCallInstrCost(CalledFn, ResultTy, Tys, Ctx.CostKind);
3241 if (isSingleScalar()) {
3242 if (CalledFn->isIntrinsic())
3243 ScalarCallCost = std::min(
3244 ScalarCallCost,
3245 getCostForIntrinsics(CalledFn->getIntrinsicID(), ArgOps, *this,
3246 ElementCount::getFixed(1), Ctx));
3247 return ScalarCallCost;
3248 }
3249
3250 return ScalarCallCost * VF.getFixedValue() +
3251 Ctx.getScalarizationOverhead(ResultTy, ArgOps, VF);
3252 }
3253 case Instruction::Add:
3254 case Instruction::Sub:
3255 case Instruction::FAdd:
3256 case Instruction::FSub:
3257 case Instruction::Mul:
3258 case Instruction::FMul:
3259 case Instruction::FDiv:
3260 case Instruction::FRem:
3261 case Instruction::Shl:
3262 case Instruction::LShr:
3263 case Instruction::AShr:
3264 case Instruction::And:
3265 case Instruction::Or:
3266 case Instruction::Xor:
3267 case Instruction::ICmp:
3268 case Instruction::FCmp:
3270 Ctx) *
3271 (isSingleScalar() ? 1 : VF.getFixedValue());
3272 case Instruction::SDiv:
3273 case Instruction::UDiv:
3274 case Instruction::SRem:
3275 case Instruction::URem: {
3276 InstructionCost ScalarCost =
3278 if (isSingleScalar())
3279 return ScalarCost;
3280
3281 ScalarCost = ScalarCost * VF.getFixedValue() +
3282 Ctx.getScalarizationOverhead(Ctx.Types.inferScalarType(this),
3283 to_vector(operands()), VF);
3284 // If the recipe is not predicated (i.e. not in a replicate region), return
3285 // the scalar cost. Otherwise handle predicated cost.
3286 if (!getRegion()->isReplicator())
3287 return ScalarCost;
3288
3289 // Account for the phi nodes that we will create.
3290 ScalarCost += VF.getFixedValue() *
3291 Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
3292 // Scale the cost by the probability of executing the predicated blocks.
3293 // This assumes the predicated block for each vector lane is equally
3294 // likely.
3295 ScalarCost /= Ctx.getPredBlockCostDivisor(UI->getParent());
3296 return ScalarCost;
3297 }
3298 case Instruction::Load:
3299 case Instruction::Store: {
3300 // TODO: See getMemInstScalarizationCost for how to handle replicating and
3301 // predicated cases.
3302 const VPRegionBlock *ParentRegion = getRegion();
3303 if (ParentRegion && ParentRegion->isReplicator())
3304 break;
3305
3306 bool IsLoad = UI->getOpcode() == Instruction::Load;
3307 const VPValue *PtrOp = getOperand(!IsLoad);
3308 const SCEV *PtrSCEV = getAddressAccessSCEV(PtrOp, Ctx.SE, Ctx.L);
3310 break;
3311
3312 Type *ValTy = Ctx.Types.inferScalarType(IsLoad ? this : getOperand(0));
3313 Type *ScalarPtrTy = Ctx.Types.inferScalarType(PtrOp);
3314 const Align Alignment = getLoadStoreAlignment(UI);
3315 unsigned AS = cast<PointerType>(ScalarPtrTy)->getAddressSpace();
3317 InstructionCost ScalarMemOpCost = Ctx.TTI.getMemoryOpCost(
3318 UI->getOpcode(), ValTy, Alignment, AS, Ctx.CostKind, OpInfo);
3319
3320 Type *PtrTy = isSingleScalar() ? ScalarPtrTy : toVectorTy(ScalarPtrTy, VF);
3321 bool PreferVectorizedAddressing = Ctx.TTI.prefersVectorizedAddressing();
3322 bool UsedByLoadStoreAddress =
3323 !PreferVectorizedAddressing && isUsedByLoadStoreAddress(this);
3324 InstructionCost ScalarCost =
3325 ScalarMemOpCost + Ctx.TTI.getAddressComputationCost(
3326 PtrTy, UsedByLoadStoreAddress ? nullptr : &Ctx.SE,
3327 PtrSCEV, Ctx.CostKind);
3328 if (isSingleScalar())
3329 return ScalarCost;
3330
3331 SmallVector<const VPValue *> OpsToScalarize;
3332 Type *ResultTy = Type::getVoidTy(PtrTy->getContext());
3333 // Set ResultTy and OpsToScalarize, if scalarization is needed. Currently we
3334 // don't assign scalarization overhead in general, if the target prefers
3335 // vectorized addressing or the loaded value is used as part of an address
3336 // of another load or store.
3337 if (!UsedByLoadStoreAddress) {
3338 bool EfficientVectorLoadStore =
3339 Ctx.TTI.supportsEfficientVectorElementLoadStore();
3340 if (!(IsLoad && !PreferVectorizedAddressing) &&
3341 !(!IsLoad && EfficientVectorLoadStore))
3342 append_range(OpsToScalarize, operands());
3343
3344 if (!EfficientVectorLoadStore)
3345 ResultTy = Ctx.Types.inferScalarType(this);
3346 }
3347
3348 return (ScalarCost * VF.getFixedValue()) +
3349 Ctx.getScalarizationOverhead(ResultTy, OpsToScalarize, VF, true);
3350 }
3351 }
3352
3353 return Ctx.getLegacyCost(UI, VF);
3354}
3355
3356#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3358 VPSlotTracker &SlotTracker) const {
3359 O << Indent << (IsSingleScalar ? "CLONE " : "REPLICATE ");
3360
3361 if (!getUnderlyingInstr()->getType()->isVoidTy()) {
3363 O << " = ";
3364 }
3365 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) {
3366 O << "call";
3367 printFlags(O);
3368 O << "@" << CB->getCalledFunction()->getName() << "(";
3370 O, [&O, &SlotTracker](VPValue *Op) {
3371 Op->printAsOperand(O, SlotTracker);
3372 });
3373 O << ")";
3374 } else {
3376 printFlags(O);
3378 }
3379
3380 if (shouldPack())
3381 O << " (S->V)";
3382}
3383#endif
3384
3386 assert(State.Lane && "Branch on Mask works only on single instance.");
3387
3388 VPValue *BlockInMask = getOperand(0);
3389 Value *ConditionBit = State.get(BlockInMask, *State.Lane);
3390
3391 // Replace the temporary unreachable terminator with a new conditional branch,
3392 // whose two destinations will be set later when they are created.
3393 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
3394 assert(isa<UnreachableInst>(CurrentTerminator) &&
3395 "Expected to replace unreachable terminator with conditional branch.");
3396 auto CondBr =
3397 State.Builder.CreateCondBr(ConditionBit, State.CFG.PrevBB, nullptr);
3398 CondBr->setSuccessor(0, nullptr);
3399 CurrentTerminator->eraseFromParent();
3400}
3401
3403 VPCostContext &Ctx) const {
3404 // The legacy cost model doesn't assign costs to branches for individual
3405 // replicate regions. Match the current behavior in the VPlan cost model for
3406 // now.
3407 return 0;
3408}
3409
3411 assert(State.Lane && "Predicated instruction PHI works per instance.");
3412 Instruction *ScalarPredInst =
3413 cast<Instruction>(State.get(getOperand(0), *State.Lane));
3414 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
3415 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
3416 assert(PredicatingBB && "Predicated block has no single predecessor.");
3418 "operand must be VPReplicateRecipe");
3419
3420 // By current pack/unpack logic we need to generate only a single phi node: if
3421 // a vector value for the predicated instruction exists at this point it means
3422 // the instruction has vector users only, and a phi for the vector value is
3423 // needed. In this case the recipe of the predicated instruction is marked to
3424 // also do that packing, thereby "hoisting" the insert-element sequence.
3425 // Otherwise, a phi node for the scalar value is needed.
3426 if (State.hasVectorValue(getOperand(0))) {
3427 auto *VecI = cast<Instruction>(State.get(getOperand(0)));
3429 "Packed operands must generate an insertelement or insertvalue");
3430
3431 // If VectorI is a struct, it will be a sequence like:
3432 // %1 = insertvalue %unmodified, %x, 0
3433 // %2 = insertvalue %1, %y, 1
3434 // %VectorI = insertvalue %2, %z, 2
3435 // To get the unmodified vector we need to look through the chain.
3436 if (auto *StructTy = dyn_cast<StructType>(VecI->getType()))
3437 for (unsigned I = 0; I < StructTy->getNumContainedTypes() - 1; I++)
3438 VecI = cast<InsertValueInst>(VecI->getOperand(0));
3439
3440 PHINode *VPhi = State.Builder.CreatePHI(VecI->getType(), 2);
3441 VPhi->addIncoming(VecI->getOperand(0), PredicatingBB); // Unmodified vector.
3442 VPhi->addIncoming(VecI, PredicatedBB); // New vector with inserted element.
3443 if (State.hasVectorValue(this))
3444 State.reset(this, VPhi);
3445 else
3446 State.set(this, VPhi);
3447 // NOTE: Currently we need to update the value of the operand, so the next
3448 // predicated iteration inserts its generated value in the correct vector.
3449 State.reset(getOperand(0), VPhi);
3450 } else {
3451 if (vputils::onlyFirstLaneUsed(this) && !State.Lane->isFirstLane())
3452 return;
3453
3454 Type *PredInstType = State.TypeAnalysis.inferScalarType(getOperand(0));
3455 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
3456 Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
3457 PredicatingBB);
3458 Phi->addIncoming(ScalarPredInst, PredicatedBB);
3459 if (State.hasScalarValue(this, *State.Lane))
3460 State.reset(this, Phi, *State.Lane);
3461 else
3462 State.set(this, Phi, *State.Lane);
3463 // NOTE: Currently we need to update the value of the operand, so the next
3464 // predicated iteration inserts its generated value in the correct vector.
3465 State.reset(getOperand(0), Phi, *State.Lane);
3466 }
3467}
3468
3469#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3471 VPSlotTracker &SlotTracker) const {
3472 O << Indent << "PHI-PREDICATED-INSTRUCTION ";
3474 O << " = ";
3476}
3477#endif
3478
3480 VPCostContext &Ctx) const {
3482 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3483 ->getAddressSpace();
3484 unsigned Opcode = isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(this)
3485 ? Instruction::Load
3486 : Instruction::Store;
3487
3488 if (!Consecutive) {
3489 // TODO: Using the original IR may not be accurate.
3490 // Currently, ARM will use the underlying IR to calculate gather/scatter
3491 // instruction cost.
3492 assert(!Reverse &&
3493 "Inconsecutive memory access should not have the order.");
3494
3496 Type *PtrTy = Ptr->getType();
3497
3498 // If the address value is uniform across all lanes, then the address can be
3499 // calculated with scalar type and broadcast.
3501 PtrTy = toVectorTy(PtrTy, VF);
3502
3503 return Ctx.TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
3504 Ctx.CostKind) +
3505 Ctx.TTI.getGatherScatterOpCost(Opcode, Ty, Ptr, IsMasked, Alignment,
3506 Ctx.CostKind, &Ingredient);
3507 }
3508
3510 if (IsMasked) {
3511 unsigned IID = isa<VPWidenLoadRecipe>(this) ? Intrinsic::masked_load
3512 : Intrinsic::masked_store;
3513 Cost +=
3514 Ctx.TTI.getMaskedMemoryOpCost({IID, Ty, Alignment, AS}, Ctx.CostKind);
3515 } else {
3516 TTI::OperandValueInfo OpInfo = Ctx.getOperandInfo(
3518 : getOperand(1));
3519 Cost += Ctx.TTI.getMemoryOpCost(Opcode, Ty, Alignment, AS, Ctx.CostKind,
3520 OpInfo, &Ingredient);
3521 }
3522 if (!Reverse)
3523 return Cost;
3524
3525 return Cost += Ctx.TTI.getShuffleCost(
3527 cast<VectorType>(Ty), {}, Ctx.CostKind, 0);
3528}
3529
3531 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3532 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3533 bool CreateGather = !isConsecutive();
3534
3535 auto &Builder = State.Builder;
3536 Value *Mask = nullptr;
3537 if (auto *VPMask = getMask()) {
3538 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3539 // of a null all-one mask is a null mask.
3540 Mask = State.get(VPMask);
3541 if (isReverse())
3542 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3543 }
3544
3545 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateGather);
3546 Value *NewLI;
3547 if (CreateGather) {
3548 NewLI = Builder.CreateMaskedGather(DataTy, Addr, Alignment, Mask, nullptr,
3549 "wide.masked.gather");
3550 } else if (Mask) {
3551 NewLI =
3552 Builder.CreateMaskedLoad(DataTy, Addr, Alignment, Mask,
3553 PoisonValue::get(DataTy), "wide.masked.load");
3554 } else {
3555 NewLI = Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "wide.load");
3556 }
3558 if (Reverse)
3559 NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
3560 State.set(this, NewLI);
3561}
3562
3563#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3565 VPSlotTracker &SlotTracker) const {
3566 O << Indent << "WIDEN ";
3568 O << " = load ";
3570}
3571#endif
3572
3573/// Use all-true mask for reverse rather than actual mask, as it avoids a
3574/// dependence w/o affecting the result.
3576 Value *EVL, const Twine &Name) {
3577 VectorType *ValTy = cast<VectorType>(Operand->getType());
3578 Value *AllTrueMask =
3579 Builder.CreateVectorSplat(ValTy->getElementCount(), Builder.getTrue());
3580 return Builder.CreateIntrinsic(ValTy, Intrinsic::experimental_vp_reverse,
3581 {Operand, AllTrueMask, EVL}, nullptr, Name);
3582}
3583
3585 Type *ScalarDataTy = getLoadStoreType(&Ingredient);
3586 auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
3587 bool CreateGather = !isConsecutive();
3588
3589 auto &Builder = State.Builder;
3590 CallInst *NewLI;
3591 Value *EVL = State.get(getEVL(), VPLane(0));
3592 Value *Addr = State.get(getAddr(), !CreateGather);
3593 Value *Mask = nullptr;
3594 if (VPValue *VPMask = getMask()) {
3595 Mask = State.get(VPMask);
3596 if (isReverse())
3597 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3598 } else {
3599 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3600 }
3601
3602 if (CreateGather) {
3603 NewLI =
3604 Builder.CreateIntrinsic(DataTy, Intrinsic::vp_gather, {Addr, Mask, EVL},
3605 nullptr, "wide.masked.gather");
3606 } else {
3607 NewLI = Builder.CreateIntrinsic(DataTy, Intrinsic::vp_load,
3608 {Addr, Mask, EVL}, nullptr, "vp.op.load");
3609 }
3610 NewLI->addParamAttr(
3612 applyMetadata(*NewLI);
3613 Instruction *Res = NewLI;
3614 if (isReverse())
3615 Res = createReverseEVL(Builder, Res, EVL, "vp.reverse");
3616 State.set(this, Res);
3617}
3618
3620 VPCostContext &Ctx) const {
3621 if (!Consecutive || IsMasked)
3622 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3623
3624 // We need to use the getMaskedMemoryOpCost() instead of getMemoryOpCost()
3625 // here because the EVL recipes using EVL to replace the tail mask. But in the
3626 // legacy model, it will always calculate the cost of mask.
3627 // TODO: Using getMemoryOpCost() instead of getMaskedMemoryOpCost when we
3628 // don't need to compare to the legacy cost model.
3630 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3631 ->getAddressSpace();
3632 // FIXME: getMaskedMemoryOpCost assumes masked_* intrinsics.
3633 // After migrating to getMemIntrinsicInstrCost, switch this to vp_load.
3634 InstructionCost Cost = Ctx.TTI.getMaskedMemoryOpCost(
3635 {Intrinsic::masked_load, Ty, Alignment, AS}, Ctx.CostKind);
3636 if (!Reverse)
3637 return Cost;
3638
3639 return Cost + Ctx.TTI.getShuffleCost(
3641 cast<VectorType>(Ty), {}, Ctx.CostKind, 0);
3642}
3643
3644#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3646 VPSlotTracker &SlotTracker) const {
3647 O << Indent << "WIDEN ";
3649 O << " = vp.load ";
3651}
3652#endif
3653
3655 VPValue *StoredVPValue = getStoredValue();
3656 bool CreateScatter = !isConsecutive();
3657
3658 auto &Builder = State.Builder;
3659
3660 Value *Mask = nullptr;
3661 if (auto *VPMask = getMask()) {
3662 // Mask reversal is only needed for non-all-one (null) masks, as reverse
3663 // of a null all-one mask is a null mask.
3664 Mask = State.get(VPMask);
3665 if (isReverse())
3666 Mask = Builder.CreateVectorReverse(Mask, "reverse");
3667 }
3668
3669 Value *StoredVal = State.get(StoredVPValue);
3670 if (isReverse()) {
3671 // If we store to reverse consecutive memory locations, then we need
3672 // to reverse the order of elements in the stored value.
3673 StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
3674 // We don't want to update the value in the map as it might be used in
3675 // another expression. So don't call resetVectorValue(StoredVal).
3676 }
3677 Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
3678 Instruction *NewSI = nullptr;
3679 if (CreateScatter)
3680 NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
3681 else if (Mask)
3682 NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
3683 else
3684 NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
3685 applyMetadata(*NewSI);
3686}
3687
3688#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3690 VPSlotTracker &SlotTracker) const {
3691 O << Indent << "WIDEN store ";
3693}
3694#endif
3695
3697 VPValue *StoredValue = getStoredValue();
3698 bool CreateScatter = !isConsecutive();
3699
3700 auto &Builder = State.Builder;
3701
3702 CallInst *NewSI = nullptr;
3703 Value *StoredVal = State.get(StoredValue);
3704 Value *EVL = State.get(getEVL(), VPLane(0));
3705 if (isReverse())
3706 StoredVal = createReverseEVL(Builder, StoredVal, EVL, "vp.reverse");
3707 Value *Mask = nullptr;
3708 if (VPValue *VPMask = getMask()) {
3709 Mask = State.get(VPMask);
3710 if (isReverse())
3711 Mask = createReverseEVL(Builder, Mask, EVL, "vp.reverse.mask");
3712 } else {
3713 Mask = Builder.CreateVectorSplat(State.VF, Builder.getTrue());
3714 }
3715 Value *Addr = State.get(getAddr(), !CreateScatter);
3716 if (CreateScatter) {
3717 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3718 Intrinsic::vp_scatter,
3719 {StoredVal, Addr, Mask, EVL});
3720 } else {
3721 NewSI = Builder.CreateIntrinsic(Type::getVoidTy(EVL->getContext()),
3722 Intrinsic::vp_store,
3723 {StoredVal, Addr, Mask, EVL});
3724 }
3725 NewSI->addParamAttr(
3727 applyMetadata(*NewSI);
3728}
3729
3731 VPCostContext &Ctx) const {
3732 if (!Consecutive || IsMasked)
3733 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3734
3735 // We need to use the getMaskedMemoryOpCost() instead of getMemoryOpCost()
3736 // here because the EVL recipes using EVL to replace the tail mask. But in the
3737 // legacy model, it will always calculate the cost of mask.
3738 // TODO: Using getMemoryOpCost() instead of getMaskedMemoryOpCost when we
3739 // don't need to compare to the legacy cost model.
3741 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
3742 ->getAddressSpace();
3743 // FIXME: getMaskedMemoryOpCost assumes masked_* intrinsics.
3744 // After migrating to getMemIntrinsicInstrCost, switch this to vp_store.
3745 InstructionCost Cost = Ctx.TTI.getMaskedMemoryOpCost(
3746 {Intrinsic::masked_store, Ty, Alignment, AS}, Ctx.CostKind);
3747 if (!Reverse)
3748 return Cost;
3749
3750 return Cost + Ctx.TTI.getShuffleCost(
3752 cast<VectorType>(Ty), {}, Ctx.CostKind, 0);
3753}
3754
3755#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3757 VPSlotTracker &SlotTracker) const {
3758 O << Indent << "WIDEN vp.store ";
3760}
3761#endif
3762
3764 VectorType *DstVTy, const DataLayout &DL) {
3765 // Verify that V is a vector type with same number of elements as DstVTy.
3766 auto VF = DstVTy->getElementCount();
3767 auto *SrcVecTy = cast<VectorType>(V->getType());
3768 assert(VF == SrcVecTy->getElementCount() && "Vector dimensions do not match");
3769 Type *SrcElemTy = SrcVecTy->getElementType();
3770 Type *DstElemTy = DstVTy->getElementType();
3771 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3772 "Vector elements must have same size");
3773
3774 // Do a direct cast if element types are castable.
3775 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3776 return Builder.CreateBitOrPointerCast(V, DstVTy);
3777 }
3778 // V cannot be directly casted to desired vector type.
3779 // May happen when V is a floating point vector but DstVTy is a vector of
3780 // pointers or vice-versa. Handle this using a two-step bitcast using an
3781 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3782 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3783 "Only one type should be a pointer type");
3784 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3785 "Only one type should be a floating point type");
3786 Type *IntTy =
3787 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3788 auto *VecIntTy = VectorType::get(IntTy, VF);
3789 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3790 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3791}
3792
3793/// Return a vector containing interleaved elements from multiple
3794/// smaller input vectors.
3796 const Twine &Name) {
3797 unsigned Factor = Vals.size();
3798 assert(Factor > 1 && "Tried to interleave invalid number of vectors");
3799
3800 VectorType *VecTy = cast<VectorType>(Vals[0]->getType());
3801#ifndef NDEBUG
3802 for (Value *Val : Vals)
3803 assert(Val->getType() == VecTy && "Tried to interleave mismatched types");
3804#endif
3805
3806 // Scalable vectors cannot use arbitrary shufflevectors (only splats), so
3807 // must use intrinsics to interleave.
3808 if (VecTy->isScalableTy()) {
3809 assert(Factor <= 8 && "Unsupported interleave factor for scalable vectors");
3810 return Builder.CreateVectorInterleave(Vals, Name);
3811 }
3812
3813 // Fixed length. Start by concatenating all vectors into a wide vector.
3814 Value *WideVec = concatenateVectors(Builder, Vals);
3815
3816 // Interleave the elements into the wide vector.
3817 const unsigned NumElts = VecTy->getElementCount().getFixedValue();
3818 return Builder.CreateShuffleVector(
3819 WideVec, createInterleaveMask(NumElts, Factor), Name);
3820}
3821
3822// Try to vectorize the interleave group that \p Instr belongs to.
3823//
3824// E.g. Translate following interleaved load group (factor = 3):
3825// for (i = 0; i < N; i+=3) {
3826// R = Pic[i]; // Member of index 0
3827// G = Pic[i+1]; // Member of index 1
3828// B = Pic[i+2]; // Member of index 2
3829// ... // do something to R, G, B
3830// }
3831// To:
3832// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
3833// %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
3834// %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
3835// %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
3836//
3837// Or translate following interleaved store group (factor = 3):
3838// for (i = 0; i < N; i+=3) {
3839// ... do something to R, G, B
3840// Pic[i] = R; // Member of index 0
3841// Pic[i+1] = G; // Member of index 1
3842// Pic[i+2] = B; // Member of index 2
3843// }
3844// To:
3845// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
3846// %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
3847// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
3848// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
3849// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
3851 assert(!State.Lane && "Interleave group being replicated.");
3852 assert((!needsMaskForGaps() || !State.VF.isScalable()) &&
3853 "Masking gaps for scalable vectors is not yet supported.");
3855 Instruction *Instr = Group->getInsertPos();
3856
3857 // Prepare for the vector type of the interleaved load/store.
3858 Type *ScalarTy = getLoadStoreType(Instr);
3859 unsigned InterleaveFactor = Group->getFactor();
3860 auto *VecTy = VectorType::get(ScalarTy, State.VF * InterleaveFactor);
3861
3862 VPValue *BlockInMask = getMask();
3863 VPValue *Addr = getAddr();
3864 Value *ResAddr = State.get(Addr, VPLane(0));
3865
3866 auto CreateGroupMask = [&BlockInMask, &State,
3867 &InterleaveFactor](Value *MaskForGaps) -> Value * {
3868 if (State.VF.isScalable()) {
3869 assert(!MaskForGaps && "Interleaved groups with gaps are not supported.");
3870 assert(InterleaveFactor <= 8 &&
3871 "Unsupported deinterleave factor for scalable vectors");
3872 auto *ResBlockInMask = State.get(BlockInMask);
3873 SmallVector<Value *> Ops(InterleaveFactor, ResBlockInMask);
3874 return interleaveVectors(State.Builder, Ops, "interleaved.mask");
3875 }
3876
3877 if (!BlockInMask)
3878 return MaskForGaps;
3879
3880 Value *ResBlockInMask = State.get(BlockInMask);
3881 Value *ShuffledMask = State.Builder.CreateShuffleVector(
3882 ResBlockInMask,
3883 createReplicatedMask(InterleaveFactor, State.VF.getFixedValue()),
3884 "interleaved.mask");
3885 return MaskForGaps ? State.Builder.CreateBinOp(Instruction::And,
3886 ShuffledMask, MaskForGaps)
3887 : ShuffledMask;
3888 };
3889
3890 const DataLayout &DL = Instr->getDataLayout();
3891 // Vectorize the interleaved load group.
3892 if (isa<LoadInst>(Instr)) {
3893 Value *MaskForGaps = nullptr;
3894 if (needsMaskForGaps()) {
3895 MaskForGaps =
3896 createBitMaskForGaps(State.Builder, State.VF.getFixedValue(), *Group);
3897 assert(MaskForGaps && "Mask for Gaps is required but it is null");
3898 }
3899
3900 Instruction *NewLoad;
3901 if (BlockInMask || MaskForGaps) {
3902 Value *GroupMask = CreateGroupMask(MaskForGaps);
3903 Value *PoisonVec = PoisonValue::get(VecTy);
3904 NewLoad = State.Builder.CreateMaskedLoad(VecTy, ResAddr,
3905 Group->getAlign(), GroupMask,
3906 PoisonVec, "wide.masked.vec");
3907 } else
3908 NewLoad = State.Builder.CreateAlignedLoad(VecTy, ResAddr,
3909 Group->getAlign(), "wide.vec");
3910 applyMetadata(*NewLoad);
3911 // TODO: Also manage existing metadata using VPIRMetadata.
3912 Group->addMetadata(NewLoad);
3913
3915 if (VecTy->isScalableTy()) {
3916 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
3917 // so must use intrinsics to deinterleave.
3918 assert(InterleaveFactor <= 8 &&
3919 "Unsupported deinterleave factor for scalable vectors");
3920 NewLoad = State.Builder.CreateIntrinsic(
3921 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
3922 NewLoad->getType(), NewLoad,
3923 /*FMFSource=*/nullptr, "strided.vec");
3924 }
3925
3926 auto CreateStridedVector = [&InterleaveFactor, &State,
3927 &NewLoad](unsigned Index) -> Value * {
3928 assert(Index < InterleaveFactor && "Illegal group index");
3929 if (State.VF.isScalable())
3930 return State.Builder.CreateExtractValue(NewLoad, Index);
3931
3932 // For fixed length VF, use shuffle to extract the sub-vectors from the
3933 // wide load.
3934 auto StrideMask =
3935 createStrideMask(Index, InterleaveFactor, State.VF.getFixedValue());
3936 return State.Builder.CreateShuffleVector(NewLoad, StrideMask,
3937 "strided.vec");
3938 };
3939
3940 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
3941 Instruction *Member = Group->getMember(I);
3942
3943 // Skip the gaps in the group.
3944 if (!Member)
3945 continue;
3946
3947 Value *StridedVec = CreateStridedVector(I);
3948
3949 // If this member has different type, cast the result type.
3950 if (Member->getType() != ScalarTy) {
3951 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
3952 StridedVec =
3953 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
3954 }
3955
3956 if (Group->isReverse())
3957 StridedVec = State.Builder.CreateVectorReverse(StridedVec, "reverse");
3958
3959 State.set(VPDefs[J], StridedVec);
3960 ++J;
3961 }
3962 return;
3963 }
3964
3965 // The sub vector type for current instruction.
3966 auto *SubVT = VectorType::get(ScalarTy, State.VF);
3967
3968 // Vectorize the interleaved store group.
3969 Value *MaskForGaps =
3970 createBitMaskForGaps(State.Builder, State.VF.getKnownMinValue(), *Group);
3971 assert(((MaskForGaps != nullptr) == needsMaskForGaps()) &&
3972 "Mismatch between NeedsMaskForGaps and MaskForGaps");
3973 ArrayRef<VPValue *> StoredValues = getStoredValues();
3974 // Collect the stored vector from each member.
3975 SmallVector<Value *, 4> StoredVecs;
3976 unsigned StoredIdx = 0;
3977 for (unsigned i = 0; i < InterleaveFactor; i++) {
3978 assert((Group->getMember(i) || MaskForGaps) &&
3979 "Fail to get a member from an interleaved store group");
3980 Instruction *Member = Group->getMember(i);
3981
3982 // Skip the gaps in the group.
3983 if (!Member) {
3984 Value *Undef = PoisonValue::get(SubVT);
3985 StoredVecs.push_back(Undef);
3986 continue;
3987 }
3988
3989 Value *StoredVec = State.get(StoredValues[StoredIdx]);
3990 ++StoredIdx;
3991
3992 if (Group->isReverse())
3993 StoredVec = State.Builder.CreateVectorReverse(StoredVec, "reverse");
3994
3995 // If this member has different type, cast it to a unified type.
3996
3997 if (StoredVec->getType() != SubVT)
3998 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
3999
4000 StoredVecs.push_back(StoredVec);
4001 }
4002
4003 // Interleave all the smaller vectors into one wider vector.
4004 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4005 Instruction *NewStoreInstr;
4006 if (BlockInMask || MaskForGaps) {
4007 Value *GroupMask = CreateGroupMask(MaskForGaps);
4008 NewStoreInstr = State.Builder.CreateMaskedStore(
4009 IVec, ResAddr, Group->getAlign(), GroupMask);
4010 } else
4011 NewStoreInstr =
4012 State.Builder.CreateAlignedStore(IVec, ResAddr, Group->getAlign());
4013
4014 applyMetadata(*NewStoreInstr);
4015 // TODO: Also manage existing metadata using VPIRMetadata.
4016 Group->addMetadata(NewStoreInstr);
4017}
4018
4019#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4021 VPSlotTracker &SlotTracker) const {
4023 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4024 IG->getInsertPos()->printAsOperand(O, false);
4025 O << ", ";
4027 VPValue *Mask = getMask();
4028 if (Mask) {
4029 O << ", ";
4030 Mask->printAsOperand(O, SlotTracker);
4031 }
4032
4033 unsigned OpIdx = 0;
4034 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4035 if (!IG->getMember(i))
4036 continue;
4037 if (getNumStoreOperands() > 0) {
4038 O << "\n" << Indent << " store ";
4040 O << " to index " << i;
4041 } else {
4042 O << "\n" << Indent << " ";
4044 O << " = load from index " << i;
4045 }
4046 ++OpIdx;
4047 }
4048}
4049#endif
4050
4052 assert(!State.Lane && "Interleave group being replicated.");
4053 assert(State.VF.isScalable() &&
4054 "Only support scalable VF for EVL tail-folding.");
4056 "Masking gaps for scalable vectors is not yet supported.");
4058 Instruction *Instr = Group->getInsertPos();
4059
4060 // Prepare for the vector type of the interleaved load/store.
4061 Type *ScalarTy = getLoadStoreType(Instr);
4062 unsigned InterleaveFactor = Group->getFactor();
4063 assert(InterleaveFactor <= 8 &&
4064 "Unsupported deinterleave/interleave factor for scalable vectors");
4065 ElementCount WideVF = State.VF * InterleaveFactor;
4066 auto *VecTy = VectorType::get(ScalarTy, WideVF);
4067
4068 VPValue *Addr = getAddr();
4069 Value *ResAddr = State.get(Addr, VPLane(0));
4070 Value *EVL = State.get(getEVL(), VPLane(0));
4071 Value *InterleaveEVL = State.Builder.CreateMul(
4072 EVL, ConstantInt::get(EVL->getType(), InterleaveFactor), "interleave.evl",
4073 /* NUW= */ true, /* NSW= */ true);
4074 LLVMContext &Ctx = State.Builder.getContext();
4075
4076 Value *GroupMask = nullptr;
4077 if (VPValue *BlockInMask = getMask()) {
4078 SmallVector<Value *> Ops(InterleaveFactor, State.get(BlockInMask));
4079 GroupMask = interleaveVectors(State.Builder, Ops, "interleaved.mask");
4080 } else {
4081 GroupMask =
4082 State.Builder.CreateVectorSplat(WideVF, State.Builder.getTrue());
4083 }
4084
4085 // Vectorize the interleaved load group.
4086 if (isa<LoadInst>(Instr)) {
4087 CallInst *NewLoad = State.Builder.CreateIntrinsic(
4088 VecTy, Intrinsic::vp_load, {ResAddr, GroupMask, InterleaveEVL}, nullptr,
4089 "wide.vp.load");
4090 NewLoad->addParamAttr(0,
4091 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4092
4093 applyMetadata(*NewLoad);
4094 // TODO: Also manage existing metadata using VPIRMetadata.
4095 Group->addMetadata(NewLoad);
4096
4097 // Scalable vectors cannot use arbitrary shufflevectors (only splats),
4098 // so must use intrinsics to deinterleave.
4099 NewLoad = State.Builder.CreateIntrinsic(
4100 Intrinsic::getDeinterleaveIntrinsicID(InterleaveFactor),
4101 NewLoad->getType(), NewLoad,
4102 /*FMFSource=*/nullptr, "strided.vec");
4103
4104 const DataLayout &DL = Instr->getDataLayout();
4105 for (unsigned I = 0, J = 0; I < InterleaveFactor; ++I) {
4106 Instruction *Member = Group->getMember(I);
4107 // Skip the gaps in the group.
4108 if (!Member)
4109 continue;
4110
4111 Value *StridedVec = State.Builder.CreateExtractValue(NewLoad, I);
4112 // If this member has different type, cast the result type.
4113 if (Member->getType() != ScalarTy) {
4114 VectorType *OtherVTy = VectorType::get(Member->getType(), State.VF);
4115 StridedVec =
4116 createBitOrPointerCast(State.Builder, StridedVec, OtherVTy, DL);
4117 }
4118
4119 State.set(getVPValue(J), StridedVec);
4120 ++J;
4121 }
4122 return;
4123 } // End for interleaved load.
4124
4125 // The sub vector type for current instruction.
4126 auto *SubVT = VectorType::get(ScalarTy, State.VF);
4127 // Vectorize the interleaved store group.
4128 ArrayRef<VPValue *> StoredValues = getStoredValues();
4129 // Collect the stored vector from each member.
4130 SmallVector<Value *, 4> StoredVecs;
4131 const DataLayout &DL = Instr->getDataLayout();
4132 for (unsigned I = 0, StoredIdx = 0; I < InterleaveFactor; I++) {
4133 Instruction *Member = Group->getMember(I);
4134 // Skip the gaps in the group.
4135 if (!Member) {
4136 StoredVecs.push_back(PoisonValue::get(SubVT));
4137 continue;
4138 }
4139
4140 Value *StoredVec = State.get(StoredValues[StoredIdx]);
4141 // If this member has different type, cast it to a unified type.
4142 if (StoredVec->getType() != SubVT)
4143 StoredVec = createBitOrPointerCast(State.Builder, StoredVec, SubVT, DL);
4144
4145 StoredVecs.push_back(StoredVec);
4146 ++StoredIdx;
4147 }
4148
4149 // Interleave all the smaller vectors into one wider vector.
4150 Value *IVec = interleaveVectors(State.Builder, StoredVecs, "interleaved.vec");
4151 CallInst *NewStore =
4152 State.Builder.CreateIntrinsic(Type::getVoidTy(Ctx), Intrinsic::vp_store,
4153 {IVec, ResAddr, GroupMask, InterleaveEVL});
4154 NewStore->addParamAttr(1,
4155 Attribute::getWithAlignment(Ctx, Group->getAlign()));
4156
4157 applyMetadata(*NewStore);
4158 // TODO: Also manage existing metadata using VPIRMetadata.
4159 Group->addMetadata(NewStore);
4160}
4161
4162#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4164 VPSlotTracker &SlotTracker) const {
4166 O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
4167 IG->getInsertPos()->printAsOperand(O, false);
4168 O << ", ";
4170 O << ", ";
4172 if (VPValue *Mask = getMask()) {
4173 O << ", ";
4174 Mask->printAsOperand(O, SlotTracker);
4175 }
4176
4177 unsigned OpIdx = 0;
4178 for (unsigned i = 0; i < IG->getFactor(); ++i) {
4179 if (!IG->getMember(i))
4180 continue;
4181 if (getNumStoreOperands() > 0) {
4182 O << "\n" << Indent << " vp.store ";
4184 O << " to index " << i;
4185 } else {
4186 O << "\n" << Indent << " ";
4188 O << " = vp.load from index " << i;
4189 }
4190 ++OpIdx;
4191 }
4192}
4193#endif
4194
4196 VPCostContext &Ctx) const {
4197 Instruction *InsertPos = getInsertPos();
4198 // Find the VPValue index of the interleave group. We need to skip gaps.
4199 unsigned InsertPosIdx = 0;
4200 for (unsigned Idx = 0; IG->getFactor(); ++Idx)
4201 if (auto *Member = IG->getMember(Idx)) {
4202 if (Member == InsertPos)
4203 break;
4204 InsertPosIdx++;
4205 }
4206 Type *ValTy = Ctx.Types.inferScalarType(
4207 getNumDefinedValues() > 0 ? getVPValue(InsertPosIdx)
4208 : getStoredValues()[InsertPosIdx]);
4209 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4210 unsigned AS = cast<PointerType>(Ctx.Types.inferScalarType(getAddr()))
4211 ->getAddressSpace();
4212
4213 unsigned InterleaveFactor = IG->getFactor();
4214 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4215
4216 // Holds the indices of existing members in the interleaved group.
4218 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4219 if (IG->getMember(IF))
4220 Indices.push_back(IF);
4221
4222 // Calculate the cost of the whole interleaved group.
4223 InstructionCost Cost = Ctx.TTI.getInterleavedMemoryOpCost(
4224 InsertPos->getOpcode(), WideVecTy, IG->getFactor(), Indices,
4225 IG->getAlign(), AS, Ctx.CostKind, getMask(), NeedsMaskForGaps);
4226
4227 if (!IG->isReverse())
4228 return Cost;
4229
4230 return Cost + IG->getNumMembers() *
4231 Ctx.TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4232 VectorTy, VectorTy, {}, Ctx.CostKind,
4233 0);
4234}
4235
4236#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4238 VPSlotTracker &SlotTracker) const {
4239 O << Indent << "EMIT ";
4241 O << " = CANONICAL-INDUCTION ";
4243}
4244#endif
4245
4247 return vputils::onlyScalarValuesUsed(this) &&
4248 (!IsScalable || vputils::onlyFirstLaneUsed(this));
4249}
4250
4251#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4253 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4254 assert((getNumOperands() == 3 || getNumOperands() == 5) &&
4255 "unexpected number of operands");
4256 O << Indent << "EMIT ";
4258 O << " = WIDEN-POINTER-INDUCTION ";
4260 O << ", ";
4262 O << ", ";
4264 if (getNumOperands() == 5) {
4265 O << ", ";
4267 O << ", ";
4269 }
4270}
4271
4273 VPSlotTracker &SlotTracker) const {
4274 O << Indent << "EMIT ";
4276 O << " = EXPAND SCEV " << *Expr;
4277}
4278#endif
4279
4281 Value *CanonicalIV = State.get(getOperand(0), /*IsScalar*/ true);
4282 Type *STy = CanonicalIV->getType();
4283 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
4284 ElementCount VF = State.VF;
4285 Value *VStart = VF.isScalar()
4286 ? CanonicalIV
4287 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
4288 Value *VStep = createStepForVF(Builder, STy, VF, getUnrollPart(*this));
4289 if (VF.isVector()) {
4290 VStep = Builder.CreateVectorSplat(VF, VStep);
4291 VStep =
4292 Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
4293 }
4294 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
4295 State.set(this, CanonicalVectorIV);
4296}
4297
4298#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4300 VPSlotTracker &SlotTracker) const {
4301 O << Indent << "EMIT ";
4303 O << " = WIDEN-CANONICAL-INDUCTION ";
4305}
4306#endif
4307
4309 auto &Builder = State.Builder;
4310 // Create a vector from the initial value.
4311 auto *VectorInit = getStartValue()->getLiveInIRValue();
4312
4313 Type *VecTy = State.VF.isScalar()
4314 ? VectorInit->getType()
4315 : VectorType::get(VectorInit->getType(), State.VF);
4316
4317 BasicBlock *VectorPH =
4318 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4319 if (State.VF.isVector()) {
4320 auto *IdxTy = Builder.getInt32Ty();
4321 auto *One = ConstantInt::get(IdxTy, 1);
4322 IRBuilder<>::InsertPointGuard Guard(Builder);
4323 Builder.SetInsertPoint(VectorPH->getTerminator());
4324 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
4325 auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4326 VectorInit = Builder.CreateInsertElement(
4327 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
4328 }
4329
4330 // Create a phi node for the new recurrence.
4331 PHINode *Phi = PHINode::Create(VecTy, 2, "vector.recur");
4332 Phi->insertBefore(State.CFG.PrevBB->getFirstInsertionPt());
4333 Phi->addIncoming(VectorInit, VectorPH);
4334 State.set(this, Phi);
4335}
4336
4339 VPCostContext &Ctx) const {
4340 if (VF.isScalar())
4341 return Ctx.TTI.getCFInstrCost(Instruction::PHI, Ctx.CostKind);
4342
4343 return 0;
4344}
4345
4346#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4348 raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const {
4349 O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
4351 O << " = phi ";
4353}
4354#endif
4355
4357 // Reductions do not have to start at zero. They can start with
4358 // any loop invariant values.
4359 VPValue *StartVPV = getStartValue();
4360
4361 // In order to support recurrences we need to be able to vectorize Phi nodes.
4362 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4363 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4364 // this value when we vectorize all of the instructions that use the PHI.
4365 BasicBlock *VectorPH =
4366 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4367 bool ScalarPHI = State.VF.isScalar() || isInLoop();
4368 Value *StartV = State.get(StartVPV, ScalarPHI);
4369 Type *VecTy = StartV->getType();
4370
4371 BasicBlock *HeaderBB = State.CFG.PrevBB;
4372 assert(State.CurrentParentLoop->getHeader() == HeaderBB &&
4373 "recipe must be in the vector loop header");
4374 auto *Phi = PHINode::Create(VecTy, 2, "vec.phi");
4375 Phi->insertBefore(HeaderBB->getFirstInsertionPt());
4376 State.set(this, Phi, isInLoop());
4377
4378 Phi->addIncoming(StartV, VectorPH);
4379}
4380
4381#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4383 VPSlotTracker &SlotTracker) const {
4384 O << Indent << "WIDEN-REDUCTION-PHI ";
4385
4387 O << " = phi ";
4389 if (getVFScaleFactor() > 1)
4390 O << " (VF scaled by 1/" << getVFScaleFactor() << ")";
4391}
4392#endif
4393
4395 Value *Op0 = State.get(getOperand(0));
4396 Type *VecTy = Op0->getType();
4397 Instruction *VecPhi = State.Builder.CreatePHI(VecTy, 2, Name);
4398 State.set(this, VecPhi);
4399}
4400
4401#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4403 VPSlotTracker &SlotTracker) const {
4404 O << Indent << "WIDEN-PHI ";
4405
4407 O << " = phi ";
4409}
4410#endif
4411
4412// TODO: It would be good to use the existing VPWidenPHIRecipe instead and
4413// remove VPActiveLaneMaskPHIRecipe.
4415 BasicBlock *VectorPH =
4416 State.CFG.VPBB2IRBB.at(getParent()->getCFGPredecessor(0));
4417 Value *StartMask = State.get(getOperand(0));
4418 PHINode *Phi =
4419 State.Builder.CreatePHI(StartMask->getType(), 2, "active.lane.mask");
4420 Phi->addIncoming(StartMask, VectorPH);
4421 State.set(this, Phi);
4422}
4423
4424#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4426 VPSlotTracker &SlotTracker) const {
4427 O << Indent << "ACTIVE-LANE-MASK-PHI ";
4428
4430 O << " = phi ";
4432}
4433#endif
4434
4435#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4437 VPSlotTracker &SlotTracker) const {
4438 O << Indent << "EXPLICIT-VECTOR-LENGTH-BASED-IV-PHI ";
4439
4441 O << " = phi ";
4443}
4444#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 GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file provides a LoopVectorizationPlanner class.
static const SCEV * getAddressAccessSCEV(Value *Ptr, LoopVectorizationLegality *Legal, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
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 the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file contains the declarations of different VPlan-related auxiliary helpers.
static Instruction * createReverseEVL(IRBuilderBase &Builder, Value *Operand, Value *EVL, const Twine &Name)
Use all-true mask for reverse rather than actual mask, as it avoids a dependence w/o affecting the re...
static Value * interleaveVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vals, const Twine &Name)
Return a vector containing interleaved elements from multiple smaller input vectors.
static InstructionCost getCostForIntrinsics(Intrinsic::ID ID, ArrayRef< const VPValue * > Operands, const VPRecipeWithIRFlags &R, ElementCount VF, VPCostContext &Ctx)
Compute the cost for the intrinsic ID with Operands, produced by R.
static Value * createBitOrPointerCast(IRBuilderBase &Builder, Value *V, VectorType *DstVTy, const DataLayout &DL)
SmallVector< Value *, 2 > VectorParts
static bool isUsedByLoadStoreAddress(const VPUser *V)
Returns true if V is used as part of the address of another load or store.
static void scalarizeInstruction(const Instruction *Instr, VPReplicateRecipe *RepRecipe, const VPLane &Lane, VPTransformState &State)
A helper function to scalarize a single Instruction in the innermost loop.
static Constant * getSignedIntOrFpConstant(Type *Ty, int64_t C)
A helper function that returns an integer or floating-point constant with value C.
static BranchInst * createCondBranch(Value *Cond, VPBasicBlock *VPBB, VPTransformState &State)
Create a conditional branch using Cond branching to the successors of VPBB.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
This file contains the declarations of the Vectorization Plan base classes:
static const uint32_t IV[8]
Definition blake3_impl.h:83
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
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...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Conditional or Unconditional Branch instruction.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
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.
Definition InstrTypes.h:982
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
static LLVM_ABI StringRef getPredicateName(Predicate P)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:131
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:163
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
A debug info location.
Definition DebugLoc.h:124
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:22
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:272
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:661
bool doesNotThrow() const
Determine if the function cannot unwind.
Definition Function.h:594
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:214
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:2579
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2633
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2567
LLVM_ABI Value * CreateVectorSplice(Value *V1, Value *V2, int64_t Imm, const Twine &Name="")
Return a vector splice intrinsic if using scalable vectors, otherwise return a shufflevector.
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:2626
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:2645
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:562
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2039
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition IRBuilder.h:345
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:567
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2336
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:527
LLVM_ABI CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1725
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:522
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2466
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1808
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2332
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1134
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1420
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2085
LLVMContext & getContext() const
Definition IRBuilder.h:203
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1403
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:507
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1708
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2344
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2442
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1573
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1437
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
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:318
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
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.
static bool isSignedRecurrenceKind(RecurKind Kind)
Returns true if recurrece kind is a signed redux kind.
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 bool isFindLastIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
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.
The main scalar evolution driver.
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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.
@ None
The cast is not used with a load/store of any kind.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:280
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:300
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
value_op_iterator value_op_end()
Definition User.h:313
void setOperand(unsigned i, Value *Val)
Definition User.h:237
Value * getOperand(unsigned i) const
Definition User.h:232
value_op_iterator value_op_begin()
Definition User.h:310
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:3955
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4008
iterator end()
Definition VPlan.h:3992
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4021
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:2530
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:2525
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:204
VPlan * getPlan()
Definition VPlan.cpp:161
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:349
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:198
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.
This class augments a recipe with a set of VPValues defined by the recipe.
Definition VPlanValue.h:310
LLVM_ABI_FOR_TEST void dump() const
Dump the VPDef to stderr (for debugging).
Definition VPlan.cpp:122
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:431
ArrayRef< VPValue * > definedValues()
Returns an ArrayRef of the values defined by the VPDef.
Definition VPlanValue.h:426
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:404
VPValue * getVPValue(unsigned I)
Returns the VPValue with index I defined by the VPDef.
Definition VPlanValue.h:416
friend class VPValue
Definition VPlanValue.h:311
unsigned getVPDefID() const
Definition VPlanValue.h:436
VPValue * getStepValue() const
Definition VPlan.h:3755
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStartValue() const
Definition VPlan.h:3754
LLVM_ABI_FOR_TEST 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.
void decompose()
Insert the recipes of the expression back into the VPlan, directly before the current recipe.
bool isSingleScalar() const
Returns true if the result of this VPExpressionRecipe is a single-scalar.
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:2083
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:1790
Class to record and manage LLVM IR flags.
Definition VPlan.h:609
FastMathFlagsTy FMFs
Definition VPlan.h:680
bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
WrapFlagsTy WrapFlags
Definition VPlan.h:674
CmpInst::Predicate CmpPredicate
Definition VPlan.h:673
void printFlags(raw_ostream &O) const
GEPNoWrapFlags GEPFlags
Definition VPlan.h:678
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:858
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlags() const
TruncFlagsTy TruncFlags
Definition VPlan.h:675
CmpInst::Predicate getPredicate() const
Definition VPlan.h:835
ExactFlagsTy ExactFlags
Definition VPlan.h:677
bool hasNoSignedWrap() const
Definition VPlan.h:884
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:850
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:853
DisjointFlagsTy DisjointFlags
Definition VPlan.h:676
unsigned AllFlags
Definition VPlan.h:682
bool hasNoUnsignedWrap() const
Definition VPlan.h:873
FCmpFlagsTy FCmpFlags
Definition VPlan.h:681
NonNegFlagsTy NonNegFlags
Definition VPlan.h:679
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:795
Instruction & getInstruction() const
Definition VPlan.h:1444
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void extractLastLaneOfFirstOperand(VPBuilder &Builder)
Update the recipes first operand to the last lane of the operand using Builder.
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:1419
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void intersect(const VPIRMetadata &MD)
Intersect this VPIRMetada object with MD, keeping only metadata nodes that are common to both.
VPIRMetadata()=default
void applyMetadata(Instruction &I) const
Add all metadata to I.
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.
bool doesGeneratePerAllLanes() const
Returns true if this VPInstruction generates scalar values for all lanes.
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1124
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1069
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1114
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1127
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1066
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1118
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1061
@ BuildStructVector
Given operands of (the same) struct type, creates a struct of fixed- width vectors each containing a ...
Definition VPlan.h:1058
@ VScale
Returns the value for vscale.
Definition VPlan.h:1129
@ CanonicalIVIncrementForPart
Definition VPlan.h:1051
bool hasResult() const
Definition VPlan.h:1195
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:1235
unsigned getOpcode() const
Definition VPlan.h:1179
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
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...
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:2641
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this recipe.
Instruction * getInsertPos() const
Definition VPlan.h:2645
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:2643
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:2635
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:2664
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:2629
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:2739
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:2752
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:2702
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()
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1334
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
const VPBasicBlock * getIncomingBlock(unsigned Idx) const
Returns the incoming block with index Idx.
Definition VPlan.h:4099
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:1359
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1326
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
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:387
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:4260
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override final
Print the recipe, delegating to printRecipe().
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:408
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:479
void moveBefore(VPBasicBlock &BB, iplist< VPRecipeBase >::iterator I)
Unlink this recipe and insert into BB before I.
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...
bool isScalarCast() const
Return true if the recipe is a scalar cast.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:398
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:2902
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:2459
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2476
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:2844
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:2855
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:2857
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:2840
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:2846
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:2853
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:2848
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:4143
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4211
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:2924
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
bool isSingleScalar() const
Definition VPlan.h:2965
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.
unsigned getOpcode() const
Definition VPlan.h:2994
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPValue * getStepValue() const
Definition VPlan.h:3821
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.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition VPlan.h:531
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:595
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:533
This class can be used to assign names to VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
Helper to access the operand that contains the unroll part for this recipe after unrolling.
Definition VPlan.h:970
VPValue * getUnrollPartOperand(const VPUser &U) const
Return the VPValue operand containing the unroll part or null if there is no such operand.
unsigned getUnrollPart(const VPUser &U) const
Return the unroll part.
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:207
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1420
operand_range operands()
Definition VPlanValue.h:275
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:251
unsigned getNumOperands() const
Definition VPlanValue.h:245
operand_iterator op_begin()
Definition VPlanValue.h:271
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:246
virtual bool usesFirstLaneOnly(const VPValue *Op) const
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlanValue.h:290
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:48
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1374
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:131
friend class VPExpressionRecipe
Definition VPlanValue.h:53
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1416
bool hasMoreThanOneUniqueUser() const
Returns true if the value has more than one unique user.
Definition VPlanValue.h:140
Value * getLiveInIRValue() const
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition VPlanValue.h:183
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:85
VPValue(const unsigned char SC, Value *UV=nullptr, VPDef *Def=nullptr)
Definition VPlan.cpp:94
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1377
user_iterator user_begin()
Definition VPlanValue.h:130
unsigned getNumUsers() const
Definition VPlanValue.h:113
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the VPlan.
Definition VPlanValue.h:178
user_range users()
Definition VPlanValue.h:134
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:1990
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,...
operand_range args()
Definition VPlan.h:1746
Function * getCalledScalarFunction() const
Definition VPlan.h:1742
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.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
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.
Type * getResultType() const
Returns the result type of the cast.
Definition VPlan.h:1596
void execute(VPTransformState &State) override
Produce widened copies of the cast.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCastRecipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
Type * getSourceElementType() const
Definition VPlan.h:1892
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2146
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition VPlan.h:2253
Type * getScalarType() const
Returns the scalar type of the induction.
Definition VPlan.h:2262
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.
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:1678
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.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Type * getResultType() const
Return the scalar return type of the intrinsic.
Definition VPlan.h:1681
void execute(VPTransformState &State) override
Produce a widened version of the vector intrinsic.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this vector intrinsic.
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3249
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition VPlan.h:3246
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3289
Instruction & Ingredient
Definition VPlan.h:3237
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenMemoryRecipe.
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3243
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3303
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3240
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3296
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition VPlan.h:3293
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 getUF() const
Definition VPlan.h:4498
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1011
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.cpp:1099
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:838
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
iterator erase(iterator where)
Definition ilist.h:204
pointer remove(iterator &IT)
Definition ilist.h:188
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#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
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Intrinsic::ID getDeinterleaveIntrinsicID(unsigned Factor)
Returns the corresponding llvm.vector.deinterleaveN intrinsic for factor N.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
bool match(Val *V, const Pattern &P)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
GEPLikeRecipe_match< Op0_t, Op1_t > m_GetElementPtr(const Op0_t &Op0, const Op1_t &Op1)
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
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 onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
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.
const SCEV * getSCEVExprForVPValue(const VPValue *V, ScalarEvolution &SE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
@ Offset
Definition DWP.cpp:532
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:829
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI Value * createFindLastIVReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind, Value *Start, Value *Sentinel)
Create a reduction of the given vector Src for a reduction of the kind RecurKind::FindLastIV.
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:1725
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
InstructionCost Cost
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:2472
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
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
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2231
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.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:1732
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:406
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:207
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:1739
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
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
@ Other
Any other memory.
Definition ModRef.h:68
bool canVectorizeTy(Type *Ty)
Returns true if Ty is a valid vector element type, void, or an unpacked literal struct where all elem...
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()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ 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
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
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:1897
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.
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
LLVM_ABI Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, Value *InitVal, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of kind RecurKind::AnyOf.
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.
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:1482
PHINode & getIRPhi()
Definition VPlan.h:1490
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.
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:923
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:924
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
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:263
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
ElementCount VF
The chosen Vectorization Factor of the loop being vectorized.
void execute(VPTransformState &State) override
Generate the wide load or gather.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3380
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.
VPValue * getCond() const
Definition VPlan.h:1833
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenSelectRecipe.
void execute(VPTransformState &State) override
Produce a widened version of the select instruction.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:3463
void execute(VPTransformState &State) override
Generate the wide store or scatter.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreEVLRecipe.
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3466
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.
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:3426