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