1 //===- LoopVectorizationPlanner.h - Planner for LoopVectorization ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This file provides a LoopVectorizationPlanner class. 11 /// InnerLoopVectorizer vectorizes loops which contain only one basic 12 /// LoopVectorizationPlanner - drives the vectorization process after having 13 /// passed Legality checks. 14 /// The planner builds and optimizes the Vectorization Plans which record the 15 /// decisions how to vectorize the given loop. In particular, represent the 16 /// control-flow of the vectorized version, the replication of instructions that 17 /// are to be scalarized, and interleave access groups. 18 /// 19 /// Also provides a VPlan-based builder utility analogous to IRBuilder. 20 /// It provides an instruction-level API for generating VPInstructions while 21 /// abstracting away the Recipe manipulation details. 22 //===----------------------------------------------------------------------===// 23 24 #ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H 25 #define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H 26 27 #include "VPlan.h" 28 #include "llvm/ADT/SmallSet.h" 29 #include "llvm/Support/InstructionCost.h" 30 31 namespace llvm { 32 33 class LoopInfo; 34 class DominatorTree; 35 class LoopVectorizationLegality; 36 class LoopVectorizationCostModel; 37 class PredicatedScalarEvolution; 38 class LoopVectorizeHints; 39 class OptimizationRemarkEmitter; 40 class TargetTransformInfo; 41 class TargetLibraryInfo; 42 class VPRecipeBuilder; 43 44 /// VPlan-based builder utility analogous to IRBuilder. 45 class VPBuilder { 46 VPBasicBlock *BB = nullptr; 47 VPBasicBlock::iterator InsertPt = VPBasicBlock::iterator(); 48 49 /// Insert \p VPI in BB at InsertPt if BB is set. 50 VPInstruction *tryInsertInstruction(VPInstruction *VPI) { 51 if (BB) 52 BB->insert(VPI, InsertPt); 53 return VPI; 54 } 55 56 VPInstruction *createInstruction(unsigned Opcode, 57 ArrayRef<VPValue *> Operands, DebugLoc DL, 58 const Twine &Name = "") { 59 return tryInsertInstruction(new VPInstruction(Opcode, Operands, DL, Name)); 60 } 61 62 VPInstruction *createInstruction(unsigned Opcode, 63 std::initializer_list<VPValue *> Operands, 64 DebugLoc DL, const Twine &Name = "") { 65 return createInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL, Name); 66 } 67 68 public: 69 VPBuilder() = default; 70 VPBuilder(VPBasicBlock *InsertBB) { setInsertPoint(InsertBB); } 71 72 /// Clear the insertion point: created instructions will not be inserted into 73 /// a block. 74 void clearInsertionPoint() { 75 BB = nullptr; 76 InsertPt = VPBasicBlock::iterator(); 77 } 78 79 VPBasicBlock *getInsertBlock() const { return BB; } 80 VPBasicBlock::iterator getInsertPoint() const { return InsertPt; } 81 82 /// InsertPoint - A saved insertion point. 83 class VPInsertPoint { 84 VPBasicBlock *Block = nullptr; 85 VPBasicBlock::iterator Point; 86 87 public: 88 /// Creates a new insertion point which doesn't point to anything. 89 VPInsertPoint() = default; 90 91 /// Creates a new insertion point at the given location. 92 VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint) 93 : Block(InsertBlock), Point(InsertPoint) {} 94 95 /// Returns true if this insert point is set. 96 bool isSet() const { return Block != nullptr; } 97 98 VPBasicBlock *getBlock() const { return Block; } 99 VPBasicBlock::iterator getPoint() const { return Point; } 100 }; 101 102 /// Sets the current insert point to a previously-saved location. 103 void restoreIP(VPInsertPoint IP) { 104 if (IP.isSet()) 105 setInsertPoint(IP.getBlock(), IP.getPoint()); 106 else 107 clearInsertionPoint(); 108 } 109 110 /// This specifies that created VPInstructions should be appended to the end 111 /// of the specified block. 112 void setInsertPoint(VPBasicBlock *TheBB) { 113 assert(TheBB && "Attempting to set a null insert point"); 114 BB = TheBB; 115 InsertPt = BB->end(); 116 } 117 118 /// This specifies that created instructions should be inserted at the 119 /// specified point. 120 void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP) { 121 BB = TheBB; 122 InsertPt = IP; 123 } 124 125 /// This specifies that created instructions should be inserted at the 126 /// specified point. 127 void setInsertPoint(VPRecipeBase *IP) { 128 BB = IP->getParent(); 129 InsertPt = IP->getIterator(); 130 } 131 132 /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as 133 /// its underlying Instruction. 134 VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands, 135 Instruction *Inst = nullptr, const Twine &Name = "") { 136 DebugLoc DL; 137 if (Inst) 138 DL = Inst->getDebugLoc(); 139 VPInstruction *NewVPInst = createInstruction(Opcode, Operands, DL, Name); 140 NewVPInst->setUnderlyingValue(Inst); 141 return NewVPInst; 142 } 143 VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands, 144 DebugLoc DL, const Twine &Name = "") { 145 return createInstruction(Opcode, Operands, DL, Name); 146 } 147 148 VPInstruction *createOverflowingOp(unsigned Opcode, 149 std::initializer_list<VPValue *> Operands, 150 VPRecipeWithIRFlags::WrapFlagsTy WrapFlags, 151 DebugLoc DL, const Twine &Name = "") { 152 return tryInsertInstruction( 153 new VPInstruction(Opcode, Operands, WrapFlags, DL, Name)); 154 } 155 VPValue *createNot(VPValue *Operand, DebugLoc DL, const Twine &Name = "") { 156 return createInstruction(VPInstruction::Not, {Operand}, DL, Name); 157 } 158 159 VPValue *createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL, 160 const Twine &Name = "") { 161 return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}, DL, Name); 162 } 163 164 VPValue *createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL, 165 const Twine &Name = "") { 166 return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS}, DL, Name); 167 } 168 169 VPValue *createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, 170 DebugLoc DL, const Twine &Name = "") { 171 return createNaryOp(Instruction::Select, {Cond, TrueVal, FalseVal}, DL, 172 Name); 173 } 174 175 /// Create a new ICmp VPInstruction with predicate \p Pred and operands \p A 176 /// and \p B. 177 /// TODO: add createFCmp when needed. 178 VPValue *createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, 179 DebugLoc DL = {}, const Twine &Name = ""); 180 181 //===--------------------------------------------------------------------===// 182 // RAII helpers. 183 //===--------------------------------------------------------------------===// 184 185 /// RAII object that stores the current insertion point and restores it when 186 /// the object is destroyed. 187 class InsertPointGuard { 188 VPBuilder &Builder; 189 VPBasicBlock *Block; 190 VPBasicBlock::iterator Point; 191 192 public: 193 InsertPointGuard(VPBuilder &B) 194 : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {} 195 196 InsertPointGuard(const InsertPointGuard &) = delete; 197 InsertPointGuard &operator=(const InsertPointGuard &) = delete; 198 199 ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); } 200 }; 201 }; 202 203 /// TODO: The following VectorizationFactor was pulled out of 204 /// LoopVectorizationCostModel class. LV also deals with 205 /// VectorizerParams::VectorizationFactor and VectorizationCostTy. 206 /// We need to streamline them. 207 208 /// Information about vectorization costs. 209 struct VectorizationFactor { 210 /// Vector width with best cost. 211 ElementCount Width; 212 213 /// Cost of the loop with that width. 214 InstructionCost Cost; 215 216 /// Cost of the scalar loop. 217 InstructionCost ScalarCost; 218 219 /// The minimum trip count required to make vectorization profitable, e.g. due 220 /// to runtime checks. 221 ElementCount MinProfitableTripCount; 222 223 VectorizationFactor(ElementCount Width, InstructionCost Cost, 224 InstructionCost ScalarCost) 225 : Width(Width), Cost(Cost), ScalarCost(ScalarCost) {} 226 227 /// Width 1 means no vectorization, cost 0 means uncomputed cost. 228 static VectorizationFactor Disabled() { 229 return {ElementCount::getFixed(1), 0, 0}; 230 } 231 232 bool operator==(const VectorizationFactor &rhs) const { 233 return Width == rhs.Width && Cost == rhs.Cost; 234 } 235 236 bool operator!=(const VectorizationFactor &rhs) const { 237 return !(*this == rhs); 238 } 239 }; 240 241 /// ElementCountComparator creates a total ordering for ElementCount 242 /// for the purposes of using it in a set structure. 243 struct ElementCountComparator { 244 bool operator()(const ElementCount &LHS, const ElementCount &RHS) const { 245 return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) < 246 std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue()); 247 } 248 }; 249 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>; 250 251 /// A class that represents two vectorization factors (initialized with 0 by 252 /// default). One for fixed-width vectorization and one for scalable 253 /// vectorization. This can be used by the vectorizer to choose from a range of 254 /// fixed and/or scalable VFs in order to find the most cost-effective VF to 255 /// vectorize with. 256 struct FixedScalableVFPair { 257 ElementCount FixedVF; 258 ElementCount ScalableVF; 259 260 FixedScalableVFPair() 261 : FixedVF(ElementCount::getFixed(0)), 262 ScalableVF(ElementCount::getScalable(0)) {} 263 FixedScalableVFPair(const ElementCount &Max) : FixedScalableVFPair() { 264 *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max; 265 } 266 FixedScalableVFPair(const ElementCount &FixedVF, 267 const ElementCount &ScalableVF) 268 : FixedVF(FixedVF), ScalableVF(ScalableVF) { 269 assert(!FixedVF.isScalable() && ScalableVF.isScalable() && 270 "Invalid scalable properties"); 271 } 272 273 static FixedScalableVFPair getNone() { return FixedScalableVFPair(); } 274 275 /// \return true if either fixed- or scalable VF is non-zero. 276 explicit operator bool() const { return FixedVF || ScalableVF; } 277 278 /// \return true if either fixed- or scalable VF is a valid vector VF. 279 bool hasVector() const { return FixedVF.isVector() || ScalableVF.isVector(); } 280 }; 281 282 /// Planner drives the vectorization process after having passed 283 /// Legality checks. 284 class LoopVectorizationPlanner { 285 /// The loop that we evaluate. 286 Loop *OrigLoop; 287 288 /// Loop Info analysis. 289 LoopInfo *LI; 290 291 /// The dominator tree. 292 DominatorTree *DT; 293 294 /// Target Library Info. 295 const TargetLibraryInfo *TLI; 296 297 /// Target Transform Info. 298 const TargetTransformInfo &TTI; 299 300 /// The legality analysis. 301 LoopVectorizationLegality *Legal; 302 303 /// The profitability analysis. 304 LoopVectorizationCostModel &CM; 305 306 /// The interleaved access analysis. 307 InterleavedAccessInfo &IAI; 308 309 PredicatedScalarEvolution &PSE; 310 311 const LoopVectorizeHints &Hints; 312 313 OptimizationRemarkEmitter *ORE; 314 315 SmallVector<VPlanPtr, 4> VPlans; 316 317 /// Profitable vector factors. 318 SmallVector<VectorizationFactor, 8> ProfitableVFs; 319 320 /// A builder used to construct the current plan. 321 VPBuilder Builder; 322 323 public: 324 LoopVectorizationPlanner( 325 Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, 326 const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal, 327 LoopVectorizationCostModel &CM, InterleavedAccessInfo &IAI, 328 PredicatedScalarEvolution &PSE, const LoopVectorizeHints &Hints, 329 OptimizationRemarkEmitter *ORE) 330 : OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM), 331 IAI(IAI), PSE(PSE), Hints(Hints), ORE(ORE) {} 332 333 /// Plan how to best vectorize, return the best VF and its cost, or 334 /// std::nullopt if vectorization and interleaving should be avoided up front. 335 std::optional<VectorizationFactor> plan(ElementCount UserVF, unsigned UserIC); 336 337 /// Use the VPlan-native path to plan how to best vectorize, return the best 338 /// VF and its cost. 339 VectorizationFactor planInVPlanNativePath(ElementCount UserVF); 340 341 /// Return the best VPlan for \p VF. 342 VPlan &getBestPlanFor(ElementCount VF) const; 343 344 /// Generate the IR code for the body of the vectorized loop according to the 345 /// best selected \p VF, \p UF and VPlan \p BestPlan. 346 /// TODO: \p IsEpilogueVectorization is needed to avoid issues due to epilogue 347 /// vectorization re-using plans for both the main and epilogue vector loops. 348 /// It should be removed once the re-use issue has been fixed. 349 /// \p ExpandedSCEVs is passed during execution of the plan for epilogue loop 350 /// to re-use expansion results generated during main plan execution. Returns 351 /// a mapping of SCEVs to their expanded IR values. Note that this is a 352 /// temporary workaround needed due to the current epilogue handling. 353 DenseMap<const SCEV *, Value *> 354 executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, 355 InnerLoopVectorizer &LB, DominatorTree *DT, 356 bool IsEpilogueVectorization, 357 const DenseMap<const SCEV *, Value *> *ExpandedSCEVs = nullptr); 358 359 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 360 void printPlans(raw_ostream &O); 361 #endif 362 363 /// Look through the existing plans and return true if we have one with 364 /// vectorization factor \p VF. 365 bool hasPlanWithVF(ElementCount VF) const { 366 return any_of(VPlans, 367 [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); }); 368 } 369 370 /// Test a \p Predicate on a \p Range of VF's. Return the value of applying 371 /// \p Predicate on Range.Start, possibly decreasing Range.End such that the 372 /// returned value holds for the entire \p Range. 373 static bool 374 getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate, 375 VFRange &Range); 376 377 /// \return The most profitable vectorization factor and the cost of that VF 378 /// for vectorizing the epilogue. Returns VectorizationFactor::Disabled if 379 /// epilogue vectorization is not supported for the loop. 380 VectorizationFactor 381 selectEpilogueVectorizationFactor(const ElementCount MaxVF, unsigned IC); 382 383 protected: 384 /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive, 385 /// according to the information gathered by Legal when it checked if it is 386 /// legal to vectorize the loop. 387 void buildVPlans(ElementCount MinVF, ElementCount MaxVF); 388 389 private: 390 /// Build a VPlan according to the information gathered by Legal. \return a 391 /// VPlan for vectorization factors \p Range.Start and up to \p Range.End 392 /// exclusive, possibly decreasing \p Range.End. 393 VPlanPtr buildVPlan(VFRange &Range); 394 395 /// Build a VPlan using VPRecipes according to the information gather by 396 /// Legal. This method is only used for the legacy inner loop vectorizer. 397 /// \p Range's largest included VF is restricted to the maximum VF the 398 /// returned VPlan is valid for. If no VPlan can be built for the input range, 399 /// set the largest included VF to the maximum VF for which no plan could be 400 /// built. 401 VPlanPtr tryToBuildVPlanWithVPRecipes(VFRange &Range); 402 403 /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive, 404 /// according to the information gathered by Legal when it checked if it is 405 /// legal to vectorize the loop. This method creates VPlans using VPRecipes. 406 void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF); 407 408 // Adjust the recipes for reductions. For in-loop reductions the chain of 409 // instructions leading from the loop exit instr to the phi need to be 410 // converted to reductions, with one operand being vector and the other being 411 // the scalar reduction chain. For other reductions, a select is introduced 412 // between the phi and live-out recipes when folding the tail. 413 void adjustRecipesForReductions(VPBasicBlock *LatchVPBB, VPlanPtr &Plan, 414 VPRecipeBuilder &RecipeBuilder, 415 ElementCount MinVF); 416 417 /// \return The most profitable vectorization factor and the cost of that VF. 418 /// This method checks every VF in \p CandidateVFs. 419 VectorizationFactor 420 selectVectorizationFactor(const ElementCountSet &CandidateVFs); 421 422 /// Returns true if the per-lane cost of VectorizationFactor A is lower than 423 /// that of B. 424 bool isMoreProfitable(const VectorizationFactor &A, 425 const VectorizationFactor &B) const; 426 427 /// Determines if we have the infrastructure to vectorize the loop and its 428 /// epilogue, assuming the main loop is vectorized by \p VF. 429 bool isCandidateForEpilogueVectorization(const ElementCount VF) const; 430 }; 431 432 } // namespace llvm 433 434 #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H 435