LLVM 24.0.0git
VPlan.cpp
Go to the documentation of this file.
1//===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
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 is the LLVM vectorization plan. It represents a candidate for
11/// vectorization, allowing to plan and optimize how to vectorize a given loop
12/// before generating LLVM-IR.
13/// The vectorizer uses vectorization plans to estimate the costs of potential
14/// candidates and if profitable to execute the desired plan, generating vector
15/// LLVM-IR code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "VPlan.h"
21#include "VPlanCFG.h"
22#include "VPlanDominatorTree.h"
23#include "VPlanHelpers.h"
24#include "VPlanPatternMatch.h"
25#include "VPlanTransforms.h"
26#include "VPlanUtils.h"
27#include "VectorizeOptions.h"
29#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Twine.h"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/CFG.h"
38#include "llvm/IR/IRBuilder.h"
39#include "llvm/IR/Instruction.h"
41#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
45#include "llvm/Support/Debug.h"
51#include <cassert>
52#include <string>
53
54using namespace llvm;
55using namespace llvm::VPlanPatternMatch;
56
57/// @{
58/// Metadata attribute names
59const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
61 "llvm.loop.vectorize.followup_vectorized";
63 "llvm.loop.vectorize.followup_epilogue";
64/// @}
65
66#define DEBUG_TYPE "loop-vectorize"
67
68#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
70 const VPBasicBlock *Parent = R.getParent();
71 VPSlotTracker SlotTracker(Parent ? Parent->getPlan() : nullptr);
72 R.print(OS, "", SlotTracker);
73 return OS;
74}
75#endif
76
78 const ElementCount &VF) const {
79 switch (LaneKind) {
81 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
82 return Builder.CreateSub(
83 Builder.CreateElementCount(Builder.getInt32Ty(), VF),
84 Builder.getInt32(VF.getKnownMinValue() - Lane));
86 return Builder.getInt64(Lane);
87 }
88 llvm_unreachable("Unknown lane kind");
89}
90
91#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
93 if (const VPRecipeBase *R = getDefiningRecipe())
94 R->print(OS, "", SlotTracker);
95 else
97}
98
99void VPValue::dump() const {
100 const VPRecipeBase *Instr = getDefiningRecipe();
102 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
104 dbgs() << "\n";
105}
106
107void VPRecipeBase::dump() const {
108 VPSlotTracker SlotTracker(getParent() ? getParent()->getPlan() : nullptr);
109 print(dbgs(), "", SlotTracker);
110 dbgs() << "\n";
111}
112#endif
113
114#if !defined(NDEBUG)
115bool VPRecipeValue::isDefinedBy(const VPDef *D) const {
116 return getDefiningRecipe() == D;
117}
118#endif
119
121 auto *RecipeValue = dyn_cast<VPRecipeValue>(this);
122 if (!RecipeValue)
123 return nullptr;
124 if (auto *MultiDef = dyn_cast<VPMultiDefValue>(RecipeValue))
125 return MultiDef->getDef();
126 return static_cast<VPSingleDefRecipe *>(RecipeValue);
127}
128
130 return const_cast<VPValue *>(this)->getDefiningRecipe();
131}
132
134 return cast<VPIRValue>(this)->getValue();
135}
136
138
140 switch (getVPValueID()) {
141 case VPVIRValueSC:
142 return cast<VPIRValue>(this)->getType();
143 case VPRegionValueSC:
144 return cast<VPRegionValue>(this)->getType();
145 case VPVSymbolicSC:
146 return cast<VPSymbolicValue>(this)->getType();
149 return cast<VPRecipeValue>(this)->getScalarType();
150 }
151 llvm_unreachable("Unhandled VPValue subclass");
152}
153
155 assert(Users.empty() &&
156 "trying to delete a VPRecipeValue with remaining users");
157}
158
161 assert(Def && "VPSingleDefValue requires a defining recipe");
162 Def->addDefinedValue(this);
163}
164
166 getDefiningRecipe()->removeDefinedValue(this);
167}
168
170 : VPRecipeValue(VPVMultiDefValueSC, UV, Ty), Def(Def) {
171 assert(Def && "VPMultiDefValue requires a defining recipe");
172 Def->addDefinedValue(this);
173}
174
176 getDefiningRecipe()->removeDefinedValue(this);
177}
178
179/// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
186
193
194/// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
196 const VPBlockBase *Block = this;
198 Block = Region->getExiting();
200}
201
208
210 if (!Successors.empty() || !Parent)
211 return this;
212 assert(Parent->getExiting() == this &&
213 "Block w/o successors not the exiting block of its parent.");
214 return Parent->getEnclosingBlockWithSuccessors();
215}
216
218 if (!Predecessors.empty() || !Parent)
219 return this;
220 assert(Parent->getEntry() == this &&
221 "Block w/o predecessors not the entry of its parent.");
222 return Parent->getEnclosingBlockWithPredecessors();
223}
224
226 iterator It = begin();
227 while (It != end() && It->isPhi())
228 It++;
229 return It;
230}
231
239
240Value *VPTransformState::get(const VPValue *Def, const VPLane &Lane) {
242 "VPRegionValue must be materialized before VPTransformState::get");
244 return Def->getUnderlyingValue();
245
246 if (hasScalarValue(Def, Lane))
247 return Data.VPV2Scalars[Def][Lane.mapToCacheIndex(VF)];
248
249 if (!Lane.isFirstLane() && vputils::isSingleScalar(Def) &&
251 return Data.VPV2Scalars[Def][0];
252 }
253
255 auto *VecPart = Data.VPV2Vector[Def];
256 if (!VecPart->getType()->isVectorTy()) {
257 assert(Lane.isFirstLane() && "cannot get lane > 0 for scalar");
258 return VecPart;
259 }
260 // TODO: Cache created scalar values.
261 Value *LaneV = Lane.getAsRuntimeExpr(Builder, VF);
262 auto *Extract = Builder.CreateExtractElement(VecPart, LaneV);
263 // set(Def, Extract, Instance);
264 return Extract;
265}
266
267Value *VPTransformState::get(const VPValue *Def, bool NeedsSingleScalar) {
269 "VPRegionValue must be materialized before VPTransformState::get");
270 if (NeedsSingleScalar) {
271 assert((VF.isScalar() || isa<VPIRValue, VPSymbolicValue>(Def) ||
273 (hasScalarValue(Def, VPLane(0)) &&
274 Data.VPV2Scalars[Def].size() == 1)) &&
275 "Trying to access a single scalar per part but has multiple scalars "
276 "per part.");
277 return get(Def, VPLane(0));
278 }
279
280 // If Values have been set for this Def return the one relevant for \p Part.
281 if (hasVectorValue(Def))
282 return Data.VPV2Vector[Def];
283
284 auto GetBroadcastInstrs = [this](Value *V) {
285 if (VF.isScalar())
286 return V;
287 // Broadcast the scalar into all locations in the vector.
288 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
289 return Shuf;
290 };
291
292 Value *ScalarValue = get(Def, VPLane(0));
295 if (auto *LastInst = dyn_cast<Instruction>(get(Def, LastLane)))
296 // Set the insert point after the last scalarized instruction. This
297 // ensures the insertelement sequence will directly follow the scalar
298 // definitions.
299 if (auto InsertPt = LastInst->getInsertionPointAfterDef())
300 Builder.SetInsertPoint(*InsertPt);
301 Value *VectorValue = GetBroadcastInstrs(ScalarValue);
302 set(Def, VectorValue);
303 return VectorValue;
304}
305
307 const DILocation *DIL = DL;
308 // When a FSDiscriminator is enabled, we don't need to add the multiply
309 // factors to the discriminators.
310 if (DIL &&
311 Builder.GetInsertBlock()
312 ->getParent()
313 ->shouldEmitDebugInfoForProfiling() &&
315 // FIXME: For scalable vectors, assume vscale=1.
316 unsigned UF = Plan->getConcreteUF();
317 auto NewDIL =
318 DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
319 if (NewDIL)
320 Builder.SetCurrentDebugLocation(*NewDIL);
321 else
322 LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
323 << DIL->getFilename() << " Line: " << DIL->getLine());
324 } else
325 Builder.SetCurrentDebugLocation(DL);
326}
327
329 for (VPBlockBase *VPB : vp_depth_first_shallow(Plan->getEntry())) {
330 if (!VPBlockUtils::isHeader(VPB, VPDT))
331 continue;
332 auto *Header = cast<VPBasicBlock>(VPB);
333 auto *LatchVPBB = cast<VPBasicBlock>(Header->getPredecessors()[1]);
334 BasicBlock *VectorLatchBB = CFG.VPBB2IRBB[LatchVPBB];
335
336 for (VPSingleDefRecipe &PhiR :
337 map_range(Header->phis(), CastTo<VPSingleDefRecipe>)) {
338 bool NeedsSingleScalar =
341 cast<VPReductionPHIRecipe>(PhiR).isInLoop());
342
343 Value *Phi = get(&PhiR, NeedsSingleScalar);
344 Value *Val = get(PhiR.getOperand(1), NeedsSingleScalar);
345 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
346 }
347 }
348}
349
350BasicBlock *VPBasicBlock::createEmptyBasicBlock(VPTransformState &State) {
351 auto &CFG = State.CFG;
352 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
353 // Pred stands for Predessor. Prev stands for Previous - last visited/created.
354 BasicBlock *PrevBB = CFG.PrevBB;
355 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
356 PrevBB->getParent(), CFG.ExitBB);
357 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
358
359 return NewBB;
360}
361
363 auto &CFG = State.CFG;
364 BasicBlock *NewBB = CFG.VPBB2IRBB[this];
365
366 // Register NewBB in its loop. In innermost loops its the same for all
367 // BB's.
368 Loop *ParentLoop = State.CurrentParentLoop;
369 // If this block has a sole successor that is an exit block or is an exit
370 // block itself then it needs adding to the same parent loop as the exit
371 // block.
372 VPBlockBase *SuccOrExitVPB = getSingleSuccessor();
373 SuccOrExitVPB = SuccOrExitVPB ? SuccOrExitVPB : this;
374 if (State.Plan->isExitBlock(SuccOrExitVPB)) {
375 ParentLoop = State.LI->getLoopFor(
376 cast<VPIRBasicBlock>(SuccOrExitVPB)->getIRBasicBlock());
377 }
378
379 if (ParentLoop && !State.LI->getLoopFor(NewBB))
380 ParentLoop->addBasicBlockToLoop(NewBB, *State.LI);
381
383 if (VPBlockUtils::isHeader(this, State.VPDT)) {
384 // There's no block for the latch yet, connect to the preheader only.
385 Preds = {getPredecessors()[0]};
386 } else {
387 Preds = to_vector(getPredecessors());
388 }
389
390 // Hook up the new basic block to its predecessors.
391 for (VPBlockBase *PredVPBlock : Preds) {
392 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
393 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
394 assert(CFG.VPBB2IRBB.contains(PredVPBB) &&
395 "Predecessor basic-block not found building successor.");
396 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
397 auto *PredBBTerminator = PredBB->getTerminator();
398 LLVM_DEBUG(dbgs() << "LV: draw edge from " << PredBB->getName() << '\n');
399
400 if (isa<UnreachableInst>(PredBBTerminator)) {
401 assert(PredVPSuccessors.size() == 1 &&
402 "Predecessor ending w/o branch must have single successor.");
403 DebugLoc DL = PredBBTerminator->getDebugLoc();
404 PredBBTerminator->eraseFromParent();
405 auto *Br = UncondBrInst::Create(NewBB, PredBB);
406 Br->setDebugLoc(DL);
407 } else if (auto *UBI = dyn_cast<UncondBrInst>(PredBBTerminator)) {
408 UBI->setSuccessor(NewBB);
409 } else {
410 // Set each forward successor here when it is created, excluding
411 // backedges. A backward successor is set when the branch is created.
412 // Generated successors are redirected, as for the entry block and for
413 // blocks bypassing a vector loop during epilogue vectorization. Edges
414 // already present in the generated IR need no update; this happens during
415 // epilogue vectorization, where the plan models blocks generated for the
416 // main vector loop.
417 // TODO: Remove the exception by modeling those terminators using
418 // BranchOnCond.
419 auto *TermBr = cast<CondBrInst>(PredBBTerminator);
420 if (TermBr->getSuccessor(0) != NewBB &&
421 TermBr->getSuccessor(1) != NewBB) {
422 unsigned Idx = PredVPSuccessors.front() == this ? 0 : 1;
423 BasicBlock *ReplacedSucc = TermBr->getSuccessor(Idx);
424 assert(
425 (!ReplacedSucc || isa<VPIRBasicBlock>(PredVPBB)) &&
426 "only VPIRBasicBlock predecessors may have an existing successor "
427 "redirected");
428 if (ReplacedSucc)
429 ReplacedSucc->removePredecessor(PredBB, /*KeepOneInputPHIs=*/true);
430 TermBr->setSuccessor(Idx, NewBB);
431 if (ReplacedSucc)
432 CFG.DTU.applyUpdates({{DominatorTree::Delete, PredBB, ReplacedSucc}});
433 }
434 }
435 CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}});
436 }
437}
438
441 "VPIRBasicBlock can have at most two successors at the moment!");
442 // Move completely disconnected blocks to their final position.
443 if (IRBB->hasNPredecessors(0) && succ_begin(IRBB) == succ_end(IRBB))
444 IRBB->moveAfter(State->CFG.PrevBB);
445 State->Builder.SetInsertPoint(IRBB->getTerminator());
446 State->CFG.PrevBB = IRBB;
447 State->CFG.VPBB2IRBB[this] = IRBB;
448 executeRecipes(State, IRBB);
449 // Create a branch instruction to terminate IRBB if one was not created yet
450 // and is needed.
451 if (getSingleSuccessor() && isa<UnreachableInst>(IRBB->getTerminator())) {
452 auto *Br = State->Builder.CreateBr(IRBB);
453 Br->setOperand(0, nullptr);
454 IRBB->getTerminator()->eraseFromParent();
455 } else {
456 assert((getNumSuccessors() == 0 ||
457 isa<UncondBrInst, CondBrInst>(IRBB->getTerminator())) &&
458 "other blocks must be terminated by a branch");
459 }
460
461 connectToPredecessors(*State);
462}
463
464VPIRBasicBlock *VPIRBasicBlock::clone() {
465 auto *NewBlock = getPlan()->createEmptyVPIRBasicBlock(IRBB);
466 for (VPRecipeBase &R : Recipes)
467 NewBlock->appendRecipe(R.clone());
468 return NewBlock;
469}
470
472 if (VPBlockUtils::isHeader(this, State->VPDT)) {
473 // Create and register the new vector loop.
474 Loop *PrevParentLoop = State->CurrentParentLoop;
475 State->CurrentParentLoop = State->LI->AllocateLoop();
476
477 // Insert the new loop into the loop nest and register the new basic blocks
478 // before calling any utilities such as SCEV that require valid LoopInfo.
479 if (PrevParentLoop)
480 PrevParentLoop->addChildLoop(State->CurrentParentLoop);
481 else
482 State->LI->addTopLevelLoop(State->CurrentParentLoop);
483 }
484
485 // 1. Create an IR basic block.
486 BasicBlock *NewBB = createEmptyBasicBlock(*State);
487
488 State->Builder.SetInsertPoint(NewBB);
489 // Temporarily terminate with unreachable until CFG is rewired.
490 UnreachableInst *Terminator = State->Builder.CreateUnreachable();
491 State->Builder.SetInsertPoint(Terminator);
492
493 State->CFG.PrevBB = NewBB;
494 State->CFG.VPBB2IRBB[this] = NewBB;
495 connectToPredecessors(*State);
496
497 // 2. Fill the IR basic block with IR instructions.
498 executeRecipes(State, NewBB);
499
500 // If this block is a latch, update CurrentParentLoop.
501 if (VPBlockUtils::isLatch(this, State->VPDT))
502 State->CurrentParentLoop = State->CurrentParentLoop->getParentLoop();
503}
504
505VPBasicBlock *VPBasicBlock::clone() {
506 auto *NewBlock = getPlan()->createVPBasicBlock(getName());
507 for (VPRecipeBase &R : *this)
508 NewBlock->appendRecipe(R.clone());
509 return NewBlock;
510}
511
513 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB: " << getName()
514 << " in BB: " << BB->getName() << '\n');
515
516 for (VPRecipeBase &Recipe : Recipes) {
517 State->setDebugLocFrom(Recipe.getDebugLoc());
518 Recipe.execute(*State);
519 }
520
521 LLVM_DEBUG(dbgs() << "LV: filled BB: " << *BB);
522}
523
524VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
525 assert((SplitAt == end() || SplitAt->getParent() == this) &&
526 "can only split at a position in the same block");
527
528 // Create new empty block after the block to split.
529 auto *SplitBlock = getPlan()->createVPBasicBlock(getName() + ".split");
531
532 // If this is the exiting block, make the split the new exiting block.
533 auto *ParentRegion = getParent();
534 if (ParentRegion && ParentRegion->getExiting() == this)
535 ParentRegion->setExiting(SplitBlock);
536
537 // Finally, move the recipes starting at SplitAt to new block.
538 for (VPRecipeBase &ToMove :
539 make_early_inc_range(make_range(SplitAt, this->end())))
540 ToMove.moveBefore(SplitBlock->end());
541
542 return SplitBlock;
543}
544
545/// Return the enclosing loop region for region \p P. The templated version is
546/// used to support both const and non-const block arguments.
547template <typename T> static T *getEnclosingLoopRegionForRegion(T *P) {
548 if (P && P->isReplicator()) {
549 P = P->getParent();
550 // Multiple loop regions can be nested, but replicate regions can only be
551 // nested inside a loop region or must be outside any other region.
552 assert((!P || !P->isReplicator()) && "unexpected nested replicate regions");
553 }
554 return P;
555}
556
560
564
565static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
566 if (VPBB->empty()) {
567 assert(
568 VPBB->getNumSuccessors() < 2 &&
569 "block with multiple successors doesn't have a recipe as terminator");
570 return false;
571 }
572
573 const VPRecipeBase *R = &VPBB->back();
574 [[maybe_unused]] bool IsSwitch =
576 cast<VPInstruction>(R)->getOpcode() == Instruction::Switch;
577 [[maybe_unused]] bool IsBranchOnTwoConds = match(R, m_BranchOnTwoConds());
578 [[maybe_unused]] bool IsCondBranch =
581 if (VPBB->getNumSuccessors() == 2 ||
582 (VPBB->isExiting() && !VPBB->getParent()->isReplicator())) {
583 assert((IsCondBranch || IsSwitch || IsBranchOnTwoConds) &&
584 "block with multiple successors not terminated by "
585 "conditional branch nor switch recipe");
586
587 return true;
588 }
589
590 if (VPBB->getNumSuccessors() > 2) {
591 assert((IsSwitch || IsBranchOnTwoConds) &&
592 "block with more than 2 successors not terminated by a switch or "
593 "branch-on-two-conds recipe");
594 return true;
595 }
596
597 assert(
598 !IsCondBranch && !IsBranchOnTwoConds &&
599 "block with 0 or 1 successors terminated by conditional branch recipe");
600 return false;
601}
602
604 if (hasConditionalTerminator(this))
605 return &back();
606 return nullptr;
607}
608
610 if (hasConditionalTerminator(this))
611 return &back();
612 return nullptr;
613}
614
616 return getParent() && getParent()->getExitingBasicBlock() == this;
617}
618
619#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
624
625void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
626 if (!hasSuccessors()) {
627 O << Indent << "No successors\n";
628 } else {
629 O << Indent << "Successor(s): ";
630 ListSeparator LS;
631 for (auto *Succ : getSuccessors())
632 O << LS << Succ->getName();
633 O << '\n';
634 }
635}
636
637void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
638 VPSlotTracker &SlotTracker) const {
639 O << Indent << getName() << ":\n";
640
641 auto RecipeIndent = Indent + " ";
642 for (const VPRecipeBase &Recipe : *this) {
643 Recipe.print(O, RecipeIndent, SlotTracker);
644 O << '\n';
645 }
646
647 printSuccessors(O, Indent);
648}
649#endif
650
651std::pair<VPBlockBase *, VPBlockBase *>
654 VPBlockBase *Exiting = nullptr;
655 bool InRegion = Entry->getParent();
656 // First, clone blocks reachable from Entry.
657 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
658 VPBlockBase *NewBB = BB->clone();
659 Old2NewVPBlocks[BB] = NewBB;
660 if (InRegion && BB->getNumSuccessors() == 0) {
661 assert(!Exiting && "Multiple exiting blocks?");
662 Exiting = BB;
663 }
664 }
665 assert((!InRegion || Exiting) && "regions must have a single exiting block");
666
667 // Second, update the predecessors & successors of the cloned blocks.
668 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
669 VPBlockBase *NewBB = Old2NewVPBlocks[BB];
671 for (VPBlockBase *Pred : BB->getPredecessors()) {
672 NewPreds.push_back(Old2NewVPBlocks[Pred]);
673 }
674 NewBB->setPredecessors(NewPreds);
676 for (VPBlockBase *Succ : BB->successors()) {
677 NewSuccs.push_back(Old2NewVPBlocks[Succ]);
678 }
679 NewBB->setSuccessors(NewSuccs);
680 }
681
682#if !defined(NDEBUG)
683 // Verify that the order of predecessors and successors matches in the cloned
684 // version.
685 for (const auto &[OldBB, NewBB] :
687 vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) {
688 for (const auto &[OldPred, NewPred] :
689 zip(OldBB->getPredecessors(), NewBB->getPredecessors()))
690 assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors");
691
692 for (const auto &[OldSucc, NewSucc] :
693 zip(OldBB->successors(), NewBB->successors()))
694 assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors");
695 }
696#endif
697
698 return std::make_pair(Old2NewVPBlocks[Entry],
699 Exiting ? Old2NewVPBlocks[Exiting] : nullptr);
700}
701
703 const auto *EntryBB = cast<VPBasicBlock>(getEntry());
704 assert(isReplicator() && EntryBB && EntryBB->size() == 1 &&
705 "not a valid replicating region");
706 return cast<VPBranchOnMaskRecipe>(&EntryBB->front());
707}
708
709VPRegionBlock *VPRegionBlock::clone() {
710 const auto &[NewEntry, NewExiting] = VPBlockUtils::cloneFrom(getEntry());
711 VPlan &Plan = *getPlan();
712 VPRegionValue *CanIV = getCanonicalIV();
713 VPRegionBlock *NewRegion =
714 CanIV ? Plan.createLoopRegion(CanIV->getType(), CanIV->getDebugLoc(),
715 getName(), NewEntry, NewExiting)
716 : Plan.createReplicateRegion(NewEntry, NewExiting, getName());
717
718 if (getHeaderMask())
719 NewRegion->createHeaderMask();
720
721 if (CanIV && !hasCanonicalIVNUW())
722 NewRegion->CanIVInfo->clearNUW();
723
724 for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))
725 Block->setParent(NewRegion);
726 return NewRegion;
727}
728
730 llvm_unreachable("regions must get dissolved before ::execute");
731}
732
735 for (VPRecipeBase &R : Recipes)
736 Cost += R.cost(VF, Ctx);
737
738 // Charge cost for unconditional branches outside replicate regions that
739 // cannot be folded.
740 const VPBlockBase *Succ = getSingleSuccessor();
741 const VPRegionBlock *Region = getParent();
742 if (Succ && !Succ->getSinglePredecessor() &&
743 (!Region || !Region->isReplicator())) {
744 Cost += Ctx.Opts.force_target_instruction_cost
745 ? InstructionCost(*Ctx.Opts.force_target_instruction_cost)
746 : Ctx.TTI.getCFInstrCost(Instruction::UncondBr, Ctx.CostKind);
747 }
748 return Cost;
749}
750
751const VPBasicBlock *VPBasicBlock::getCFGPredecessor(unsigned Idx) const {
752 const VPBlockBase *Pred = nullptr;
753 if (hasPredecessors()) {
754 Pred = getPredecessors()[Idx];
755 } else {
756 auto *Region = getParent();
757 assert(Region && !Region->isReplicator() && Region->getEntry() == this &&
758 "must be in the entry block of a non-replicate region");
759 assert(Idx < 2 && Region->getNumPredecessors() == 1 &&
760 "loop region has a single predecessor (preheader), its entry block "
761 "has 2 incoming blocks");
762
763 // Idx == 0 selects the predecessor of the region, Idx == 1 selects the
764 // region itself whose exiting block feeds the phi across the backedge.
765 Pred = Idx == 0 ? Region->getSinglePredecessor() : Region;
766 }
767 return Pred->getExitingBasicBlock();
768}
769
771 if (!isReplicator()) {
774 Cost += Block->cost(VF, Ctx);
775 // Add the costs of the loop's backedge and canonical IV increment
776 auto AddCost = [&](InstructionCost C, const char *Name) {
777 if (Ctx.Opts.force_target_instruction_cost)
778 C = InstructionCost(*Ctx.Opts.force_target_instruction_cost);
779 LLVM_DEBUG(dbgs() << "Cost of " << C << " for VF " << VF << ": " << Name
780 << "\n");
781 Cost += C;
782 };
783 AddCost(Ctx.TTI.getCFInstrCost(Instruction::UncondBr, Ctx.CostKind),
784 "vector loop backedge");
786 AddCost(Ctx.TTI.getArithmeticInstrCost(
787 Instruction::Add, getCanonicalIVType(), Ctx.CostKind),
788 "canonical IV increment");
789 return Cost;
790 }
791
792 // Compute the cost of a replicate region. Replicating isn't supported for
793 // scalable vectors, return an invalid cost for them.
794 // TODO: Discard scalable VPlans with replicate recipes earlier after
795 // construction.
796 if (VF.isScalable())
798
799 // Compute and return the cost of the branch on the mask in the entry, the
800 // conditionally executed recipes and the unconditional branch from the
801 // conditionally executed block to the exiting block for each lane.
802 assert(VF.isVector() && "Can only compute vector cost at the moment.");
804
805 // If the vector loop executes at most once and the region is predicated on
806 // the header mask, the branches fold away.
808 match(getEntryBranchOnMask()->getOperand(0),
810 return Then->cost(VF, Ctx);
811
812 InstructionCost Cost = getEntry()->cost(VF, Ctx);
813 Cost += Then->cost(VF, Ctx);
814 InstructionCost ThenBranchCost;
815 if (Ctx.Opts.force_target_instruction_cost) {
816 ThenBranchCost = InstructionCost(*Ctx.Opts.force_target_instruction_cost);
817 } else {
818 ThenBranchCost =
819 VF.getFixedValue() *
820 Ctx.TTI.getCFInstrCost(Instruction::UncondBr, Ctx.CostKind);
821 ThenBranchCost /=
822 Ctx.getCostDivisor(getEntryBranchOnMask()->getExecutionFrequency());
823 }
824 LLVM_DEBUG(dbgs() << "Cost of " << ThenBranchCost << " for VF " << VF
825 << ": unconditional branches from " << Then->getName()
826 << "\n");
827 return Cost + ThenBranchCost;
828}
829
830#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
832 VPSlotTracker &SlotTracker) const {
833 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
834 auto NewIndent = Indent + " ";
835 if (auto *CanIV = getCanonicalIV()) {
836 O << '\n';
837 CanIV->print(O, SlotTracker);
838 O << " = CANONICAL-IV\n";
839 }
840 if (auto *HdrMask = getUsedHeaderMask()) {
841 HdrMask->print(O, SlotTracker);
842 O << " = HEADER-MASK\n";
843 }
844 for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
845 O << '\n';
846 BlockBase->print(O, NewIndent, SlotTracker);
847 }
848 O << Indent << "}\n";
849
850 printSuccessors(O, Indent);
851}
852#endif
853
855 auto *Header = cast<VPBasicBlock>(getEntry());
856 auto *ExitingLatch = cast<VPBasicBlock>(getExiting());
857 auto *CanIV = getCanonicalIV();
858 if (!CanIV->user_empty()) {
859 VPlan &Plan = *getPlan();
860 auto *Zero = Plan.getZero(CanIV->getType());
861 DebugLoc DL = CanIV->getDebugLoc();
863 VPBuilder HeaderBuilder(Header->begin());
864 auto *ScalarR =
865 HeaderBuilder.createScalarPhi({Zero, CanIVInc}, DL, "index");
866 CanIV->replaceAllUsesWith(ScalarR);
867 }
868
869 VPBlockBase *Preheader = getSinglePredecessor();
870 VPBlockUtils::disconnectBlocks(Preheader, this);
871
872 for (VPBlockBase *VPB : vp_depth_first_shallow(Entry))
873 VPB->setParent(getParent());
874
875 VPBlockUtils::connectBlocks(Preheader, Header);
876 VPBlockUtils::transferSuccessors(this, ExitingLatch);
877 VPBlockUtils::connectBlocks(ExitingLatch, Header);
878}
879
881 // TODO: Represent the increment as VPRegionValue as well.
882 VPRegionValue *CanIV = getCanonicalIV();
883 assert(CanIV && "Expected a canonical IV");
884
885 if (auto *Inc = vputils::findCanonicalIVIncrement(*getPlan()))
886 return Inc;
887
888 assert(!getPlan()->getVFxUF().isMaterialized() &&
889 "VFxUF can be used only before it is materialized.");
890 auto *ExitingLatch = cast<VPBasicBlock>(getExiting());
891 return VPBuilder(ExitingLatch->getTerminator())
892 .createOverflowingOp(Instruction::Add, {CanIV, &getPlan()->getVFxUF()},
893 {hasCanonicalIVNUW(), /* HasNSW */ false},
894 CanIV->getDebugLoc(), "index.next");
895}
896
897VPlan::VPlan(Loop *L, Type *IdxTy)
898 : VectorTripCount(IdxTy), VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
899 setEntry(createVPIRBasicBlock(L->getLoopPreheader()));
900 ScalarHeader = createVPIRBasicBlock(L->getHeader());
901
902 SmallVector<BasicBlock *> IRExitBlocks;
903 L->getUniqueExitBlocks(IRExitBlocks);
904 for (BasicBlock *EB : IRExitBlocks)
905 ExitBlocks.push_back(createVPIRBasicBlock(EB));
906}
907
909 VPSymbolicValue DummyValue(nullptr);
910
911 // Redirect all recipe operands to DummyValue before deleting blocks.
912 for (VPBasicBlock *VPBB :
914 for (VPRecipeBase &R : *VPBB)
915 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
916 R.setOperand(I, &DummyValue);
917
918 for (auto [Idx, VPB] : enumerate(CreatedBlocks)) {
919 assert(VPB->getNumber() == Idx && "block with mismatched number");
920 delete VPB;
921 }
922 for (VPValue *VPV : getLiveIns())
923 delete VPV;
924}
925
927 return is_contained(ExitBlocks, VPBB);
928}
929
930/// To make RUN_VPLAN_PASS print final VPlan.
931static void printFinalVPlan(VPlan &) {}
932
933/// Generate the code inside the preheader and body of the vectorized loop.
934/// Assumes a single pre-header basic-block was created for this. Introduce
935/// additional basic-blocks as needed, and fill them all.
938 "all region blocks must be dissolved before ::execute");
939
940 // Initialize CFG state.
941 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
942
943 // Update VPDominatorTree since VPBasicBlock may be removed after State was
944 // constructed.
945 State->VPDT.recalculate(*this);
946
947 // Disconnect VectorPreHeader from ExitBB in both the CFG and DT.
948 BasicBlock *VectorPreHeader = State->CFG.PrevBB;
949 cast<UncondBrInst>(VectorPreHeader->getTerminator())->setSuccessor(nullptr);
950 State->CFG.DTU.applyUpdates(
951 {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}});
952
953 LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << State->VF
954 << ", UF=" << getConcreteUF() << '\n');
955 setName("Final VPlan");
956 // TODO: RUN_VPLAN_PASS/VPlanTransforms::runPass should automatically dump
957 // VPlans after some specific stages when "-debug" is specified, but that
958 // hasn't been implemented yet. For now, just do both:
959 LLVM_DEBUG(dump());
961
962 BasicBlock *ScalarPh = State->CFG.ExitBB;
963 VPBasicBlock *ScalarPhVPBB = getScalarPreheader();
964 if (ScalarPhVPBB) {
965 // Disconnect scalar preheader and scalar header, as the dominator tree edge
966 // will be updated as part of VPlan execution. This allows keeping the DTU
967 // logic generic during VPlan execution.
968 State->CFG.DTU.applyUpdates(
969 {{DominatorTree::Delete, ScalarPh, ScalarPh->getSingleSuccessor()}});
970 }
972 Entry);
973 // Generate code for the VPlan, in parts of the vector skeleton, loop body and
974 // successor blocks including the middle, exit and scalar preheader blocks.
975 for (VPBlockBase *Block : RPOT)
976 Block->execute(State);
977
978 // Fix up LoopInfo for extra dispatch blocks when vectorizing loops with early
979 // exits. For dispatch blocks, we need to find the smallest common loop of all
980 // successors that are in a loop. Note: we only need to update loop info for
981 // blocks after the middle block, but there is no easy way to get those at
982 // this point.
983 for (VPBlockBase *VPB : reverse(RPOT)) {
984 auto *VPBB = dyn_cast<VPBasicBlock>(VPB);
985 if (!VPBB || isa<VPIRBasicBlock>(VPBB))
986 continue;
987 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
988 Loop *L = State->LI->getLoopFor(BB);
989 if (!L || any_of(successors(BB),
990 [L](BasicBlock *Succ) { return L->contains(Succ); }))
991 continue;
992 // Find the innermost loop containing all successors that are in a loop.
993 // Successors not in any loop don't constrain the target loop.
994 Loop *Target = nullptr;
995 for (BasicBlock *Succ : successors(BB)) {
996 Loop *SuccLoop = State->LI->getLoopFor(Succ);
997 if (!SuccLoop)
998 continue;
999 if (!Target)
1000 Target = SuccLoop;
1001 else
1002 Target = State->LI->getSmallestCommonLoop(Target, SuccLoop);
1003 }
1004 State->LI->removeBlock(BB);
1005 if (Target)
1006 Target->addBasicBlockToLoop(BB, *State->LI);
1007 }
1008
1009 // If the original loop is unreachable, delete it and all its blocks.
1010 if (!ScalarPhVPBB) {
1011 // DeleteDeadBlocks will remove single-entry phis. Remove them from the exit
1012 // VPIRBBs in VPlan as well, otherwise we would retain references to deleted
1013 // IR instructions.
1014 for (VPIRBasicBlock *EB : getExitBlocks()) {
1015 for (VPRecipeBase &R : make_early_inc_range(EB->phis())) {
1016 if (R.getNumOperands() == 1)
1017 R.eraseFromParent();
1018 }
1019 }
1020
1021 Loop *OrigLoop =
1022 State->LI->getLoopFor(getScalarHeader()->getIRBasicBlock());
1023 SmallVector<BasicBlock *> Blocks(OrigLoop->block_begin(),
1024 OrigLoop->block_end());
1025 Blocks.push_back(ScalarPh);
1026 while (!OrigLoop->isInnermost())
1027 State->LI->erase(*OrigLoop->begin());
1028 State->LI->erase(OrigLoop);
1029 for (auto *BB : Blocks)
1030 State->LI->removeBlock(BB);
1031 DeleteDeadBlocks(Blocks, &State->CFG.DTU);
1032 }
1033
1034 State->CFG.DTU.flush();
1035
1036 // Fix the latch (backedge) value of all header phis in all loop headers.
1037 State->fixupHeaderPhis();
1038}
1039
1041 // For now only return the cost of the vector loop region, ignoring any other
1042 // blocks, like the preheader or middle blocks, expect for checking them for
1043 // recipes with invalid costs.
1045
1046 // If the cost of the loop region is invalid or any recipe in the skeleton
1047 // outside loop regions are invalid return an invalid cost.
1050 [&VF, &Ctx](VPBasicBlock *VPBB) {
1051 return !VPBB->cost(VF, Ctx).isValid();
1052 }))
1054
1055 return Cost;
1056}
1057
1059 // Find the vector loop region by following the last successor of each block,
1060 // starting from the plan's entry; the vector code path is always the last
1061 // successor. When vectorizing the epilogue, the path leads through the blocks
1062 // generated for the main vector loop. Each block on the path is entered from
1063 // its first predecessor. Stop at a block entered from another predecessor,
1064 // e.g. a loop header entered via its back-edge in a plain CFG, before regions
1065 // are created or after they have been dissolved.
1066 for (VPBlockBase *B = Entry; B;) {
1067 if (auto *R = dyn_cast<VPRegionBlock>(B))
1068 return R->isReplicator() || R->getNumPredecessors() != 1 ? nullptr : R;
1069 if (!B->hasSuccessors())
1070 return nullptr;
1071 VPBlockBase *Succ = B->getSuccessors().back();
1072 if (Succ->getPredecessors().front() != B)
1073 return nullptr;
1074 B = Succ;
1075 }
1076 return nullptr;
1077}
1078
1080 return const_cast<VPlan *>(this)->getVectorLoopRegion();
1081}
1082
1084 const VPRegionBlock *LoopRegion = getVectorLoopRegion();
1085 assert(LoopRegion && "expected a vector loop region");
1087 vp_depth_first_shallow(LoopRegion->getEntry())),
1088 [](const VPRegionBlock *R) { return !R->isReplicator(); });
1089}
1090
1091#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1094
1095 if (!VF.user_empty()) {
1096 O << "\nLive-in ";
1097 VF.printAsOperand(O, SlotTracker);
1098 O << " = VF";
1099 }
1100
1101 if (!UF.user_empty()) {
1102 O << "\nLive-in ";
1103 UF.printAsOperand(O, SlotTracker);
1104 O << " = UF";
1105 }
1106
1107 if (!VFxUF.user_empty()) {
1108 O << "\nLive-in ";
1109 VFxUF.printAsOperand(O, SlotTracker);
1110 O << " = VF * UF";
1111 }
1112
1113 if (!VectorTripCount.user_empty()) {
1114 O << "\nLive-in ";
1115 VectorTripCount.printAsOperand(O, SlotTracker);
1116 O << " = vector-trip-count";
1117 }
1118
1119 O << "\n";
1120 if (TripCount && !TripCount->user_empty()) {
1121 if (isa<VPIRValue>(TripCount))
1122 O << "Live-in ";
1123 TripCount->printAsOperand(O, SlotTracker);
1124 O << " = original trip-count";
1125 O << "\n";
1126 }
1127}
1128
1132
1133 O << "VPlan '" << getName() << "' {";
1134
1135 printLiveIns(O);
1136
1138 RPOT(getEntry());
1139 for (const VPBlockBase *Block : RPOT) {
1140 O << '\n';
1141 Block->print(O, "", SlotTracker);
1142 }
1143
1144 O << "}\n";
1145}
1146
1147std::string VPlan::getName() const {
1148 std::string Out;
1149 raw_string_ostream RSO(Out);
1150 RSO << Name << " for ";
1151 if (!VFs.empty()) {
1152 RSO << "VF={" << VFs[0];
1153 for (ElementCount VF : drop_begin(VFs))
1154 RSO << "," << VF;
1155 RSO << "},";
1156 }
1157
1158 if (UFs.empty()) {
1159 RSO << "UF>=1";
1160 } else {
1161 RSO << "UF={" << UFs[0];
1162 for (unsigned UF : drop_begin(UFs))
1163 RSO << "," << UF;
1164 RSO << "}";
1165 }
1166
1167 return Out;
1168}
1169
1172 VPlanPrinter Printer(O, *this);
1173 Printer.dump();
1174}
1175
1177void VPlan::dump() const { print(dbgs()); }
1178#endif
1179
1180static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry,
1181 DenseMap<VPValue *, VPValue *> &Old2NewVPValues) {
1182 // Update the operands of all cloned recipes starting at NewEntry. This
1183 // traverses all reachable blocks. This is done in two steps, to handle cycles
1184 // in PHI recipes.
1186 OldDeepRPOT(Entry);
1188 NewDeepRPOT(NewEntry);
1189 // First, collect all mappings from old to new VPValues defined by cloned
1190 // recipes.
1191 for (const auto &[OldBB, NewBB] :
1194 assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() &&
1195 "blocks must have the same number of recipes");
1196 for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
1197 assert(OldR.getNumOperands() == NewR.getNumOperands() &&
1198 "recipes must have the same number of operands");
1199 assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() &&
1200 "recipes must define the same number of operands");
1201 for (const auto &[OldV, NewV] :
1202 zip(OldR.definedValues(), NewR.definedValues()))
1203 Old2NewVPValues[OldV] = NewV;
1204 }
1205 }
1206
1207 // Update all operands to use cloned VPValues.
1208 for (VPBasicBlock *NewBB :
1210 for (VPRecipeBase &NewR : *NewBB)
1211 for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
1212 VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I));
1213 NewR.setOperand(I, NewOp);
1214 }
1215 }
1216}
1217
1219 unsigned NumBlocksBeforeCloning = CreatedBlocks.size();
1220 // Clone blocks.
1221 const auto &[NewEntry, __] = VPBlockUtils::cloneFrom(Entry);
1222
1223 BasicBlock *ScalarHeaderIRBB = getScalarHeader()->getIRBasicBlock();
1224 VPIRBasicBlock *NewScalarHeader = nullptr;
1225 if (getScalarHeader()->hasPredecessors()) {
1226 NewScalarHeader = cast<VPIRBasicBlock>(*find_if(
1227 vp_depth_first_shallow(NewEntry), [ScalarHeaderIRBB](VPBlockBase *VPB) {
1228 auto *VPIRBB = dyn_cast<VPIRBasicBlock>(VPB);
1229 return VPIRBB && VPIRBB->getIRBasicBlock() == ScalarHeaderIRBB;
1230 }));
1231 } else {
1232 NewScalarHeader = createVPIRBasicBlock(ScalarHeaderIRBB);
1233 }
1234 // Create VPlan, clone live-ins and remap operands in the cloned blocks.
1235 auto *NewPlan =
1236 new VPlan(cast<VPBasicBlock>(NewEntry), NewScalarHeader, getIndexType());
1237 DenseMap<VPValue *, VPValue *> Old2NewVPValues;
1238 for (VPIRValue *OldLiveIn : getLiveIns())
1239 Old2NewVPValues[OldLiveIn] = NewPlan->getOrAddLiveIn(OldLiveIn);
1240
1241 if (auto *TripCountIRV = dyn_cast_or_null<VPIRValue>(TripCount))
1242 Old2NewVPValues[TripCountIRV] = NewPlan->getOrAddLiveIn(TripCountIRV);
1243 // else NewTripCount will be created and inserted into Old2NewVPValues when
1244 // TripCount is cloned. In any case NewPlan->TripCount is updated below.
1245
1246 assert(none_of(Old2NewVPValues.keys(), IsaPred<VPSymbolicValue>) &&
1247 "All VPSymbolicValues must be handled below");
1248
1249 if (auto *LoopRegion = getVectorLoopRegion()) {
1250 auto *NewLoopRegion = NewPlan->getVectorLoopRegion();
1251 for (auto [Old, New] : zip_equal(LoopRegion->getRegionValues(),
1252 NewLoopRegion->getRegionValues())) {
1253 Old2NewVPValues[Old] = New;
1254 if (Old->isMaterialized())
1255 New->markMaterialized();
1256 }
1257 }
1258
1259 // Map and propagate materialized state for symbolic values.
1260 for (auto [OldSV, NewSV] :
1261 {std::pair{&VectorTripCount, &NewPlan->VectorTripCount},
1262 {&VF, &NewPlan->VF},
1263 {&UF, &NewPlan->UF},
1264 {&VFxUF, &NewPlan->VFxUF}}) {
1265 Old2NewVPValues[OldSV] = NewSV;
1266 if (OldSV->isMaterialized())
1267 NewSV->markMaterialized();
1268 }
1269
1270 remapOperands(Entry, NewEntry, Old2NewVPValues);
1271
1272 // Initialize remaining fields of cloned VPlan.
1273 NewPlan->VFs = VFs;
1274 NewPlan->UFs = UFs;
1275 // TODO: Adjust names.
1276 NewPlan->Name = Name;
1277 if (TripCount) {
1278 assert(Old2NewVPValues.contains(TripCount) &&
1279 "TripCount must have been added to Old2NewVPValues");
1280 NewPlan->TripCount = Old2NewVPValues[TripCount];
1281 }
1282
1283 // Transfer all cloned blocks (the second half of all current blocks) from
1284 // current to new VPlan.
1285 unsigned NumBlocksAfterCloning = CreatedBlocks.size();
1286 for (unsigned I :
1287 seq<unsigned>(NumBlocksBeforeCloning, NumBlocksAfterCloning)) {
1288 this->CreatedBlocks[I]->setPlan(NewPlan);
1289 this->CreatedBlocks[I]->setNumber(NewPlan->CreatedBlocks.size());
1290 NewPlan->CreatedBlocks.push_back(this->CreatedBlocks[I]);
1291 }
1292 CreatedBlocks.truncate(NumBlocksBeforeCloning);
1293
1294 // Update ExitBlocks of the new plan.
1295 for (VPBlockBase *VPB : NewPlan->CreatedBlocks) {
1296 if (VPB->getNumSuccessors() == 0 && isa<VPIRBasicBlock>(VPB) &&
1297 VPB != NewScalarHeader)
1298 NewPlan->ExitBlocks.push_back(cast<VPIRBasicBlock>(VPB));
1299 }
1300
1301 return NewPlan;
1302}
1303
1305 auto *VPIRBB = new VPIRBasicBlock(IRBB);
1306 VPIRBB->setPlan(this);
1307 VPIRBB->setNumber(CreatedBlocks.size());
1308 CreatedBlocks.push_back(VPIRBB);
1309 return VPIRBB;
1310}
1311
1313 auto *VPIRBB = createEmptyVPIRBasicBlock(IRBB);
1314 for (Instruction &I :
1315 make_range(IRBB->begin(), IRBB->getTerminator()->getIterator()))
1316 VPIRBB->appendRecipe(VPIRInstruction::create(I));
1317 return VPIRBB;
1318}
1319
1320#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1321
1322Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1323 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1324 Twine(getOrCreateBID(Block));
1325}
1326
1328 Depth = 1;
1329 bumpIndent(0);
1330 OS << "digraph VPlan {\n";
1331 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1332 if (!Plan.getName().empty())
1333 OS << "\\n" << DOT::EscapeString(Plan.getName());
1334
1335 {
1336 // Print live-ins.
1337 std::string Str;
1338 raw_string_ostream SS(Str);
1339 Plan.printLiveIns(SS);
1341 StringRef(Str).rtrim('\n').split(Lines, "\n");
1342 for (auto Line : Lines)
1343 OS << DOT::EscapeString(Line.str()) << "\\n";
1344 }
1345
1346 OS << "\"]\n";
1347 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1348 OS << "edge [fontname=Courier, fontsize=30]\n";
1349 OS << "compound=true\n";
1350
1351 for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
1352 dumpBlock(Block);
1353
1354 OS << "}\n";
1355}
1356
1357void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1359 dumpBasicBlock(BasicBlock);
1361 dumpRegion(Region);
1362 else
1363 llvm_unreachable("Unsupported kind of VPBlock.");
1364}
1365
1366void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1367 bool Hidden, const Twine &Label) {
1368 // Due to "dot" we print an edge between two regions as an edge between the
1369 // exiting basic block and the entry basic of the respective regions.
1370 const VPBlockBase *Tail = From->getExitingBasicBlock();
1371 const VPBlockBase *Head = To->getEntryBasicBlock();
1372 OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1373 OS << " [ label=\"" << Label << '\"';
1374 if (Tail != From)
1375 OS << " ltail=" << getUID(From);
1376 if (Head != To)
1377 OS << " lhead=" << getUID(To);
1378 if (Hidden)
1379 OS << "; splines=none";
1380 OS << "]\n";
1381}
1382
1383void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1384 auto &Successors = Block->getSuccessors();
1385 if (Successors.size() == 1)
1386 drawEdge(Block, Successors.front(), false, "");
1387 else if (Successors.size() == 2) {
1388 drawEdge(Block, Successors.front(), false, "T");
1389 drawEdge(Block, Successors.back(), false, "F");
1390 } else {
1391 unsigned SuccessorNumber = 0;
1392 for (auto *Successor : Successors)
1393 drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1394 }
1395}
1396
1397void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1398 // Implement dot-formatted dump by performing plain-text dump into the
1399 // temporary storage followed by some post-processing.
1400 OS << Indent << getUID(BasicBlock) << " [label =\n";
1401 bumpIndent(1);
1402 std::string Str;
1403 raw_string_ostream SS(Str);
1404 // Use no indentation as we need to wrap the lines into quotes ourselves.
1405 BasicBlock->print(SS, "", SlotTracker);
1406
1407 // We need to process each line of the output separately, so split
1408 // single-string plain-text dump.
1410 StringRef(Str).rtrim('\n').split(Lines, "\n");
1411
1412 auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1413 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1414 };
1415
1416 // Don't need the "+" after the last line.
1417 for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1418 EmitLine(Line, " +\n");
1419 EmitLine(Lines.back(), "\n");
1420
1421 bumpIndent(-1);
1422 OS << Indent << "]\n";
1423
1424 dumpEdges(BasicBlock);
1425}
1426
1427void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1428 OS << Indent << "subgraph " << getUID(Region) << " {\n";
1429 bumpIndent(1);
1430 OS << Indent << "fontname=Courier\n"
1431 << Indent << "label=\""
1432 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1433 << DOT::EscapeString(Region->getName()) << "\"\n";
1434
1435 if (auto *CanIV = Region->getCanonicalIV()) {
1436 OS << Indent << "\"";
1437 std::string Op;
1438 raw_string_ostream S(Op);
1439 CanIV->printAsOperand(S, SlotTracker);
1440 OS << DOT::EscapeString(Op);
1441 OS << " = CANONICAL-IV\"\n";
1442 }
1443
1444 // Dump the blocks of the region.
1445 assert(Region->getEntry() && "Region contains no inner blocks.");
1446 for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
1447 dumpBlock(Block);
1448 bumpIndent(-1);
1449 OS << Indent << "}\n";
1450 dumpEdges(Region);
1451}
1452
1453#endif
1454
1455/// Returns true if there is a vector loop region and \p VPV is defined in a
1456/// loop region.
1457static bool isDefinedInsideLoopRegions(const VPValue *VPV) {
1458 if (isa<VPRegionValue>(VPV))
1459 return true;
1460 const VPRecipeBase *DefR = VPV->getDefiningRecipe();
1461 return DefR && (DefR->getParent()->getEnclosingLoopRegion() ||
1462 !DefR->getParent()->getPlan()->getVectorLoopRegion());
1463}
1464
1469 replaceUsesWithIf(New, [](VPUser *) { return true; });
1470 if (auto *SV = dyn_cast<VPSymbolicValue>(this))
1471 SV->markMaterialized();
1472}
1473
1475 VPValue *New, llvm::function_ref<bool(VPUser *U)> ShouldReplace) {
1477 // Note that this early exit is required for correctness; the implementation
1478 // below relies on the number of users for this VPValue to decrease, which
1479 // isn't the case if this == New.
1480 if (this == New)
1481 return;
1482
1483 for (unsigned J = 0; J < getNumUsers();) {
1484 VPUser *User = Users[J];
1485 bool RemovedUser = false;
1486 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
1487 if (User->getOperand(I) != this || !ShouldReplace(User))
1488 continue;
1489
1490 RemovedUser = true;
1491 User->setOperand(I, New);
1492 }
1493 // If a user got removed after updating the current user, the next user to
1494 // update will be moved to the current position, so we only need to
1495 // increment the index if the number of users did not change.
1496 if (!RemovedUser)
1497 J++;
1498 }
1499}
1500
1502 for (unsigned Idx = 0; Idx != getNumOperands(); ++Idx) {
1503 if (getOperand(Idx) == From)
1504 setOperand(Idx, To);
1505 }
1506}
1507
1508#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1510 OS << Tracker.getOrCreateName(this);
1511}
1512
1515 Op->printAsOperand(O, SlotTracker);
1516 });
1517}
1518#endif
1519
1520void VPSlotTracker::assignName(const VPValue *V) {
1521 assert(!VPValue2Name.contains(V) && "VPValue already has a name!");
1522 auto *UV = V->getUnderlyingValue();
1523 auto *VPI = dyn_cast_or_null<VPInstruction>(V);
1524 if (!UV && !(VPI && !VPI->getName().empty())) {
1525 VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str();
1526 NextSlot++;
1527 return;
1528 }
1529
1530 // Use the name of the underlying Value, wrapped in "ir<>", and versioned by
1531 // appending ".Number" to the name if there are multiple uses.
1532 std::string Name;
1533 if (UV)
1534 Name = getName(UV);
1535 else
1536 Name = VPI->getName();
1537
1538 assert(!Name.empty() && "Name cannot be empty.");
1539 StringRef Prefix = UV ? "ir<" : "vp<%";
1540 std::string BaseName = (Twine(Prefix) + Name + Twine(">")).str();
1541
1542 // First assign the base name for V.
1543 const auto &[A, _] = VPValue2Name.try_emplace(V, BaseName);
1544 // Integer or FP constants with different types will result in the same string
1545 // due to stripping types.
1547 return;
1548
1549 // If it is already used by C > 0 other VPValues, increase the version counter
1550 // C and use it for V.
1551 const auto &[C, UseInserted] = BaseName2Version.try_emplace(BaseName, 0);
1552 if (!UseInserted) {
1553 C->second++;
1554 A->second = (BaseName + Twine(".") + Twine(C->second)).str();
1555 }
1556}
1557
1558void VPSlotTracker::assignNames(const VPlan &Plan) {
1559 if (!Plan.VF.user_empty())
1560 assignName(&Plan.VF);
1561 if (!Plan.UF.user_empty())
1562 assignName(&Plan.UF);
1563 if (!Plan.VFxUF.user_empty())
1564 assignName(&Plan.VFxUF);
1565 assignName(&Plan.VectorTripCount);
1566 for (VPValue *LI : Plan.getLiveIns())
1567 assignName(LI);
1568
1569 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
1570 RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
1571 for (const VPBlockBase *VPB : RPOT) {
1572 if (auto *VPBB = dyn_cast<VPBasicBlock>(VPB))
1573 assignNames(VPBB);
1574 else
1575 for (auto *RV : cast<VPRegionBlock>(VPB)->getRegionValues())
1576 assignName(RV);
1577 }
1578}
1579
1580void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) {
1581 for (const VPRecipeBase &Recipe : *VPBB)
1582 for (VPValue *Def : Recipe.definedValues())
1583 assignName(Def);
1584}
1585
1586ModuleSlotTracker &VPSlotTracker::getOrCreateMST() {
1587 // F is null for unit tests with incomplete IR.
1588 if (!MST) {
1589 MST = std::make_unique<ModuleSlotTracker>(getModule());
1590 if (F)
1591 MST->incorporateFunction(*F);
1592 }
1593 return *MST;
1594}
1595
1596std::string VPSlotTracker::getName(const Value *V) {
1597 std::string Name;
1598 raw_string_ostream S(Name);
1599 // If V isn't an instruction in a basic block or named, it can be printed
1600 // directly without ModuleSlotTracker.
1601 auto *I = dyn_cast<Instruction>(V);
1602 if (!I || I->hasName() || !I->getParent()) {
1603 V->printAsOperand(S, false);
1604 return Name;
1605 }
1606
1607 V->printAsOperand(S, false, getOrCreateMST());
1608 return Name;
1609}
1610
1612 N->printAsOperand(O, getOrCreateMST(), getModule());
1613}
1614
1615std::string VPSlotTracker::getOrCreateName(const VPValue *V) const {
1616 std::string Name = VPValue2Name.lookup(V);
1617 if (!Name.empty())
1618 return Name;
1619
1620 // If no name was assigned, no VPlan was provided when creating the slot
1621 // tracker or it is not reachable from the provided VPlan. This can happen,
1622 // e.g. when trying to print a recipe that has not been inserted into a VPlan
1623 // in a debugger.
1624 // TODO: Update VPSlotTracker constructor to assign names to recipes &
1625 // VPValues not associated with a VPlan, instead of constructing names ad-hoc
1626 // here.
1627
1628 // Use the underlying value's name, if there is one.
1629 if (auto *UV = V->getUnderlyingValue()) {
1630 std::string Name;
1631 raw_string_ostream S(Name);
1632 UV->printAsOperand(S, false);
1633 return (Twine("ir<") + Name + ">").str();
1634 }
1635
1636 return "<badref>";
1637}
1638
1640 const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
1641 assert(!Range.isEmpty() && "Trying to test an empty VF range.");
1642 bool PredicateAtRangeStart = Predicate(Range.Start);
1643
1644 for (ElementCount TmpVF : VFRange(Range.Start * 2, Range.End))
1645 if (Predicate(TmpVF) != PredicateAtRangeStart) {
1646 Range.End = TmpVF;
1647 break;
1648 }
1649
1650 return PredicateAtRangeStart;
1651}
1652
1654 assert(count_if(VPlans,
1655 [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
1656 1 &&
1657 "Multiple VPlans for VF.");
1658
1659 for (const VPlanPtr &Plan : VPlans) {
1660 if (Plan->hasVF(VF))
1661 return *Plan.get();
1662 }
1663 llvm_unreachable("No plan found!");
1664}
1665
1668 // Reserve first location for self reference to the LoopID metadata node.
1669 MDs.push_back(nullptr);
1670 bool IsUnrollMetadata = false;
1671 MDNode *LoopID = L->getLoopID();
1672 if (LoopID) {
1673 // First find existing loop unrolling disable metadata.
1674 for (unsigned I = 1, IE = LoopID->getNumOperands(); I < IE; ++I) {
1675 auto *MD = dyn_cast<MDNode>(LoopID->getOperand(I));
1676 if (MD) {
1677 const auto *S = dyn_cast<MDString>(MD->getOperand(0));
1678 if (!S)
1679 continue;
1680 if (S->getString().starts_with("llvm.loop.unroll.runtime.disable"))
1681 continue;
1682 IsUnrollMetadata =
1683 S->getString().starts_with("llvm.loop.unroll.disable");
1684 }
1685 MDs.push_back(LoopID->getOperand(I));
1686 }
1687 }
1688
1689 if (!IsUnrollMetadata) {
1690 // Add runtime unroll disable metadata.
1691 LLVMContext &Context = L->getHeader()->getContext();
1692 SmallVector<Metadata *, 1> DisableOperands;
1693 DisableOperands.push_back(
1694 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1695 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1696 MDs.push_back(DisableNode);
1697 MDNode *NewLoopID = MDNode::get(Context, MDs);
1698 // Set operand 0 to refer to the loop id itself.
1699 NewLoopID->replaceOperandWith(0, NewLoopID);
1700 L->setLoopID(NewLoopID);
1701 }
1702}
1703
1705 Loop *VectorLoop, VPBasicBlock *HeaderVPBB, const VPlan &Plan,
1706 bool VectorizingEpilogue, MDNode *OrigLoopID,
1707 std::optional<unsigned> OrigAverageTripCount,
1708 unsigned OrigLoopInvocationWeight, unsigned EstimatedVFxUF,
1709 bool DisableRuntimeUnroll, bool UnrollVectorizedLoop) {
1710 // Update the metadata of the scalar loop. Skip the update when vectorizing
1711 // the epilogue loop to ensure it is updated only once. Also skip the update
1712 // when the scalar loop became unreachable.
1713 auto *ScalarPH = Plan.getScalarPreheader();
1714 if (ScalarPH && !VectorizingEpilogue) {
1715 std::optional<MDNode *> RemainderLoopID =
1718 if (RemainderLoopID) {
1719 OrigLoop->setLoopID(*RemainderLoopID);
1720 } else {
1721 if (DisableRuntimeUnroll)
1723
1724 LoopVectorizeHints Hints(Opts, OrigLoop,
1725 /*InterleaveOnlyWhenForced*/ false, *ORE);
1726 Hints.setAlreadyVectorized();
1727 }
1728 }
1729 // Tag the scalar remainder so downstream passes (e.g. the unroller and
1730 // WarnMissedTransforms) can produce more informative remarks. Only emit
1731 // when remarks are enabled.
1732 if (ORE->enabled() && ScalarPH && ScalarPH->hasPredecessors())
1733 OrigLoop->addIntLoopAttribute("llvm.loop.vectorize.epilogue", 1);
1734
1735 if (!VectorLoop)
1736 return;
1737
1738 if (std::optional<MDNode *> VectorizedLoopID = makeFollowupLoopID(
1739 OrigLoopID, {LLVMLoopVectorizeFollowupAll,
1741 VectorLoop->setLoopID(*VectorizedLoopID);
1742 } else {
1743 // Keep all loop hints from the original loop on the vector loop (we'll
1744 // replace the vectorizer-specific hints below).
1745 if (OrigLoopID)
1746 VectorLoop->setLoopID(OrigLoopID);
1747
1748 if (!VectorizingEpilogue) {
1749 LoopVectorizeHints Hints(Opts, VectorLoop,
1750 /*InterleaveOnlyWhenForced*/ false, *ORE);
1751 Hints.setAlreadyVectorized();
1752 }
1753 }
1754 // Tag the vector loop body so downstream passes can identify it. Only
1755 // emit when remarks are enabled.
1756 if (ORE->enabled())
1757 VectorLoop->addIntLoopAttribute("llvm.loop.vectorize.body", 1);
1758 if (!UnrollVectorizedLoop || VectorizingEpilogue)
1760
1761 // Set/update profile weights for the vector and remainder loops as original
1762 // loop iterations are now distributed among them. Note that original loop
1763 // becomes the scalar remainder loop after vectorization.
1764 //
1765 // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
1766 // end up getting slightly roughened result but that should be OK since
1767 // profile is not inherently precise anyway. Note also possible bypass of
1768 // vector code caused by legality checks is ignored, assigning all the weight
1769 // to the vector loop, optimistically.
1770 //
1771 // For scalable vectorization we can't know at compile time how many
1772 // iterations of the loop are handled in one vector iteration, so instead
1773 // use the value of vscale used for tuning.
1774 unsigned AverageVectorTripCount = 0;
1775 unsigned RemainderAverageTripCount = 0;
1776 auto EC = VectorLoop->getLoopPreheader()->getParent()->getEntryCount();
1777 auto IsProfiled = EC && *EC != 0;
1778 if (!OrigAverageTripCount) {
1779 if (!IsProfiled)
1780 return;
1781 auto &SE = *PSE.getSE();
1782 AverageVectorTripCount = SE.getSmallConstantTripCount(VectorLoop);
1783 if (!AverageVectorTripCount)
1784 return;
1785 if (ScalarPH)
1786 RemainderAverageTripCount =
1787 SE.getSmallConstantTripCount(OrigLoop) % EstimatedVFxUF;
1788 // Setting to 1 should be sufficient to generate the correct branch weights.
1789 OrigLoopInvocationWeight = 1;
1790 } else {
1791 // Calculate number of iterations in unrolled loop.
1792 AverageVectorTripCount = *OrigAverageTripCount / EstimatedVFxUF;
1793 // Calculate number of iterations for remainder loop.
1794 RemainderAverageTripCount = *OrigAverageTripCount % EstimatedVFxUF;
1795 }
1796 if (HeaderVPBB) {
1797 setLoopEstimatedTripCount(VectorLoop, AverageVectorTripCount,
1798 OrigLoopInvocationWeight);
1799 }
1800
1801 if (ScalarPH) {
1802 setLoopEstimatedTripCount(OrigLoop, RemainderAverageTripCount,
1803 OrigLoopInvocationWeight);
1804 }
1805}
1806
1807#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1809 if (VPlans.empty()) {
1810 O << "LV: No VPlans built.\n";
1811 return;
1812 }
1813 for (const auto &Plan : VPlans)
1814 if (Opts.vplan_print_in_dot_format)
1815 Plan->printDOT(O);
1816 else
1817 Plan->print(O);
1818}
1819#endif
1820
1821bool llvm::canConstantBeExtended(const APInt *C, Type *NarrowType,
1823 APInt TruncatedVal = C->trunc(NarrowType->getScalarSizeInBits());
1824 unsigned WideSize = C->getBitWidth();
1825 APInt ExtendedVal = ExtKind == TTI::PR_SignExtend
1826 ? TruncatedVal.sext(WideSize)
1827 : TruncatedVal.zext(WideSize);
1828 return ExtendedVal == *C;
1829}
1830
1833 if (auto *IRV = dyn_cast<VPIRValue>(V))
1834 return TTI::getOperandInfo(IRV->getValue());
1835
1836 return {};
1837}
1838
1839#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1841 if (!PlanForSlotTracker)
1842 return nullptr;
1843 if (!SlotTracker)
1844 SlotTracker = std::make_unique<VPSlotTracker>(PlanForSlotTracker);
1845 return SlotTracker.get();
1846}
1847#endif
1848
1851 TTI::VectorInstrContext VIC, bool AlwaysIncludeReplicatingR) {
1852 if (VF.isScalar())
1853 return 0;
1854
1855 assert(!VF.isScalable() &&
1856 "Scalarization overhead not supported for scalable vectors");
1857
1858 InstructionCost ScalarizationCost = 0;
1859 // Compute the cost of scalarizing the result if needed.
1860 if (!ResultTy->isVoidTy()) {
1861 for (Type *VectorTy :
1862 to_vector(getContainedTypes(toVectorizedTy(ResultTy, VF)))) {
1863 ScalarizationCost += TTI.getScalarizationOverhead(
1865 /*Insert=*/true, /*Extract=*/false, CostKind,
1866 /*ForPoisonSrc=*/true, {}, VIC);
1867 }
1868 }
1869 // Compute the cost of scalarizing the operands, skipping ones that do not
1870 // require extraction/scalarization and do not incur any overhead.
1871 SmallPtrSet<const VPValue *, 4> UniqueOperands;
1873 for (auto *Op : Operands) {
1874 if (isa<VPIRValue>(Op) ||
1875 (!AlwaysIncludeReplicatingR &&
1878 cast<VPReplicateRecipe>(Op)->getOpcode() == Instruction::Load) ||
1879 !UniqueOperands.insert(Op).second)
1880 continue;
1881 Tys.push_back(toVectorizedTy(Op->getScalarType(), VF));
1882 }
1883 return ScalarizationCost +
1884 TTI.getOperandsScalarizationOverhead(Tys, CostKind, VIC);
1885}
1886
1888 ElementCount VF) {
1889 const Instruction *UI = R->getUnderlyingInstr();
1890 if (isa<LoadInst>(UI))
1891 return true;
1892 assert(isa<StoreInst>(UI) && "R must either be a load or store");
1893
1894 if (!NumPredStores) {
1895 // Count the number of predicated stores in the VPlan, caching the result.
1896 // Only stores where scatter is not legal are counted, matching the legacy
1897 // cost model behavior.
1898 const VPlan &Plan = *R->getParent()->getPlan();
1899 NumPredStores = 0;
1900 for (const VPRegionBlock *VPRB :
1903 assert(VPRB->isReplicator() && "must only contain replicate regions");
1904 for (const VPBasicBlock *VPBB :
1906 vp_depth_first_shallow(VPRB->getEntry()))) {
1907 for (const VPReplicateRecipe &RepR :
1909 if (!isa<StoreInst>(RepR.getUnderlyingInstr()))
1910 continue;
1911 // Check if scatter is legal for this store. If so, don't count it.
1912 Type *Ty = RepR.getOperand(0)->getScalarType();
1913 auto *VTy = VectorType::get(Ty, VF);
1914 const Align Alignment =
1915 getLoadStoreAlignment(RepR.getUnderlyingInstr());
1916 if (!TTI.isLegalMaskedScatter(VTy, Alignment))
1917 ++(*NumPredStores);
1918 }
1919 }
1920 }
1921 }
1922 return *NumPredStores > Opts.vectorize_num_stores_pred;
1923}
1924
1926 return is_contained({Intrinsic::assume, Intrinsic::lifetime_end,
1927 Intrinsic::lifetime_start, Intrinsic::sideeffect,
1928 Intrinsic::pseudoprobe,
1929 Intrinsic::experimental_noalias_scope_decl},
1930 ID);
1931}
1932
1933uint64_t
1934VPCostContext::getCostDivisor(std::optional<VPExecutionFrequency> Freq) const {
1935 if (CostKind == TTI::TCK_CodeSize || !Freq)
1936 return 1;
1937 // A recorded frequency is neither zero nor always-executing, so the
1938 // probability is non-zero and the division below is safe.
1939 return divideNearest(
1941 vputils::getExecutionProbability(Freq->Freq).getNumerator());
1942}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
amdgpu next use AMDGPU Next Use Analysis Printer
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
Flatten the CFG
#define _
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This file defines the LoopVectorizationLegality class.
This file provides a LoopVectorizationPlanner class.
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static StringRef getName(Value *V)
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS(PASS,...)
static void addRuntimeUnrollDisableMetaData(Loop *L)
Definition VPlan.cpp:1666
static void printFinalVPlan(VPlan &)
To make RUN_VPLAN_PASS print final VPlan.
Definition VPlan.cpp:931
static T * getEnclosingLoopRegionForRegion(T *P)
Return the enclosing loop region for region P.
Definition VPlan.cpp:547
const char LLVMLoopVectorizeFollowupAll[]
Definition VPlan.cpp:59
static bool isDefinedInsideLoopRegions(const VPValue *VPV)
Returns true if there is a vector loop region and VPV is defined in a loop region.
Definition VPlan.cpp:1457
static bool hasConditionalTerminator(const VPBasicBlock *VPBB)
Definition VPlan.cpp:565
const char LLVMLoopVectorizeFollowupVectorized[]
Definition VPlan.cpp:60
static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry, DenseMap< VPValue *, VPValue * > &Old2NewVPValues)
Definition VPlan.cpp:1180
const char LLVMLoopVectorizeFollowupEpilogue[]
Definition VPlan.cpp:62
This file contains the declarations of the Vectorization Plan base classes:
static bool IsCondBranch(unsigned BrOpc)
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:460
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
static uint32_t getDenominator()
std::optional< const DILocation * > cloneByMultiplyingDuplicationFactor(unsigned DF) const
Returns a new DILocation with duplication factor DF * current duplication factor encoded in the discr...
A debug info location.
Definition DebugLoc.h:126
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:321
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
std::optional< uint64_t > getEntryCount() const
Get the entry count for this function.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
static InstructionCost getInvalid(CostType Val=0)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
A helper class to return the specified delimiter string after the first invocation of operator String...
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
block_iterator block_end() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
iterator begin() const
block_iterator block_begin() const
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
Definition VPlan.cpp:1653
void updateLoopMetadataAndProfileInfo(Loop *VectorLoop, VPBasicBlock *HeaderVPBB, const VPlan &Plan, bool VectorizingEpilogue, MDNode *OrigLoopID, std::optional< unsigned > OrigAverageTripCount, unsigned OrigLoopInvocationWeight, unsigned EstimatedVFxUF, bool DisableRuntimeUnroll, bool UnrollVectorizedLoop)
Update loop metadata and profile info for both the scalar remainder loop and VectorLoop,...
Definition VPlan.cpp:1704
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
Definition VPlan.cpp:1639
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1808
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
LLVM_ABI void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI void addIntLoopAttribute(StringRef Name, unsigned Value, ArrayRef< StringRef > RemovePrefixes={}) const
Add an integer metadata attribute to this loop's loop-ID node.
Definition LoopInfo.cpp:608
LLVM_ABI void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition LoopInfo.cpp:576
Metadata node.
Definition Metadata.h:1087
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
Manage lifetime of a slot tracker for printing IR.
BlockT * getEntry() const
Get the entry BasicBlock of the Region.
Definition RegionInfo.h:323
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.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:370
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
StringRef rtrim(char Char) const
Return string with consecutive Char characters starting from the right removed.
Definition StringRef.h:830
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
@ TCK_CodeSize
Instruction code size.
llvm::VectorInstrContext VectorInstrContext
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
This function has undefined behavior.
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4512
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4593
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4543
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition VPlan.cpp:471
iterator end()
Definition VPlan.h:4553
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4551
VPBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition VPlan.cpp:505
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of this VPBasicBlock.
Definition VPlan.cpp:733
const VPBasicBlock * getCFGPredecessor(unsigned Idx) const
Returns the predecessor block at index Idx with the predecessors as per the corresponding plain CFG.
Definition VPlan.cpp:751
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:225
void connectToPredecessors(VPTransformState &State)
Connect the VPBBs predecessors' in the VPlan CFG to the IR basic block generated for this VPBB.
Definition VPlan.cpp:362
VPRegionBlock * getEnclosingLoopRegion()
Definition VPlan.cpp:557
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition VPlan.cpp:524
RecipeListTy Recipes
The VPRecipes held in the order of output instructions to generate.
Definition VPlan.h:4527
void executeRecipes(VPTransformState *State, BasicBlock *BB)
Execute the recipes in the IR basic block BB.
Definition VPlan.cpp:512
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPBsicBlock to O, prefixing all lines with Indent.
Definition VPlan.cpp:637
bool isExiting() const
Returns true if the block is exiting it's parent region.
Definition VPlan.cpp:615
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:603
const VPRecipeBase & back() const
Definition VPlan.h:4565
bool empty() const
Definition VPlan.h:4562
size_t size() const
Definition VPlan.h:4561
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:80
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:290
VPRegionBlock * getParent()
Definition VPlan.h:178
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:195
size_t getNumSuccessors() const
Definition VPlan.h:228
iterator_range< VPBlockBase ** > successors()
Definition VPlan.h:210
virtual void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Print plain-text dump of this VPBlockBase to O, prefixing all lines with Indent.
bool hasPredecessors() const
Returns true if this block has any predecessors.
Definition VPlan.h:208
void printSuccessors(raw_ostream &O, const Twine &Indent) const
Print the successors of this block to O, prefixing all lines with Indent.
Definition VPlan.cpp:625
size_t getNumPredecessors() const
Definition VPlan.h:229
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:281
VPBlockBase * getEnclosingBlockWithPredecessors()
Definition VPlan.cpp:217
bool hasSuccessors() const
Returns true if this block has any successors.
Definition VPlan.h:206
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:213
virtual InstructionCost cost(ElementCount VF, VPCostContext &Ctx)=0
Return the cost of the block.
VPlan * getPlan()
Definition VPlan.h:182
const std::string & getName() const
Definition VPlan.h:169
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:224
const VPBlocksTy & getHierarchicalSuccessors()
Definition VPlan.h:248
VPBlockBase * getEnclosingBlockWithSuccessors()
An Enclosing Block of a block B is any block containing B, including B itself.
Definition VPlan.cpp:209
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:180
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:218
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:202
VPBlockBase(VPBlockTy SC, const std::string &N)
Definition VPlan.h:375
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition VPlanUtils.h:349
static bool isLatch(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop latch, using isHeader().
static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop header, based on regions or VPDT in their absence.
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:394
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:412
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:460
static void transferSuccessors(VPBlockBase *Old, VPBlockBase *New)
Transfer successors from Old to New. New must have no successors.
Definition VPlanUtils.h:444
static std::pair< VPBlockBase *, VPBlockBase * > cloneFrom(VPBlockBase *Entry)
Clone the CFG for all nodes reachable from Entry, including cloning the blocks and their recipes.
Definition VPlan.cpp:652
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3568
VPInstruction * createOverflowingOp(unsigned Opcode, ArrayRef< VPValue * > Operands, VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt, Type *ResultTy=nullptr)
Create a phi with IncomingValues, using the default flags for the result type, unless Flags is set.
This class augments a recipe with a set of VPValues defined by the recipe.
Definition VPlanValue.h:503
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4671
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition VPlan.cpp:439
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4695
VPIRBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition VPlan.cpp:464
static LLVM_ABI_FOR_TEST VPIRInstruction * create(Instruction &I)
Create a new VPIRPhi for \I , if it is a PHINode, otherwise create a VPIRInstruction.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1311
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)
Value * getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const
Returns an expression describing the lane index that can be used at runtime.
Definition VPlan.cpp:77
bool isFirstLane() const
Returns true if this is the first lane of the whole vector.
static VPLane getFirstLane()
@ ScalableLast
For ScalableLast, Lane is the offset from the start of the last N-element subvector in a scalable vec...
@ First
For First, Lane is the index into the first N elements of a fixed-vector <N x <ElTy>> or a scalable v...
unsigned mapToCacheIndex(const ElementCount &VF) const
Maps the lane to a cache index based on VF.
LLVM_ABI_FOR_TEST VPMultiDefValue(VPRecipeBase *Def, Value *UV, Type *Ty)
Definition VPlan.cpp:169
~VPMultiDefValue() override
Definition VPlan.cpp:175
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:387
void dump() const
Dump the recipe to stderr (for debugging).
Definition VPlan.cpp:107
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const
Print the recipe, delegating to printRecipe().
virtual LLVM_ABI_FOR_TEST ~VPRecipeValue()=0
Definition VPlan.cpp:154
VPRecipeValue(unsigned char SC, Value *UV, Type *Ty=nullptr)
Definition VPlanValue.h:342
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4743
VPRegionBlock * clone() override
Clone all blocks in the single-entry single-exit region of the block and their recipes without updati...
Definition VPlan.cpp:709
const VPBlockBase * getEntry() const
Definition VPlan.h:4787
void dissolveToCFGLoop()
Remove the current region from its VPlan, connecting its predecessor to its entry,...
Definition VPlan.cpp:854
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4819
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4890
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4883
VPInstruction * getOrCreateCanonicalIVIncrement()
Get the canonical IV increment instruction if it exists.
Definition VPlan.cpp:880
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of the block.
Definition VPlan.cpp:770
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPRegionBlock to O (recursively), prefixing all lines with Indent.
Definition VPlan.cpp:831
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4871
const VPBranchOnMaskRecipe * getEntryBranchOnMask() const
Return the VPBranchOnMaskRecipe from the entry block of this replicating region.
Definition VPlan.cpp:702
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4907
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPRegionBlock,...
Definition VPlan.cpp:729
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4863
const VPBlockBase * getExiting() const
Definition VPlan.h:4799
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4876
friend class VPlan
Definition VPlan.h:4744
VPValues are defined by a VPRegionBlock, like the canonical IV.
Definition VPlanValue.h:247
DebugLoc getDebugLoc() const
Returns the debug location of the VPRegionValue.
Definition VPlanValue.h:262
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3461
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:590
VPSingleDefValue(VPSingleDefRecipe *Def, Value *UV=nullptr, Type *Ty=nullptr)
Construct a VPSingleDefValue. Must only be used by VPSingleDefRecipe.
Definition VPlan.cpp:159
~VPSingleDefValue() override
Definition VPlan.cpp:165
friend class VPSingleDefRecipe
Definition VPlanValue.h:360
This class can be used to assign names to VPValues.
std::string getOrCreateName(const VPValue *V) const
Returns the name assigned to V, if there is one, otherwise try to construct one from the underlying v...
Definition VPlan.cpp:1615
const Module * getModule() const
Returns the module the plan operates on, if any.
void printMetadataAsOperand(raw_ostream &O, const MDNode *N)
Print a reference to metadata node N to O.
Definition VPlan.cpp:1611
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:212
Type * getType() const
Returns the scalar type of this symbolic value.
Definition VPlanValue.h:227
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
void replaceUsesOfWith(VPValue *From, VPValue *To)
Replaces all uses of From in the VPUser with To.
Definition VPlan.cpp:1501
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1513
operand_range operands()
Definition VPlanValue.h:472
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:445
unsigned getNumOperands() const
Definition VPlanValue.h:436
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:139
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:133
bool isDefinedOutsideLoopRegions() const
Returns true if the VPValue is defined outside any loop.
Definition VPlan.cpp:1465
unsigned getVPValueID() const
Definition VPlanValue.h:101
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:120
void printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:1509
void assertNotMaterialized() const
Assert that this VPValue has not been materialized, if it is a VPSymbolicValue.
Definition VPlanValue.h:575
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser *U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1474
bool user_empty() const
Definition VPlanValue.h:161
@ VPVSingleDefValueSC
A symbolic live-in VPValue without IR backing.
Definition VPlanValue.h:85
@ VPVSymbolicSC
A live-in VPValue wrapping an IR Value.
Definition VPlanValue.h:84
@ VPRegionValueSC
A VPValue defined by a multi-def recipe.
Definition VPlanValue.h:87
@ VPVMultiDefValueSC
A VPValue defined by a VPSingleDefRecipe.
Definition VPlanValue.h:86
void dump() const
Dump the value to stderr (for debugging).
Definition VPlan.cpp:99
void print(raw_ostream &OS, VPSlotTracker &Tracker) const
Definition VPlan.cpp:92
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1468
unsigned getNumUsers() const
Definition VPlanValue.h:115
LLVM_DUMP_METHOD void dump()
Definition VPlan.cpp:1327
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4930
LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition VPlan.cpp:1171
friend class VPSlotTracker
Definition VPlan.h:4932
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition VPlan.cpp:1147
VPBasicBlock * getEntry()
Definition VPlan.h:5022
Type * getIndexType() const
The type of the canonical induction variable of the vector loop.
Definition VPlan.h:5362
void setName(const Twine &newName)
Definition VPlan.h:5199
LLVM_ABI_FOR_TEST ~VPlan()
Definition VPlan.cpp:908
bool isExitBlock(VPBlockBase *VPBB)
Returns true if VPBB is an exit block.
Definition VPlan.cpp:926
friend class VPlanPrinter
Definition VPlan.h:4931
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5125
VPIRBasicBlock * createEmptyVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock wrapping IRBB, but do not create VPIRInstructions wrapping the instructions i...
Definition VPlan.cpp:1304
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5263
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5088
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1058
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1040
LLVM_ABI_FOR_TEST bool isOuterLoop() const
Returns true if this VPlan is for an outer loop, i.e., its vector loop region contains a nested loop ...
Definition VPlan.cpp:1083
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5181
void setEntry(VPBasicBlock *VPBB)
Definition VPlan.h:5011
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5286
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1312
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition VPlan.cpp:1177
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5078
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:936
LLVM_ABI_FOR_TEST void print(raw_ostream &O) const
Print this VPlan to O.
Definition VPlan.cpp:1130
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5084
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition VPlan.cpp:1092
LLVM_ABI_FOR_TEST VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition VPlan.cpp:1218
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI std::string EscapeString(const std::string &Label)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
bool match(Val *V, const Pattern &P)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
VPInstruction_match< VPInstruction::BranchOnTwoConds > m_BranchOnTwoConds()
VPInstruction_match< VPInstruction::BranchOnCount > m_BranchOnCount()
auto m_VPValue()
Match an arbitrary VPValue and ignore it.
VPInstruction_match< VPInstruction::BranchOnCond > m_BranchOnCond()
BranchProbability getExecutionProbability(BlockFrequency Freq)
Returns Freq as a BranchProbability, relative to the full mass.
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...
VPInstruction * findCanonicalIVIncrement(VPlan &Plan)
Find the canonical IV increment of Plan's vector loop region.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used by all users.
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
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:846
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
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:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI cl::opt< bool > EnableFSDiscriminator
VPBuilderBase<> VPBuilder
Definition VPlan.h:66
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2334
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:250
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition MathExtras.h:453
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:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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:1769
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.
bool canConstantBeExtended(const APInt *C, Type *NarrowType, TTI::PartialReductionExtendKind ExtKind)
Check if a constant CI can be safely treated as having been extended from a narrower type with the gi...
Definition VPlan.cpp:1821
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, std::optional< unsigned > EstimatedLoopInvocationWeight=std::nullopt)
Set llvm.loop.estimated_trip_count with the value EstimatedTripCount in the loop metadata of L.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
constexpr detail::CastFunc< To > CastTo
Definition Casting.h:884
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:76
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
Struct to hold various analysis needed for cost computations.
uint64_t getCostDivisor(std::optional< VPExecutionFrequency > Freq) const
Definition VPlan.cpp:1934
TargetTransformInfo::OperandValueInfo getOperandInfo(VPValue *V) const
Returns the OperandInfo for V, if it is a live-in.
Definition VPlan.cpp:1832
static bool isFreeScalarIntrinsic(Intrinsic::ID ID)
Returns true if ID is a pseudo intrinsic that is dropped via scalarization rather than widened.
Definition VPlan.cpp:1925
static bool executesAtMostOnce(const VPlan &Plan, ElementCount VF)
Returns true if the vector loop body of Plan is known to execute at most once at VF,...
std::optional< unsigned > NumPredStores
Number of predicated stores in the VPlan, computed on demand.
InstructionCost getScalarizationOverhead(Type *ResultTy, ArrayRef< const VPValue * > Operands, ElementCount VF, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None, bool AlwaysIncludeReplicatingR=false)
Estimate the overhead of scalarizing a recipe with result type ResultTy and Operands with VF.
Definition VPlan.cpp:1849
TargetTransformInfo::TargetCostKind CostKind
VPSlotTracker * getSlotTracker()
Return a VPSlotTracker to re-use for printing, lazily constructing it on first use.
Definition VPlan.cpp:1840
const TargetTransformInfo & TTI
bool useEmulatedMaskMemRefHack(const VPReplicateRecipe *R, ElementCount VF)
Returns true if an artificially high cost for emulated masked memrefs should be used.
Definition VPlan.cpp:1887
const VectorizeOptions & Opts
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:274
Type * getType() const
Returns the type of the underlying IR value.
Definition VPlan.cpp:137
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
LoopInfo * LI
Hold a pointer to LoopInfo to register new basic blocks in the loop.
void fixupHeaderPhis()
Add the backedge (latch) incoming value to the canonical, reduction and first-order recurrence phis i...
Definition VPlan.cpp:328
struct llvm::VPTransformState::DataState Data
struct llvm::VPTransformState::CFGState CFG
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
bool hasScalarValue(const VPValue *Def, VPLane Lane)
Value * get(const VPValue *Def, bool NeedsSingleScalar=false)
Get the generated vector Value for a given VPValue Def if NeedsSingleScalar is false,...
Definition VPlan.cpp:267
const TargetTransformInfo * TTI
Target Transform Info.
VPTransformState(const TargetTransformInfo *TTI, ElementCount VF, LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC, IRBuilderBase &Builder, VPlan *Plan, Loop *CurrentParentLoop)
Definition VPlan.cpp:232
VPlan * Plan
Pointer to the VPlan code is generated for.
void set(const VPValue *Def, Value *V, bool IsScalar=false)
Set the generated vector Value for a given VPValue, if IsScalar is false.
bool hasVectorValue(const VPValue *Def)
VPDominatorTree VPDT
VPlan-based dominator tree.
ElementCount VF
The chosen Vectorization Factor of the loop being vectorized.
AssumptionCache * AC
Hold a pointer to AssumptionCache to register new assumptions after replicating assume calls.
void setDebugLocFrom(DebugLoc DL)
Set the debug location in the builder using the debug location DL.
Definition VPlan.cpp:306
Loop * CurrentParentLoop
The parent loop object for the current scope, or nullptr.