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