Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlanHelpers.h
213799 views
//===- VPlanHelpers.h - VPlan-related auxiliary helpers -------------------===//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 file contains the declarations of different VPlan-related auxiliary10/// helpers.11//12//===----------------------------------------------------------------------===//1314#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLANHELPERS_H15#define LLVM_TRANSFORMS_VECTORIZE_VPLANHELPERS_H1617#include "VPlanAnalysis.h"18#include "VPlanDominatorTree.h"19#include "llvm/ADT/DenseMap.h"20#include "llvm/ADT/SmallPtrSet.h"21#include "llvm/ADT/SmallVector.h"22#include "llvm/Analysis/DomTreeUpdater.h"23#include "llvm/Analysis/TargetTransformInfo.h"24#include "llvm/IR/DebugLoc.h"25#include "llvm/IR/ModuleSlotTracker.h"26#include "llvm/Support/InstructionCost.h"2728namespace llvm {2930class AssumptionCache;31class BasicBlock;32class DominatorTree;33class InnerLoopVectorizer;34class IRBuilderBase;35class LoopInfo;36class SCEV;37class Type;38class VPBasicBlock;39class VPRegionBlock;40class VPlan;41class Value;4243/// Returns a calculation for the total number of elements for a given \p VF.44/// For fixed width vectors this value is a constant, whereas for scalable45/// vectors it is an expression determined at runtime.46Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF);4748/// Return a value for Step multiplied by VF.49Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,50int64_t Step);5152/// A helper function that returns how much we should divide the cost of a53/// predicated block by. Typically this is the reciprocal of the block54/// probability, i.e. if we return X we are assuming the predicated block will55/// execute once for every X iterations of the loop header so the block should56/// only contribute 1/X of its cost to the total cost calculation, but when57/// optimizing for code size it will just be 1 as code size costs don't depend58/// on execution probabilities.59///60/// TODO: We should use actual block probability here, if available. Currently,61/// we always assume predicated blocks have a 50% chance of executing.62inline unsigned63getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind) {64return CostKind == TTI::TCK_CodeSize ? 1 : 2;65}6667/// A range of powers-of-2 vectorization factors with fixed start and68/// adjustable end. The range includes start and excludes end, e.g.,:69/// [1, 16) = {1, 2, 4, 8}70struct VFRange {71// A power of 2.72const ElementCount Start;7374// A power of 2. If End <= Start range is empty.75ElementCount End;7677bool isEmpty() const {78return End.getKnownMinValue() <= Start.getKnownMinValue();79}8081VFRange(const ElementCount &Start, const ElementCount &End)82: Start(Start), End(End) {83assert(Start.isScalable() == End.isScalable() &&84"Both Start and End should have the same scalable flag");85assert(isPowerOf2_32(Start.getKnownMinValue()) &&86"Expected Start to be a power of 2");87assert(isPowerOf2_32(End.getKnownMinValue()) &&88"Expected End to be a power of 2");89}9091/// Iterator to iterate over vectorization factors in a VFRange.92class iterator93: public iterator_facade_base<iterator, std::forward_iterator_tag,94ElementCount> {95ElementCount VF;9697public:98iterator(ElementCount VF) : VF(VF) {}99100bool operator==(const iterator &Other) const { return VF == Other.VF; }101102ElementCount operator*() const { return VF; }103104iterator &operator++() {105VF *= 2;106return *this;107}108};109110iterator begin() { return iterator(Start); }111iterator end() {112assert(isPowerOf2_32(End.getKnownMinValue()));113return iterator(End);114}115};116117/// In what follows, the term "input IR" refers to code that is fed into the118/// vectorizer whereas the term "output IR" refers to code that is generated by119/// the vectorizer.120121/// VPLane provides a way to access lanes in both fixed width and scalable122/// vectors, where for the latter the lane index sometimes needs calculating123/// as a runtime expression.124class VPLane {125public:126/// Kind describes how to interpret Lane.127enum class Kind : uint8_t {128/// For First, Lane is the index into the first N elements of a129/// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>.130First,131/// For ScalableLast, Lane is the offset from the start of the last132/// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For133/// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of134/// 1 corresponds to `((vscale - 1) * N) + 1`, etc.135ScalableLast136};137138private:139/// in [0..VF)140unsigned Lane;141142/// Indicates how the Lane should be interpreted, as described above.143Kind LaneKind = Kind::First;144145public:146VPLane(unsigned Lane) : Lane(Lane) {}147VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {}148149static VPLane getFirstLane() { return VPLane(0, VPLane::Kind::First); }150151static VPLane getLaneFromEnd(const ElementCount &VF, unsigned Offset) {152assert(Offset > 0 && Offset <= VF.getKnownMinValue() &&153"trying to extract with invalid offset");154unsigned LaneOffset = VF.getKnownMinValue() - Offset;155Kind LaneKind;156if (VF.isScalable())157// In this case 'LaneOffset' refers to the offset from the start of the158// last subvector with VF.getKnownMinValue() elements.159LaneKind = VPLane::Kind::ScalableLast;160else161LaneKind = VPLane::Kind::First;162return VPLane(LaneOffset, LaneKind);163}164165static VPLane getLastLaneForVF(const ElementCount &VF) {166return getLaneFromEnd(VF, 1);167}168169/// Returns a compile-time known value for the lane index and asserts if the170/// lane can only be calculated at runtime.171unsigned getKnownLane() const {172assert(LaneKind == Kind::First &&173"can only get known lane from the beginning");174return Lane;175}176177/// Returns an expression describing the lane index that can be used at178/// runtime.179Value *getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const;180181/// Returns the Kind of lane offset.182Kind getKind() const { return LaneKind; }183184/// Returns true if this is the first lane of the whole vector.185bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; }186187/// Maps the lane to a cache index based on \p VF.188unsigned mapToCacheIndex(const ElementCount &VF) const {189switch (LaneKind) {190case VPLane::Kind::ScalableLast:191assert(VF.isScalable() && Lane < VF.getKnownMinValue() &&192"ScalableLast can only be used with scalable VFs");193return VF.getKnownMinValue() + Lane;194default:195assert(Lane < VF.getKnownMinValue() &&196"Cannot extract lane larger than VF");197return Lane;198}199}200};201202/// VPTransformState holds information passed down when "executing" a VPlan,203/// needed for generating the output IR.204struct VPTransformState {205VPTransformState(const TargetTransformInfo *TTI, ElementCount VF,206LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC,207IRBuilderBase &Builder, VPlan *Plan, Loop *CurrentParentLoop,208Type *CanonicalIVTy);209/// Target Transform Info.210const TargetTransformInfo *TTI;211212/// The chosen Vectorization Factor of the loop being vectorized.213ElementCount VF;214215/// Hold the index to generate specific scalar instructions. Null indicates216/// that all instances are to be generated, using either scalar or vector217/// instructions.218std::optional<VPLane> Lane;219220struct DataState {221// Each value from the original loop, when vectorized, is represented by a222// vector value in the map.223DenseMap<const VPValue *, Value *> VPV2Vector;224225DenseMap<const VPValue *, SmallVector<Value *, 4>> VPV2Scalars;226} Data;227228/// Get the generated vector Value for a given VPValue \p Def if \p IsScalar229/// is false, otherwise return the generated scalar. \See set.230Value *get(const VPValue *Def, bool IsScalar = false);231232/// Get the generated Value for a given VPValue and given Part and Lane.233Value *get(const VPValue *Def, const VPLane &Lane);234235bool hasVectorValue(const VPValue *Def) {236return Data.VPV2Vector.contains(Def);237}238239bool hasScalarValue(const VPValue *Def, VPLane Lane) {240auto I = Data.VPV2Scalars.find(Def);241if (I == Data.VPV2Scalars.end())242return false;243unsigned CacheIdx = Lane.mapToCacheIndex(VF);244return CacheIdx < I->second.size() && I->second[CacheIdx];245}246247/// Set the generated vector Value for a given VPValue, if \p248/// IsScalar is false. If \p IsScalar is true, set the scalar in lane 0.249void set(const VPValue *Def, Value *V, bool IsScalar = false) {250if (IsScalar) {251set(Def, V, VPLane(0));252return;253}254assert((VF.isScalar() || isVectorizedTy(V->getType())) &&255"scalar values must be stored as (0, 0)");256Data.VPV2Vector[Def] = V;257}258259/// Reset an existing vector value for \p Def and a given \p Part.260void reset(const VPValue *Def, Value *V) {261assert(Data.VPV2Vector.contains(Def) && "need to overwrite existing value");262Data.VPV2Vector[Def] = V;263}264265/// Set the generated scalar \p V for \p Def and the given \p Lane.266void set(const VPValue *Def, Value *V, const VPLane &Lane) {267auto &Scalars = Data.VPV2Scalars[Def];268unsigned CacheIdx = Lane.mapToCacheIndex(VF);269if (Scalars.size() <= CacheIdx)270Scalars.resize(CacheIdx + 1);271assert(!Scalars[CacheIdx] && "should overwrite existing value");272Scalars[CacheIdx] = V;273}274275/// Reset an existing scalar value for \p Def and a given \p Lane.276void reset(const VPValue *Def, Value *V, const VPLane &Lane) {277auto Iter = Data.VPV2Scalars.find(Def);278assert(Iter != Data.VPV2Scalars.end() &&279"need to overwrite existing value");280unsigned CacheIdx = Lane.mapToCacheIndex(VF);281assert(CacheIdx < Iter->second.size() &&282"need to overwrite existing value");283Iter->second[CacheIdx] = V;284}285286/// Set the debug location in the builder using the debug location \p DL.287void setDebugLocFrom(DebugLoc DL);288289/// Insert the scalar value of \p Def at \p Lane into \p Lane of \p WideValue290/// and return the resulting value.291Value *packScalarIntoVectorizedValue(const VPValue *Def, Value *WideValue,292const VPLane &Lane);293294/// Hold state information used when constructing the CFG of the output IR,295/// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.296struct CFGState {297/// The previous VPBasicBlock visited. Initially set to null.298VPBasicBlock *PrevVPBB = nullptr;299300/// The previous IR BasicBlock created or used. Initially set to the new301/// header BasicBlock.302BasicBlock *PrevBB = nullptr;303304/// The last IR BasicBlock in the output IR. Set to the exit block of the305/// vector loop.306BasicBlock *ExitBB = nullptr;307308/// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case309/// of replication, maps the BasicBlock of the last replica created.310SmallDenseMap<const VPBasicBlock *, BasicBlock *> VPBB2IRBB;311312/// Updater for the DominatorTree.313DomTreeUpdater DTU;314315CFGState(DominatorTree *DT)316: DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy) {}317} CFG;318319/// Hold a pointer to LoopInfo to register new basic blocks in the loop.320LoopInfo *LI;321322/// Hold a pointer to AssumptionCache to register new assumptions after323/// replicating assume calls.324AssumptionCache *AC;325326/// Hold a reference to the IRBuilder used to generate output IR code.327IRBuilderBase &Builder;328329/// Pointer to the VPlan code is generated for.330VPlan *Plan;331332/// The parent loop object for the current scope, or nullptr.333Loop *CurrentParentLoop = nullptr;334335/// VPlan-based type analysis.336VPTypeAnalysis TypeAnalysis;337338/// VPlan-based dominator tree.339VPDominatorTree VPDT;340};341342/// Struct to hold various analysis needed for cost computations.343struct VPCostContext {344const TargetTransformInfo &TTI;345const TargetLibraryInfo &TLI;346VPTypeAnalysis Types;347LLVMContext &LLVMCtx;348LoopVectorizationCostModel &CM;349SmallPtrSet<Instruction *, 8> SkipCostComputation;350TargetTransformInfo::TargetCostKind CostKind;351352VPCostContext(const TargetTransformInfo &TTI, const TargetLibraryInfo &TLI,353Type *CanIVTy, LoopVectorizationCostModel &CM,354TargetTransformInfo::TargetCostKind CostKind)355: TTI(TTI), TLI(TLI), Types(CanIVTy), LLVMCtx(CanIVTy->getContext()),356CM(CM), CostKind(CostKind) {}357358/// Return the cost for \p UI with \p VF using the legacy cost model as359/// fallback until computing the cost of all recipes migrates to VPlan.360InstructionCost getLegacyCost(Instruction *UI, ElementCount VF) const;361362/// Return true if the cost for \p UI shouldn't be computed, e.g. because it363/// has already been pre-computed.364bool skipCostComputation(Instruction *UI, bool IsVector) const;365366/// Returns the OperandInfo for \p V, if it is a live-in.367TargetTransformInfo::OperandValueInfo getOperandInfo(VPValue *V) const;368369/// Return true if \p I is considered uniform-after-vectorization in the370/// legacy cost model for \p VF. Only used to check for additional VPlan371/// simplifications.372bool isLegacyUniformAfterVectorization(Instruction *I, ElementCount VF) const;373};374375/// This class can be used to assign names to VPValues. For VPValues without376/// underlying value, assign consecutive numbers and use those as names (wrapped377/// in vp<>). Otherwise, use the name from the underlying value (wrapped in378/// ir<>), appending a .V version number if there are multiple uses of the same379/// name. Allows querying names for VPValues for printing, similar to the380/// ModuleSlotTracker for IR values.381class VPSlotTracker {382/// Keep track of versioned names assigned to VPValues with underlying IR383/// values.384DenseMap<const VPValue *, std::string> VPValue2Name;385/// Keep track of the next number to use to version the base name.386StringMap<unsigned> BaseName2Version;387388/// Number to assign to the next VPValue without underlying value.389unsigned NextSlot = 0;390391/// Lazily created ModuleSlotTracker, used only when unnamed IR instructions392/// require slot tracking.393std::unique_ptr<ModuleSlotTracker> MST;394395void assignName(const VPValue *V);396void assignNames(const VPlan &Plan);397void assignNames(const VPBasicBlock *VPBB);398std::string getName(const Value *V);399400public:401VPSlotTracker(const VPlan *Plan = nullptr) {402if (Plan)403assignNames(*Plan);404}405406/// Returns the name assigned to \p V, if there is one, otherwise try to407/// construct one from the underlying value, if there's one; else return408/// <badref>.409std::string getOrCreateName(const VPValue *V) const;410};411412#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)413/// VPlanPrinter prints a given VPlan to a given output stream. The printing is414/// indented and follows the dot format.415class VPlanPrinter {416raw_ostream &OS;417const VPlan &Plan;418unsigned Depth = 0;419unsigned TabWidth = 2;420std::string Indent;421unsigned BID = 0;422SmallDenseMap<const VPBlockBase *, unsigned> BlockID;423424VPSlotTracker SlotTracker;425426/// Handle indentation.427void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }428429/// Print a given \p Block of the Plan.430void dumpBlock(const VPBlockBase *Block);431432/// Print the information related to the CFG edges going out of a given433/// \p Block, followed by printing the successor blocks themselves.434void dumpEdges(const VPBlockBase *Block);435436/// Print a given \p BasicBlock, including its VPRecipes, followed by printing437/// its successor blocks.438void dumpBasicBlock(const VPBasicBlock *BasicBlock);439440/// Print a given \p Region of the Plan.441void dumpRegion(const VPRegionBlock *Region);442443unsigned getOrCreateBID(const VPBlockBase *Block) {444return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;445}446447Twine getOrCreateName(const VPBlockBase *Block);448449Twine getUID(const VPBlockBase *Block);450451/// Print the information related to a CFG edge between two VPBlockBases.452void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,453const Twine &Label);454455public:456VPlanPrinter(raw_ostream &O, const VPlan &P)457: OS(O), Plan(P), SlotTracker(&P) {}458459LLVM_DUMP_METHOD void dump();460};461#endif462463} // end namespace llvm464465#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H466467468