Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp
35266 views
//===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// This is the LLVM vectorization plan. It represents a candidate for10/// vectorization, allowing to plan and optimize how to vectorize a given loop11/// before generating LLVM-IR.12/// The vectorizer uses vectorization plans to estimate the costs of potential13/// candidates and if profitable to execute the desired plan, generating vector14/// LLVM-IR code.15///16//===----------------------------------------------------------------------===//1718#include "VPlan.h"19#include "LoopVectorizationPlanner.h"20#include "VPlanCFG.h"21#include "VPlanDominatorTree.h"22#include "VPlanPatternMatch.h"23#include "llvm/ADT/PostOrderIterator.h"24#include "llvm/ADT/STLExtras.h"25#include "llvm/ADT/SmallVector.h"26#include "llvm/ADT/StringExtras.h"27#include "llvm/ADT/Twine.h"28#include "llvm/Analysis/DomTreeUpdater.h"29#include "llvm/Analysis/LoopInfo.h"30#include "llvm/IR/BasicBlock.h"31#include "llvm/IR/CFG.h"32#include "llvm/IR/IRBuilder.h"33#include "llvm/IR/Instruction.h"34#include "llvm/IR/Instructions.h"35#include "llvm/IR/Type.h"36#include "llvm/IR/Value.h"37#include "llvm/Support/Casting.h"38#include "llvm/Support/CommandLine.h"39#include "llvm/Support/Debug.h"40#include "llvm/Support/GenericDomTreeConstruction.h"41#include "llvm/Support/GraphWriter.h"42#include "llvm/Support/raw_ostream.h"43#include "llvm/Transforms/Utils/BasicBlockUtils.h"44#include "llvm/Transforms/Utils/LoopVersioning.h"45#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"46#include <cassert>47#include <string>48#include <vector>4950using namespace llvm;51using namespace llvm::VPlanPatternMatch;5253namespace llvm {54extern cl::opt<bool> EnableVPlanNativePath;55}5657#define DEBUG_TYPE "vplan"5859#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)60raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {61const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);62VPSlotTracker SlotTracker(63(Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);64V.print(OS, SlotTracker);65return OS;66}67#endif6869Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,70const ElementCount &VF) const {71switch (LaneKind) {72case VPLane::Kind::ScalableLast:73// Lane = RuntimeVF - VF.getKnownMinValue() + Lane74return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),75Builder.getInt32(VF.getKnownMinValue() - Lane));76case VPLane::Kind::First:77return Builder.getInt32(Lane);78}79llvm_unreachable("Unknown lane kind");80}8182VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)83: SubclassID(SC), UnderlyingVal(UV), Def(Def) {84if (Def)85Def->addDefinedValue(this);86}8788VPValue::~VPValue() {89assert(Users.empty() && "trying to delete a VPValue with remaining users");90if (Def)91Def->removeDefinedValue(this);92}9394#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)95void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {96if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))97R->print(OS, "", SlotTracker);98else99printAsOperand(OS, SlotTracker);100}101102void VPValue::dump() const {103const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);104VPSlotTracker SlotTracker(105(Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);106print(dbgs(), SlotTracker);107dbgs() << "\n";108}109110void VPDef::dump() const {111const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);112VPSlotTracker SlotTracker(113(Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);114print(dbgs(), "", SlotTracker);115dbgs() << "\n";116}117#endif118119VPRecipeBase *VPValue::getDefiningRecipe() {120return cast_or_null<VPRecipeBase>(Def);121}122123const VPRecipeBase *VPValue::getDefiningRecipe() const {124return cast_or_null<VPRecipeBase>(Def);125}126127// Get the top-most entry block of \p Start. This is the entry block of the128// containing VPlan. This function is templated to support both const and non-const blocks129template <typename T> static T *getPlanEntry(T *Start) {130T *Next = Start;131T *Current = Start;132while ((Next = Next->getParent()))133Current = Next;134135SmallSetVector<T *, 8> WorkList;136WorkList.insert(Current);137138for (unsigned i = 0; i < WorkList.size(); i++) {139T *Current = WorkList[i];140if (Current->getNumPredecessors() == 0)141return Current;142auto &Predecessors = Current->getPredecessors();143WorkList.insert(Predecessors.begin(), Predecessors.end());144}145146llvm_unreachable("VPlan without any entry node without predecessors");147}148149VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }150151const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }152153/// \return the VPBasicBlock that is the entry of Block, possibly indirectly.154const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {155const VPBlockBase *Block = this;156while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))157Block = Region->getEntry();158return cast<VPBasicBlock>(Block);159}160161VPBasicBlock *VPBlockBase::getEntryBasicBlock() {162VPBlockBase *Block = this;163while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))164Block = Region->getEntry();165return cast<VPBasicBlock>(Block);166}167168void VPBlockBase::setPlan(VPlan *ParentPlan) {169assert(170(ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) &&171"Can only set plan on its entry or preheader block.");172Plan = ParentPlan;173}174175/// \return the VPBasicBlock that is the exit of Block, possibly indirectly.176const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {177const VPBlockBase *Block = this;178while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))179Block = Region->getExiting();180return cast<VPBasicBlock>(Block);181}182183VPBasicBlock *VPBlockBase::getExitingBasicBlock() {184VPBlockBase *Block = this;185while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))186Block = Region->getExiting();187return cast<VPBasicBlock>(Block);188}189190VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {191if (!Successors.empty() || !Parent)192return this;193assert(Parent->getExiting() == this &&194"Block w/o successors not the exiting block of its parent.");195return Parent->getEnclosingBlockWithSuccessors();196}197198VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {199if (!Predecessors.empty() || !Parent)200return this;201assert(Parent->getEntry() == this &&202"Block w/o predecessors not the entry of its parent.");203return Parent->getEnclosingBlockWithPredecessors();204}205206void VPBlockBase::deleteCFG(VPBlockBase *Entry) {207for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry)))208delete Block;209}210211VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {212iterator It = begin();213while (It != end() && It->isPhi())214It++;215return It;216}217218VPTransformState::VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,219DominatorTree *DT, IRBuilderBase &Builder,220InnerLoopVectorizer *ILV, VPlan *Plan,221LLVMContext &Ctx)222: VF(VF), UF(UF), CFG(DT), LI(LI), Builder(Builder), ILV(ILV), Plan(Plan),223LVer(nullptr),224TypeAnalysis(Plan->getCanonicalIV()->getScalarType(), Ctx) {}225226Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {227if (Def->isLiveIn())228return Def->getLiveInIRValue();229230if (hasScalarValue(Def, Instance)) {231return Data232.PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];233}234if (!Instance.Lane.isFirstLane() &&235vputils::isUniformAfterVectorization(Def) &&236hasScalarValue(Def, {Instance.Part, VPLane::getFirstLane()})) {237return Data.PerPartScalars[Def][Instance.Part][0];238}239240assert(hasVectorValue(Def, Instance.Part));241auto *VecPart = Data.PerPartOutput[Def][Instance.Part];242if (!VecPart->getType()->isVectorTy()) {243assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");244return VecPart;245}246// TODO: Cache created scalar values.247Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);248auto *Extract = Builder.CreateExtractElement(VecPart, Lane);249// set(Def, Extract, Instance);250return Extract;251}252253Value *VPTransformState::get(VPValue *Def, unsigned Part, bool NeedsScalar) {254if (NeedsScalar) {255assert((VF.isScalar() || Def->isLiveIn() || hasVectorValue(Def, Part) ||256!vputils::onlyFirstLaneUsed(Def) ||257(hasScalarValue(Def, VPIteration(Part, 0)) &&258Data.PerPartScalars[Def][Part].size() == 1)) &&259"Trying to access a single scalar per part but has multiple scalars "260"per part.");261return get(Def, VPIteration(Part, 0));262}263264// If Values have been set for this Def return the one relevant for \p Part.265if (hasVectorValue(Def, Part))266return Data.PerPartOutput[Def][Part];267268auto GetBroadcastInstrs = [this, Def](Value *V) {269bool SafeToHoist = Def->isDefinedOutsideVectorRegions();270if (VF.isScalar())271return V;272// Place the code for broadcasting invariant variables in the new preheader.273IRBuilder<>::InsertPointGuard Guard(Builder);274if (SafeToHoist) {275BasicBlock *LoopVectorPreHeader = CFG.VPBB2IRBB[cast<VPBasicBlock>(276Plan->getVectorLoopRegion()->getSinglePredecessor())];277if (LoopVectorPreHeader)278Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());279}280281// Place the code for broadcasting invariant variables in the new preheader.282// Broadcast the scalar into all locations in the vector.283Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");284285return Shuf;286};287288if (!hasScalarValue(Def, {Part, 0})) {289assert(Def->isLiveIn() && "expected a live-in");290if (Part != 0)291return get(Def, 0);292Value *IRV = Def->getLiveInIRValue();293Value *B = GetBroadcastInstrs(IRV);294set(Def, B, Part);295return B;296}297298Value *ScalarValue = get(Def, {Part, 0});299// If we aren't vectorizing, we can just copy the scalar map values over300// to the vector map.301if (VF.isScalar()) {302set(Def, ScalarValue, Part);303return ScalarValue;304}305306bool IsUniform = vputils::isUniformAfterVectorization(Def);307308unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;309// Check if there is a scalar value for the selected lane.310if (!hasScalarValue(Def, {Part, LastLane})) {311// At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and312// VPExpandSCEVRecipes can also be uniform.313assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) ||314isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) ||315isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) &&316"unexpected recipe found to be invariant");317IsUniform = true;318LastLane = 0;319}320321auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));322// Set the insert point after the last scalarized instruction or after the323// last PHI, if LastInst is a PHI. This ensures the insertelement sequence324// will directly follow the scalar definitions.325auto OldIP = Builder.saveIP();326auto NewIP =327isa<PHINode>(LastInst)328? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())329: std::next(BasicBlock::iterator(LastInst));330Builder.SetInsertPoint(&*NewIP);331332// However, if we are vectorizing, we need to construct the vector values.333// If the value is known to be uniform after vectorization, we can just334// broadcast the scalar value corresponding to lane zero for each unroll335// iteration. Otherwise, we construct the vector values using336// insertelement instructions. Since the resulting vectors are stored in337// State, we will only generate the insertelements once.338Value *VectorValue = nullptr;339if (IsUniform) {340VectorValue = GetBroadcastInstrs(ScalarValue);341set(Def, VectorValue, Part);342} else {343// Initialize packing with insertelements to start from undef.344assert(!VF.isScalable() && "VF is assumed to be non scalable.");345Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));346set(Def, Undef, Part);347for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)348packScalarIntoVectorValue(Def, {Part, Lane});349VectorValue = get(Def, Part);350}351Builder.restoreIP(OldIP);352return VectorValue;353}354355BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {356VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();357return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];358}359360void VPTransformState::addNewMetadata(Instruction *To,361const Instruction *Orig) {362// If the loop was versioned with memchecks, add the corresponding no-alias363// metadata.364if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))365LVer->annotateInstWithNoAlias(To, Orig);366}367368void VPTransformState::addMetadata(Value *To, Instruction *From) {369// No source instruction to transfer metadata from?370if (!From)371return;372373if (Instruction *ToI = dyn_cast<Instruction>(To)) {374propagateMetadata(ToI, From);375addNewMetadata(ToI, From);376}377}378379void VPTransformState::setDebugLocFrom(DebugLoc DL) {380const DILocation *DIL = DL;381// When a FSDiscriminator is enabled, we don't need to add the multiply382// factors to the discriminators.383if (DIL &&384Builder.GetInsertBlock()385->getParent()386->shouldEmitDebugInfoForProfiling() &&387!EnableFSDiscriminator) {388// FIXME: For scalable vectors, assume vscale=1.389auto NewDIL =390DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());391if (NewDIL)392Builder.SetCurrentDebugLocation(*NewDIL);393else394LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "395<< DIL->getFilename() << " Line: " << DIL->getLine());396} else397Builder.SetCurrentDebugLocation(DIL);398}399400void VPTransformState::packScalarIntoVectorValue(VPValue *Def,401const VPIteration &Instance) {402Value *ScalarInst = get(Def, Instance);403Value *VectorValue = get(Def, Instance.Part);404VectorValue = Builder.CreateInsertElement(405VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF));406set(Def, VectorValue, Instance.Part);407}408409BasicBlock *410VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {411// BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.412// Pred stands for Predessor. Prev stands for Previous - last visited/created.413BasicBlock *PrevBB = CFG.PrevBB;414BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),415PrevBB->getParent(), CFG.ExitBB);416LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');417418// Hook up the new basic block to its predecessors.419for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {420VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();421auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();422BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];423424assert(PredBB && "Predecessor basic-block not found building successor.");425auto *PredBBTerminator = PredBB->getTerminator();426LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');427428auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);429if (isa<UnreachableInst>(PredBBTerminator)) {430assert(PredVPSuccessors.size() == 1 &&431"Predecessor ending w/o branch must have single successor.");432DebugLoc DL = PredBBTerminator->getDebugLoc();433PredBBTerminator->eraseFromParent();434auto *Br = BranchInst::Create(NewBB, PredBB);435Br->setDebugLoc(DL);436} else if (TermBr && !TermBr->isConditional()) {437TermBr->setSuccessor(0, NewBB);438} else {439// Set each forward successor here when it is created, excluding440// backedges. A backward successor is set when the branch is created.441unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;442assert(!TermBr->getSuccessor(idx) &&443"Trying to reset an existing successor block.");444TermBr->setSuccessor(idx, NewBB);445}446CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}});447}448return NewBB;449}450451void VPIRBasicBlock::execute(VPTransformState *State) {452assert(getHierarchicalSuccessors().size() <= 2 &&453"VPIRBasicBlock can have at most two successors at the moment!");454State->Builder.SetInsertPoint(getIRBasicBlock()->getTerminator());455executeRecipes(State, getIRBasicBlock());456if (getSingleSuccessor()) {457assert(isa<UnreachableInst>(getIRBasicBlock()->getTerminator()));458auto *Br = State->Builder.CreateBr(getIRBasicBlock());459Br->setOperand(0, nullptr);460getIRBasicBlock()->getTerminator()->eraseFromParent();461}462463for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {464VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();465BasicBlock *PredBB = State->CFG.VPBB2IRBB[PredVPBB];466assert(PredBB && "Predecessor basic-block not found building successor.");467LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');468469auto *PredBBTerminator = PredBB->getTerminator();470auto *TermBr = cast<BranchInst>(PredBBTerminator);471// Set each forward successor here when it is created, excluding472// backedges. A backward successor is set when the branch is created.473const auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();474unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;475assert(!TermBr->getSuccessor(idx) &&476"Trying to reset an existing successor block.");477TermBr->setSuccessor(idx, IRBB);478State->CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, IRBB}});479}480}481482void VPBasicBlock::execute(VPTransformState *State) {483bool Replica = State->Instance && !State->Instance->isFirstIteration();484VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;485VPBlockBase *SingleHPred = nullptr;486BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.487488auto IsLoopRegion = [](VPBlockBase *BB) {489auto *R = dyn_cast<VPRegionBlock>(BB);490return R && !R->isReplicator();491};492493// 1. Create an IR basic block.494if (PrevVPBB && /* A */495!((SingleHPred = getSingleHierarchicalPredecessor()) &&496SingleHPred->getExitingBasicBlock() == PrevVPBB &&497PrevVPBB->getSingleHierarchicalSuccessor() &&498(SingleHPred->getParent() == getEnclosingLoopRegion() &&499!IsLoopRegion(SingleHPred))) && /* B */500!(Replica && getPredecessors().empty())) { /* C */501// The last IR basic block is reused, as an optimization, in three cases:502// A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;503// B. when the current VPBB has a single (hierarchical) predecessor which504// is PrevVPBB and the latter has a single (hierarchical) successor which505// both are in the same non-replicator region; and506// C. when the current VPBB is an entry of a region replica - where PrevVPBB507// is the exiting VPBB of this region from a previous instance, or the508// predecessor of this region.509510NewBB = createEmptyBasicBlock(State->CFG);511State->Builder.SetInsertPoint(NewBB);512// Temporarily terminate with unreachable until CFG is rewired.513UnreachableInst *Terminator = State->Builder.CreateUnreachable();514// Register NewBB in its loop. In innermost loops its the same for all515// BB's.516if (State->CurrentVectorLoop)517State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);518State->Builder.SetInsertPoint(Terminator);519State->CFG.PrevBB = NewBB;520}521522// 2. Fill the IR basic block with IR instructions.523executeRecipes(State, NewBB);524}525526void VPBasicBlock::dropAllReferences(VPValue *NewValue) {527for (VPRecipeBase &R : Recipes) {528for (auto *Def : R.definedValues())529Def->replaceAllUsesWith(NewValue);530531for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)532R.setOperand(I, NewValue);533}534}535536void VPBasicBlock::executeRecipes(VPTransformState *State, BasicBlock *BB) {537LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()538<< " in BB:" << BB->getName() << '\n');539540State->CFG.VPBB2IRBB[this] = BB;541State->CFG.PrevVPBB = this;542543for (VPRecipeBase &Recipe : Recipes)544Recipe.execute(*State);545546LLVM_DEBUG(dbgs() << "LV: filled BB:" << *BB);547}548549VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {550assert((SplitAt == end() || SplitAt->getParent() == this) &&551"can only split at a position in the same block");552553SmallVector<VPBlockBase *, 2> Succs(successors());554// First, disconnect the current block from its successors.555for (VPBlockBase *Succ : Succs)556VPBlockUtils::disconnectBlocks(this, Succ);557558// Create new empty block after the block to split.559auto *SplitBlock = new VPBasicBlock(getName() + ".split");560VPBlockUtils::insertBlockAfter(SplitBlock, this);561562// Add successors for block to split to new block.563for (VPBlockBase *Succ : Succs)564VPBlockUtils::connectBlocks(SplitBlock, Succ);565566// Finally, move the recipes starting at SplitAt to new block.567for (VPRecipeBase &ToMove :568make_early_inc_range(make_range(SplitAt, this->end())))569ToMove.moveBefore(*SplitBlock, SplitBlock->end());570571return SplitBlock;572}573574VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {575VPRegionBlock *P = getParent();576if (P && P->isReplicator()) {577P = P->getParent();578assert(!cast<VPRegionBlock>(P)->isReplicator() &&579"unexpected nested replicate regions");580}581return P;582}583584static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {585if (VPBB->empty()) {586assert(587VPBB->getNumSuccessors() < 2 &&588"block with multiple successors doesn't have a recipe as terminator");589return false;590}591592const VPRecipeBase *R = &VPBB->back();593bool IsCondBranch = isa<VPBranchOnMaskRecipe>(R) ||594match(R, m_BranchOnCond(m_VPValue())) ||595match(R, m_BranchOnCount(m_VPValue(), m_VPValue()));596(void)IsCondBranch;597598if (VPBB->getNumSuccessors() >= 2 ||599(VPBB->isExiting() && !VPBB->getParent()->isReplicator())) {600assert(IsCondBranch && "block with multiple successors not terminated by "601"conditional branch recipe");602603return true;604}605606assert(607!IsCondBranch &&608"block with 0 or 1 successors terminated by conditional branch recipe");609return false;610}611612VPRecipeBase *VPBasicBlock::getTerminator() {613if (hasConditionalTerminator(this))614return &back();615return nullptr;616}617618const VPRecipeBase *VPBasicBlock::getTerminator() const {619if (hasConditionalTerminator(this))620return &back();621return nullptr;622}623624bool VPBasicBlock::isExiting() const {625return getParent() && getParent()->getExitingBasicBlock() == this;626}627628#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)629void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {630if (getSuccessors().empty()) {631O << Indent << "No successors\n";632} else {633O << Indent << "Successor(s): ";634ListSeparator LS;635for (auto *Succ : getSuccessors())636O << LS << Succ->getName();637O << '\n';638}639}640641void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,642VPSlotTracker &SlotTracker) const {643O << Indent << getName() << ":\n";644645auto RecipeIndent = Indent + " ";646for (const VPRecipeBase &Recipe : *this) {647Recipe.print(O, RecipeIndent, SlotTracker);648O << '\n';649}650651printSuccessors(O, Indent);652}653#endif654655static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry);656657// Clone the CFG for all nodes reachable from \p Entry, this includes cloning658// the blocks and their recipes. Operands of cloned recipes will NOT be updated.659// Remapping of operands must be done separately. Returns a pair with the new660// entry and exiting blocks of the cloned region. If \p Entry isn't part of a661// region, return nullptr for the exiting block.662static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry) {663DenseMap<VPBlockBase *, VPBlockBase *> Old2NewVPBlocks;664VPBlockBase *Exiting = nullptr;665bool InRegion = Entry->getParent();666// First, clone blocks reachable from Entry.667for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {668VPBlockBase *NewBB = BB->clone();669Old2NewVPBlocks[BB] = NewBB;670if (InRegion && BB->getNumSuccessors() == 0) {671assert(!Exiting && "Multiple exiting blocks?");672Exiting = BB;673}674}675assert((!InRegion || Exiting) && "regions must have a single exiting block");676677// Second, update the predecessors & successors of the cloned blocks.678for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {679VPBlockBase *NewBB = Old2NewVPBlocks[BB];680SmallVector<VPBlockBase *> NewPreds;681for (VPBlockBase *Pred : BB->getPredecessors()) {682NewPreds.push_back(Old2NewVPBlocks[Pred]);683}684NewBB->setPredecessors(NewPreds);685SmallVector<VPBlockBase *> NewSuccs;686for (VPBlockBase *Succ : BB->successors()) {687NewSuccs.push_back(Old2NewVPBlocks[Succ]);688}689NewBB->setSuccessors(NewSuccs);690}691692#if !defined(NDEBUG)693// Verify that the order of predecessors and successors matches in the cloned694// version.695for (const auto &[OldBB, NewBB] :696zip(vp_depth_first_shallow(Entry),697vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) {698for (const auto &[OldPred, NewPred] :699zip(OldBB->getPredecessors(), NewBB->getPredecessors()))700assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors");701702for (const auto &[OldSucc, NewSucc] :703zip(OldBB->successors(), NewBB->successors()))704assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors");705}706#endif707708return std::make_pair(Old2NewVPBlocks[Entry],709Exiting ? Old2NewVPBlocks[Exiting] : nullptr);710}711712VPRegionBlock *VPRegionBlock::clone() {713const auto &[NewEntry, NewExiting] = cloneFrom(getEntry());714auto *NewRegion =715new VPRegionBlock(NewEntry, NewExiting, getName(), isReplicator());716for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))717Block->setParent(NewRegion);718return NewRegion;719}720721void VPRegionBlock::dropAllReferences(VPValue *NewValue) {722for (VPBlockBase *Block : vp_depth_first_shallow(Entry))723// Drop all references in VPBasicBlocks and replace all uses with724// DummyValue.725Block->dropAllReferences(NewValue);726}727728void VPRegionBlock::execute(VPTransformState *State) {729ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>730RPOT(Entry);731732if (!isReplicator()) {733// Create and register the new vector loop.734Loop *PrevLoop = State->CurrentVectorLoop;735State->CurrentVectorLoop = State->LI->AllocateLoop();736BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];737Loop *ParentLoop = State->LI->getLoopFor(VectorPH);738739// Insert the new loop into the loop nest and register the new basic blocks740// before calling any utilities such as SCEV that require valid LoopInfo.741if (ParentLoop)742ParentLoop->addChildLoop(State->CurrentVectorLoop);743else744State->LI->addTopLevelLoop(State->CurrentVectorLoop);745746// Visit the VPBlocks connected to "this", starting from it.747for (VPBlockBase *Block : RPOT) {748LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');749Block->execute(State);750}751752State->CurrentVectorLoop = PrevLoop;753return;754}755756assert(!State->Instance && "Replicating a Region with non-null instance.");757758// Enter replicating mode.759State->Instance = VPIteration(0, 0);760761for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {762State->Instance->Part = Part;763assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");764for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;765++Lane) {766State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);767// Visit the VPBlocks connected to \p this, starting from it.768for (VPBlockBase *Block : RPOT) {769LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');770Block->execute(State);771}772}773}774775// Exit replicating mode.776State->Instance.reset();777}778779InstructionCost VPBasicBlock::cost(ElementCount VF, VPCostContext &Ctx) {780InstructionCost Cost = 0;781for (VPRecipeBase &R : Recipes)782Cost += R.cost(VF, Ctx);783return Cost;784}785786InstructionCost VPRegionBlock::cost(ElementCount VF, VPCostContext &Ctx) {787if (!isReplicator()) {788InstructionCost Cost = 0;789for (VPBlockBase *Block : vp_depth_first_shallow(getEntry()))790Cost += Block->cost(VF, Ctx);791InstructionCost BackedgeCost =792Ctx.TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);793LLVM_DEBUG(dbgs() << "Cost of " << BackedgeCost << " for VF " << VF794<< ": vector loop backedge\n");795Cost += BackedgeCost;796return Cost;797}798799// Compute the cost of a replicate region. Replicating isn't supported for800// scalable vectors, return an invalid cost for them.801// TODO: Discard scalable VPlans with replicate recipes earlier after802// construction.803if (VF.isScalable())804return InstructionCost::getInvalid();805806// First compute the cost of the conditionally executed recipes, followed by807// account for the branching cost, except if the mask is a header mask or808// uniform condition.809using namespace llvm::VPlanPatternMatch;810VPBasicBlock *Then = cast<VPBasicBlock>(getEntry()->getSuccessors()[0]);811InstructionCost ThenCost = Then->cost(VF, Ctx);812813// For the scalar case, we may not always execute the original predicated814// block, Thus, scale the block's cost by the probability of executing it.815if (VF.isScalar())816return ThenCost / getReciprocalPredBlockProb();817818return ThenCost;819}820821#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)822void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,823VPSlotTracker &SlotTracker) const {824O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";825auto NewIndent = Indent + " ";826for (auto *BlockBase : vp_depth_first_shallow(Entry)) {827O << '\n';828BlockBase->print(O, NewIndent, SlotTracker);829}830O << Indent << "}\n";831832printSuccessors(O, Indent);833}834#endif835836VPlan::~VPlan() {837for (auto &KV : LiveOuts)838delete KV.second;839LiveOuts.clear();840841if (Entry) {842VPValue DummyValue;843for (VPBlockBase *Block : vp_depth_first_shallow(Entry))844Block->dropAllReferences(&DummyValue);845846VPBlockBase::deleteCFG(Entry);847848Preheader->dropAllReferences(&DummyValue);849delete Preheader;850}851for (VPValue *VPV : VPLiveInsToFree)852delete VPV;853if (BackedgeTakenCount)854delete BackedgeTakenCount;855}856857VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE,858bool RequiresScalarEpilogueCheck,859bool TailFolded, Loop *TheLoop) {860VPIRBasicBlock *Entry = new VPIRBasicBlock(TheLoop->getLoopPreheader());861VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");862auto Plan = std::make_unique<VPlan>(Entry, VecPreheader);863Plan->TripCount =864vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE);865// Create VPRegionBlock, with empty header and latch blocks, to be filled866// during processing later.867VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");868VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");869VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);870auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop",871false /*isReplicator*/);872873VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader);874VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");875VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);876877VPBasicBlock *ScalarPH = new VPBasicBlock("scalar.ph");878if (!RequiresScalarEpilogueCheck) {879VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);880return Plan;881}882883// If needed, add a check in the middle block to see if we have completed884// all of the iterations in the first vector loop. Three cases:885// 1) If (N - N%VF) == N, then we *don't* need to run the remainder.886// Thus if tail is to be folded, we know we don't need to run the887// remainder and we can set the condition to true.888// 2) If we require a scalar epilogue, there is no conditional branch as889// we unconditionally branch to the scalar preheader. Do nothing.890// 3) Otherwise, construct a runtime check.891BasicBlock *IRExitBlock = TheLoop->getUniqueExitBlock();892auto *VPExitBlock = new VPIRBasicBlock(IRExitBlock);893// The connection order corresponds to the operands of the conditional branch.894VPBlockUtils::insertBlockAfter(VPExitBlock, MiddleVPBB);895VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);896897auto *ScalarLatchTerm = TheLoop->getLoopLatch()->getTerminator();898// Here we use the same DebugLoc as the scalar loop latch terminator instead899// of the corresponding compare because they may have ended up with900// different line numbers and we want to avoid awkward line stepping while901// debugging. Eg. if the compare has got a line number inside the loop.902VPBuilder Builder(MiddleVPBB);903VPValue *Cmp =904TailFolded905? Plan->getOrAddLiveIn(ConstantInt::getTrue(906IntegerType::getInt1Ty(TripCount->getType()->getContext())))907: Builder.createICmp(CmpInst::ICMP_EQ, Plan->getTripCount(),908&Plan->getVectorTripCount(),909ScalarLatchTerm->getDebugLoc(), "cmp.n");910Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp},911ScalarLatchTerm->getDebugLoc());912return Plan;913}914915void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,916Value *CanonicalIVStartValue,917VPTransformState &State) {918// Check if the backedge taken count is needed, and if so build it.919if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {920IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());921auto *TCMO = Builder.CreateSub(TripCountV,922ConstantInt::get(TripCountV->getType(), 1),923"trip.count.minus.1");924BackedgeTakenCount->setUnderlyingValue(TCMO);925}926927VectorTripCount.setUnderlyingValue(VectorTripCountV);928929IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());930// FIXME: Model VF * UF computation completely in VPlan.931VFxUF.setUnderlyingValue(932createStepForVF(Builder, TripCountV->getType(), State.VF, State.UF));933934// When vectorizing the epilogue loop, the canonical induction start value935// needs to be changed from zero to the value after the main vector loop.936// FIXME: Improve modeling for canonical IV start values in the epilogue loop.937if (CanonicalIVStartValue) {938VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue);939auto *IV = getCanonicalIV();940assert(all_of(IV->users(),941[](const VPUser *U) {942return isa<VPScalarIVStepsRecipe>(U) ||943isa<VPScalarCastRecipe>(U) ||944isa<VPDerivedIVRecipe>(U) ||945cast<VPInstruction>(U)->getOpcode() ==946Instruction::Add;947}) &&948"the canonical IV should only be used by its increment or "949"ScalarIVSteps when resetting the start value");950IV->setOperand(0, VPV);951}952}953954/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p955/// VPBB are moved to the newly created VPIRBasicBlock. VPBB must have a single956/// predecessor, which is rewired to the new VPIRBasicBlock. All successors of957/// VPBB, if any, are rewired to the new VPIRBasicBlock.958static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB) {959VPIRBasicBlock *IRMiddleVPBB = new VPIRBasicBlock(IRBB);960for (auto &R : make_early_inc_range(*VPBB))961R.moveBefore(*IRMiddleVPBB, IRMiddleVPBB->end());962VPBlockBase *PredVPBB = VPBB->getSinglePredecessor();963VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);964VPBlockUtils::connectBlocks(PredVPBB, IRMiddleVPBB);965for (auto *Succ : to_vector(VPBB->getSuccessors())) {966VPBlockUtils::connectBlocks(IRMiddleVPBB, Succ);967VPBlockUtils::disconnectBlocks(VPBB, Succ);968}969delete VPBB;970}971972/// Generate the code inside the preheader and body of the vectorized loop.973/// Assumes a single pre-header basic-block was created for this. Introduce974/// additional basic-blocks as needed, and fill them all.975void VPlan::execute(VPTransformState *State) {976// Initialize CFG state.977State->CFG.PrevVPBB = nullptr;978State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();979BasicBlock *VectorPreHeader = State->CFG.PrevBB;980State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());981982// Disconnect VectorPreHeader from ExitBB in both the CFG and DT.983cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr);984State->CFG.DTU.applyUpdates(985{{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}});986987// Replace regular VPBB's for the middle and scalar preheader blocks with988// VPIRBasicBlocks wrapping their IR blocks. The IR blocks are created during989// skeleton creation, so we can only create the VPIRBasicBlocks now during990// VPlan execution rather than earlier during VPlan construction.991BasicBlock *MiddleBB = State->CFG.ExitBB;992VPBasicBlock *MiddleVPBB =993cast<VPBasicBlock>(getVectorLoopRegion()->getSingleSuccessor());994// Find the VPBB for the scalar preheader, relying on the current structure995// when creating the middle block and its successrs: if there's a single996// predecessor, it must be the scalar preheader. Otherwise, the second997// successor is the scalar preheader.998BasicBlock *ScalarPh = MiddleBB->getSingleSuccessor();999auto &MiddleSuccs = MiddleVPBB->getSuccessors();1000assert((MiddleSuccs.size() == 1 || MiddleSuccs.size() == 2) &&1001"middle block has unexpected successors");1002VPBasicBlock *ScalarPhVPBB = cast<VPBasicBlock>(1003MiddleSuccs.size() == 1 ? MiddleSuccs[0] : MiddleSuccs[1]);1004assert(!isa<VPIRBasicBlock>(ScalarPhVPBB) &&1005"scalar preheader cannot be wrapped already");1006replaceVPBBWithIRVPBB(ScalarPhVPBB, ScalarPh);1007replaceVPBBWithIRVPBB(MiddleVPBB, MiddleBB);10081009// Disconnect the middle block from its single successor (the scalar loop1010// header) in both the CFG and DT. The branch will be recreated during VPlan1011// execution.1012auto *BrInst = new UnreachableInst(MiddleBB->getContext());1013BrInst->insertBefore(MiddleBB->getTerminator());1014MiddleBB->getTerminator()->eraseFromParent();1015State->CFG.DTU.applyUpdates({{DominatorTree::Delete, MiddleBB, ScalarPh}});10161017// Generate code in the loop pre-header and body.1018for (VPBlockBase *Block : vp_depth_first_shallow(Entry))1019Block->execute(State);10201021VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();1022BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];10231024// Fix the latch value of canonical, reduction and first-order recurrences1025// phis in the vector loop.1026VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();1027for (VPRecipeBase &R : Header->phis()) {1028// Skip phi-like recipes that generate their backedege values themselves.1029if (isa<VPWidenPHIRecipe>(&R))1030continue;10311032if (isa<VPWidenPointerInductionRecipe>(&R) ||1033isa<VPWidenIntOrFpInductionRecipe>(&R)) {1034PHINode *Phi = nullptr;1035if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {1036Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));1037} else {1038auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);1039assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) &&1040"recipe generating only scalars should have been replaced");1041auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));1042Phi = cast<PHINode>(GEP->getPointerOperand());1043}10441045Phi->setIncomingBlock(1, VectorLatchBB);10461047// Move the last step to the end of the latch block. This ensures1048// consistent placement of all induction updates.1049Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));1050Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());1051continue;1052}10531054auto *PhiR = cast<VPHeaderPHIRecipe>(&R);1055// For canonical IV, first-order recurrences and in-order reduction phis,1056// only a single part is generated, which provides the last part from the1057// previous iteration. For non-ordered reductions all UF parts are1058// generated.1059bool SinglePartNeeded =1060isa<VPCanonicalIVPHIRecipe>(PhiR) ||1061isa<VPFirstOrderRecurrencePHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||1062(isa<VPReductionPHIRecipe>(PhiR) &&1063cast<VPReductionPHIRecipe>(PhiR)->isOrdered());1064bool NeedsScalar =1065isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||1066(isa<VPReductionPHIRecipe>(PhiR) &&1067cast<VPReductionPHIRecipe>(PhiR)->isInLoop());1068unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;10691070for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {1071Value *Phi = State->get(PhiR, Part, NeedsScalar);1072Value *Val =1073State->get(PhiR->getBackedgeValue(),1074SinglePartNeeded ? State->UF - 1 : Part, NeedsScalar);1075cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);1076}1077}10781079State->CFG.DTU.flush();1080assert(State->CFG.DTU.getDomTree().verify(1081DominatorTree::VerificationLevel::Fast) &&1082"DT not preserved correctly");1083}10841085InstructionCost VPlan::cost(ElementCount VF, VPCostContext &Ctx) {1086// For now only return the cost of the vector loop region, ignoring any other1087// blocks, like the preheader or middle blocks.1088return getVectorLoopRegion()->cost(VF, Ctx);1089}10901091#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)1092void VPlan::printLiveIns(raw_ostream &O) const {1093VPSlotTracker SlotTracker(this);10941095if (VFxUF.getNumUsers() > 0) {1096O << "\nLive-in ";1097VFxUF.printAsOperand(O, SlotTracker);1098O << " = VF * UF";1099}11001101if (VectorTripCount.getNumUsers() > 0) {1102O << "\nLive-in ";1103VectorTripCount.printAsOperand(O, SlotTracker);1104O << " = vector-trip-count";1105}11061107if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {1108O << "\nLive-in ";1109BackedgeTakenCount->printAsOperand(O, SlotTracker);1110O << " = backedge-taken count";1111}11121113O << "\n";1114if (TripCount->isLiveIn())1115O << "Live-in ";1116TripCount->printAsOperand(O, SlotTracker);1117O << " = original trip-count";1118O << "\n";1119}11201121LLVM_DUMP_METHOD1122void VPlan::print(raw_ostream &O) const {1123VPSlotTracker SlotTracker(this);11241125O << "VPlan '" << getName() << "' {";11261127printLiveIns(O);11281129if (!getPreheader()->empty()) {1130O << "\n";1131getPreheader()->print(O, "", SlotTracker);1132}11331134for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {1135O << '\n';1136Block->print(O, "", SlotTracker);1137}11381139if (!LiveOuts.empty())1140O << "\n";1141for (const auto &KV : LiveOuts) {1142KV.second->print(O, SlotTracker);1143}11441145O << "}\n";1146}11471148std::string VPlan::getName() const {1149std::string Out;1150raw_string_ostream RSO(Out);1151RSO << Name << " for ";1152if (!VFs.empty()) {1153RSO << "VF={" << VFs[0];1154for (ElementCount VF : drop_begin(VFs))1155RSO << "," << VF;1156RSO << "},";1157}11581159if (UFs.empty()) {1160RSO << "UF>=1";1161} else {1162RSO << "UF={" << UFs[0];1163for (unsigned UF : drop_begin(UFs))1164RSO << "," << UF;1165RSO << "}";1166}11671168return Out;1169}11701171LLVM_DUMP_METHOD1172void VPlan::printDOT(raw_ostream &O) const {1173VPlanPrinter Printer(O, *this);1174Printer.dump();1175}11761177LLVM_DUMP_METHOD1178void VPlan::dump() const { print(dbgs()); }1179#endif11801181void VPlan::addLiveOut(PHINode *PN, VPValue *V) {1182assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");1183LiveOuts.insert({PN, new VPLiveOut(PN, V)});1184}11851186static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry,1187DenseMap<VPValue *, VPValue *> &Old2NewVPValues) {1188// Update the operands of all cloned recipes starting at NewEntry. This1189// traverses all reachable blocks. This is done in two steps, to handle cycles1190// in PHI recipes.1191ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>1192OldDeepRPOT(Entry);1193ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>1194NewDeepRPOT(NewEntry);1195// First, collect all mappings from old to new VPValues defined by cloned1196// recipes.1197for (const auto &[OldBB, NewBB] :1198zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT),1199VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) {1200assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() &&1201"blocks must have the same number of recipes");1202for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {1203assert(OldR.getNumOperands() == NewR.getNumOperands() &&1204"recipes must have the same number of operands");1205assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() &&1206"recipes must define the same number of operands");1207for (const auto &[OldV, NewV] :1208zip(OldR.definedValues(), NewR.definedValues()))1209Old2NewVPValues[OldV] = NewV;1210}1211}12121213// Update all operands to use cloned VPValues.1214for (VPBasicBlock *NewBB :1215VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) {1216for (VPRecipeBase &NewR : *NewBB)1217for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {1218VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I));1219NewR.setOperand(I, NewOp);1220}1221}1222}12231224VPlan *VPlan::duplicate() {1225// Clone blocks.1226VPBasicBlock *NewPreheader = Preheader->clone();1227const auto &[NewEntry, __] = cloneFrom(Entry);12281229// Create VPlan, clone live-ins and remap operands in the cloned blocks.1230auto *NewPlan = new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry));1231DenseMap<VPValue *, VPValue *> Old2NewVPValues;1232for (VPValue *OldLiveIn : VPLiveInsToFree) {1233Old2NewVPValues[OldLiveIn] =1234NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue());1235}1236Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;1237Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;1238if (BackedgeTakenCount) {1239NewPlan->BackedgeTakenCount = new VPValue();1240Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount;1241}1242assert(TripCount && "trip count must be set");1243if (TripCount->isLiveIn())1244Old2NewVPValues[TripCount] =1245NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue());1246// else NewTripCount will be created and inserted into Old2NewVPValues when1247// TripCount is cloned. In any case NewPlan->TripCount is updated below.12481249remapOperands(Preheader, NewPreheader, Old2NewVPValues);1250remapOperands(Entry, NewEntry, Old2NewVPValues);12511252// Clone live-outs.1253for (const auto &[_, LO] : LiveOuts)1254NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);12551256// Initialize remaining fields of cloned VPlan.1257NewPlan->VFs = VFs;1258NewPlan->UFs = UFs;1259// TODO: Adjust names.1260NewPlan->Name = Name;1261assert(Old2NewVPValues.contains(TripCount) &&1262"TripCount must have been added to Old2NewVPValues");1263NewPlan->TripCount = Old2NewVPValues[TripCount];1264return NewPlan;1265}12661267#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)12681269Twine VPlanPrinter::getUID(const VPBlockBase *Block) {1270return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +1271Twine(getOrCreateBID(Block));1272}12731274Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {1275const std::string &Name = Block->getName();1276if (!Name.empty())1277return Name;1278return "VPB" + Twine(getOrCreateBID(Block));1279}12801281void VPlanPrinter::dump() {1282Depth = 1;1283bumpIndent(0);1284OS << "digraph VPlan {\n";1285OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";1286if (!Plan.getName().empty())1287OS << "\\n" << DOT::EscapeString(Plan.getName());12881289{1290// Print live-ins.1291std::string Str;1292raw_string_ostream SS(Str);1293Plan.printLiveIns(SS);1294SmallVector<StringRef, 0> Lines;1295StringRef(Str).rtrim('\n').split(Lines, "\n");1296for (auto Line : Lines)1297OS << DOT::EscapeString(Line.str()) << "\\n";1298}12991300OS << "\"]\n";1301OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";1302OS << "edge [fontname=Courier, fontsize=30]\n";1303OS << "compound=true\n";13041305dumpBlock(Plan.getPreheader());13061307for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))1308dumpBlock(Block);13091310OS << "}\n";1311}13121313void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {1314if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))1315dumpBasicBlock(BasicBlock);1316else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))1317dumpRegion(Region);1318else1319llvm_unreachable("Unsupported kind of VPBlock.");1320}13211322void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,1323bool Hidden, const Twine &Label) {1324// Due to "dot" we print an edge between two regions as an edge between the1325// exiting basic block and the entry basic of the respective regions.1326const VPBlockBase *Tail = From->getExitingBasicBlock();1327const VPBlockBase *Head = To->getEntryBasicBlock();1328OS << Indent << getUID(Tail) << " -> " << getUID(Head);1329OS << " [ label=\"" << Label << '\"';1330if (Tail != From)1331OS << " ltail=" << getUID(From);1332if (Head != To)1333OS << " lhead=" << getUID(To);1334if (Hidden)1335OS << "; splines=none";1336OS << "]\n";1337}13381339void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {1340auto &Successors = Block->getSuccessors();1341if (Successors.size() == 1)1342drawEdge(Block, Successors.front(), false, "");1343else if (Successors.size() == 2) {1344drawEdge(Block, Successors.front(), false, "T");1345drawEdge(Block, Successors.back(), false, "F");1346} else {1347unsigned SuccessorNumber = 0;1348for (auto *Successor : Successors)1349drawEdge(Block, Successor, false, Twine(SuccessorNumber++));1350}1351}13521353void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {1354// Implement dot-formatted dump by performing plain-text dump into the1355// temporary storage followed by some post-processing.1356OS << Indent << getUID(BasicBlock) << " [label =\n";1357bumpIndent(1);1358std::string Str;1359raw_string_ostream SS(Str);1360// Use no indentation as we need to wrap the lines into quotes ourselves.1361BasicBlock->print(SS, "", SlotTracker);13621363// We need to process each line of the output separately, so split1364// single-string plain-text dump.1365SmallVector<StringRef, 0> Lines;1366StringRef(Str).rtrim('\n').split(Lines, "\n");13671368auto EmitLine = [&](StringRef Line, StringRef Suffix) {1369OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;1370};13711372// Don't need the "+" after the last line.1373for (auto Line : make_range(Lines.begin(), Lines.end() - 1))1374EmitLine(Line, " +\n");1375EmitLine(Lines.back(), "\n");13761377bumpIndent(-1);1378OS << Indent << "]\n";13791380dumpEdges(BasicBlock);1381}13821383void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {1384OS << Indent << "subgraph " << getUID(Region) << " {\n";1385bumpIndent(1);1386OS << Indent << "fontname=Courier\n"1387<< Indent << "label=\""1388<< DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")1389<< DOT::EscapeString(Region->getName()) << "\"\n";1390// Dump the blocks of the region.1391assert(Region->getEntry() && "Region contains no inner blocks.");1392for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))1393dumpBlock(Block);1394bumpIndent(-1);1395OS << Indent << "}\n";1396dumpEdges(Region);1397}13981399void VPlanIngredient::print(raw_ostream &O) const {1400if (auto *Inst = dyn_cast<Instruction>(V)) {1401if (!Inst->getType()->isVoidTy()) {1402Inst->printAsOperand(O, false);1403O << " = ";1404}1405O << Inst->getOpcodeName() << " ";1406unsigned E = Inst->getNumOperands();1407if (E > 0) {1408Inst->getOperand(0)->printAsOperand(O, false);1409for (unsigned I = 1; I < E; ++I)1410Inst->getOperand(I)->printAsOperand(O << ", ", false);1411}1412} else // !Inst1413V->printAsOperand(O, false);1414}14151416#endif14171418template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);14191420void VPValue::replaceAllUsesWith(VPValue *New) {1421replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; });1422}14231424void VPValue::replaceUsesWithIf(1425VPValue *New,1426llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) {1427// Note that this early exit is required for correctness; the implementation1428// below relies on the number of users for this VPValue to decrease, which1429// isn't the case if this == New.1430if (this == New)1431return;14321433for (unsigned J = 0; J < getNumUsers();) {1434VPUser *User = Users[J];1435bool RemovedUser = false;1436for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {1437if (User->getOperand(I) != this || !ShouldReplace(*User, I))1438continue;14391440RemovedUser = true;1441User->setOperand(I, New);1442}1443// If a user got removed after updating the current user, the next user to1444// update will be moved to the current position, so we only need to1445// increment the index if the number of users did not change.1446if (!RemovedUser)1447J++;1448}1449}14501451#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)1452void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {1453OS << Tracker.getOrCreateName(this);1454}14551456void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {1457interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {1458Op->printAsOperand(O, SlotTracker);1459});1460}1461#endif14621463void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,1464Old2NewTy &Old2New,1465InterleavedAccessInfo &IAI) {1466ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>1467RPOT(Region->getEntry());1468for (VPBlockBase *Base : RPOT) {1469visitBlock(Base, Old2New, IAI);1470}1471}14721473void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,1474InterleavedAccessInfo &IAI) {1475if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {1476for (VPRecipeBase &VPI : *VPBB) {1477if (isa<VPWidenPHIRecipe>(&VPI))1478continue;1479assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");1480auto *VPInst = cast<VPInstruction>(&VPI);14811482auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());1483if (!Inst)1484continue;1485auto *IG = IAI.getInterleaveGroup(Inst);1486if (!IG)1487continue;14881489auto NewIGIter = Old2New.find(IG);1490if (NewIGIter == Old2New.end())1491Old2New[IG] = new InterleaveGroup<VPInstruction>(1492IG->getFactor(), IG->isReverse(), IG->getAlign());14931494if (Inst == IG->getInsertPos())1495Old2New[IG]->setInsertPos(VPInst);14961497InterleaveGroupMap[VPInst] = Old2New[IG];1498InterleaveGroupMap[VPInst]->insertMember(1499VPInst, IG->getIndex(Inst),1500Align(IG->isReverse() ? (-1) * int(IG->getFactor())1501: IG->getFactor()));1502}1503} else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))1504visitRegion(Region, Old2New, IAI);1505else1506llvm_unreachable("Unsupported kind of VPBlock.");1507}15081509VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,1510InterleavedAccessInfo &IAI) {1511Old2NewTy Old2New;1512visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);1513}15141515void VPSlotTracker::assignName(const VPValue *V) {1516assert(!VPValue2Name.contains(V) && "VPValue already has a name!");1517auto *UV = V->getUnderlyingValue();1518if (!UV) {1519VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str();1520NextSlot++;1521return;1522}15231524// Use the name of the underlying Value, wrapped in "ir<>", and versioned by1525// appending ".Number" to the name if there are multiple uses.1526std::string Name;1527raw_string_ostream S(Name);1528UV->printAsOperand(S, false);1529assert(!Name.empty() && "Name cannot be empty.");1530std::string BaseName = (Twine("ir<") + Name + Twine(">")).str();15311532// First assign the base name for V.1533const auto &[A, _] = VPValue2Name.insert({V, BaseName});1534// Integer or FP constants with different types will result in he same string1535// due to stripping types.1536if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV))1537return;15381539// If it is already used by C > 0 other VPValues, increase the version counter1540// C and use it for V.1541const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0});1542if (!UseInserted) {1543C->second++;1544A->second = (BaseName + Twine(".") + Twine(C->second)).str();1545}1546}15471548void VPSlotTracker::assignNames(const VPlan &Plan) {1549if (Plan.VFxUF.getNumUsers() > 0)1550assignName(&Plan.VFxUF);1551assignName(&Plan.VectorTripCount);1552if (Plan.BackedgeTakenCount)1553assignName(Plan.BackedgeTakenCount);1554for (VPValue *LI : Plan.VPLiveInsToFree)1555assignName(LI);1556assignNames(Plan.getPreheader());15571558ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>1559RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));1560for (const VPBasicBlock *VPBB :1561VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))1562assignNames(VPBB);1563}15641565void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) {1566for (const VPRecipeBase &Recipe : *VPBB)1567for (VPValue *Def : Recipe.definedValues())1568assignName(Def);1569}15701571std::string VPSlotTracker::getOrCreateName(const VPValue *V) const {1572std::string Name = VPValue2Name.lookup(V);1573if (!Name.empty())1574return Name;15751576// If no name was assigned, no VPlan was provided when creating the slot1577// tracker or it is not reachable from the provided VPlan. This can happen,1578// e.g. when trying to print a recipe that has not been inserted into a VPlan1579// in a debugger.1580// TODO: Update VPSlotTracker constructor to assign names to recipes &1581// VPValues not associated with a VPlan, instead of constructing names ad-hoc1582// here.1583const VPRecipeBase *DefR = V->getDefiningRecipe();1584(void)DefR;1585assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) &&1586"VPValue defined by a recipe in a VPlan?");15871588// Use the underlying value's name, if there is one.1589if (auto *UV = V->getUnderlyingValue()) {1590std::string Name;1591raw_string_ostream S(Name);1592UV->printAsOperand(S, false);1593return (Twine("ir<") + Name + ">").str();1594}15951596return "<badref>";1597}15981599bool vputils::onlyFirstLaneUsed(const VPValue *Def) {1600return all_of(Def->users(),1601[Def](const VPUser *U) { return U->onlyFirstLaneUsed(Def); });1602}16031604bool vputils::onlyFirstPartUsed(const VPValue *Def) {1605return all_of(Def->users(),1606[Def](const VPUser *U) { return U->onlyFirstPartUsed(Def); });1607}16081609VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,1610ScalarEvolution &SE) {1611if (auto *Expanded = Plan.getSCEVExpansion(Expr))1612return Expanded;1613VPValue *Expanded = nullptr;1614if (auto *E = dyn_cast<SCEVConstant>(Expr))1615Expanded = Plan.getOrAddLiveIn(E->getValue());1616else if (auto *E = dyn_cast<SCEVUnknown>(Expr))1617Expanded = Plan.getOrAddLiveIn(E->getValue());1618else {1619Expanded = new VPExpandSCEVRecipe(Expr, SE);1620Plan.getPreheader()->appendRecipe(Expanded->getDefiningRecipe());1621}1622Plan.addSCEVExpansion(Expr, Expanded);1623return Expanded;1624}16251626bool vputils::isHeaderMask(VPValue *V, VPlan &Plan) {1627if (isa<VPActiveLaneMaskPHIRecipe>(V))1628return true;16291630auto IsWideCanonicalIV = [](VPValue *A) {1631return isa<VPWidenCanonicalIVRecipe>(A) ||1632(isa<VPWidenIntOrFpInductionRecipe>(A) &&1633cast<VPWidenIntOrFpInductionRecipe>(A)->isCanonical());1634};16351636VPValue *A, *B;1637if (match(V, m_ActiveLaneMask(m_VPValue(A), m_VPValue(B))))1638return B == Plan.getTripCount() &&1639(match(A, m_ScalarIVSteps(m_CanonicalIV(), m_SpecificInt(1))) ||1640IsWideCanonicalIV(A));16411642return match(V, m_Binary<Instruction::ICmp>(m_VPValue(A), m_VPValue(B))) &&1643IsWideCanonicalIV(A) && B == Plan.getOrCreateBackedgeTakenCount();1644}164516461647