1 //===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// This file contains the declarations of the Vectorization Plan base classes: 11 /// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual 12 /// VPBlockBase, together implementing a Hierarchical CFG; 13 /// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be 14 /// treated as proper graphs for generic algorithms; 15 /// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained 16 /// within VPBasicBlocks; 17 /// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned 18 /// instruction; 19 /// 5. The VPlan class holding a candidate for vectorization; 20 /// 6. The VPlanPrinter class providing a way to print a plan in dot format; 21 /// These are documented in docs/VectorizationPlan.rst. 22 // 23 //===----------------------------------------------------------------------===// 24 25 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 26 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 27 28 #include "VPlanValue.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/DepthFirstIterator.h" 31 #include "llvm/ADT/GraphTraits.h" 32 #include "llvm/ADT/MapVector.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/SmallBitVector.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallVector.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/ADT/ilist.h" 39 #include "llvm/ADT/ilist_node.h" 40 #include "llvm/Analysis/LoopInfo.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/FMF.h" 44 #include <algorithm> 45 #include <cassert> 46 #include <cstddef> 47 #include <string> 48 49 namespace llvm { 50 51 class BasicBlock; 52 class DominatorTree; 53 class InductionDescriptor; 54 class InnerLoopVectorizer; 55 class IRBuilderBase; 56 class LoopInfo; 57 class raw_ostream; 58 class RecurrenceDescriptor; 59 class Value; 60 class VPBasicBlock; 61 class VPRegionBlock; 62 class VPlan; 63 class VPReplicateRecipe; 64 class VPlanSlp; 65 66 /// Returns a calculation for the total number of elements for a given \p VF. 67 /// For fixed width vectors this value is a constant, whereas for scalable 68 /// vectors it is an expression determined at runtime. 69 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF); 70 71 /// Return a value for Step multiplied by VF. 72 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, 73 int64_t Step); 74 75 /// A range of powers-of-2 vectorization factors with fixed start and 76 /// adjustable end. The range includes start and excludes end, e.g.,: 77 /// [1, 9) = {1, 2, 4, 8} 78 struct VFRange { 79 // A power of 2. 80 const ElementCount Start; 81 82 // Need not be a power of 2. If End <= Start range is empty. 83 ElementCount End; 84 85 bool isEmpty() const { 86 return End.getKnownMinValue() <= Start.getKnownMinValue(); 87 } 88 89 VFRange(const ElementCount &Start, const ElementCount &End) 90 : Start(Start), End(End) { 91 assert(Start.isScalable() == End.isScalable() && 92 "Both Start and End should have the same scalable flag"); 93 assert(isPowerOf2_32(Start.getKnownMinValue()) && 94 "Expected Start to be a power of 2"); 95 } 96 }; 97 98 using VPlanPtr = std::unique_ptr<VPlan>; 99 100 /// In what follows, the term "input IR" refers to code that is fed into the 101 /// vectorizer whereas the term "output IR" refers to code that is generated by 102 /// the vectorizer. 103 104 /// VPLane provides a way to access lanes in both fixed width and scalable 105 /// vectors, where for the latter the lane index sometimes needs calculating 106 /// as a runtime expression. 107 class VPLane { 108 public: 109 /// Kind describes how to interpret Lane. 110 enum class Kind : uint8_t { 111 /// For First, Lane is the index into the first N elements of a 112 /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>. 113 First, 114 /// For ScalableLast, Lane is the offset from the start of the last 115 /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For 116 /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of 117 /// 1 corresponds to `((vscale - 1) * N) + 1`, etc. 118 ScalableLast 119 }; 120 121 private: 122 /// in [0..VF) 123 unsigned Lane; 124 125 /// Indicates how the Lane should be interpreted, as described above. 126 Kind LaneKind; 127 128 public: 129 VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {} 130 131 static VPLane getFirstLane() { return VPLane(0, VPLane::Kind::First); } 132 133 static VPLane getLastLaneForVF(const ElementCount &VF) { 134 unsigned LaneOffset = VF.getKnownMinValue() - 1; 135 Kind LaneKind; 136 if (VF.isScalable()) 137 // In this case 'LaneOffset' refers to the offset from the start of the 138 // last subvector with VF.getKnownMinValue() elements. 139 LaneKind = VPLane::Kind::ScalableLast; 140 else 141 LaneKind = VPLane::Kind::First; 142 return VPLane(LaneOffset, LaneKind); 143 } 144 145 /// Returns a compile-time known value for the lane index and asserts if the 146 /// lane can only be calculated at runtime. 147 unsigned getKnownLane() const { 148 assert(LaneKind == Kind::First); 149 return Lane; 150 } 151 152 /// Returns an expression describing the lane index that can be used at 153 /// runtime. 154 Value *getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const; 155 156 /// Returns the Kind of lane offset. 157 Kind getKind() const { return LaneKind; } 158 159 /// Returns true if this is the first lane of the whole vector. 160 bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; } 161 162 /// Maps the lane to a cache index based on \p VF. 163 unsigned mapToCacheIndex(const ElementCount &VF) const { 164 switch (LaneKind) { 165 case VPLane::Kind::ScalableLast: 166 assert(VF.isScalable() && Lane < VF.getKnownMinValue()); 167 return VF.getKnownMinValue() + Lane; 168 default: 169 assert(Lane < VF.getKnownMinValue()); 170 return Lane; 171 } 172 } 173 174 /// Returns the maxmimum number of lanes that we are able to consider 175 /// caching for \p VF. 176 static unsigned getNumCachedLanes(const ElementCount &VF) { 177 return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1); 178 } 179 }; 180 181 /// VPIteration represents a single point in the iteration space of the output 182 /// (vectorized and/or unrolled) IR loop. 183 struct VPIteration { 184 /// in [0..UF) 185 unsigned Part; 186 187 VPLane Lane; 188 189 VPIteration(unsigned Part, unsigned Lane, 190 VPLane::Kind Kind = VPLane::Kind::First) 191 : Part(Part), Lane(Lane, Kind) {} 192 193 VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {} 194 195 bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); } 196 }; 197 198 /// VPTransformState holds information passed down when "executing" a VPlan, 199 /// needed for generating the output IR. 200 struct VPTransformState { 201 VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI, 202 DominatorTree *DT, IRBuilderBase &Builder, 203 InnerLoopVectorizer *ILV, VPlan *Plan) 204 : VF(VF), UF(UF), LI(LI), DT(DT), Builder(Builder), ILV(ILV), Plan(Plan) { 205 } 206 207 /// The chosen Vectorization and Unroll Factors of the loop being vectorized. 208 ElementCount VF; 209 unsigned UF; 210 211 /// Hold the indices to generate specific scalar instructions. Null indicates 212 /// that all instances are to be generated, using either scalar or vector 213 /// instructions. 214 Optional<VPIteration> Instance; 215 216 struct DataState { 217 /// A type for vectorized values in the new loop. Each value from the 218 /// original loop, when vectorized, is represented by UF vector values in 219 /// the new unrolled loop, where UF is the unroll factor. 220 typedef SmallVector<Value *, 2> PerPartValuesTy; 221 222 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput; 223 224 using ScalarsPerPartValuesTy = SmallVector<SmallVector<Value *, 4>, 2>; 225 DenseMap<VPValue *, ScalarsPerPartValuesTy> PerPartScalars; 226 } Data; 227 228 /// Get the generated Value for a given VPValue and a given Part. Note that 229 /// as some Defs are still created by ILV and managed in its ValueMap, this 230 /// method will delegate the call to ILV in such cases in order to provide 231 /// callers a consistent API. 232 /// \see set. 233 Value *get(VPValue *Def, unsigned Part); 234 235 /// Get the generated Value for a given VPValue and given Part and Lane. 236 Value *get(VPValue *Def, const VPIteration &Instance); 237 238 bool hasVectorValue(VPValue *Def, unsigned Part) { 239 auto I = Data.PerPartOutput.find(Def); 240 return I != Data.PerPartOutput.end() && Part < I->second.size() && 241 I->second[Part]; 242 } 243 244 bool hasAnyVectorValue(VPValue *Def) const { 245 return Data.PerPartOutput.find(Def) != Data.PerPartOutput.end(); 246 } 247 248 bool hasScalarValue(VPValue *Def, VPIteration Instance) { 249 auto I = Data.PerPartScalars.find(Def); 250 if (I == Data.PerPartScalars.end()) 251 return false; 252 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 253 return Instance.Part < I->second.size() && 254 CacheIdx < I->second[Instance.Part].size() && 255 I->second[Instance.Part][CacheIdx]; 256 } 257 258 /// Set the generated Value for a given VPValue and a given Part. 259 void set(VPValue *Def, Value *V, unsigned Part) { 260 if (!Data.PerPartOutput.count(Def)) { 261 DataState::PerPartValuesTy Entry(UF); 262 Data.PerPartOutput[Def] = Entry; 263 } 264 Data.PerPartOutput[Def][Part] = V; 265 } 266 /// Reset an existing vector value for \p Def and a given \p Part. 267 void reset(VPValue *Def, Value *V, unsigned Part) { 268 auto Iter = Data.PerPartOutput.find(Def); 269 assert(Iter != Data.PerPartOutput.end() && 270 "need to overwrite existing value"); 271 Iter->second[Part] = V; 272 } 273 274 /// Set the generated scalar \p V for \p Def and the given \p Instance. 275 void set(VPValue *Def, Value *V, const VPIteration &Instance) { 276 auto Iter = Data.PerPartScalars.insert({Def, {}}); 277 auto &PerPartVec = Iter.first->second; 278 while (PerPartVec.size() <= Instance.Part) 279 PerPartVec.emplace_back(); 280 auto &Scalars = PerPartVec[Instance.Part]; 281 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 282 while (Scalars.size() <= CacheIdx) 283 Scalars.push_back(nullptr); 284 assert(!Scalars[CacheIdx] && "should overwrite existing value"); 285 Scalars[CacheIdx] = V; 286 } 287 288 /// Reset an existing scalar value for \p Def and a given \p Instance. 289 void reset(VPValue *Def, Value *V, const VPIteration &Instance) { 290 auto Iter = Data.PerPartScalars.find(Def); 291 assert(Iter != Data.PerPartScalars.end() && 292 "need to overwrite existing value"); 293 assert(Instance.Part < Iter->second.size() && 294 "need to overwrite existing value"); 295 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF); 296 assert(CacheIdx < Iter->second[Instance.Part].size() && 297 "need to overwrite existing value"); 298 Iter->second[Instance.Part][CacheIdx] = V; 299 } 300 301 /// Hold state information used when constructing the CFG of the output IR, 302 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks. 303 struct CFGState { 304 /// The previous VPBasicBlock visited. Initially set to null. 305 VPBasicBlock *PrevVPBB = nullptr; 306 307 /// The previous IR BasicBlock created or used. Initially set to the new 308 /// header BasicBlock. 309 BasicBlock *PrevBB = nullptr; 310 311 /// The last IR BasicBlock in the output IR. Set to the exit block of the 312 /// vector loop. 313 BasicBlock *ExitBB = nullptr; 314 315 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case 316 /// of replication, maps the BasicBlock of the last replica created. 317 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB; 318 319 CFGState() = default; 320 321 /// Returns the BasicBlock* mapped to the pre-header of the loop region 322 /// containing \p R. 323 BasicBlock *getPreheaderBBFor(VPRecipeBase *R); 324 } CFG; 325 326 /// Hold a pointer to LoopInfo to register new basic blocks in the loop. 327 LoopInfo *LI; 328 329 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop. 330 DominatorTree *DT; 331 332 /// Hold a reference to the IRBuilder used to generate output IR code. 333 IRBuilderBase &Builder; 334 335 VPValue2ValueTy VPValue2Value; 336 337 /// Hold the canonical scalar IV of the vector loop (start=0, step=VF*UF). 338 Value *CanonicalIV = nullptr; 339 340 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods. 341 InnerLoopVectorizer *ILV; 342 343 /// Pointer to the VPlan code is generated for. 344 VPlan *Plan; 345 346 /// Holds recipes that may generate a poison value that is used after 347 /// vectorization, even when their operands are not poison. 348 SmallPtrSet<VPRecipeBase *, 16> MayGeneratePoisonRecipes; 349 350 /// The loop object for the current parent region, or nullptr. 351 Loop *CurrentVectorLoop = nullptr; 352 }; 353 354 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph. 355 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock. 356 class VPBlockBase { 357 friend class VPBlockUtils; 358 359 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast). 360 361 /// An optional name for the block. 362 std::string Name; 363 364 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if 365 /// it is a topmost VPBlockBase. 366 VPRegionBlock *Parent = nullptr; 367 368 /// List of predecessor blocks. 369 SmallVector<VPBlockBase *, 1> Predecessors; 370 371 /// List of successor blocks. 372 SmallVector<VPBlockBase *, 1> Successors; 373 374 /// VPlan containing the block. Can only be set on the entry block of the 375 /// plan. 376 VPlan *Plan = nullptr; 377 378 /// Add \p Successor as the last successor to this block. 379 void appendSuccessor(VPBlockBase *Successor) { 380 assert(Successor && "Cannot add nullptr successor!"); 381 Successors.push_back(Successor); 382 } 383 384 /// Add \p Predecessor as the last predecessor to this block. 385 void appendPredecessor(VPBlockBase *Predecessor) { 386 assert(Predecessor && "Cannot add nullptr predecessor!"); 387 Predecessors.push_back(Predecessor); 388 } 389 390 /// Remove \p Predecessor from the predecessors of this block. 391 void removePredecessor(VPBlockBase *Predecessor) { 392 auto Pos = find(Predecessors, Predecessor); 393 assert(Pos && "Predecessor does not exist"); 394 Predecessors.erase(Pos); 395 } 396 397 /// Remove \p Successor from the successors of this block. 398 void removeSuccessor(VPBlockBase *Successor) { 399 auto Pos = find(Successors, Successor); 400 assert(Pos && "Successor does not exist"); 401 Successors.erase(Pos); 402 } 403 404 protected: 405 VPBlockBase(const unsigned char SC, const std::string &N) 406 : SubclassID(SC), Name(N) {} 407 408 public: 409 /// An enumeration for keeping track of the concrete subclass of VPBlockBase 410 /// that are actually instantiated. Values of this enumeration are kept in the 411 /// SubclassID field of the VPBlockBase objects. They are used for concrete 412 /// type identification. 413 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC }; 414 415 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>; 416 417 virtual ~VPBlockBase() = default; 418 419 const std::string &getName() const { return Name; } 420 421 void setName(const Twine &newName) { Name = newName.str(); } 422 423 /// \return an ID for the concrete type of this object. 424 /// This is used to implement the classof checks. This should not be used 425 /// for any other purpose, as the values may change as LLVM evolves. 426 unsigned getVPBlockID() const { return SubclassID; } 427 428 VPRegionBlock *getParent() { return Parent; } 429 const VPRegionBlock *getParent() const { return Parent; } 430 431 /// \return A pointer to the plan containing the current block. 432 VPlan *getPlan(); 433 const VPlan *getPlan() const; 434 435 /// Sets the pointer of the plan containing the block. The block must be the 436 /// entry block into the VPlan. 437 void setPlan(VPlan *ParentPlan); 438 439 void setParent(VPRegionBlock *P) { Parent = P; } 440 441 /// \return the VPBasicBlock that is the entry of this VPBlockBase, 442 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this 443 /// VPBlockBase is a VPBasicBlock, it is returned. 444 const VPBasicBlock *getEntryBasicBlock() const; 445 VPBasicBlock *getEntryBasicBlock(); 446 447 /// \return the VPBasicBlock that is the exiting this VPBlockBase, 448 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this 449 /// VPBlockBase is a VPBasicBlock, it is returned. 450 const VPBasicBlock *getExitingBasicBlock() const; 451 VPBasicBlock *getExitingBasicBlock(); 452 453 const VPBlocksTy &getSuccessors() const { return Successors; } 454 VPBlocksTy &getSuccessors() { return Successors; } 455 456 iterator_range<VPBlockBase **> successors() { return Successors; } 457 458 const VPBlocksTy &getPredecessors() const { return Predecessors; } 459 VPBlocksTy &getPredecessors() { return Predecessors; } 460 461 /// \return the successor of this VPBlockBase if it has a single successor. 462 /// Otherwise return a null pointer. 463 VPBlockBase *getSingleSuccessor() const { 464 return (Successors.size() == 1 ? *Successors.begin() : nullptr); 465 } 466 467 /// \return the predecessor of this VPBlockBase if it has a single 468 /// predecessor. Otherwise return a null pointer. 469 VPBlockBase *getSinglePredecessor() const { 470 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr); 471 } 472 473 size_t getNumSuccessors() const { return Successors.size(); } 474 size_t getNumPredecessors() const { return Predecessors.size(); } 475 476 /// An Enclosing Block of a block B is any block containing B, including B 477 /// itself. \return the closest enclosing block starting from "this", which 478 /// has successors. \return the root enclosing block if all enclosing blocks 479 /// have no successors. 480 VPBlockBase *getEnclosingBlockWithSuccessors(); 481 482 /// \return the closest enclosing block starting from "this", which has 483 /// predecessors. \return the root enclosing block if all enclosing blocks 484 /// have no predecessors. 485 VPBlockBase *getEnclosingBlockWithPredecessors(); 486 487 /// \return the successors either attached directly to this VPBlockBase or, if 488 /// this VPBlockBase is the exit block of a VPRegionBlock and has no 489 /// successors of its own, search recursively for the first enclosing 490 /// VPRegionBlock that has successors and return them. If no such 491 /// VPRegionBlock exists, return the (empty) successors of the topmost 492 /// VPBlockBase reached. 493 const VPBlocksTy &getHierarchicalSuccessors() { 494 return getEnclosingBlockWithSuccessors()->getSuccessors(); 495 } 496 497 /// \return the hierarchical successor of this VPBlockBase if it has a single 498 /// hierarchical successor. Otherwise return a null pointer. 499 VPBlockBase *getSingleHierarchicalSuccessor() { 500 return getEnclosingBlockWithSuccessors()->getSingleSuccessor(); 501 } 502 503 /// \return the predecessors either attached directly to this VPBlockBase or, 504 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no 505 /// predecessors of its own, search recursively for the first enclosing 506 /// VPRegionBlock that has predecessors and return them. If no such 507 /// VPRegionBlock exists, return the (empty) predecessors of the topmost 508 /// VPBlockBase reached. 509 const VPBlocksTy &getHierarchicalPredecessors() { 510 return getEnclosingBlockWithPredecessors()->getPredecessors(); 511 } 512 513 /// \return the hierarchical predecessor of this VPBlockBase if it has a 514 /// single hierarchical predecessor. Otherwise return a null pointer. 515 VPBlockBase *getSingleHierarchicalPredecessor() { 516 return getEnclosingBlockWithPredecessors()->getSinglePredecessor(); 517 } 518 519 /// Set a given VPBlockBase \p Successor as the single successor of this 520 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor. 521 /// This VPBlockBase must have no successors. 522 void setOneSuccessor(VPBlockBase *Successor) { 523 assert(Successors.empty() && "Setting one successor when others exist."); 524 appendSuccessor(Successor); 525 } 526 527 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two 528 /// successors of this VPBlockBase. This VPBlockBase is not added as 529 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no 530 /// successors. 531 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) { 532 assert(Successors.empty() && "Setting two successors when others exist."); 533 appendSuccessor(IfTrue); 534 appendSuccessor(IfFalse); 535 } 536 537 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase. 538 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added 539 /// as successor of any VPBasicBlock in \p NewPreds. 540 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) { 541 assert(Predecessors.empty() && "Block predecessors already set."); 542 for (auto *Pred : NewPreds) 543 appendPredecessor(Pred); 544 } 545 546 /// Remove all the predecessor of this block. 547 void clearPredecessors() { Predecessors.clear(); } 548 549 /// Remove all the successors of this block. 550 void clearSuccessors() { Successors.clear(); } 551 552 /// The method which generates the output IR that correspond to this 553 /// VPBlockBase, thereby "executing" the VPlan. 554 virtual void execute(struct VPTransformState *State) = 0; 555 556 /// Delete all blocks reachable from a given VPBlockBase, inclusive. 557 static void deleteCFG(VPBlockBase *Entry); 558 559 /// Return true if it is legal to hoist instructions into this block. 560 bool isLegalToHoistInto() { 561 // There are currently no constraints that prevent an instruction to be 562 // hoisted into a VPBlockBase. 563 return true; 564 } 565 566 /// Replace all operands of VPUsers in the block with \p NewValue and also 567 /// replaces all uses of VPValues defined in the block with NewValue. 568 virtual void dropAllReferences(VPValue *NewValue) = 0; 569 570 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 571 void printAsOperand(raw_ostream &OS, bool PrintType) const { 572 OS << getName(); 573 } 574 575 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines 576 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using 577 /// consequtive numbers. 578 /// 579 /// Note that the numbering is applied to the whole VPlan, so printing 580 /// individual blocks is consistent with the whole VPlan printing. 581 virtual void print(raw_ostream &O, const Twine &Indent, 582 VPSlotTracker &SlotTracker) const = 0; 583 584 /// Print plain-text dump of this VPlan to \p O. 585 void print(raw_ostream &O) const { 586 VPSlotTracker SlotTracker(getPlan()); 587 print(O, "", SlotTracker); 588 } 589 590 /// Print the successors of this block to \p O, prefixing all lines with \p 591 /// Indent. 592 void printSuccessors(raw_ostream &O, const Twine &Indent) const; 593 594 /// Dump this VPBlockBase to dbgs(). 595 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 596 #endif 597 }; 598 599 /// A value that is used outside the VPlan. The operand of the user needs to be 600 /// added to the associated LCSSA phi node. 601 class VPLiveOut : public VPUser { 602 PHINode *Phi; 603 604 public: 605 VPLiveOut(PHINode *Phi, VPValue *Op) 606 : VPUser({Op}, VPUser::VPUserID::LiveOut), Phi(Phi) {} 607 608 /// Fixup the wrapped LCSSA phi node in the unique exit block. This simply 609 /// means we need to add the appropriate incoming value from the middle 610 /// block as exiting edges from the scalar epilogue loop (if present) are 611 /// already in place, and we exit the vector loop exclusively to the middle 612 /// block. 613 void fixPhi(VPlan &Plan, VPTransformState &State); 614 615 /// Returns true if the VPLiveOut uses scalars of operand \p Op. 616 bool usesScalars(const VPValue *Op) const override { 617 assert(is_contained(operands(), Op) && 618 "Op must be an operand of the recipe"); 619 return true; 620 } 621 622 PHINode *getPhi() const { return Phi; } 623 }; 624 625 /// VPRecipeBase is a base class modeling a sequence of one or more output IR 626 /// instructions. VPRecipeBase owns the the VPValues it defines through VPDef 627 /// and is responsible for deleting its defined values. Single-value 628 /// VPRecipeBases that also inherit from VPValue must make sure to inherit from 629 /// VPRecipeBase before VPValue. 630 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>, 631 public VPDef, 632 public VPUser { 633 friend VPBasicBlock; 634 friend class VPBlockUtils; 635 636 /// Each VPRecipe belongs to a single VPBasicBlock. 637 VPBasicBlock *Parent = nullptr; 638 639 public: 640 VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands) 641 : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {} 642 643 template <typename IterT> 644 VPRecipeBase(const unsigned char SC, iterator_range<IterT> Operands) 645 : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {} 646 virtual ~VPRecipeBase() = default; 647 648 /// \return the VPBasicBlock which this VPRecipe belongs to. 649 VPBasicBlock *getParent() { return Parent; } 650 const VPBasicBlock *getParent() const { return Parent; } 651 652 /// The method which generates the output IR instructions that correspond to 653 /// this VPRecipe, thereby "executing" the VPlan. 654 virtual void execute(struct VPTransformState &State) = 0; 655 656 /// Insert an unlinked recipe into a basic block immediately before 657 /// the specified recipe. 658 void insertBefore(VPRecipeBase *InsertPos); 659 /// Insert an unlinked recipe into \p BB immediately before the insertion 660 /// point \p IP; 661 void insertBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator IP); 662 663 /// Insert an unlinked Recipe into a basic block immediately after 664 /// the specified Recipe. 665 void insertAfter(VPRecipeBase *InsertPos); 666 667 /// Unlink this recipe from its current VPBasicBlock and insert it into 668 /// the VPBasicBlock that MovePos lives in, right after MovePos. 669 void moveAfter(VPRecipeBase *MovePos); 670 671 /// Unlink this recipe and insert into BB before I. 672 /// 673 /// \pre I is a valid iterator into BB. 674 void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I); 675 676 /// This method unlinks 'this' from the containing basic block, but does not 677 /// delete it. 678 void removeFromParent(); 679 680 /// This method unlinks 'this' from the containing basic block and deletes it. 681 /// 682 /// \returns an iterator pointing to the element after the erased one 683 iplist<VPRecipeBase>::iterator eraseFromParent(); 684 685 /// Returns the underlying instruction, if the recipe is a VPValue or nullptr 686 /// otherwise. 687 Instruction *getUnderlyingInstr() { 688 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 689 } 690 const Instruction *getUnderlyingInstr() const { 691 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 692 } 693 694 /// Method to support type inquiry through isa, cast, and dyn_cast. 695 static inline bool classof(const VPDef *D) { 696 // All VPDefs are also VPRecipeBases. 697 return true; 698 } 699 700 static inline bool classof(const VPUser *U) { 701 return U->getVPUserID() == VPUser::VPUserID::Recipe; 702 } 703 704 /// Returns true if the recipe may have side-effects. 705 bool mayHaveSideEffects() const; 706 707 /// Returns true for PHI-like recipes. 708 bool isPhi() const { 709 return getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC; 710 } 711 712 /// Returns true if the recipe may read from memory. 713 bool mayReadFromMemory() const; 714 715 /// Returns true if the recipe may write to memory. 716 bool mayWriteToMemory() const; 717 718 /// Returns true if the recipe may read from or write to memory. 719 bool mayReadOrWriteMemory() const { 720 return mayReadFromMemory() || mayWriteToMemory(); 721 } 722 }; 723 724 inline bool VPUser::classof(const VPDef *Def) { 725 return Def->getVPDefID() == VPRecipeBase::VPInstructionSC || 726 Def->getVPDefID() == VPRecipeBase::VPWidenSC || 727 Def->getVPDefID() == VPRecipeBase::VPWidenCallSC || 728 Def->getVPDefID() == VPRecipeBase::VPWidenSelectSC || 729 Def->getVPDefID() == VPRecipeBase::VPWidenGEPSC || 730 Def->getVPDefID() == VPRecipeBase::VPBlendSC || 731 Def->getVPDefID() == VPRecipeBase::VPInterleaveSC || 732 Def->getVPDefID() == VPRecipeBase::VPReplicateSC || 733 Def->getVPDefID() == VPRecipeBase::VPReductionSC || 734 Def->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC || 735 Def->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 736 } 737 738 /// This is a concrete Recipe that models a single VPlan-level instruction. 739 /// While as any Recipe it may generate a sequence of IR instructions when 740 /// executed, these instructions would always form a single-def expression as 741 /// the VPInstruction is also a single def-use vertex. 742 class VPInstruction : public VPRecipeBase, public VPValue { 743 friend class VPlanSlp; 744 745 public: 746 /// VPlan opcodes, extending LLVM IR with idiomatics instructions. 747 enum { 748 FirstOrderRecurrenceSplice = 749 Instruction::OtherOpsEnd + 1, // Combines the incoming and previous 750 // values of a first-order recurrence. 751 Not, 752 ICmpULE, 753 SLPLoad, 754 SLPStore, 755 ActiveLaneMask, 756 CanonicalIVIncrement, 757 CanonicalIVIncrementNUW, 758 BranchOnCount, 759 BranchOnCond 760 }; 761 762 private: 763 typedef unsigned char OpcodeTy; 764 OpcodeTy Opcode; 765 FastMathFlags FMF; 766 DebugLoc DL; 767 768 /// Utility method serving execute(): generates a single instance of the 769 /// modeled instruction. 770 void generateInstruction(VPTransformState &State, unsigned Part); 771 772 protected: 773 void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); } 774 775 public: 776 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands, DebugLoc DL) 777 : VPRecipeBase(VPRecipeBase::VPInstructionSC, Operands), 778 VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode), 779 DL(DL) {} 780 781 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands, 782 DebugLoc DL = {}) 783 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL) {} 784 785 /// Method to support type inquiry through isa, cast, and dyn_cast. 786 static inline bool classof(const VPValue *V) { 787 return V->getVPValueID() == VPValue::VPVInstructionSC; 788 } 789 790 VPInstruction *clone() const { 791 SmallVector<VPValue *, 2> Operands(operands()); 792 return new VPInstruction(Opcode, Operands, DL); 793 } 794 795 /// Method to support type inquiry through isa, cast, and dyn_cast. 796 static inline bool classof(const VPDef *R) { 797 return R->getVPDefID() == VPRecipeBase::VPInstructionSC; 798 } 799 800 /// Extra classof implementations to allow directly casting from VPUser -> 801 /// VPInstruction. 802 static inline bool classof(const VPUser *U) { 803 auto *R = dyn_cast<VPRecipeBase>(U); 804 return R && R->getVPDefID() == VPRecipeBase::VPInstructionSC; 805 } 806 static inline bool classof(const VPRecipeBase *R) { 807 return R->getVPDefID() == VPRecipeBase::VPInstructionSC; 808 } 809 810 unsigned getOpcode() const { return Opcode; } 811 812 /// Generate the instruction. 813 /// TODO: We currently execute only per-part unless a specific instance is 814 /// provided. 815 void execute(VPTransformState &State) override; 816 817 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 818 /// Print the VPInstruction to \p O. 819 void print(raw_ostream &O, const Twine &Indent, 820 VPSlotTracker &SlotTracker) const override; 821 822 /// Print the VPInstruction to dbgs() (for debugging). 823 LLVM_DUMP_METHOD void dump() const; 824 #endif 825 826 /// Return true if this instruction may modify memory. 827 bool mayWriteToMemory() const { 828 // TODO: we can use attributes of the called function to rule out memory 829 // modifications. 830 return Opcode == Instruction::Store || Opcode == Instruction::Call || 831 Opcode == Instruction::Invoke || Opcode == SLPStore; 832 } 833 834 bool hasResult() const { 835 // CallInst may or may not have a result, depending on the called function. 836 // Conservatively return calls have results for now. 837 switch (getOpcode()) { 838 case Instruction::Ret: 839 case Instruction::Br: 840 case Instruction::Store: 841 case Instruction::Switch: 842 case Instruction::IndirectBr: 843 case Instruction::Resume: 844 case Instruction::CatchRet: 845 case Instruction::Unreachable: 846 case Instruction::Fence: 847 case Instruction::AtomicRMW: 848 case VPInstruction::BranchOnCond: 849 case VPInstruction::BranchOnCount: 850 return false; 851 default: 852 return true; 853 } 854 } 855 856 /// Set the fast-math flags. 857 void setFastMathFlags(FastMathFlags FMFNew); 858 859 /// Returns true if the recipe only uses the first lane of operand \p Op. 860 bool onlyFirstLaneUsed(const VPValue *Op) const override { 861 assert(is_contained(operands(), Op) && 862 "Op must be an operand of the recipe"); 863 if (getOperand(0) != Op) 864 return false; 865 switch (getOpcode()) { 866 default: 867 return false; 868 case VPInstruction::ActiveLaneMask: 869 case VPInstruction::CanonicalIVIncrement: 870 case VPInstruction::CanonicalIVIncrementNUW: 871 case VPInstruction::BranchOnCount: 872 return true; 873 }; 874 llvm_unreachable("switch should return"); 875 } 876 }; 877 878 /// VPWidenRecipe is a recipe for producing a copy of vector type its 879 /// ingredient. This recipe covers most of the traditional vectorization cases 880 /// where each ingredient transforms into a vectorized version of itself. 881 class VPWidenRecipe : public VPRecipeBase, public VPValue { 882 public: 883 template <typename IterT> 884 VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands) 885 : VPRecipeBase(VPRecipeBase::VPWidenSC, Operands), 886 VPValue(VPValue::VPVWidenSC, &I, this) {} 887 888 ~VPWidenRecipe() override = default; 889 890 /// Method to support type inquiry through isa, cast, and dyn_cast. 891 static inline bool classof(const VPDef *D) { 892 return D->getVPDefID() == VPRecipeBase::VPWidenSC; 893 } 894 static inline bool classof(const VPValue *V) { 895 return V->getVPValueID() == VPValue::VPVWidenSC; 896 } 897 898 /// Produce widened copies of all Ingredients. 899 void execute(VPTransformState &State) override; 900 901 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 902 /// Print the recipe. 903 void print(raw_ostream &O, const Twine &Indent, 904 VPSlotTracker &SlotTracker) const override; 905 #endif 906 }; 907 908 /// A recipe for widening Call instructions. 909 class VPWidenCallRecipe : public VPRecipeBase, public VPValue { 910 911 public: 912 template <typename IterT> 913 VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments) 914 : VPRecipeBase(VPRecipeBase::VPWidenCallSC, CallArguments), 915 VPValue(VPValue::VPVWidenCallSC, &I, this) {} 916 917 ~VPWidenCallRecipe() override = default; 918 919 /// Method to support type inquiry through isa, cast, and dyn_cast. 920 static inline bool classof(const VPDef *D) { 921 return D->getVPDefID() == VPRecipeBase::VPWidenCallSC; 922 } 923 924 /// Produce a widened version of the call instruction. 925 void execute(VPTransformState &State) override; 926 927 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 928 /// Print the recipe. 929 void print(raw_ostream &O, const Twine &Indent, 930 VPSlotTracker &SlotTracker) const override; 931 #endif 932 }; 933 934 /// A recipe for widening select instructions. 935 class VPWidenSelectRecipe : public VPRecipeBase, public VPValue { 936 937 /// Is the condition of the select loop invariant? 938 bool InvariantCond; 939 940 public: 941 template <typename IterT> 942 VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands, 943 bool InvariantCond) 944 : VPRecipeBase(VPRecipeBase::VPWidenSelectSC, Operands), 945 VPValue(VPValue::VPVWidenSelectSC, &I, this), 946 InvariantCond(InvariantCond) {} 947 948 ~VPWidenSelectRecipe() override = default; 949 950 /// Method to support type inquiry through isa, cast, and dyn_cast. 951 static inline bool classof(const VPDef *D) { 952 return D->getVPDefID() == VPRecipeBase::VPWidenSelectSC; 953 } 954 955 /// Produce a widened version of the select instruction. 956 void execute(VPTransformState &State) override; 957 958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 959 /// Print the recipe. 960 void print(raw_ostream &O, const Twine &Indent, 961 VPSlotTracker &SlotTracker) const override; 962 #endif 963 }; 964 965 /// A recipe for handling GEP instructions. 966 class VPWidenGEPRecipe : public VPRecipeBase, public VPValue { 967 bool IsPtrLoopInvariant; 968 SmallBitVector IsIndexLoopInvariant; 969 970 public: 971 template <typename IterT> 972 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands) 973 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 974 VPValue(VPWidenGEPSC, GEP, this), 975 IsIndexLoopInvariant(GEP->getNumIndices(), false) {} 976 977 template <typename IterT> 978 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands, 979 Loop *OrigLoop) 980 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 981 VPValue(VPValue::VPVWidenGEPSC, GEP, this), 982 IsIndexLoopInvariant(GEP->getNumIndices(), false) { 983 IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand()); 984 for (auto Index : enumerate(GEP->indices())) 985 IsIndexLoopInvariant[Index.index()] = 986 OrigLoop->isLoopInvariant(Index.value().get()); 987 } 988 ~VPWidenGEPRecipe() override = default; 989 990 /// Method to support type inquiry through isa, cast, and dyn_cast. 991 static inline bool classof(const VPDef *D) { 992 return D->getVPDefID() == VPRecipeBase::VPWidenGEPSC; 993 } 994 995 /// Generate the gep nodes. 996 void execute(VPTransformState &State) override; 997 998 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 999 /// Print the recipe. 1000 void print(raw_ostream &O, const Twine &Indent, 1001 VPSlotTracker &SlotTracker) const override; 1002 #endif 1003 }; 1004 1005 /// A recipe for handling phi nodes of integer and floating-point inductions, 1006 /// producing their vector values. 1007 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase, public VPValue { 1008 PHINode *IV; 1009 const InductionDescriptor &IndDesc; 1010 bool NeedsScalarIV; 1011 bool NeedsVectorIV; 1012 1013 public: 1014 VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, 1015 const InductionDescriptor &IndDesc, 1016 bool NeedsScalarIV, bool NeedsVectorIV) 1017 : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}), 1018 VPValue(IV, this), IV(IV), IndDesc(IndDesc), 1019 NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {} 1020 1021 VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, 1022 const InductionDescriptor &IndDesc, 1023 TruncInst *Trunc, bool NeedsScalarIV, 1024 bool NeedsVectorIV) 1025 : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}), 1026 VPValue(Trunc, this), IV(IV), IndDesc(IndDesc), 1027 NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {} 1028 1029 ~VPWidenIntOrFpInductionRecipe() override = default; 1030 1031 /// Method to support type inquiry through isa, cast, and dyn_cast. 1032 static inline bool classof(const VPDef *D) { 1033 return D->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC; 1034 } 1035 1036 /// Generate the vectorized and scalarized versions of the phi node as 1037 /// needed by their users. 1038 void execute(VPTransformState &State) override; 1039 1040 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1041 /// Print the recipe. 1042 void print(raw_ostream &O, const Twine &Indent, 1043 VPSlotTracker &SlotTracker) const override; 1044 #endif 1045 1046 /// Returns the start value of the induction. 1047 VPValue *getStartValue() { return getOperand(0); } 1048 const VPValue *getStartValue() const { return getOperand(0); } 1049 1050 /// Returns the step value of the induction. 1051 VPValue *getStepValue() { return getOperand(1); } 1052 const VPValue *getStepValue() const { return getOperand(1); } 1053 1054 /// Returns the first defined value as TruncInst, if it is one or nullptr 1055 /// otherwise. 1056 TruncInst *getTruncInst() { 1057 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 1058 } 1059 const TruncInst *getTruncInst() const { 1060 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 1061 } 1062 1063 PHINode *getPHINode() { return IV; } 1064 1065 /// Returns the induction descriptor for the recipe. 1066 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; } 1067 1068 /// Returns true if the induction is canonical, i.e. starting at 0 and 1069 /// incremented by UF * VF (= the original IV is incremented by 1). 1070 bool isCanonical() const; 1071 1072 /// Returns the scalar type of the induction. 1073 const Type *getScalarType() const { 1074 const TruncInst *TruncI = getTruncInst(); 1075 return TruncI ? TruncI->getType() : IV->getType(); 1076 } 1077 1078 /// Returns true if a scalar phi needs to be created for the induction. 1079 bool needsScalarIV() const { return NeedsScalarIV; } 1080 1081 /// Returns true if a vector phi needs to be created for the induction. 1082 bool needsVectorIV() const { return NeedsVectorIV; } 1083 }; 1084 1085 /// A pure virtual base class for all recipes modeling header phis, including 1086 /// phis for first order recurrences, pointer inductions and reductions. The 1087 /// start value is the first operand of the recipe and the incoming value from 1088 /// the backedge is the second operand. 1089 class VPHeaderPHIRecipe : public VPRecipeBase, public VPValue { 1090 protected: 1091 VPHeaderPHIRecipe(unsigned char VPVID, unsigned char VPDefID, PHINode *Phi, 1092 VPValue *Start = nullptr) 1093 : VPRecipeBase(VPDefID, {}), VPValue(VPVID, Phi, this) { 1094 if (Start) 1095 addOperand(Start); 1096 } 1097 1098 public: 1099 ~VPHeaderPHIRecipe() override = default; 1100 1101 /// Method to support type inquiry through isa, cast, and dyn_cast. 1102 static inline bool classof(const VPRecipeBase *B) { 1103 return B->getVPDefID() == VPRecipeBase::VPCanonicalIVPHISC || 1104 B->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC || 1105 B->getVPDefID() == VPRecipeBase::VPReductionPHISC || 1106 B->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC || 1107 B->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1108 } 1109 static inline bool classof(const VPValue *V) { 1110 return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC || 1111 V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC || 1112 V->getVPValueID() == VPValue::VPVReductionPHISC || 1113 V->getVPValueID() == VPValue::VPVWidenIntOrFpInductionSC || 1114 V->getVPValueID() == VPValue::VPVWidenPHISC; 1115 } 1116 1117 /// Generate the phi nodes. 1118 void execute(VPTransformState &State) override = 0; 1119 1120 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1121 /// Print the recipe. 1122 void print(raw_ostream &O, const Twine &Indent, 1123 VPSlotTracker &SlotTracker) const override = 0; 1124 #endif 1125 1126 /// Returns the start value of the phi, if one is set. 1127 VPValue *getStartValue() { 1128 return getNumOperands() == 0 ? nullptr : getOperand(0); 1129 } 1130 VPValue *getStartValue() const { 1131 return getNumOperands() == 0 ? nullptr : getOperand(0); 1132 } 1133 1134 /// Returns the incoming value from the loop backedge. 1135 VPValue *getBackedgeValue() { 1136 return getOperand(1); 1137 } 1138 1139 /// Returns the backedge value as a recipe. The backedge value is guaranteed 1140 /// to be a recipe. 1141 VPRecipeBase *getBackedgeRecipe() { 1142 return cast<VPRecipeBase>(getBackedgeValue()->getDef()); 1143 } 1144 }; 1145 1146 class VPWidenPointerInductionRecipe : public VPHeaderPHIRecipe { 1147 const InductionDescriptor &IndDesc; 1148 1149 /// SCEV used to expand step. 1150 /// FIXME: move expansion of step to the pre-header, once it is modeled 1151 /// explicitly. 1152 ScalarEvolution &SE; 1153 1154 public: 1155 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p 1156 /// Start. 1157 VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start, 1158 const InductionDescriptor &IndDesc, 1159 ScalarEvolution &SE) 1160 : VPHeaderPHIRecipe(VPVWidenPointerInductionSC, VPWidenPointerInductionSC, 1161 Phi), 1162 IndDesc(IndDesc), SE(SE) { 1163 addOperand(Start); 1164 } 1165 1166 ~VPWidenPointerInductionRecipe() override = default; 1167 1168 /// Method to support type inquiry through isa, cast, and dyn_cast. 1169 static inline bool classof(const VPRecipeBase *B) { 1170 return B->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC; 1171 } 1172 static inline bool classof(const VPHeaderPHIRecipe *R) { 1173 return R->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC; 1174 } 1175 static inline bool classof(const VPValue *V) { 1176 return V->getVPValueID() == VPValue::VPVWidenPointerInductionSC; 1177 } 1178 1179 /// Generate vector values for the pointer induction. 1180 void execute(VPTransformState &State) override; 1181 1182 /// Returns true if only scalar values will be generated. 1183 bool onlyScalarsGenerated(ElementCount VF); 1184 1185 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1186 /// Print the recipe. 1187 void print(raw_ostream &O, const Twine &Indent, 1188 VPSlotTracker &SlotTracker) const override; 1189 #endif 1190 }; 1191 1192 /// A recipe for handling header phis that are widened in the vector loop. 1193 /// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are 1194 /// managed in the recipe directly. 1195 class VPWidenPHIRecipe : public VPHeaderPHIRecipe { 1196 /// List of incoming blocks. Only used in the VPlan native path. 1197 SmallVector<VPBasicBlock *, 2> IncomingBlocks; 1198 1199 public: 1200 /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start. 1201 VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr) 1202 : VPHeaderPHIRecipe(VPVWidenPHISC, VPWidenPHISC, Phi) { 1203 if (Start) 1204 addOperand(Start); 1205 } 1206 1207 ~VPWidenPHIRecipe() override = default; 1208 1209 /// Method to support type inquiry through isa, cast, and dyn_cast. 1210 static inline bool classof(const VPRecipeBase *B) { 1211 return B->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1212 } 1213 static inline bool classof(const VPHeaderPHIRecipe *R) { 1214 return R->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1215 } 1216 static inline bool classof(const VPValue *V) { 1217 return V->getVPValueID() == VPValue::VPVWidenPHISC; 1218 } 1219 1220 /// Generate the phi/select nodes. 1221 void execute(VPTransformState &State) override; 1222 1223 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1224 /// Print the recipe. 1225 void print(raw_ostream &O, const Twine &Indent, 1226 VPSlotTracker &SlotTracker) const override; 1227 #endif 1228 1229 /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi. 1230 void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) { 1231 addOperand(IncomingV); 1232 IncomingBlocks.push_back(IncomingBlock); 1233 } 1234 1235 /// Returns the \p I th incoming VPBasicBlock. 1236 VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; } 1237 1238 /// Returns the \p I th incoming VPValue. 1239 VPValue *getIncomingValue(unsigned I) { return getOperand(I); } 1240 }; 1241 1242 /// A recipe for handling first-order recurrence phis. The start value is the 1243 /// first operand of the recipe and the incoming value from the backedge is the 1244 /// second operand. 1245 struct VPFirstOrderRecurrencePHIRecipe : public VPHeaderPHIRecipe { 1246 VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start) 1247 : VPHeaderPHIRecipe(VPVFirstOrderRecurrencePHISC, 1248 VPFirstOrderRecurrencePHISC, Phi, &Start) {} 1249 1250 /// Method to support type inquiry through isa, cast, and dyn_cast. 1251 static inline bool classof(const VPRecipeBase *R) { 1252 return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC; 1253 } 1254 static inline bool classof(const VPHeaderPHIRecipe *R) { 1255 return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC; 1256 } 1257 static inline bool classof(const VPValue *V) { 1258 return V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC; 1259 } 1260 1261 void execute(VPTransformState &State) override; 1262 1263 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1264 /// Print the recipe. 1265 void print(raw_ostream &O, const Twine &Indent, 1266 VPSlotTracker &SlotTracker) const override; 1267 #endif 1268 }; 1269 1270 /// A recipe for handling reduction phis. The start value is the first operand 1271 /// of the recipe and the incoming value from the backedge is the second 1272 /// operand. 1273 class VPReductionPHIRecipe : public VPHeaderPHIRecipe { 1274 /// Descriptor for the reduction. 1275 const RecurrenceDescriptor &RdxDesc; 1276 1277 /// The phi is part of an in-loop reduction. 1278 bool IsInLoop; 1279 1280 /// The phi is part of an ordered reduction. Requires IsInLoop to be true. 1281 bool IsOrdered; 1282 1283 public: 1284 /// Create a new VPReductionPHIRecipe for the reduction \p Phi described by \p 1285 /// RdxDesc. 1286 VPReductionPHIRecipe(PHINode *Phi, const RecurrenceDescriptor &RdxDesc, 1287 VPValue &Start, bool IsInLoop = false, 1288 bool IsOrdered = false) 1289 : VPHeaderPHIRecipe(VPVReductionPHISC, VPReductionPHISC, Phi, &Start), 1290 RdxDesc(RdxDesc), IsInLoop(IsInLoop), IsOrdered(IsOrdered) { 1291 assert((!IsOrdered || IsInLoop) && "IsOrdered requires IsInLoop"); 1292 } 1293 1294 ~VPReductionPHIRecipe() override = default; 1295 1296 /// Method to support type inquiry through isa, cast, and dyn_cast. 1297 static inline bool classof(const VPRecipeBase *R) { 1298 return R->getVPDefID() == VPRecipeBase::VPReductionPHISC; 1299 } 1300 static inline bool classof(const VPHeaderPHIRecipe *R) { 1301 return R->getVPDefID() == VPRecipeBase::VPReductionPHISC; 1302 } 1303 static inline bool classof(const VPValue *V) { 1304 return V->getVPValueID() == VPValue::VPVReductionPHISC; 1305 } 1306 1307 /// Generate the phi/select nodes. 1308 void execute(VPTransformState &State) override; 1309 1310 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1311 /// Print the recipe. 1312 void print(raw_ostream &O, const Twine &Indent, 1313 VPSlotTracker &SlotTracker) const override; 1314 #endif 1315 1316 const RecurrenceDescriptor &getRecurrenceDescriptor() const { 1317 return RdxDesc; 1318 } 1319 1320 /// Returns true, if the phi is part of an ordered reduction. 1321 bool isOrdered() const { return IsOrdered; } 1322 1323 /// Returns true, if the phi is part of an in-loop reduction. 1324 bool isInLoop() const { return IsInLoop; } 1325 }; 1326 1327 /// A recipe for vectorizing a phi-node as a sequence of mask-based select 1328 /// instructions. 1329 class VPBlendRecipe : public VPRecipeBase, public VPValue { 1330 PHINode *Phi; 1331 1332 public: 1333 /// The blend operation is a User of the incoming values and of their 1334 /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value 1335 /// might be incoming with a full mask for which there is no VPValue. 1336 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands) 1337 : VPRecipeBase(VPBlendSC, Operands), 1338 VPValue(VPValue::VPVBlendSC, Phi, this), Phi(Phi) { 1339 assert(Operands.size() > 0 && 1340 ((Operands.size() == 1) || (Operands.size() % 2 == 0)) && 1341 "Expected either a single incoming value or a positive even number " 1342 "of operands"); 1343 } 1344 1345 /// Method to support type inquiry through isa, cast, and dyn_cast. 1346 static inline bool classof(const VPDef *D) { 1347 return D->getVPDefID() == VPRecipeBase::VPBlendSC; 1348 } 1349 1350 /// Return the number of incoming values, taking into account that a single 1351 /// incoming value has no mask. 1352 unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; } 1353 1354 /// Return incoming value number \p Idx. 1355 VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); } 1356 1357 /// Return mask number \p Idx. 1358 VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); } 1359 1360 /// Generate the phi/select nodes. 1361 void execute(VPTransformState &State) override; 1362 1363 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1364 /// Print the recipe. 1365 void print(raw_ostream &O, const Twine &Indent, 1366 VPSlotTracker &SlotTracker) const override; 1367 #endif 1368 1369 /// Returns true if the recipe only uses the first lane of operand \p Op. 1370 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1371 assert(is_contained(operands(), Op) && 1372 "Op must be an operand of the recipe"); 1373 // Recursing through Blend recipes only, must terminate at header phi's the 1374 // latest. 1375 return all_of(users(), 1376 [this](VPUser *U) { return U->onlyFirstLaneUsed(this); }); 1377 } 1378 }; 1379 1380 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load 1381 /// or stores into one wide load/store and shuffles. The first operand of a 1382 /// VPInterleave recipe is the address, followed by the stored values, followed 1383 /// by an optional mask. 1384 class VPInterleaveRecipe : public VPRecipeBase { 1385 const InterleaveGroup<Instruction> *IG; 1386 1387 bool HasMask = false; 1388 1389 public: 1390 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr, 1391 ArrayRef<VPValue *> StoredValues, VPValue *Mask) 1392 : VPRecipeBase(VPInterleaveSC, {Addr}), IG(IG) { 1393 for (unsigned i = 0; i < IG->getFactor(); ++i) 1394 if (Instruction *I = IG->getMember(i)) { 1395 if (I->getType()->isVoidTy()) 1396 continue; 1397 new VPValue(I, this); 1398 } 1399 1400 for (auto *SV : StoredValues) 1401 addOperand(SV); 1402 if (Mask) { 1403 HasMask = true; 1404 addOperand(Mask); 1405 } 1406 } 1407 ~VPInterleaveRecipe() override = default; 1408 1409 /// Method to support type inquiry through isa, cast, and dyn_cast. 1410 static inline bool classof(const VPDef *D) { 1411 return D->getVPDefID() == VPRecipeBase::VPInterleaveSC; 1412 } 1413 1414 /// Return the address accessed by this recipe. 1415 VPValue *getAddr() const { 1416 return getOperand(0); // Address is the 1st, mandatory operand. 1417 } 1418 1419 /// Return the mask used by this recipe. Note that a full mask is represented 1420 /// by a nullptr. 1421 VPValue *getMask() const { 1422 // Mask is optional and therefore the last, currently 2nd operand. 1423 return HasMask ? getOperand(getNumOperands() - 1) : nullptr; 1424 } 1425 1426 /// Return the VPValues stored by this interleave group. If it is a load 1427 /// interleave group, return an empty ArrayRef. 1428 ArrayRef<VPValue *> getStoredValues() const { 1429 // The first operand is the address, followed by the stored values, followed 1430 // by an optional mask. 1431 return ArrayRef<VPValue *>(op_begin(), getNumOperands()) 1432 .slice(1, getNumStoreOperands()); 1433 } 1434 1435 /// Generate the wide load or store, and shuffles. 1436 void execute(VPTransformState &State) override; 1437 1438 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1439 /// Print the recipe. 1440 void print(raw_ostream &O, const Twine &Indent, 1441 VPSlotTracker &SlotTracker) const override; 1442 #endif 1443 1444 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; } 1445 1446 /// Returns the number of stored operands of this interleave group. Returns 0 1447 /// for load interleave groups. 1448 unsigned getNumStoreOperands() const { 1449 return getNumOperands() - (HasMask ? 2 : 1); 1450 } 1451 1452 /// The recipe only uses the first lane of the address. 1453 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1454 assert(is_contained(operands(), Op) && 1455 "Op must be an operand of the recipe"); 1456 return Op == getAddr() && all_of(getStoredValues(), [Op](VPValue *StoredV) { 1457 return Op != StoredV; 1458 }); 1459 } 1460 }; 1461 1462 /// A recipe to represent inloop reduction operations, performing a reduction on 1463 /// a vector operand into a scalar value, and adding the result to a chain. 1464 /// The Operands are {ChainOp, VecOp, [Condition]}. 1465 class VPReductionRecipe : public VPRecipeBase, public VPValue { 1466 /// The recurrence decriptor for the reduction in question. 1467 const RecurrenceDescriptor *RdxDesc; 1468 /// Pointer to the TTI, needed to create the target reduction 1469 const TargetTransformInfo *TTI; 1470 1471 public: 1472 VPReductionRecipe(const RecurrenceDescriptor *R, Instruction *I, 1473 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, 1474 const TargetTransformInfo *TTI) 1475 : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}), 1476 VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) { 1477 if (CondOp) 1478 addOperand(CondOp); 1479 } 1480 1481 ~VPReductionRecipe() override = default; 1482 1483 /// Method to support type inquiry through isa, cast, and dyn_cast. 1484 static inline bool classof(const VPValue *V) { 1485 return V->getVPValueID() == VPValue::VPVReductionSC; 1486 } 1487 1488 /// Generate the reduction in the loop 1489 void execute(VPTransformState &State) override; 1490 1491 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1492 /// Print the recipe. 1493 void print(raw_ostream &O, const Twine &Indent, 1494 VPSlotTracker &SlotTracker) const override; 1495 #endif 1496 1497 /// The VPValue of the scalar Chain being accumulated. 1498 VPValue *getChainOp() const { return getOperand(0); } 1499 /// The VPValue of the vector value to be reduced. 1500 VPValue *getVecOp() const { return getOperand(1); } 1501 /// The VPValue of the condition for the block. 1502 VPValue *getCondOp() const { 1503 return getNumOperands() > 2 ? getOperand(2) : nullptr; 1504 } 1505 }; 1506 1507 /// VPReplicateRecipe replicates a given instruction producing multiple scalar 1508 /// copies of the original scalar type, one per lane, instead of producing a 1509 /// single copy of widened type for all lanes. If the instruction is known to be 1510 /// uniform only one copy, per lane zero, will be generated. 1511 class VPReplicateRecipe : public VPRecipeBase, public VPValue { 1512 /// Indicator if only a single replica per lane is needed. 1513 bool IsUniform; 1514 1515 /// Indicator if the replicas are also predicated. 1516 bool IsPredicated; 1517 1518 /// Indicator if the scalar values should also be packed into a vector. 1519 bool AlsoPack; 1520 1521 public: 1522 template <typename IterT> 1523 VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands, 1524 bool IsUniform, bool IsPredicated = false) 1525 : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this), 1526 IsUniform(IsUniform), IsPredicated(IsPredicated) { 1527 // Retain the previous behavior of predicateInstructions(), where an 1528 // insert-element of a predicated instruction got hoisted into the 1529 // predicated basic block iff it was its only user. This is achieved by 1530 // having predicated instructions also pack their values into a vector by 1531 // default unless they have a replicated user which uses their scalar value. 1532 AlsoPack = IsPredicated && !I->use_empty(); 1533 } 1534 1535 ~VPReplicateRecipe() override = default; 1536 1537 /// Method to support type inquiry through isa, cast, and dyn_cast. 1538 static inline bool classof(const VPDef *D) { 1539 return D->getVPDefID() == VPRecipeBase::VPReplicateSC; 1540 } 1541 1542 static inline bool classof(const VPValue *V) { 1543 return V->getVPValueID() == VPValue::VPVReplicateSC; 1544 } 1545 1546 /// Generate replicas of the desired Ingredient. Replicas will be generated 1547 /// for all parts and lanes unless a specific part and lane are specified in 1548 /// the \p State. 1549 void execute(VPTransformState &State) override; 1550 1551 void setAlsoPack(bool Pack) { AlsoPack = Pack; } 1552 1553 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1554 /// Print the recipe. 1555 void print(raw_ostream &O, const Twine &Indent, 1556 VPSlotTracker &SlotTracker) const override; 1557 #endif 1558 1559 bool isUniform() const { return IsUniform; } 1560 1561 bool isPacked() const { return AlsoPack; } 1562 1563 bool isPredicated() const { return IsPredicated; } 1564 1565 /// Returns true if the recipe only uses the first lane of operand \p Op. 1566 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1567 assert(is_contained(operands(), Op) && 1568 "Op must be an operand of the recipe"); 1569 return isUniform(); 1570 } 1571 1572 /// Returns true if the recipe uses scalars of operand \p Op. 1573 bool usesScalars(const VPValue *Op) const override { 1574 assert(is_contained(operands(), Op) && 1575 "Op must be an operand of the recipe"); 1576 return true; 1577 } 1578 }; 1579 1580 /// A recipe for generating conditional branches on the bits of a mask. 1581 class VPBranchOnMaskRecipe : public VPRecipeBase { 1582 public: 1583 VPBranchOnMaskRecipe(VPValue *BlockInMask) 1584 : VPRecipeBase(VPBranchOnMaskSC, {}) { 1585 if (BlockInMask) // nullptr means all-one mask. 1586 addOperand(BlockInMask); 1587 } 1588 1589 /// Method to support type inquiry through isa, cast, and dyn_cast. 1590 static inline bool classof(const VPDef *D) { 1591 return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC; 1592 } 1593 1594 /// Generate the extraction of the appropriate bit from the block mask and the 1595 /// conditional branch. 1596 void execute(VPTransformState &State) override; 1597 1598 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1599 /// Print the recipe. 1600 void print(raw_ostream &O, const Twine &Indent, 1601 VPSlotTracker &SlotTracker) const override { 1602 O << Indent << "BRANCH-ON-MASK "; 1603 if (VPValue *Mask = getMask()) 1604 Mask->printAsOperand(O, SlotTracker); 1605 else 1606 O << " All-One"; 1607 } 1608 #endif 1609 1610 /// Return the mask used by this recipe. Note that a full mask is represented 1611 /// by a nullptr. 1612 VPValue *getMask() const { 1613 assert(getNumOperands() <= 1 && "should have either 0 or 1 operands"); 1614 // Mask is optional. 1615 return getNumOperands() == 1 ? getOperand(0) : nullptr; 1616 } 1617 }; 1618 1619 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when 1620 /// control converges back from a Branch-on-Mask. The phi nodes are needed in 1621 /// order to merge values that are set under such a branch and feed their uses. 1622 /// The phi nodes can be scalar or vector depending on the users of the value. 1623 /// This recipe works in concert with VPBranchOnMaskRecipe. 1624 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue { 1625 public: 1626 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi 1627 /// nodes after merging back from a Branch-on-Mask. 1628 VPPredInstPHIRecipe(VPValue *PredV) 1629 : VPRecipeBase(VPPredInstPHISC, PredV), 1630 VPValue(VPValue::VPVPredInstPHI, nullptr, this) {} 1631 ~VPPredInstPHIRecipe() override = default; 1632 1633 /// Method to support type inquiry through isa, cast, and dyn_cast. 1634 static inline bool classof(const VPDef *D) { 1635 return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC; 1636 } 1637 1638 /// Generates phi nodes for live-outs as needed to retain SSA form. 1639 void execute(VPTransformState &State) override; 1640 1641 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1642 /// Print the recipe. 1643 void print(raw_ostream &O, const Twine &Indent, 1644 VPSlotTracker &SlotTracker) const override; 1645 #endif 1646 1647 /// Returns true if the recipe uses scalars of operand \p Op. 1648 bool usesScalars(const VPValue *Op) const override { 1649 assert(is_contained(operands(), Op) && 1650 "Op must be an operand of the recipe"); 1651 return true; 1652 } 1653 }; 1654 1655 /// A Recipe for widening load/store operations. 1656 /// The recipe uses the following VPValues: 1657 /// - For load: Address, optional mask 1658 /// - For store: Address, stored value, optional mask 1659 /// TODO: We currently execute only per-part unless a specific instance is 1660 /// provided. 1661 class VPWidenMemoryInstructionRecipe : public VPRecipeBase { 1662 Instruction &Ingredient; 1663 1664 // Whether the loaded-from / stored-to addresses are consecutive. 1665 bool Consecutive; 1666 1667 // Whether the consecutive loaded/stored addresses are in reverse order. 1668 bool Reverse; 1669 1670 void setMask(VPValue *Mask) { 1671 if (!Mask) 1672 return; 1673 addOperand(Mask); 1674 } 1675 1676 bool isMasked() const { 1677 return isStore() ? getNumOperands() == 3 : getNumOperands() == 2; 1678 } 1679 1680 public: 1681 VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, 1682 bool Consecutive, bool Reverse) 1683 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}), Ingredient(Load), 1684 Consecutive(Consecutive), Reverse(Reverse) { 1685 assert((Consecutive || !Reverse) && "Reverse implies consecutive"); 1686 new VPValue(VPValue::VPVMemoryInstructionSC, &Load, this); 1687 setMask(Mask); 1688 } 1689 1690 VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr, 1691 VPValue *StoredValue, VPValue *Mask, 1692 bool Consecutive, bool Reverse) 1693 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}), 1694 Ingredient(Store), Consecutive(Consecutive), Reverse(Reverse) { 1695 assert((Consecutive || !Reverse) && "Reverse implies consecutive"); 1696 setMask(Mask); 1697 } 1698 1699 /// Method to support type inquiry through isa, cast, and dyn_cast. 1700 static inline bool classof(const VPDef *D) { 1701 return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 1702 } 1703 1704 /// Return the address accessed by this recipe. 1705 VPValue *getAddr() const { 1706 return getOperand(0); // Address is the 1st, mandatory operand. 1707 } 1708 1709 /// Return the mask used by this recipe. Note that a full mask is represented 1710 /// by a nullptr. 1711 VPValue *getMask() const { 1712 // Mask is optional and therefore the last operand. 1713 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr; 1714 } 1715 1716 /// Returns true if this recipe is a store. 1717 bool isStore() const { return isa<StoreInst>(Ingredient); } 1718 1719 /// Return the address accessed by this recipe. 1720 VPValue *getStoredValue() const { 1721 assert(isStore() && "Stored value only available for store instructions"); 1722 return getOperand(1); // Stored value is the 2nd, mandatory operand. 1723 } 1724 1725 // Return whether the loaded-from / stored-to addresses are consecutive. 1726 bool isConsecutive() const { return Consecutive; } 1727 1728 // Return whether the consecutive loaded/stored addresses are in reverse 1729 // order. 1730 bool isReverse() const { return Reverse; } 1731 1732 /// Generate the wide load/store. 1733 void execute(VPTransformState &State) override; 1734 1735 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1736 /// Print the recipe. 1737 void print(raw_ostream &O, const Twine &Indent, 1738 VPSlotTracker &SlotTracker) const override; 1739 #endif 1740 1741 /// Returns true if the recipe only uses the first lane of operand \p Op. 1742 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1743 assert(is_contained(operands(), Op) && 1744 "Op must be an operand of the recipe"); 1745 1746 // Widened, consecutive memory operations only demand the first lane of 1747 // their address, unless the same operand is also stored. That latter can 1748 // happen with opaque pointers. 1749 return Op == getAddr() && isConsecutive() && 1750 (!isStore() || Op != getStoredValue()); 1751 } 1752 1753 Instruction &getIngredient() const { return Ingredient; } 1754 }; 1755 1756 /// Recipe to expand a SCEV expression. 1757 class VPExpandSCEVRecipe : public VPRecipeBase, public VPValue { 1758 const SCEV *Expr; 1759 ScalarEvolution &SE; 1760 1761 public: 1762 VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE) 1763 : VPRecipeBase(VPExpandSCEVSC, {}), VPValue(nullptr, this), Expr(Expr), 1764 SE(SE) {} 1765 1766 ~VPExpandSCEVRecipe() override = default; 1767 1768 /// Method to support type inquiry through isa, cast, and dyn_cast. 1769 static inline bool classof(const VPDef *D) { 1770 return D->getVPDefID() == VPExpandSCEVSC; 1771 } 1772 1773 /// Generate a canonical vector induction variable of the vector loop, with 1774 void execute(VPTransformState &State) override; 1775 1776 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1777 /// Print the recipe. 1778 void print(raw_ostream &O, const Twine &Indent, 1779 VPSlotTracker &SlotTracker) const override; 1780 #endif 1781 1782 const SCEV *getSCEV() const { return Expr; } 1783 }; 1784 1785 /// Canonical scalar induction phi of the vector loop. Starting at the specified 1786 /// start value (either 0 or the resume value when vectorizing the epilogue 1787 /// loop). VPWidenCanonicalIVRecipe represents the vector version of the 1788 /// canonical induction variable. 1789 class VPCanonicalIVPHIRecipe : public VPHeaderPHIRecipe { 1790 DebugLoc DL; 1791 1792 public: 1793 VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL) 1794 : VPHeaderPHIRecipe(VPValue::VPVCanonicalIVPHISC, VPCanonicalIVPHISC, 1795 nullptr, StartV), 1796 DL(DL) {} 1797 1798 ~VPCanonicalIVPHIRecipe() override = default; 1799 1800 /// Method to support type inquiry through isa, cast, and dyn_cast. 1801 static inline bool classof(const VPDef *D) { 1802 return D->getVPDefID() == VPCanonicalIVPHISC; 1803 } 1804 static inline bool classof(const VPHeaderPHIRecipe *D) { 1805 return D->getVPDefID() == VPCanonicalIVPHISC; 1806 } 1807 static inline bool classof(const VPValue *V) { 1808 return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC; 1809 } 1810 1811 /// Generate the canonical scalar induction phi of the vector loop. 1812 void execute(VPTransformState &State) override; 1813 1814 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1815 /// Print the recipe. 1816 void print(raw_ostream &O, const Twine &Indent, 1817 VPSlotTracker &SlotTracker) const override; 1818 #endif 1819 1820 /// Returns the scalar type of the induction. 1821 const Type *getScalarType() const { 1822 return getOperand(0)->getLiveInIRValue()->getType(); 1823 } 1824 1825 /// Returns true if the recipe only uses the first lane of operand \p Op. 1826 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1827 assert(is_contained(operands(), Op) && 1828 "Op must be an operand of the recipe"); 1829 return true; 1830 } 1831 }; 1832 1833 /// A Recipe for widening the canonical induction variable of the vector loop. 1834 class VPWidenCanonicalIVRecipe : public VPRecipeBase, public VPValue { 1835 public: 1836 VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV) 1837 : VPRecipeBase(VPWidenCanonicalIVSC, {CanonicalIV}), 1838 VPValue(VPValue::VPVWidenCanonicalIVSC, nullptr, this) {} 1839 1840 ~VPWidenCanonicalIVRecipe() override = default; 1841 1842 /// Method to support type inquiry through isa, cast, and dyn_cast. 1843 static inline bool classof(const VPDef *D) { 1844 return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1845 } 1846 1847 /// Extra classof implementations to allow directly casting from VPUser -> 1848 /// VPWidenCanonicalIVRecipe. 1849 static inline bool classof(const VPUser *U) { 1850 auto *R = dyn_cast<VPRecipeBase>(U); 1851 return R && R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1852 } 1853 static inline bool classof(const VPRecipeBase *R) { 1854 return R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1855 } 1856 1857 /// Generate a canonical vector induction variable of the vector loop, with 1858 /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and 1859 /// step = <VF*UF, VF*UF, ..., VF*UF>. 1860 void execute(VPTransformState &State) override; 1861 1862 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1863 /// Print the recipe. 1864 void print(raw_ostream &O, const Twine &Indent, 1865 VPSlotTracker &SlotTracker) const override; 1866 #endif 1867 1868 /// Returns the scalar type of the induction. 1869 const Type *getScalarType() const { 1870 return cast<VPCanonicalIVPHIRecipe>(getOperand(0)->getDef()) 1871 ->getScalarType(); 1872 } 1873 }; 1874 1875 /// A recipe for handling phi nodes of integer and floating-point inductions, 1876 /// producing their scalar values. 1877 class VPScalarIVStepsRecipe : public VPRecipeBase, public VPValue { 1878 /// Scalar type to use for the generated values. 1879 Type *Ty; 1880 /// If not nullptr, truncate the generated values to TruncToTy. 1881 Type *TruncToTy; 1882 const InductionDescriptor &IndDesc; 1883 1884 public: 1885 VPScalarIVStepsRecipe(Type *Ty, const InductionDescriptor &IndDesc, 1886 VPValue *CanonicalIV, VPValue *Start, VPValue *Step, 1887 Type *TruncToTy) 1888 : VPRecipeBase(VPScalarIVStepsSC, {CanonicalIV, Start, Step}), 1889 VPValue(nullptr, this), Ty(Ty), TruncToTy(TruncToTy), IndDesc(IndDesc) { 1890 } 1891 1892 ~VPScalarIVStepsRecipe() override = default; 1893 1894 /// Method to support type inquiry through isa, cast, and dyn_cast. 1895 static inline bool classof(const VPDef *D) { 1896 return D->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1897 } 1898 /// Extra classof implementations to allow directly casting from VPUser -> 1899 /// VPScalarIVStepsRecipe. 1900 static inline bool classof(const VPUser *U) { 1901 auto *R = dyn_cast<VPRecipeBase>(U); 1902 return R && R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1903 } 1904 static inline bool classof(const VPRecipeBase *R) { 1905 return R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1906 } 1907 1908 /// Generate the scalarized versions of the phi node as needed by their users. 1909 void execute(VPTransformState &State) override; 1910 1911 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1912 /// Print the recipe. 1913 void print(raw_ostream &O, const Twine &Indent, 1914 VPSlotTracker &SlotTracker) const override; 1915 #endif 1916 1917 /// Returns true if the induction is canonical, i.e. starting at 0 and 1918 /// incremented by UF * VF (= the original IV is incremented by 1). 1919 bool isCanonical() const; 1920 1921 VPCanonicalIVPHIRecipe *getCanonicalIV() const; 1922 VPValue *getStartValue() const { return getOperand(1); } 1923 VPValue *getStepValue() const { return getOperand(2); } 1924 1925 /// Returns true if the recipe only uses the first lane of operand \p Op. 1926 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1927 assert(is_contained(operands(), Op) && 1928 "Op must be an operand of the recipe"); 1929 return true; 1930 } 1931 }; 1932 1933 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It 1934 /// holds a sequence of zero or more VPRecipe's each representing a sequence of 1935 /// output IR instructions. All PHI-like recipes must come before any non-PHI recipes. 1936 class VPBasicBlock : public VPBlockBase { 1937 public: 1938 using RecipeListTy = iplist<VPRecipeBase>; 1939 1940 private: 1941 /// The VPRecipes held in the order of output instructions to generate. 1942 RecipeListTy Recipes; 1943 1944 public: 1945 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr) 1946 : VPBlockBase(VPBasicBlockSC, Name.str()) { 1947 if (Recipe) 1948 appendRecipe(Recipe); 1949 } 1950 1951 ~VPBasicBlock() override { 1952 while (!Recipes.empty()) 1953 Recipes.pop_back(); 1954 } 1955 1956 /// Instruction iterators... 1957 using iterator = RecipeListTy::iterator; 1958 using const_iterator = RecipeListTy::const_iterator; 1959 using reverse_iterator = RecipeListTy::reverse_iterator; 1960 using const_reverse_iterator = RecipeListTy::const_reverse_iterator; 1961 1962 //===--------------------------------------------------------------------===// 1963 /// Recipe iterator methods 1964 /// 1965 inline iterator begin() { return Recipes.begin(); } 1966 inline const_iterator begin() const { return Recipes.begin(); } 1967 inline iterator end() { return Recipes.end(); } 1968 inline const_iterator end() const { return Recipes.end(); } 1969 1970 inline reverse_iterator rbegin() { return Recipes.rbegin(); } 1971 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); } 1972 inline reverse_iterator rend() { return Recipes.rend(); } 1973 inline const_reverse_iterator rend() const { return Recipes.rend(); } 1974 1975 inline size_t size() const { return Recipes.size(); } 1976 inline bool empty() const { return Recipes.empty(); } 1977 inline const VPRecipeBase &front() const { return Recipes.front(); } 1978 inline VPRecipeBase &front() { return Recipes.front(); } 1979 inline const VPRecipeBase &back() const { return Recipes.back(); } 1980 inline VPRecipeBase &back() { return Recipes.back(); } 1981 1982 /// Returns a reference to the list of recipes. 1983 RecipeListTy &getRecipeList() { return Recipes; } 1984 1985 /// Returns a pointer to a member of the recipe list. 1986 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) { 1987 return &VPBasicBlock::Recipes; 1988 } 1989 1990 /// Method to support type inquiry through isa, cast, and dyn_cast. 1991 static inline bool classof(const VPBlockBase *V) { 1992 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC; 1993 } 1994 1995 void insert(VPRecipeBase *Recipe, iterator InsertPt) { 1996 assert(Recipe && "No recipe to append."); 1997 assert(!Recipe->Parent && "Recipe already in VPlan"); 1998 Recipe->Parent = this; 1999 Recipes.insert(InsertPt, Recipe); 2000 } 2001 2002 /// Augment the existing recipes of a VPBasicBlock with an additional 2003 /// \p Recipe as the last recipe. 2004 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); } 2005 2006 /// The method which generates the output IR instructions that correspond to 2007 /// this VPBasicBlock, thereby "executing" the VPlan. 2008 void execute(struct VPTransformState *State) override; 2009 2010 /// Return the position of the first non-phi node recipe in the block. 2011 iterator getFirstNonPhi(); 2012 2013 /// Returns an iterator range over the PHI-like recipes in the block. 2014 iterator_range<iterator> phis() { 2015 return make_range(begin(), getFirstNonPhi()); 2016 } 2017 2018 void dropAllReferences(VPValue *NewValue) override; 2019 2020 /// Split current block at \p SplitAt by inserting a new block between the 2021 /// current block and its successors and moving all recipes starting at 2022 /// SplitAt to the new block. Returns the new block. 2023 VPBasicBlock *splitAt(iterator SplitAt); 2024 2025 VPRegionBlock *getEnclosingLoopRegion(); 2026 2027 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2028 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p 2029 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers. 2030 /// 2031 /// Note that the numbering is applied to the whole VPlan, so printing 2032 /// individual blocks is consistent with the whole VPlan printing. 2033 void print(raw_ostream &O, const Twine &Indent, 2034 VPSlotTracker &SlotTracker) const override; 2035 using VPBlockBase::print; // Get the print(raw_stream &O) version. 2036 #endif 2037 2038 /// If the block has multiple successors, return the branch recipe terminating 2039 /// the block. If there are no or only a single successor, return nullptr; 2040 VPRecipeBase *getTerminator(); 2041 const VPRecipeBase *getTerminator() const; 2042 2043 /// Returns true if the block is exiting it's parent region. 2044 bool isExiting() const; 2045 2046 private: 2047 /// Create an IR BasicBlock to hold the output instructions generated by this 2048 /// VPBasicBlock, and return it. Update the CFGState accordingly. 2049 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG); 2050 }; 2051 2052 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks 2053 /// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG. 2054 /// A VPRegionBlock may indicate that its contents are to be replicated several 2055 /// times. This is designed to support predicated scalarization, in which a 2056 /// scalar if-then code structure needs to be generated VF * UF times. Having 2057 /// this replication indicator helps to keep a single model for multiple 2058 /// candidate VF's. The actual replication takes place only once the desired VF 2059 /// and UF have been determined. 2060 class VPRegionBlock : public VPBlockBase { 2061 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock. 2062 VPBlockBase *Entry; 2063 2064 /// Hold the Single Exiting block of the SESE region modelled by the 2065 /// VPRegionBlock. 2066 VPBlockBase *Exiting; 2067 2068 /// An indicator whether this region is to generate multiple replicated 2069 /// instances of output IR corresponding to its VPBlockBases. 2070 bool IsReplicator; 2071 2072 public: 2073 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting, 2074 const std::string &Name = "", bool IsReplicator = false) 2075 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting), 2076 IsReplicator(IsReplicator) { 2077 assert(Entry->getPredecessors().empty() && "Entry block has predecessors."); 2078 assert(Exiting->getSuccessors().empty() && "Exit block has successors."); 2079 Entry->setParent(this); 2080 Exiting->setParent(this); 2081 } 2082 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false) 2083 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exiting(nullptr), 2084 IsReplicator(IsReplicator) {} 2085 2086 ~VPRegionBlock() override { 2087 if (Entry) { 2088 VPValue DummyValue; 2089 Entry->dropAllReferences(&DummyValue); 2090 deleteCFG(Entry); 2091 } 2092 } 2093 2094 /// Method to support type inquiry through isa, cast, and dyn_cast. 2095 static inline bool classof(const VPBlockBase *V) { 2096 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC; 2097 } 2098 2099 const VPBlockBase *getEntry() const { return Entry; } 2100 VPBlockBase *getEntry() { return Entry; } 2101 2102 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p 2103 /// EntryBlock must have no predecessors. 2104 void setEntry(VPBlockBase *EntryBlock) { 2105 assert(EntryBlock->getPredecessors().empty() && 2106 "Entry block cannot have predecessors."); 2107 Entry = EntryBlock; 2108 EntryBlock->setParent(this); 2109 } 2110 2111 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a 2112 // specific interface of llvm::Function, instead of using 2113 // GraphTraints::getEntryNode. We should add a new template parameter to 2114 // DominatorTreeBase representing the Graph type. 2115 VPBlockBase &front() const { return *Entry; } 2116 2117 const VPBlockBase *getExiting() const { return Exiting; } 2118 VPBlockBase *getExiting() { return Exiting; } 2119 2120 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p 2121 /// ExitingBlock must have no successors. 2122 void setExiting(VPBlockBase *ExitingBlock) { 2123 assert(ExitingBlock->getSuccessors().empty() && 2124 "Exit block cannot have successors."); 2125 Exiting = ExitingBlock; 2126 ExitingBlock->setParent(this); 2127 } 2128 2129 /// Returns the pre-header VPBasicBlock of the loop region. 2130 VPBasicBlock *getPreheaderVPBB() { 2131 assert(!isReplicator() && "should only get pre-header of loop regions"); 2132 return getSinglePredecessor()->getExitingBasicBlock(); 2133 } 2134 2135 /// An indicator whether this region is to generate multiple replicated 2136 /// instances of output IR corresponding to its VPBlockBases. 2137 bool isReplicator() const { return IsReplicator; } 2138 2139 /// The method which generates the output IR instructions that correspond to 2140 /// this VPRegionBlock, thereby "executing" the VPlan. 2141 void execute(struct VPTransformState *State) override; 2142 2143 void dropAllReferences(VPValue *NewValue) override; 2144 2145 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2146 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with 2147 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using 2148 /// consequtive numbers. 2149 /// 2150 /// Note that the numbering is applied to the whole VPlan, so printing 2151 /// individual regions is consistent with the whole VPlan printing. 2152 void print(raw_ostream &O, const Twine &Indent, 2153 VPSlotTracker &SlotTracker) const override; 2154 using VPBlockBase::print; // Get the print(raw_stream &O) version. 2155 #endif 2156 }; 2157 2158 //===----------------------------------------------------------------------===// 2159 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs // 2160 //===----------------------------------------------------------------------===// 2161 2162 // The following set of template specializations implement GraphTraits to treat 2163 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note 2164 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the 2165 // VPBlockBase is a VPRegionBlock, this specialization provides access to its 2166 // successors/predecessors but not to the blocks inside the region. 2167 2168 template <> struct GraphTraits<VPBlockBase *> { 2169 using NodeRef = VPBlockBase *; 2170 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 2171 2172 static NodeRef getEntryNode(NodeRef N) { return N; } 2173 2174 static inline ChildIteratorType child_begin(NodeRef N) { 2175 return N->getSuccessors().begin(); 2176 } 2177 2178 static inline ChildIteratorType child_end(NodeRef N) { 2179 return N->getSuccessors().end(); 2180 } 2181 }; 2182 2183 template <> struct GraphTraits<const VPBlockBase *> { 2184 using NodeRef = const VPBlockBase *; 2185 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator; 2186 2187 static NodeRef getEntryNode(NodeRef N) { return N; } 2188 2189 static inline ChildIteratorType child_begin(NodeRef N) { 2190 return N->getSuccessors().begin(); 2191 } 2192 2193 static inline ChildIteratorType child_end(NodeRef N) { 2194 return N->getSuccessors().end(); 2195 } 2196 }; 2197 2198 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead 2199 // of successors for the inverse traversal. 2200 template <> struct GraphTraits<Inverse<VPBlockBase *>> { 2201 using NodeRef = VPBlockBase *; 2202 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 2203 2204 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; } 2205 2206 static inline ChildIteratorType child_begin(NodeRef N) { 2207 return N->getPredecessors().begin(); 2208 } 2209 2210 static inline ChildIteratorType child_end(NodeRef N) { 2211 return N->getPredecessors().end(); 2212 } 2213 }; 2214 2215 // The following set of template specializations implement GraphTraits to 2216 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important 2217 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases 2218 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so 2219 // there won't be automatic recursion into other VPBlockBases that turn to be 2220 // VPRegionBlocks. 2221 2222 template <> 2223 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> { 2224 using GraphRef = VPRegionBlock *; 2225 using nodes_iterator = df_iterator<NodeRef>; 2226 2227 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 2228 2229 static nodes_iterator nodes_begin(GraphRef N) { 2230 return nodes_iterator::begin(N->getEntry()); 2231 } 2232 2233 static nodes_iterator nodes_end(GraphRef N) { 2234 // df_iterator::end() returns an empty iterator so the node used doesn't 2235 // matter. 2236 return nodes_iterator::end(N); 2237 } 2238 }; 2239 2240 template <> 2241 struct GraphTraits<const VPRegionBlock *> 2242 : public GraphTraits<const VPBlockBase *> { 2243 using GraphRef = const VPRegionBlock *; 2244 using nodes_iterator = df_iterator<NodeRef>; 2245 2246 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 2247 2248 static nodes_iterator nodes_begin(GraphRef N) { 2249 return nodes_iterator::begin(N->getEntry()); 2250 } 2251 2252 static nodes_iterator nodes_end(GraphRef N) { 2253 // df_iterator::end() returns an empty iterator so the node used doesn't 2254 // matter. 2255 return nodes_iterator::end(N); 2256 } 2257 }; 2258 2259 template <> 2260 struct GraphTraits<Inverse<VPRegionBlock *>> 2261 : public GraphTraits<Inverse<VPBlockBase *>> { 2262 using GraphRef = VPRegionBlock *; 2263 using nodes_iterator = df_iterator<NodeRef>; 2264 2265 static NodeRef getEntryNode(Inverse<GraphRef> N) { 2266 return N.Graph->getExiting(); 2267 } 2268 2269 static nodes_iterator nodes_begin(GraphRef N) { 2270 return nodes_iterator::begin(N->getExiting()); 2271 } 2272 2273 static nodes_iterator nodes_end(GraphRef N) { 2274 // df_iterator::end() returns an empty iterator so the node used doesn't 2275 // matter. 2276 return nodes_iterator::end(N); 2277 } 2278 }; 2279 2280 /// Iterator to traverse all successors of a VPBlockBase node. This includes the 2281 /// entry node of VPRegionBlocks. Exit blocks of a region implicitly have their 2282 /// parent region's successors. This ensures all blocks in a region are visited 2283 /// before any blocks in a successor region when doing a reverse post-order 2284 // traversal of the graph. 2285 template <typename BlockPtrTy> 2286 class VPAllSuccessorsIterator 2287 : public iterator_facade_base<VPAllSuccessorsIterator<BlockPtrTy>, 2288 std::forward_iterator_tag, VPBlockBase> { 2289 BlockPtrTy Block; 2290 /// Index of the current successor. For VPBasicBlock nodes, this simply is the 2291 /// index for the successor array. For VPRegionBlock, SuccessorIdx == 0 is 2292 /// used for the region's entry block, and SuccessorIdx - 1 are the indices 2293 /// for the successor array. 2294 size_t SuccessorIdx; 2295 2296 static BlockPtrTy getBlockWithSuccs(BlockPtrTy Current) { 2297 while (Current && Current->getNumSuccessors() == 0) 2298 Current = Current->getParent(); 2299 return Current; 2300 } 2301 2302 /// Templated helper to dereference successor \p SuccIdx of \p Block. Used by 2303 /// both the const and non-const operator* implementations. 2304 template <typename T1> static T1 deref(T1 Block, unsigned SuccIdx) { 2305 if (auto *R = dyn_cast<VPRegionBlock>(Block)) { 2306 if (SuccIdx == 0) 2307 return R->getEntry(); 2308 SuccIdx--; 2309 } 2310 2311 // For exit blocks, use the next parent region with successors. 2312 return getBlockWithSuccs(Block)->getSuccessors()[SuccIdx]; 2313 } 2314 2315 public: 2316 VPAllSuccessorsIterator(BlockPtrTy Block, size_t Idx = 0) 2317 : Block(Block), SuccessorIdx(Idx) {} 2318 VPAllSuccessorsIterator(const VPAllSuccessorsIterator &Other) 2319 : Block(Other.Block), SuccessorIdx(Other.SuccessorIdx) {} 2320 2321 VPAllSuccessorsIterator &operator=(const VPAllSuccessorsIterator &R) { 2322 Block = R.Block; 2323 SuccessorIdx = R.SuccessorIdx; 2324 return *this; 2325 } 2326 2327 static VPAllSuccessorsIterator end(BlockPtrTy Block) { 2328 BlockPtrTy ParentWithSuccs = getBlockWithSuccs(Block); 2329 unsigned NumSuccessors = ParentWithSuccs 2330 ? ParentWithSuccs->getNumSuccessors() 2331 : Block->getNumSuccessors(); 2332 2333 if (auto *R = dyn_cast<VPRegionBlock>(Block)) 2334 return {R, NumSuccessors + 1}; 2335 return {Block, NumSuccessors}; 2336 } 2337 2338 bool operator==(const VPAllSuccessorsIterator &R) const { 2339 return Block == R.Block && SuccessorIdx == R.SuccessorIdx; 2340 } 2341 2342 const VPBlockBase *operator*() const { return deref(Block, SuccessorIdx); } 2343 2344 BlockPtrTy operator*() { return deref(Block, SuccessorIdx); } 2345 2346 VPAllSuccessorsIterator &operator++() { 2347 SuccessorIdx++; 2348 return *this; 2349 } 2350 2351 VPAllSuccessorsIterator operator++(int X) { 2352 VPAllSuccessorsIterator Orig = *this; 2353 SuccessorIdx++; 2354 return Orig; 2355 } 2356 }; 2357 2358 /// Helper for GraphTraits specialization that traverses through VPRegionBlocks. 2359 template <typename BlockTy> class VPBlockRecursiveTraversalWrapper { 2360 BlockTy Entry; 2361 2362 public: 2363 VPBlockRecursiveTraversalWrapper(BlockTy Entry) : Entry(Entry) {} 2364 BlockTy getEntry() { return Entry; } 2365 }; 2366 2367 /// GraphTraits specialization to recursively traverse VPBlockBase nodes, 2368 /// including traversing through VPRegionBlocks. Exit blocks of a region 2369 /// implicitly have their parent region's successors. This ensures all blocks in 2370 /// a region are visited before any blocks in a successor region when doing a 2371 /// reverse post-order traversal of the graph. 2372 template <> 2373 struct GraphTraits<VPBlockRecursiveTraversalWrapper<VPBlockBase *>> { 2374 using NodeRef = VPBlockBase *; 2375 using ChildIteratorType = VPAllSuccessorsIterator<VPBlockBase *>; 2376 2377 static NodeRef 2378 getEntryNode(VPBlockRecursiveTraversalWrapper<VPBlockBase *> N) { 2379 return N.getEntry(); 2380 } 2381 2382 static inline ChildIteratorType child_begin(NodeRef N) { 2383 return ChildIteratorType(N); 2384 } 2385 2386 static inline ChildIteratorType child_end(NodeRef N) { 2387 return ChildIteratorType::end(N); 2388 } 2389 }; 2390 2391 template <> 2392 struct GraphTraits<VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> { 2393 using NodeRef = const VPBlockBase *; 2394 using ChildIteratorType = VPAllSuccessorsIterator<const VPBlockBase *>; 2395 2396 static NodeRef 2397 getEntryNode(VPBlockRecursiveTraversalWrapper<const VPBlockBase *> N) { 2398 return N.getEntry(); 2399 } 2400 2401 static inline ChildIteratorType child_begin(NodeRef N) { 2402 return ChildIteratorType(N); 2403 } 2404 2405 static inline ChildIteratorType child_end(NodeRef N) { 2406 return ChildIteratorType::end(N); 2407 } 2408 }; 2409 2410 /// VPlan models a candidate for vectorization, encoding various decisions take 2411 /// to produce efficient output IR, including which branches, basic-blocks and 2412 /// output IR instructions to generate, and their cost. VPlan holds a 2413 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry 2414 /// VPBlock. 2415 class VPlan { 2416 friend class VPlanPrinter; 2417 friend class VPSlotTracker; 2418 2419 /// Hold the single entry to the Hierarchical CFG of the VPlan. 2420 VPBlockBase *Entry; 2421 2422 /// Holds the VFs applicable to this VPlan. 2423 SmallSetVector<ElementCount, 2> VFs; 2424 2425 /// Holds the name of the VPlan, for printing. 2426 std::string Name; 2427 2428 /// Holds all the external definitions created for this VPlan. External 2429 /// definitions must be immutable and hold a pointer to their underlying IR. 2430 DenseMap<Value *, VPValue *> VPExternalDefs; 2431 2432 /// Represents the trip count of the original loop, for folding 2433 /// the tail. 2434 VPValue *TripCount = nullptr; 2435 2436 /// Represents the backedge taken count of the original loop, for folding 2437 /// the tail. It equals TripCount - 1. 2438 VPValue *BackedgeTakenCount = nullptr; 2439 2440 /// Represents the vector trip count. 2441 VPValue VectorTripCount; 2442 2443 /// Holds a mapping between Values and their corresponding VPValue inside 2444 /// VPlan. 2445 Value2VPValueTy Value2VPValue; 2446 2447 /// Contains all VPValues that been allocated by addVPValue directly and need 2448 /// to be free when the plan's destructor is called. 2449 SmallVector<VPValue *, 16> VPValuesToFree; 2450 2451 /// Indicates whether it is safe use the Value2VPValue mapping or if the 2452 /// mapping cannot be used any longer, because it is stale. 2453 bool Value2VPValueEnabled = true; 2454 2455 /// Values used outside the plan. 2456 MapVector<PHINode *, VPLiveOut *> LiveOuts; 2457 2458 public: 2459 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) { 2460 if (Entry) 2461 Entry->setPlan(this); 2462 } 2463 2464 ~VPlan() { 2465 clearLiveOuts(); 2466 2467 if (Entry) { 2468 VPValue DummyValue; 2469 for (VPBlockBase *Block : depth_first(Entry)) 2470 Block->dropAllReferences(&DummyValue); 2471 2472 VPBlockBase::deleteCFG(Entry); 2473 } 2474 for (VPValue *VPV : VPValuesToFree) 2475 delete VPV; 2476 if (TripCount) 2477 delete TripCount; 2478 if (BackedgeTakenCount) 2479 delete BackedgeTakenCount; 2480 for (auto &P : VPExternalDefs) 2481 delete P.second; 2482 } 2483 2484 /// Prepare the plan for execution, setting up the required live-in values. 2485 void prepareToExecute(Value *TripCount, Value *VectorTripCount, 2486 Value *CanonicalIVStartValue, VPTransformState &State); 2487 2488 /// Generate the IR code for this VPlan. 2489 void execute(struct VPTransformState *State); 2490 2491 VPBlockBase *getEntry() { return Entry; } 2492 const VPBlockBase *getEntry() const { return Entry; } 2493 2494 VPBlockBase *setEntry(VPBlockBase *Block) { 2495 Entry = Block; 2496 Block->setPlan(this); 2497 return Entry; 2498 } 2499 2500 /// The trip count of the original loop. 2501 VPValue *getOrCreateTripCount() { 2502 if (!TripCount) 2503 TripCount = new VPValue(); 2504 return TripCount; 2505 } 2506 2507 /// The backedge taken count of the original loop. 2508 VPValue *getOrCreateBackedgeTakenCount() { 2509 if (!BackedgeTakenCount) 2510 BackedgeTakenCount = new VPValue(); 2511 return BackedgeTakenCount; 2512 } 2513 2514 /// The vector trip count. 2515 VPValue &getVectorTripCount() { return VectorTripCount; } 2516 2517 /// Mark the plan to indicate that using Value2VPValue is not safe any 2518 /// longer, because it may be stale. 2519 void disableValue2VPValue() { Value2VPValueEnabled = false; } 2520 2521 void addVF(ElementCount VF) { VFs.insert(VF); } 2522 2523 bool hasVF(ElementCount VF) { return VFs.count(VF); } 2524 2525 const std::string &getName() const { return Name; } 2526 2527 void setName(const Twine &newName) { Name = newName.str(); } 2528 2529 /// Get the existing or add a new external definition for \p V. 2530 VPValue *getOrAddExternalDef(Value *V) { 2531 auto I = VPExternalDefs.insert({V, nullptr}); 2532 if (I.second) 2533 I.first->second = new VPValue(V); 2534 return I.first->second; 2535 } 2536 2537 void addVPValue(Value *V) { 2538 assert(Value2VPValueEnabled && 2539 "IR value to VPValue mapping may be out of date!"); 2540 assert(V && "Trying to add a null Value to VPlan"); 2541 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2542 VPValue *VPV = new VPValue(V); 2543 Value2VPValue[V] = VPV; 2544 VPValuesToFree.push_back(VPV); 2545 } 2546 2547 void addVPValue(Value *V, VPValue *VPV) { 2548 assert(Value2VPValueEnabled && "Value2VPValue mapping may be out of date!"); 2549 assert(V && "Trying to add a null Value to VPlan"); 2550 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2551 Value2VPValue[V] = VPV; 2552 } 2553 2554 /// Returns the VPValue for \p V. \p OverrideAllowed can be used to disable 2555 /// checking whether it is safe to query VPValues using IR Values. 2556 VPValue *getVPValue(Value *V, bool OverrideAllowed = false) { 2557 assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) && 2558 "Value2VPValue mapping may be out of date!"); 2559 assert(V && "Trying to get the VPValue of a null Value"); 2560 assert(Value2VPValue.count(V) && "Value does not exist in VPlan"); 2561 return Value2VPValue[V]; 2562 } 2563 2564 /// Gets the VPValue or adds a new one (if none exists yet) for \p V. \p 2565 /// OverrideAllowed can be used to disable checking whether it is safe to 2566 /// query VPValues using IR Values. 2567 VPValue *getOrAddVPValue(Value *V, bool OverrideAllowed = false) { 2568 assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) && 2569 "Value2VPValue mapping may be out of date!"); 2570 assert(V && "Trying to get or add the VPValue of a null Value"); 2571 if (!Value2VPValue.count(V)) 2572 addVPValue(V); 2573 return getVPValue(V); 2574 } 2575 2576 void removeVPValueFor(Value *V) { 2577 assert(Value2VPValueEnabled && 2578 "IR value to VPValue mapping may be out of date!"); 2579 Value2VPValue.erase(V); 2580 } 2581 2582 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2583 /// Print this VPlan to \p O. 2584 void print(raw_ostream &O) const; 2585 2586 /// Print this VPlan in DOT format to \p O. 2587 void printDOT(raw_ostream &O) const; 2588 2589 /// Dump the plan to stderr (for debugging). 2590 LLVM_DUMP_METHOD void dump() const; 2591 #endif 2592 2593 /// Returns a range mapping the values the range \p Operands to their 2594 /// corresponding VPValues. 2595 iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>> 2596 mapToVPValues(User::op_range Operands) { 2597 std::function<VPValue *(Value *)> Fn = [this](Value *Op) { 2598 return getOrAddVPValue(Op); 2599 }; 2600 return map_range(Operands, Fn); 2601 } 2602 2603 /// Returns true if \p VPV is uniform after vectorization. 2604 bool isUniformAfterVectorization(VPValue *VPV) const { 2605 auto RepR = dyn_cast_or_null<VPReplicateRecipe>(VPV->getDef()); 2606 return !VPV->getDef() || (RepR && RepR->isUniform()); 2607 } 2608 2609 /// Returns the VPRegionBlock of the vector loop. 2610 VPRegionBlock *getVectorLoopRegion() { 2611 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor()); 2612 } 2613 const VPRegionBlock *getVectorLoopRegion() const { 2614 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor()); 2615 } 2616 2617 /// Returns the canonical induction recipe of the vector loop. 2618 VPCanonicalIVPHIRecipe *getCanonicalIV() { 2619 VPBasicBlock *EntryVPBB = getVectorLoopRegion()->getEntryBasicBlock(); 2620 if (EntryVPBB->empty()) { 2621 // VPlan native path. 2622 EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor()); 2623 } 2624 return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin()); 2625 } 2626 2627 void addLiveOut(PHINode *PN, VPValue *V); 2628 2629 void clearLiveOuts() { 2630 for (auto &KV : LiveOuts) 2631 delete KV.second; 2632 LiveOuts.clear(); 2633 } 2634 2635 void removeLiveOut(PHINode *PN) { 2636 delete LiveOuts[PN]; 2637 LiveOuts.erase(PN); 2638 } 2639 2640 const MapVector<PHINode *, VPLiveOut *> &getLiveOuts() const { 2641 return LiveOuts; 2642 } 2643 2644 private: 2645 /// Add to the given dominator tree the header block and every new basic block 2646 /// that was created between it and the latch block, inclusive. 2647 static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, 2648 BasicBlock *LoopPreHeaderBB, 2649 BasicBlock *LoopExitBB); 2650 }; 2651 2652 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2653 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is 2654 /// indented and follows the dot format. 2655 class VPlanPrinter { 2656 raw_ostream &OS; 2657 const VPlan &Plan; 2658 unsigned Depth = 0; 2659 unsigned TabWidth = 2; 2660 std::string Indent; 2661 unsigned BID = 0; 2662 SmallDenseMap<const VPBlockBase *, unsigned> BlockID; 2663 2664 VPSlotTracker SlotTracker; 2665 2666 /// Handle indentation. 2667 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); } 2668 2669 /// Print a given \p Block of the Plan. 2670 void dumpBlock(const VPBlockBase *Block); 2671 2672 /// Print the information related to the CFG edges going out of a given 2673 /// \p Block, followed by printing the successor blocks themselves. 2674 void dumpEdges(const VPBlockBase *Block); 2675 2676 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing 2677 /// its successor blocks. 2678 void dumpBasicBlock(const VPBasicBlock *BasicBlock); 2679 2680 /// Print a given \p Region of the Plan. 2681 void dumpRegion(const VPRegionBlock *Region); 2682 2683 unsigned getOrCreateBID(const VPBlockBase *Block) { 2684 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++; 2685 } 2686 2687 Twine getOrCreateName(const VPBlockBase *Block); 2688 2689 Twine getUID(const VPBlockBase *Block); 2690 2691 /// Print the information related to a CFG edge between two VPBlockBases. 2692 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden, 2693 const Twine &Label); 2694 2695 public: 2696 VPlanPrinter(raw_ostream &O, const VPlan &P) 2697 : OS(O), Plan(P), SlotTracker(&P) {} 2698 2699 LLVM_DUMP_METHOD void dump(); 2700 }; 2701 2702 struct VPlanIngredient { 2703 const Value *V; 2704 2705 VPlanIngredient(const Value *V) : V(V) {} 2706 2707 void print(raw_ostream &O) const; 2708 }; 2709 2710 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) { 2711 I.print(OS); 2712 return OS; 2713 } 2714 2715 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) { 2716 Plan.print(OS); 2717 return OS; 2718 } 2719 #endif 2720 2721 //===----------------------------------------------------------------------===// 2722 // VPlan Utilities 2723 //===----------------------------------------------------------------------===// 2724 2725 /// Class that provides utilities for VPBlockBases in VPlan. 2726 class VPBlockUtils { 2727 public: 2728 VPBlockUtils() = delete; 2729 2730 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p 2731 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p 2732 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's 2733 /// successors are moved from \p BlockPtr to \p NewBlock. \p NewBlock must 2734 /// have neither successors nor predecessors. 2735 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) { 2736 assert(NewBlock->getSuccessors().empty() && 2737 NewBlock->getPredecessors().empty() && 2738 "Can't insert new block with predecessors or successors."); 2739 NewBlock->setParent(BlockPtr->getParent()); 2740 SmallVector<VPBlockBase *> Succs(BlockPtr->successors()); 2741 for (VPBlockBase *Succ : Succs) { 2742 disconnectBlocks(BlockPtr, Succ); 2743 connectBlocks(NewBlock, Succ); 2744 } 2745 connectBlocks(BlockPtr, NewBlock); 2746 } 2747 2748 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p 2749 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p 2750 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr 2751 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors 2752 /// and \p IfTrue and \p IfFalse must have neither successors nor 2753 /// predecessors. 2754 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 2755 VPBlockBase *BlockPtr) { 2756 assert(IfTrue->getSuccessors().empty() && 2757 "Can't insert IfTrue with successors."); 2758 assert(IfFalse->getSuccessors().empty() && 2759 "Can't insert IfFalse with successors."); 2760 BlockPtr->setTwoSuccessors(IfTrue, IfFalse); 2761 IfTrue->setPredecessors({BlockPtr}); 2762 IfFalse->setPredecessors({BlockPtr}); 2763 IfTrue->setParent(BlockPtr->getParent()); 2764 IfFalse->setParent(BlockPtr->getParent()); 2765 } 2766 2767 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to 2768 /// the successors of \p From and \p From to the predecessors of \p To. Both 2769 /// VPBlockBases must have the same parent, which can be null. Both 2770 /// VPBlockBases can be already connected to other VPBlockBases. 2771 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) { 2772 assert((From->getParent() == To->getParent()) && 2773 "Can't connect two block with different parents"); 2774 assert(From->getNumSuccessors() < 2 && 2775 "Blocks can't have more than two successors."); 2776 From->appendSuccessor(To); 2777 To->appendPredecessor(From); 2778 } 2779 2780 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To 2781 /// from the successors of \p From and \p From from the predecessors of \p To. 2782 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) { 2783 assert(To && "Successor to disconnect is null."); 2784 From->removeSuccessor(To); 2785 To->removePredecessor(From); 2786 } 2787 2788 /// Try to merge \p Block into its single predecessor, if \p Block is a 2789 /// VPBasicBlock and its predecessor has a single successor. Returns a pointer 2790 /// to the predecessor \p Block was merged into or nullptr otherwise. 2791 static VPBasicBlock *tryToMergeBlockIntoPredecessor(VPBlockBase *Block) { 2792 auto *VPBB = dyn_cast<VPBasicBlock>(Block); 2793 auto *PredVPBB = 2794 dyn_cast_or_null<VPBasicBlock>(Block->getSinglePredecessor()); 2795 if (!VPBB || !PredVPBB || PredVPBB->getNumSuccessors() != 1) 2796 return nullptr; 2797 2798 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) 2799 R.moveBefore(*PredVPBB, PredVPBB->end()); 2800 VPBlockUtils::disconnectBlocks(PredVPBB, VPBB); 2801 auto *ParentRegion = cast<VPRegionBlock>(Block->getParent()); 2802 if (ParentRegion->getExiting() == Block) 2803 ParentRegion->setExiting(PredVPBB); 2804 SmallVector<VPBlockBase *> Successors(Block->successors()); 2805 for (auto *Succ : Successors) { 2806 VPBlockUtils::disconnectBlocks(Block, Succ); 2807 VPBlockUtils::connectBlocks(PredVPBB, Succ); 2808 } 2809 delete Block; 2810 return PredVPBB; 2811 } 2812 2813 /// Return an iterator range over \p Range which only includes \p BlockTy 2814 /// blocks. The accesses are casted to \p BlockTy. 2815 template <typename BlockTy, typename T> 2816 static auto blocksOnly(const T &Range) { 2817 // Create BaseTy with correct const-ness based on BlockTy. 2818 using BaseTy = 2819 typename std::conditional<std::is_const<BlockTy>::value, 2820 const VPBlockBase, VPBlockBase>::type; 2821 2822 // We need to first create an iterator range over (const) BlocktTy & instead 2823 // of (const) BlockTy * for filter_range to work properly. 2824 auto Mapped = 2825 map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; }); 2826 auto Filter = make_filter_range( 2827 Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); }); 2828 return map_range(Filter, [](BaseTy &Block) -> BlockTy * { 2829 return cast<BlockTy>(&Block); 2830 }); 2831 } 2832 }; 2833 2834 class VPInterleavedAccessInfo { 2835 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *> 2836 InterleaveGroupMap; 2837 2838 /// Type for mapping of instruction based interleave groups to VPInstruction 2839 /// interleave groups 2840 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *, 2841 InterleaveGroup<VPInstruction> *>; 2842 2843 /// Recursively \p Region and populate VPlan based interleave groups based on 2844 /// \p IAI. 2845 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New, 2846 InterleavedAccessInfo &IAI); 2847 /// Recursively traverse \p Block and populate VPlan based interleave groups 2848 /// based on \p IAI. 2849 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 2850 InterleavedAccessInfo &IAI); 2851 2852 public: 2853 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI); 2854 2855 ~VPInterleavedAccessInfo() { 2856 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet; 2857 // Avoid releasing a pointer twice. 2858 for (auto &I : InterleaveGroupMap) 2859 DelSet.insert(I.second); 2860 for (auto *Ptr : DelSet) 2861 delete Ptr; 2862 } 2863 2864 /// Get the interleave group that \p Instr belongs to. 2865 /// 2866 /// \returns nullptr if doesn't have such group. 2867 InterleaveGroup<VPInstruction> * 2868 getInterleaveGroup(VPInstruction *Instr) const { 2869 return InterleaveGroupMap.lookup(Instr); 2870 } 2871 }; 2872 2873 /// Class that maps (parts of) an existing VPlan to trees of combined 2874 /// VPInstructions. 2875 class VPlanSlp { 2876 enum class OpMode { Failed, Load, Opcode }; 2877 2878 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as 2879 /// DenseMap keys. 2880 struct BundleDenseMapInfo { 2881 static SmallVector<VPValue *, 4> getEmptyKey() { 2882 return {reinterpret_cast<VPValue *>(-1)}; 2883 } 2884 2885 static SmallVector<VPValue *, 4> getTombstoneKey() { 2886 return {reinterpret_cast<VPValue *>(-2)}; 2887 } 2888 2889 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) { 2890 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2891 } 2892 2893 static bool isEqual(const SmallVector<VPValue *, 4> &LHS, 2894 const SmallVector<VPValue *, 4> &RHS) { 2895 return LHS == RHS; 2896 } 2897 }; 2898 2899 /// Mapping of values in the original VPlan to a combined VPInstruction. 2900 DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo> 2901 BundleToCombined; 2902 2903 VPInterleavedAccessInfo &IAI; 2904 2905 /// Basic block to operate on. For now, only instructions in a single BB are 2906 /// considered. 2907 const VPBasicBlock &BB; 2908 2909 /// Indicates whether we managed to combine all visited instructions or not. 2910 bool CompletelySLP = true; 2911 2912 /// Width of the widest combined bundle in bits. 2913 unsigned WidestBundleBits = 0; 2914 2915 using MultiNodeOpTy = 2916 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>; 2917 2918 // Input operand bundles for the current multi node. Each multi node operand 2919 // bundle contains values not matching the multi node's opcode. They will 2920 // be reordered in reorderMultiNodeOps, once we completed building a 2921 // multi node. 2922 SmallVector<MultiNodeOpTy, 4> MultiNodeOps; 2923 2924 /// Indicates whether we are building a multi node currently. 2925 bool MultiNodeActive = false; 2926 2927 /// Check if we can vectorize Operands together. 2928 bool areVectorizable(ArrayRef<VPValue *> Operands) const; 2929 2930 /// Add combined instruction \p New for the bundle \p Operands. 2931 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New); 2932 2933 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now. 2934 VPInstruction *markFailed(); 2935 2936 /// Reorder operands in the multi node to maximize sequential memory access 2937 /// and commutative operations. 2938 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps(); 2939 2940 /// Choose the best candidate to use for the lane after \p Last. The set of 2941 /// candidates to choose from are values with an opcode matching \p Last's 2942 /// or loads consecutive to \p Last. 2943 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last, 2944 SmallPtrSetImpl<VPValue *> &Candidates, 2945 VPInterleavedAccessInfo &IAI); 2946 2947 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2948 /// Print bundle \p Values to dbgs(). 2949 void dumpBundle(ArrayRef<VPValue *> Values); 2950 #endif 2951 2952 public: 2953 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {} 2954 2955 ~VPlanSlp() = default; 2956 2957 /// Tries to build an SLP tree rooted at \p Operands and returns a 2958 /// VPInstruction combining \p Operands, if they can be combined. 2959 VPInstruction *buildGraph(ArrayRef<VPValue *> Operands); 2960 2961 /// Return the width of the widest combined bundle in bits. 2962 unsigned getWidestBundleBits() const { return WidestBundleBits; } 2963 2964 /// Return true if all visited instruction can be combined. 2965 bool isCompletelySLP() const { return CompletelySLP; } 2966 }; 2967 2968 namespace vputils { 2969 2970 /// Returns true if only the first lane of \p Def is used. 2971 bool onlyFirstLaneUsed(VPValue *Def); 2972 2973 /// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p 2974 /// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in 2975 /// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's 2976 /// pre-header already contains a recipe expanding \p Expr, return it. If not, 2977 /// create a new one. 2978 VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 2979 ScalarEvolution &SE); 2980 } // end namespace vputils 2981 2982 } // end namespace llvm 2983 2984 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 2985