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 /// VPRecipeBase is a base class modeling a sequence of one or more output IR 668 /// instructions. VPRecipeBase owns the the VPValues it defines through VPDef 669 /// and is responsible for deleting its defined values. Single-value 670 /// VPRecipeBases that also inherit from VPValue must make sure to inherit from 671 /// VPRecipeBase before VPValue. 672 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>, 673 public VPDef, 674 public VPUser { 675 friend VPBasicBlock; 676 friend class VPBlockUtils; 677 678 /// Each VPRecipe belongs to a single VPBasicBlock. 679 VPBasicBlock *Parent = nullptr; 680 681 public: 682 VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands) 683 : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {} 684 685 template <typename IterT> 686 VPRecipeBase(const unsigned char SC, iterator_range<IterT> Operands) 687 : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {} 688 virtual ~VPRecipeBase() = default; 689 690 /// \return the VPBasicBlock which this VPRecipe belongs to. 691 VPBasicBlock *getParent() { return Parent; } 692 const VPBasicBlock *getParent() const { return Parent; } 693 694 /// The method which generates the output IR instructions that correspond to 695 /// this VPRecipe, thereby "executing" the VPlan. 696 virtual void execute(struct VPTransformState &State) = 0; 697 698 /// Insert an unlinked recipe into a basic block immediately before 699 /// the specified recipe. 700 void insertBefore(VPRecipeBase *InsertPos); 701 /// Insert an unlinked recipe into \p BB immediately before the insertion 702 /// point \p IP; 703 void insertBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator IP); 704 705 /// Insert an unlinked Recipe into a basic block immediately after 706 /// the specified Recipe. 707 void insertAfter(VPRecipeBase *InsertPos); 708 709 /// Unlink this recipe from its current VPBasicBlock and insert it into 710 /// the VPBasicBlock that MovePos lives in, right after MovePos. 711 void moveAfter(VPRecipeBase *MovePos); 712 713 /// Unlink this recipe and insert into BB before I. 714 /// 715 /// \pre I is a valid iterator into BB. 716 void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I); 717 718 /// This method unlinks 'this' from the containing basic block, but does not 719 /// delete it. 720 void removeFromParent(); 721 722 /// This method unlinks 'this' from the containing basic block and deletes it. 723 /// 724 /// \returns an iterator pointing to the element after the erased one 725 iplist<VPRecipeBase>::iterator eraseFromParent(); 726 727 /// Returns the underlying instruction, if the recipe is a VPValue or nullptr 728 /// otherwise. 729 Instruction *getUnderlyingInstr() { 730 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 731 } 732 const Instruction *getUnderlyingInstr() const { 733 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()); 734 } 735 736 /// Method to support type inquiry through isa, cast, and dyn_cast. 737 static inline bool classof(const VPDef *D) { 738 // All VPDefs are also VPRecipeBases. 739 return true; 740 } 741 742 static inline bool classof(const VPUser *U) { 743 return U->getVPUserID() == VPUser::VPUserID::Recipe; 744 } 745 746 /// Returns true if the recipe may have side-effects. 747 bool mayHaveSideEffects() const; 748 749 /// Returns true for PHI-like recipes. 750 bool isPhi() const { 751 return getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC; 752 } 753 754 /// Returns true if the recipe may read from memory. 755 bool mayReadFromMemory() const; 756 757 /// Returns true if the recipe may write to memory. 758 bool mayWriteToMemory() const; 759 760 /// Returns true if the recipe may read from or write to memory. 761 bool mayReadOrWriteMemory() const { 762 return mayReadFromMemory() || mayWriteToMemory(); 763 } 764 }; 765 766 inline bool VPUser::classof(const VPDef *Def) { 767 return Def->getVPDefID() == VPRecipeBase::VPInstructionSC || 768 Def->getVPDefID() == VPRecipeBase::VPWidenSC || 769 Def->getVPDefID() == VPRecipeBase::VPWidenCallSC || 770 Def->getVPDefID() == VPRecipeBase::VPWidenSelectSC || 771 Def->getVPDefID() == VPRecipeBase::VPWidenGEPSC || 772 Def->getVPDefID() == VPRecipeBase::VPBlendSC || 773 Def->getVPDefID() == VPRecipeBase::VPInterleaveSC || 774 Def->getVPDefID() == VPRecipeBase::VPReplicateSC || 775 Def->getVPDefID() == VPRecipeBase::VPReductionSC || 776 Def->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC || 777 Def->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 778 } 779 780 /// This is a concrete Recipe that models a single VPlan-level instruction. 781 /// While as any Recipe it may generate a sequence of IR instructions when 782 /// executed, these instructions would always form a single-def expression as 783 /// the VPInstruction is also a single def-use vertex. 784 class VPInstruction : public VPRecipeBase, public VPValue { 785 friend class VPlanSlp; 786 787 public: 788 /// VPlan opcodes, extending LLVM IR with idiomatics instructions. 789 enum { 790 FirstOrderRecurrenceSplice = 791 Instruction::OtherOpsEnd + 1, // Combines the incoming and previous 792 // values of a first-order recurrence. 793 Not, 794 ICmpULE, 795 SLPLoad, 796 SLPStore, 797 ActiveLaneMask, 798 CanonicalIVIncrement, 799 CanonicalIVIncrementNUW, 800 BranchOnCount, 801 }; 802 803 private: 804 typedef unsigned char OpcodeTy; 805 OpcodeTy Opcode; 806 FastMathFlags FMF; 807 DebugLoc DL; 808 809 /// Utility method serving execute(): generates a single instance of the 810 /// modeled instruction. 811 void generateInstruction(VPTransformState &State, unsigned Part); 812 813 protected: 814 void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); } 815 816 public: 817 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands, DebugLoc DL) 818 : VPRecipeBase(VPRecipeBase::VPInstructionSC, Operands), 819 VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode), 820 DL(DL) {} 821 822 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands, 823 DebugLoc DL = {}) 824 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL) {} 825 826 /// Method to support type inquiry through isa, cast, and dyn_cast. 827 static inline bool classof(const VPValue *V) { 828 return V->getVPValueID() == VPValue::VPVInstructionSC; 829 } 830 831 VPInstruction *clone() const { 832 SmallVector<VPValue *, 2> Operands(operands()); 833 return new VPInstruction(Opcode, Operands, DL); 834 } 835 836 /// Method to support type inquiry through isa, cast, and dyn_cast. 837 static inline bool classof(const VPDef *R) { 838 return R->getVPDefID() == VPRecipeBase::VPInstructionSC; 839 } 840 841 /// Extra classof implementations to allow directly casting from VPUser -> 842 /// VPInstruction. 843 static inline bool classof(const VPUser *U) { 844 auto *R = dyn_cast<VPRecipeBase>(U); 845 return R && R->getVPDefID() == VPRecipeBase::VPInstructionSC; 846 } 847 static inline bool classof(const VPRecipeBase *R) { 848 return R->getVPDefID() == VPRecipeBase::VPInstructionSC; 849 } 850 851 unsigned getOpcode() const { return Opcode; } 852 853 /// Generate the instruction. 854 /// TODO: We currently execute only per-part unless a specific instance is 855 /// provided. 856 void execute(VPTransformState &State) override; 857 858 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 859 /// Print the VPInstruction to \p O. 860 void print(raw_ostream &O, const Twine &Indent, 861 VPSlotTracker &SlotTracker) const override; 862 863 /// Print the VPInstruction to dbgs() (for debugging). 864 LLVM_DUMP_METHOD void dump() const; 865 #endif 866 867 /// Return true if this instruction may modify memory. 868 bool mayWriteToMemory() const { 869 // TODO: we can use attributes of the called function to rule out memory 870 // modifications. 871 return Opcode == Instruction::Store || Opcode == Instruction::Call || 872 Opcode == Instruction::Invoke || Opcode == SLPStore; 873 } 874 875 bool hasResult() const { 876 // CallInst may or may not have a result, depending on the called function. 877 // Conservatively return calls have results for now. 878 switch (getOpcode()) { 879 case Instruction::Ret: 880 case Instruction::Br: 881 case Instruction::Store: 882 case Instruction::Switch: 883 case Instruction::IndirectBr: 884 case Instruction::Resume: 885 case Instruction::CatchRet: 886 case Instruction::Unreachable: 887 case Instruction::Fence: 888 case Instruction::AtomicRMW: 889 case VPInstruction::BranchOnCount: 890 return false; 891 default: 892 return true; 893 } 894 } 895 896 /// Set the fast-math flags. 897 void setFastMathFlags(FastMathFlags FMFNew); 898 899 /// Returns true if the recipe only uses the first lane of operand \p Op. 900 bool onlyFirstLaneUsed(const VPValue *Op) const override { 901 assert(is_contained(operands(), Op) && 902 "Op must be an operand of the recipe"); 903 if (getOperand(0) != Op) 904 return false; 905 switch (getOpcode()) { 906 default: 907 return false; 908 case VPInstruction::ActiveLaneMask: 909 case VPInstruction::CanonicalIVIncrement: 910 case VPInstruction::CanonicalIVIncrementNUW: 911 case VPInstruction::BranchOnCount: 912 return true; 913 }; 914 llvm_unreachable("switch should return"); 915 } 916 }; 917 918 /// VPWidenRecipe is a recipe for producing a copy of vector type its 919 /// ingredient. This recipe covers most of the traditional vectorization cases 920 /// where each ingredient transforms into a vectorized version of itself. 921 class VPWidenRecipe : public VPRecipeBase, public VPValue { 922 public: 923 template <typename IterT> 924 VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands) 925 : VPRecipeBase(VPRecipeBase::VPWidenSC, Operands), 926 VPValue(VPValue::VPVWidenSC, &I, this) {} 927 928 ~VPWidenRecipe() override = default; 929 930 /// Method to support type inquiry through isa, cast, and dyn_cast. 931 static inline bool classof(const VPDef *D) { 932 return D->getVPDefID() == VPRecipeBase::VPWidenSC; 933 } 934 static inline bool classof(const VPValue *V) { 935 return V->getVPValueID() == VPValue::VPVWidenSC; 936 } 937 938 /// Produce widened copies of all Ingredients. 939 void execute(VPTransformState &State) override; 940 941 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 942 /// Print the recipe. 943 void print(raw_ostream &O, const Twine &Indent, 944 VPSlotTracker &SlotTracker) const override; 945 #endif 946 }; 947 948 /// A recipe for widening Call instructions. 949 class VPWidenCallRecipe : public VPRecipeBase, public VPValue { 950 951 public: 952 template <typename IterT> 953 VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments) 954 : VPRecipeBase(VPRecipeBase::VPWidenCallSC, CallArguments), 955 VPValue(VPValue::VPVWidenCallSC, &I, this) {} 956 957 ~VPWidenCallRecipe() override = default; 958 959 /// Method to support type inquiry through isa, cast, and dyn_cast. 960 static inline bool classof(const VPDef *D) { 961 return D->getVPDefID() == VPRecipeBase::VPWidenCallSC; 962 } 963 964 /// Produce a widened version of the call instruction. 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 select instructions. 975 class VPWidenSelectRecipe : public VPRecipeBase, public VPValue { 976 977 /// Is the condition of the select loop invariant? 978 bool InvariantCond; 979 980 public: 981 template <typename IterT> 982 VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands, 983 bool InvariantCond) 984 : VPRecipeBase(VPRecipeBase::VPWidenSelectSC, Operands), 985 VPValue(VPValue::VPVWidenSelectSC, &I, this), 986 InvariantCond(InvariantCond) {} 987 988 ~VPWidenSelectRecipe() override = default; 989 990 /// Method to support type inquiry through isa, cast, and dyn_cast. 991 static inline bool classof(const VPDef *D) { 992 return D->getVPDefID() == VPRecipeBase::VPWidenSelectSC; 993 } 994 995 /// Produce a widened version of the select instruction. 996 void execute(VPTransformState &State) override; 997 998 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 999 /// Print the recipe. 1000 void print(raw_ostream &O, const Twine &Indent, 1001 VPSlotTracker &SlotTracker) const override; 1002 #endif 1003 }; 1004 1005 /// A recipe for handling GEP instructions. 1006 class VPWidenGEPRecipe : public VPRecipeBase, public VPValue { 1007 bool IsPtrLoopInvariant; 1008 SmallBitVector IsIndexLoopInvariant; 1009 1010 public: 1011 template <typename IterT> 1012 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands) 1013 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 1014 VPValue(VPWidenGEPSC, GEP, this), 1015 IsIndexLoopInvariant(GEP->getNumIndices(), false) {} 1016 1017 template <typename IterT> 1018 VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands, 1019 Loop *OrigLoop) 1020 : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands), 1021 VPValue(VPValue::VPVWidenGEPSC, GEP, this), 1022 IsIndexLoopInvariant(GEP->getNumIndices(), false) { 1023 IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand()); 1024 for (auto Index : enumerate(GEP->indices())) 1025 IsIndexLoopInvariant[Index.index()] = 1026 OrigLoop->isLoopInvariant(Index.value().get()); 1027 } 1028 ~VPWidenGEPRecipe() override = default; 1029 1030 /// Method to support type inquiry through isa, cast, and dyn_cast. 1031 static inline bool classof(const VPDef *D) { 1032 return D->getVPDefID() == VPRecipeBase::VPWidenGEPSC; 1033 } 1034 1035 /// Generate the gep nodes. 1036 void execute(VPTransformState &State) override; 1037 1038 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1039 /// Print the recipe. 1040 void print(raw_ostream &O, const Twine &Indent, 1041 VPSlotTracker &SlotTracker) const override; 1042 #endif 1043 }; 1044 1045 /// A recipe for handling phi nodes of integer and floating-point inductions, 1046 /// producing their vector values. 1047 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase, public VPValue { 1048 PHINode *IV; 1049 const InductionDescriptor &IndDesc; 1050 bool NeedsScalarIV; 1051 bool NeedsVectorIV; 1052 1053 public: 1054 VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, 1055 const InductionDescriptor &IndDesc, 1056 bool NeedsScalarIV, bool NeedsVectorIV) 1057 : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}), 1058 VPValue(IV, this), IV(IV), IndDesc(IndDesc), 1059 NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {} 1060 1061 VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, 1062 const InductionDescriptor &IndDesc, 1063 TruncInst *Trunc, bool NeedsScalarIV, 1064 bool NeedsVectorIV) 1065 : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}), 1066 VPValue(Trunc, this), IV(IV), IndDesc(IndDesc), 1067 NeedsScalarIV(NeedsScalarIV), NeedsVectorIV(NeedsVectorIV) {} 1068 1069 ~VPWidenIntOrFpInductionRecipe() override = default; 1070 1071 /// Method to support type inquiry through isa, cast, and dyn_cast. 1072 static inline bool classof(const VPDef *D) { 1073 return D->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC; 1074 } 1075 1076 /// Generate the vectorized and scalarized versions of the phi node as 1077 /// needed by their users. 1078 void execute(VPTransformState &State) override; 1079 1080 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1081 /// Print the recipe. 1082 void print(raw_ostream &O, const Twine &Indent, 1083 VPSlotTracker &SlotTracker) const override; 1084 #endif 1085 1086 /// Returns the start value of the induction. 1087 VPValue *getStartValue() { return getOperand(0); } 1088 const VPValue *getStartValue() const { return getOperand(0); } 1089 1090 /// Returns the step value of the induction. 1091 VPValue *getStepValue() { return getOperand(1); } 1092 const VPValue *getStepValue() const { return getOperand(1); } 1093 1094 /// Returns the first defined value as TruncInst, if it is one or nullptr 1095 /// otherwise. 1096 TruncInst *getTruncInst() { 1097 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 1098 } 1099 const TruncInst *getTruncInst() const { 1100 return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue()); 1101 } 1102 1103 PHINode *getPHINode() { return IV; } 1104 1105 /// Returns the induction descriptor for the recipe. 1106 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; } 1107 1108 /// Returns true if the induction is canonical, i.e. starting at 0 and 1109 /// incremented by UF * VF (= the original IV is incremented by 1). 1110 bool isCanonical() const; 1111 1112 /// Returns the scalar type of the induction. 1113 const Type *getScalarType() const { 1114 const TruncInst *TruncI = getTruncInst(); 1115 return TruncI ? TruncI->getType() : IV->getType(); 1116 } 1117 1118 /// Returns true if a scalar phi needs to be created for the induction. 1119 bool needsScalarIV() const { return NeedsScalarIV; } 1120 1121 /// Returns true if a vector phi needs to be created for the induction. 1122 bool needsVectorIV() const { return NeedsVectorIV; } 1123 }; 1124 1125 /// A pure virtual base class for all recipes modeling header phis, including 1126 /// phis for first order recurrences, pointer inductions and reductions. The 1127 /// start value is the first operand of the recipe and the incoming value from 1128 /// the backedge is the second operand. 1129 class VPHeaderPHIRecipe : public VPRecipeBase, public VPValue { 1130 protected: 1131 VPHeaderPHIRecipe(unsigned char VPVID, unsigned char VPDefID, PHINode *Phi, 1132 VPValue *Start = nullptr) 1133 : VPRecipeBase(VPDefID, {}), VPValue(VPVID, Phi, this) { 1134 if (Start) 1135 addOperand(Start); 1136 } 1137 1138 public: 1139 ~VPHeaderPHIRecipe() override = default; 1140 1141 /// Method to support type inquiry through isa, cast, and dyn_cast. 1142 static inline bool classof(const VPRecipeBase *B) { 1143 return B->getVPDefID() == VPRecipeBase::VPCanonicalIVPHISC || 1144 B->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC || 1145 B->getVPDefID() == VPRecipeBase::VPReductionPHISC || 1146 B->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC || 1147 B->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1148 } 1149 static inline bool classof(const VPValue *V) { 1150 return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC || 1151 V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC || 1152 V->getVPValueID() == VPValue::VPVReductionPHISC || 1153 V->getVPValueID() == VPValue::VPVWidenIntOrFpInductionSC || 1154 V->getVPValueID() == VPValue::VPVWidenPHISC; 1155 } 1156 1157 /// Generate the phi nodes. 1158 void execute(VPTransformState &State) override = 0; 1159 1160 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1161 /// Print the recipe. 1162 void print(raw_ostream &O, const Twine &Indent, 1163 VPSlotTracker &SlotTracker) const override = 0; 1164 #endif 1165 1166 /// Returns the start value of the phi, if one is set. 1167 VPValue *getStartValue() { 1168 return getNumOperands() == 0 ? nullptr : getOperand(0); 1169 } 1170 VPValue *getStartValue() const { 1171 return getNumOperands() == 0 ? nullptr : getOperand(0); 1172 } 1173 1174 /// Returns the incoming value from the loop backedge. 1175 VPValue *getBackedgeValue() { 1176 return getOperand(1); 1177 } 1178 1179 /// Returns the backedge value as a recipe. The backedge value is guaranteed 1180 /// to be a recipe. 1181 VPRecipeBase *getBackedgeRecipe() { 1182 return cast<VPRecipeBase>(getBackedgeValue()->getDef()); 1183 } 1184 }; 1185 1186 class VPWidenPointerInductionRecipe : public VPHeaderPHIRecipe { 1187 const InductionDescriptor &IndDesc; 1188 1189 /// SCEV used to expand step. 1190 /// FIXME: move expansion of step to the pre-header, once it is modeled 1191 /// explicitly. 1192 ScalarEvolution &SE; 1193 1194 public: 1195 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p 1196 /// Start. 1197 VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start, 1198 const InductionDescriptor &IndDesc, 1199 ScalarEvolution &SE) 1200 : VPHeaderPHIRecipe(VPVWidenPointerInductionSC, VPWidenPointerInductionSC, 1201 Phi), 1202 IndDesc(IndDesc), SE(SE) { 1203 addOperand(Start); 1204 } 1205 1206 ~VPWidenPointerInductionRecipe() override = default; 1207 1208 /// Method to support type inquiry through isa, cast, and dyn_cast. 1209 static inline bool classof(const VPRecipeBase *B) { 1210 return B->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC; 1211 } 1212 static inline bool classof(const VPHeaderPHIRecipe *R) { 1213 return R->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC; 1214 } 1215 static inline bool classof(const VPValue *V) { 1216 return V->getVPValueID() == VPValue::VPVWidenPointerInductionSC; 1217 } 1218 1219 /// Generate vector values for the pointer induction. 1220 void execute(VPTransformState &State) override; 1221 1222 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1223 /// Print the recipe. 1224 void print(raw_ostream &O, const Twine &Indent, 1225 VPSlotTracker &SlotTracker) const override; 1226 #endif 1227 }; 1228 1229 /// A recipe for handling header phis that are widened in the vector loop. 1230 /// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are 1231 /// managed in the recipe directly. 1232 class VPWidenPHIRecipe : public VPHeaderPHIRecipe { 1233 /// List of incoming blocks. Only used in the VPlan native path. 1234 SmallVector<VPBasicBlock *, 2> IncomingBlocks; 1235 1236 public: 1237 /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start. 1238 VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr) 1239 : VPHeaderPHIRecipe(VPVWidenPHISC, VPWidenPHISC, Phi) { 1240 if (Start) 1241 addOperand(Start); 1242 } 1243 1244 ~VPWidenPHIRecipe() override = default; 1245 1246 /// Method to support type inquiry through isa, cast, and dyn_cast. 1247 static inline bool classof(const VPRecipeBase *B) { 1248 return B->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1249 } 1250 static inline bool classof(const VPHeaderPHIRecipe *R) { 1251 return R->getVPDefID() == VPRecipeBase::VPWidenPHISC; 1252 } 1253 static inline bool classof(const VPValue *V) { 1254 return V->getVPValueID() == VPValue::VPVWidenPHISC; 1255 } 1256 1257 /// Generate the phi/select nodes. 1258 void execute(VPTransformState &State) override; 1259 1260 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1261 /// Print the recipe. 1262 void print(raw_ostream &O, const Twine &Indent, 1263 VPSlotTracker &SlotTracker) const override; 1264 #endif 1265 1266 /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi. 1267 void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) { 1268 addOperand(IncomingV); 1269 IncomingBlocks.push_back(IncomingBlock); 1270 } 1271 1272 /// Returns the \p I th incoming VPBasicBlock. 1273 VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; } 1274 1275 /// Returns the \p I th incoming VPValue. 1276 VPValue *getIncomingValue(unsigned I) { return getOperand(I); } 1277 }; 1278 1279 /// A recipe for handling first-order recurrence phis. The start value is the 1280 /// first operand of the recipe and the incoming value from the backedge is the 1281 /// second operand. 1282 struct VPFirstOrderRecurrencePHIRecipe : public VPHeaderPHIRecipe { 1283 VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start) 1284 : VPHeaderPHIRecipe(VPVFirstOrderRecurrencePHISC, 1285 VPFirstOrderRecurrencePHISC, Phi, &Start) {} 1286 1287 /// Method to support type inquiry through isa, cast, and dyn_cast. 1288 static inline bool classof(const VPRecipeBase *R) { 1289 return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC; 1290 } 1291 static inline bool classof(const VPHeaderPHIRecipe *R) { 1292 return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC; 1293 } 1294 static inline bool classof(const VPValue *V) { 1295 return V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC; 1296 } 1297 1298 void execute(VPTransformState &State) override; 1299 1300 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1301 /// Print the recipe. 1302 void print(raw_ostream &O, const Twine &Indent, 1303 VPSlotTracker &SlotTracker) const override; 1304 #endif 1305 }; 1306 1307 /// A recipe for handling reduction phis. The start value is the first operand 1308 /// of the recipe and the incoming value from the backedge is the second 1309 /// operand. 1310 class VPReductionPHIRecipe : public VPHeaderPHIRecipe { 1311 /// Descriptor for the reduction. 1312 const RecurrenceDescriptor &RdxDesc; 1313 1314 /// The phi is part of an in-loop reduction. 1315 bool IsInLoop; 1316 1317 /// The phi is part of an ordered reduction. Requires IsInLoop to be true. 1318 bool IsOrdered; 1319 1320 public: 1321 /// Create a new VPReductionPHIRecipe for the reduction \p Phi described by \p 1322 /// RdxDesc. 1323 VPReductionPHIRecipe(PHINode *Phi, const RecurrenceDescriptor &RdxDesc, 1324 VPValue &Start, bool IsInLoop = false, 1325 bool IsOrdered = false) 1326 : VPHeaderPHIRecipe(VPVReductionPHISC, VPReductionPHISC, Phi, &Start), 1327 RdxDesc(RdxDesc), IsInLoop(IsInLoop), IsOrdered(IsOrdered) { 1328 assert((!IsOrdered || IsInLoop) && "IsOrdered requires IsInLoop"); 1329 } 1330 1331 ~VPReductionPHIRecipe() override = default; 1332 1333 /// Method to support type inquiry through isa, cast, and dyn_cast. 1334 static inline bool classof(const VPRecipeBase *R) { 1335 return R->getVPDefID() == VPRecipeBase::VPReductionPHISC; 1336 } 1337 static inline bool classof(const VPHeaderPHIRecipe *R) { 1338 return R->getVPDefID() == VPRecipeBase::VPReductionPHISC; 1339 } 1340 static inline bool classof(const VPValue *V) { 1341 return V->getVPValueID() == VPValue::VPVReductionPHISC; 1342 } 1343 1344 /// Generate the phi/select nodes. 1345 void execute(VPTransformState &State) override; 1346 1347 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1348 /// Print the recipe. 1349 void print(raw_ostream &O, const Twine &Indent, 1350 VPSlotTracker &SlotTracker) const override; 1351 #endif 1352 1353 const RecurrenceDescriptor &getRecurrenceDescriptor() const { 1354 return RdxDesc; 1355 } 1356 1357 /// Returns true, if the phi is part of an ordered reduction. 1358 bool isOrdered() const { return IsOrdered; } 1359 1360 /// Returns true, if the phi is part of an in-loop reduction. 1361 bool isInLoop() const { return IsInLoop; } 1362 }; 1363 1364 /// A recipe for vectorizing a phi-node as a sequence of mask-based select 1365 /// instructions. 1366 class VPBlendRecipe : public VPRecipeBase, public VPValue { 1367 PHINode *Phi; 1368 1369 public: 1370 /// The blend operation is a User of the incoming values and of their 1371 /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value 1372 /// might be incoming with a full mask for which there is no VPValue. 1373 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands) 1374 : VPRecipeBase(VPBlendSC, Operands), 1375 VPValue(VPValue::VPVBlendSC, Phi, this), Phi(Phi) { 1376 assert(Operands.size() > 0 && 1377 ((Operands.size() == 1) || (Operands.size() % 2 == 0)) && 1378 "Expected either a single incoming value or a positive even number " 1379 "of operands"); 1380 } 1381 1382 /// Method to support type inquiry through isa, cast, and dyn_cast. 1383 static inline bool classof(const VPDef *D) { 1384 return D->getVPDefID() == VPRecipeBase::VPBlendSC; 1385 } 1386 1387 /// Return the number of incoming values, taking into account that a single 1388 /// incoming value has no mask. 1389 unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; } 1390 1391 /// Return incoming value number \p Idx. 1392 VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); } 1393 1394 /// Return mask number \p Idx. 1395 VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); } 1396 1397 /// Generate the phi/select nodes. 1398 void execute(VPTransformState &State) override; 1399 1400 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1401 /// Print the recipe. 1402 void print(raw_ostream &O, const Twine &Indent, 1403 VPSlotTracker &SlotTracker) const override; 1404 #endif 1405 1406 /// Returns true if the recipe only uses the first lane of operand \p Op. 1407 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1408 assert(is_contained(operands(), Op) && 1409 "Op must be an operand of the recipe"); 1410 // Recursing through Blend recipes only, must terminate at header phi's the 1411 // latest. 1412 return all_of(users(), 1413 [this](VPUser *U) { return U->onlyFirstLaneUsed(this); }); 1414 } 1415 }; 1416 1417 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load 1418 /// or stores into one wide load/store and shuffles. The first operand of a 1419 /// VPInterleave recipe is the address, followed by the stored values, followed 1420 /// by an optional mask. 1421 class VPInterleaveRecipe : public VPRecipeBase { 1422 const InterleaveGroup<Instruction> *IG; 1423 1424 bool HasMask = false; 1425 1426 public: 1427 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr, 1428 ArrayRef<VPValue *> StoredValues, VPValue *Mask) 1429 : VPRecipeBase(VPInterleaveSC, {Addr}), IG(IG) { 1430 for (unsigned i = 0; i < IG->getFactor(); ++i) 1431 if (Instruction *I = IG->getMember(i)) { 1432 if (I->getType()->isVoidTy()) 1433 continue; 1434 new VPValue(I, this); 1435 } 1436 1437 for (auto *SV : StoredValues) 1438 addOperand(SV); 1439 if (Mask) { 1440 HasMask = true; 1441 addOperand(Mask); 1442 } 1443 } 1444 ~VPInterleaveRecipe() override = default; 1445 1446 /// Method to support type inquiry through isa, cast, and dyn_cast. 1447 static inline bool classof(const VPDef *D) { 1448 return D->getVPDefID() == VPRecipeBase::VPInterleaveSC; 1449 } 1450 1451 /// Return the address accessed by this recipe. 1452 VPValue *getAddr() const { 1453 return getOperand(0); // Address is the 1st, mandatory operand. 1454 } 1455 1456 /// Return the mask used by this recipe. Note that a full mask is represented 1457 /// by a nullptr. 1458 VPValue *getMask() const { 1459 // Mask is optional and therefore the last, currently 2nd operand. 1460 return HasMask ? getOperand(getNumOperands() - 1) : nullptr; 1461 } 1462 1463 /// Return the VPValues stored by this interleave group. If it is a load 1464 /// interleave group, return an empty ArrayRef. 1465 ArrayRef<VPValue *> getStoredValues() const { 1466 // The first operand is the address, followed by the stored values, followed 1467 // by an optional mask. 1468 return ArrayRef<VPValue *>(op_begin(), getNumOperands()) 1469 .slice(1, getNumStoreOperands()); 1470 } 1471 1472 /// Generate the wide load or store, and shuffles. 1473 void execute(VPTransformState &State) override; 1474 1475 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1476 /// Print the recipe. 1477 void print(raw_ostream &O, const Twine &Indent, 1478 VPSlotTracker &SlotTracker) const override; 1479 #endif 1480 1481 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; } 1482 1483 /// Returns the number of stored operands of this interleave group. Returns 0 1484 /// for load interleave groups. 1485 unsigned getNumStoreOperands() const { 1486 return getNumOperands() - (HasMask ? 2 : 1); 1487 } 1488 1489 /// The recipe only uses the first lane of the address. 1490 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1491 assert(is_contained(operands(), Op) && 1492 "Op must be an operand of the recipe"); 1493 return Op == getAddr() && all_of(getStoredValues(), [Op](VPValue *StoredV) { 1494 return Op != StoredV; 1495 }); 1496 } 1497 }; 1498 1499 /// A recipe to represent inloop reduction operations, performing a reduction on 1500 /// a vector operand into a scalar value, and adding the result to a chain. 1501 /// The Operands are {ChainOp, VecOp, [Condition]}. 1502 class VPReductionRecipe : public VPRecipeBase, public VPValue { 1503 /// The recurrence decriptor for the reduction in question. 1504 const RecurrenceDescriptor *RdxDesc; 1505 /// Pointer to the TTI, needed to create the target reduction 1506 const TargetTransformInfo *TTI; 1507 1508 public: 1509 VPReductionRecipe(const RecurrenceDescriptor *R, Instruction *I, 1510 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, 1511 const TargetTransformInfo *TTI) 1512 : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}), 1513 VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) { 1514 if (CondOp) 1515 addOperand(CondOp); 1516 } 1517 1518 ~VPReductionRecipe() override = default; 1519 1520 /// Method to support type inquiry through isa, cast, and dyn_cast. 1521 static inline bool classof(const VPValue *V) { 1522 return V->getVPValueID() == VPValue::VPVReductionSC; 1523 } 1524 1525 /// Generate the reduction in the loop 1526 void execute(VPTransformState &State) override; 1527 1528 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1529 /// Print the recipe. 1530 void print(raw_ostream &O, const Twine &Indent, 1531 VPSlotTracker &SlotTracker) const override; 1532 #endif 1533 1534 /// The VPValue of the scalar Chain being accumulated. 1535 VPValue *getChainOp() const { return getOperand(0); } 1536 /// The VPValue of the vector value to be reduced. 1537 VPValue *getVecOp() const { return getOperand(1); } 1538 /// The VPValue of the condition for the block. 1539 VPValue *getCondOp() const { 1540 return getNumOperands() > 2 ? getOperand(2) : nullptr; 1541 } 1542 }; 1543 1544 /// VPReplicateRecipe replicates a given instruction producing multiple scalar 1545 /// copies of the original scalar type, one per lane, instead of producing a 1546 /// single copy of widened type for all lanes. If the instruction is known to be 1547 /// uniform only one copy, per lane zero, will be generated. 1548 class VPReplicateRecipe : public VPRecipeBase, public VPValue { 1549 /// Indicator if only a single replica per lane is needed. 1550 bool IsUniform; 1551 1552 /// Indicator if the replicas are also predicated. 1553 bool IsPredicated; 1554 1555 /// Indicator if the scalar values should also be packed into a vector. 1556 bool AlsoPack; 1557 1558 public: 1559 template <typename IterT> 1560 VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands, 1561 bool IsUniform, bool IsPredicated = false) 1562 : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this), 1563 IsUniform(IsUniform), IsPredicated(IsPredicated) { 1564 // Retain the previous behavior of predicateInstructions(), where an 1565 // insert-element of a predicated instruction got hoisted into the 1566 // predicated basic block iff it was its only user. This is achieved by 1567 // having predicated instructions also pack their values into a vector by 1568 // default unless they have a replicated user which uses their scalar value. 1569 AlsoPack = IsPredicated && !I->use_empty(); 1570 } 1571 1572 ~VPReplicateRecipe() override = default; 1573 1574 /// Method to support type inquiry through isa, cast, and dyn_cast. 1575 static inline bool classof(const VPDef *D) { 1576 return D->getVPDefID() == VPRecipeBase::VPReplicateSC; 1577 } 1578 1579 static inline bool classof(const VPValue *V) { 1580 return V->getVPValueID() == VPValue::VPVReplicateSC; 1581 } 1582 1583 /// Generate replicas of the desired Ingredient. Replicas will be generated 1584 /// for all parts and lanes unless a specific part and lane are specified in 1585 /// the \p State. 1586 void execute(VPTransformState &State) override; 1587 1588 void setAlsoPack(bool Pack) { AlsoPack = Pack; } 1589 1590 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1591 /// Print the recipe. 1592 void print(raw_ostream &O, const Twine &Indent, 1593 VPSlotTracker &SlotTracker) const override; 1594 #endif 1595 1596 bool isUniform() const { return IsUniform; } 1597 1598 bool isPacked() const { return AlsoPack; } 1599 1600 bool isPredicated() const { return IsPredicated; } 1601 1602 /// Returns true if the recipe only uses the first lane of operand \p Op. 1603 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1604 assert(is_contained(operands(), Op) && 1605 "Op must be an operand of the recipe"); 1606 return isUniform(); 1607 } 1608 1609 /// Returns true if the recipe uses scalars of operand \p Op. 1610 bool usesScalars(const VPValue *Op) const override { 1611 assert(is_contained(operands(), Op) && 1612 "Op must be an operand of the recipe"); 1613 return true; 1614 } 1615 }; 1616 1617 /// A recipe for generating conditional branches on the bits of a mask. 1618 class VPBranchOnMaskRecipe : public VPRecipeBase { 1619 public: 1620 VPBranchOnMaskRecipe(VPValue *BlockInMask) 1621 : VPRecipeBase(VPBranchOnMaskSC, {}) { 1622 if (BlockInMask) // nullptr means all-one mask. 1623 addOperand(BlockInMask); 1624 } 1625 1626 /// Method to support type inquiry through isa, cast, and dyn_cast. 1627 static inline bool classof(const VPDef *D) { 1628 return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC; 1629 } 1630 1631 /// Generate the extraction of the appropriate bit from the block mask and the 1632 /// conditional branch. 1633 void execute(VPTransformState &State) override; 1634 1635 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1636 /// Print the recipe. 1637 void print(raw_ostream &O, const Twine &Indent, 1638 VPSlotTracker &SlotTracker) const override { 1639 O << Indent << "BRANCH-ON-MASK "; 1640 if (VPValue *Mask = getMask()) 1641 Mask->printAsOperand(O, SlotTracker); 1642 else 1643 O << " All-One"; 1644 } 1645 #endif 1646 1647 /// Return the mask used by this recipe. Note that a full mask is represented 1648 /// by a nullptr. 1649 VPValue *getMask() const { 1650 assert(getNumOperands() <= 1 && "should have either 0 or 1 operands"); 1651 // Mask is optional. 1652 return getNumOperands() == 1 ? getOperand(0) : nullptr; 1653 } 1654 }; 1655 1656 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when 1657 /// control converges back from a Branch-on-Mask. The phi nodes are needed in 1658 /// order to merge values that are set under such a branch and feed their uses. 1659 /// The phi nodes can be scalar or vector depending on the users of the value. 1660 /// This recipe works in concert with VPBranchOnMaskRecipe. 1661 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue { 1662 public: 1663 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi 1664 /// nodes after merging back from a Branch-on-Mask. 1665 VPPredInstPHIRecipe(VPValue *PredV) 1666 : VPRecipeBase(VPPredInstPHISC, PredV), 1667 VPValue(VPValue::VPVPredInstPHI, nullptr, this) {} 1668 ~VPPredInstPHIRecipe() override = default; 1669 1670 /// Method to support type inquiry through isa, cast, and dyn_cast. 1671 static inline bool classof(const VPDef *D) { 1672 return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC; 1673 } 1674 1675 /// Generates phi nodes for live-outs as needed to retain SSA form. 1676 void execute(VPTransformState &State) override; 1677 1678 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1679 /// Print the recipe. 1680 void print(raw_ostream &O, const Twine &Indent, 1681 VPSlotTracker &SlotTracker) const override; 1682 #endif 1683 1684 /// Returns true if the recipe uses scalars of operand \p Op. 1685 bool usesScalars(const VPValue *Op) const override { 1686 assert(is_contained(operands(), Op) && 1687 "Op must be an operand of the recipe"); 1688 return true; 1689 } 1690 }; 1691 1692 /// A Recipe for widening load/store operations. 1693 /// The recipe uses the following VPValues: 1694 /// - For load: Address, optional mask 1695 /// - For store: Address, stored value, optional mask 1696 /// TODO: We currently execute only per-part unless a specific instance is 1697 /// provided. 1698 class VPWidenMemoryInstructionRecipe : public VPRecipeBase, public VPValue { 1699 Instruction &Ingredient; 1700 1701 // Whether the loaded-from / stored-to addresses are consecutive. 1702 bool Consecutive; 1703 1704 // Whether the consecutive loaded/stored addresses are in reverse order. 1705 bool Reverse; 1706 1707 void setMask(VPValue *Mask) { 1708 if (!Mask) 1709 return; 1710 addOperand(Mask); 1711 } 1712 1713 bool isMasked() const { 1714 return isStore() ? getNumOperands() == 3 : getNumOperands() == 2; 1715 } 1716 1717 public: 1718 VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, 1719 bool Consecutive, bool Reverse) 1720 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}), 1721 VPValue(VPValue::VPVMemoryInstructionSC, &Load, this), Ingredient(Load), 1722 Consecutive(Consecutive), Reverse(Reverse) { 1723 assert((Consecutive || !Reverse) && "Reverse implies consecutive"); 1724 setMask(Mask); 1725 } 1726 1727 VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr, 1728 VPValue *StoredValue, VPValue *Mask, 1729 bool Consecutive, bool Reverse) 1730 : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}), 1731 VPValue(VPValue::VPVMemoryInstructionSC, &Store, this), 1732 Ingredient(Store), Consecutive(Consecutive), Reverse(Reverse) { 1733 assert((Consecutive || !Reverse) && "Reverse implies consecutive"); 1734 setMask(Mask); 1735 } 1736 1737 /// Method to support type inquiry through isa, cast, and dyn_cast. 1738 static inline bool classof(const VPDef *D) { 1739 return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC; 1740 } 1741 1742 /// Return the address accessed by this recipe. 1743 VPValue *getAddr() const { 1744 return getOperand(0); // Address is the 1st, mandatory operand. 1745 } 1746 1747 /// Return the mask used by this recipe. Note that a full mask is represented 1748 /// by a nullptr. 1749 VPValue *getMask() const { 1750 // Mask is optional and therefore the last operand. 1751 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr; 1752 } 1753 1754 /// Returns true if this recipe is a store. 1755 bool isStore() const { return isa<StoreInst>(Ingredient); } 1756 1757 /// Return the address accessed by this recipe. 1758 VPValue *getStoredValue() const { 1759 assert(isStore() && "Stored value only available for store instructions"); 1760 return getOperand(1); // Stored value is the 2nd, mandatory operand. 1761 } 1762 1763 // Return whether the loaded-from / stored-to addresses are consecutive. 1764 bool isConsecutive() const { return Consecutive; } 1765 1766 // Return whether the consecutive loaded/stored addresses are in reverse 1767 // order. 1768 bool isReverse() const { return Reverse; } 1769 1770 /// Generate the wide load/store. 1771 void execute(VPTransformState &State) override; 1772 1773 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1774 /// Print the recipe. 1775 void print(raw_ostream &O, const Twine &Indent, 1776 VPSlotTracker &SlotTracker) const override; 1777 #endif 1778 1779 /// Returns true if the recipe only uses the first lane of operand \p Op. 1780 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1781 assert(is_contained(operands(), Op) && 1782 "Op must be an operand of the recipe"); 1783 1784 // Widened, consecutive memory operations only demand the first lane of 1785 // their address, unless the same operand is also stored. That latter can 1786 // happen with opaque pointers. 1787 return Op == getAddr() && isConsecutive() && 1788 (!isStore() || Op != getStoredValue()); 1789 } 1790 }; 1791 1792 /// Recipe to expand a SCEV expression. 1793 class VPExpandSCEVRecipe : public VPRecipeBase, public VPValue { 1794 const SCEV *Expr; 1795 ScalarEvolution &SE; 1796 1797 public: 1798 VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE) 1799 : VPRecipeBase(VPExpandSCEVSC, {}), VPValue(nullptr, this), Expr(Expr), 1800 SE(SE) {} 1801 1802 ~VPExpandSCEVRecipe() override = default; 1803 1804 /// Method to support type inquiry through isa, cast, and dyn_cast. 1805 static inline bool classof(const VPDef *D) { 1806 return D->getVPDefID() == VPExpandSCEVSC; 1807 } 1808 1809 /// Generate a canonical vector induction variable of the vector loop, with 1810 void execute(VPTransformState &State) override; 1811 1812 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1813 /// Print the recipe. 1814 void print(raw_ostream &O, const Twine &Indent, 1815 VPSlotTracker &SlotTracker) const override; 1816 #endif 1817 1818 const SCEV *getSCEV() const { return Expr; } 1819 }; 1820 1821 /// Canonical scalar induction phi of the vector loop. Starting at the specified 1822 /// start value (either 0 or the resume value when vectorizing the epilogue 1823 /// loop). VPWidenCanonicalIVRecipe represents the vector version of the 1824 /// canonical induction variable. 1825 class VPCanonicalIVPHIRecipe : public VPHeaderPHIRecipe { 1826 DebugLoc DL; 1827 1828 public: 1829 VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL) 1830 : VPHeaderPHIRecipe(VPValue::VPVCanonicalIVPHISC, VPCanonicalIVPHISC, 1831 nullptr, StartV), 1832 DL(DL) {} 1833 1834 ~VPCanonicalIVPHIRecipe() override = default; 1835 1836 /// Method to support type inquiry through isa, cast, and dyn_cast. 1837 static inline bool classof(const VPDef *D) { 1838 return D->getVPDefID() == VPCanonicalIVPHISC; 1839 } 1840 static inline bool classof(const VPHeaderPHIRecipe *D) { 1841 return D->getVPDefID() == VPCanonicalIVPHISC; 1842 } 1843 static inline bool classof(const VPValue *V) { 1844 return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC; 1845 } 1846 1847 /// Generate the canonical scalar induction phi of the vector loop. 1848 void execute(VPTransformState &State) override; 1849 1850 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1851 /// Print the recipe. 1852 void print(raw_ostream &O, const Twine &Indent, 1853 VPSlotTracker &SlotTracker) const override; 1854 #endif 1855 1856 /// Returns the scalar type of the induction. 1857 const Type *getScalarType() const { 1858 return getOperand(0)->getLiveInIRValue()->getType(); 1859 } 1860 1861 /// Returns true if the recipe only uses the first lane of operand \p Op. 1862 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1863 assert(is_contained(operands(), Op) && 1864 "Op must be an operand of the recipe"); 1865 return true; 1866 } 1867 }; 1868 1869 /// A Recipe for widening the canonical induction variable of the vector loop. 1870 class VPWidenCanonicalIVRecipe : public VPRecipeBase, public VPValue { 1871 public: 1872 VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV) 1873 : VPRecipeBase(VPWidenCanonicalIVSC, {CanonicalIV}), 1874 VPValue(VPValue::VPVWidenCanonicalIVSC, nullptr, this) {} 1875 1876 ~VPWidenCanonicalIVRecipe() override = default; 1877 1878 /// Method to support type inquiry through isa, cast, and dyn_cast. 1879 static inline bool classof(const VPDef *D) { 1880 return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1881 } 1882 1883 /// Extra classof implementations to allow directly casting from VPUser -> 1884 /// VPWidenCanonicalIVRecipe. 1885 static inline bool classof(const VPUser *U) { 1886 auto *R = dyn_cast<VPRecipeBase>(U); 1887 return R && R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1888 } 1889 static inline bool classof(const VPRecipeBase *R) { 1890 return R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC; 1891 } 1892 1893 /// Generate a canonical vector induction variable of the vector loop, with 1894 /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and 1895 /// step = <VF*UF, VF*UF, ..., VF*UF>. 1896 void execute(VPTransformState &State) override; 1897 1898 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1899 /// Print the recipe. 1900 void print(raw_ostream &O, const Twine &Indent, 1901 VPSlotTracker &SlotTracker) const override; 1902 #endif 1903 1904 /// Returns the scalar type of the induction. 1905 const Type *getScalarType() const { 1906 return cast<VPCanonicalIVPHIRecipe>(getOperand(0)->getDef()) 1907 ->getScalarType(); 1908 } 1909 }; 1910 1911 /// A recipe for handling phi nodes of integer and floating-point inductions, 1912 /// producing their scalar values. 1913 class VPScalarIVStepsRecipe : public VPRecipeBase, public VPValue { 1914 /// Scalar type to use for the generated values. 1915 Type *Ty; 1916 /// If not nullptr, truncate the generated values to TruncToTy. 1917 Type *TruncToTy; 1918 const InductionDescriptor &IndDesc; 1919 1920 public: 1921 VPScalarIVStepsRecipe(Type *Ty, const InductionDescriptor &IndDesc, 1922 VPValue *CanonicalIV, VPValue *Start, VPValue *Step, 1923 Type *TruncToTy) 1924 : VPRecipeBase(VPScalarIVStepsSC, {CanonicalIV, Start, Step}), 1925 VPValue(nullptr, this), Ty(Ty), TruncToTy(TruncToTy), IndDesc(IndDesc) { 1926 } 1927 1928 ~VPScalarIVStepsRecipe() override = default; 1929 1930 /// Method to support type inquiry through isa, cast, and dyn_cast. 1931 static inline bool classof(const VPDef *D) { 1932 return D->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1933 } 1934 /// Extra classof implementations to allow directly casting from VPUser -> 1935 /// VPScalarIVStepsRecipe. 1936 static inline bool classof(const VPUser *U) { 1937 auto *R = dyn_cast<VPRecipeBase>(U); 1938 return R && R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1939 } 1940 static inline bool classof(const VPRecipeBase *R) { 1941 return R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC; 1942 } 1943 1944 /// Generate the scalarized versions of the phi node as needed by their users. 1945 void execute(VPTransformState &State) override; 1946 1947 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1948 /// Print the recipe. 1949 void print(raw_ostream &O, const Twine &Indent, 1950 VPSlotTracker &SlotTracker) const override; 1951 #endif 1952 1953 /// Returns true if the induction is canonical, i.e. starting at 0 and 1954 /// incremented by UF * VF (= the original IV is incremented by 1). 1955 bool isCanonical() const; 1956 1957 VPCanonicalIVPHIRecipe *getCanonicalIV() const; 1958 VPValue *getStartValue() const { return getOperand(1); } 1959 VPValue *getStepValue() const { return getOperand(2); } 1960 1961 /// Returns true if the recipe only uses the first lane of operand \p Op. 1962 bool onlyFirstLaneUsed(const VPValue *Op) const override { 1963 assert(is_contained(operands(), Op) && 1964 "Op must be an operand of the recipe"); 1965 return true; 1966 } 1967 }; 1968 1969 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It 1970 /// holds a sequence of zero or more VPRecipe's each representing a sequence of 1971 /// output IR instructions. All PHI-like recipes must come before any non-PHI recipes. 1972 class VPBasicBlock : public VPBlockBase { 1973 public: 1974 using RecipeListTy = iplist<VPRecipeBase>; 1975 1976 private: 1977 /// The VPRecipes held in the order of output instructions to generate. 1978 RecipeListTy Recipes; 1979 1980 public: 1981 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr) 1982 : VPBlockBase(VPBasicBlockSC, Name.str()) { 1983 if (Recipe) 1984 appendRecipe(Recipe); 1985 } 1986 1987 ~VPBasicBlock() override { 1988 while (!Recipes.empty()) 1989 Recipes.pop_back(); 1990 } 1991 1992 /// Instruction iterators... 1993 using iterator = RecipeListTy::iterator; 1994 using const_iterator = RecipeListTy::const_iterator; 1995 using reverse_iterator = RecipeListTy::reverse_iterator; 1996 using const_reverse_iterator = RecipeListTy::const_reverse_iterator; 1997 1998 //===--------------------------------------------------------------------===// 1999 /// Recipe iterator methods 2000 /// 2001 inline iterator begin() { return Recipes.begin(); } 2002 inline const_iterator begin() const { return Recipes.begin(); } 2003 inline iterator end() { return Recipes.end(); } 2004 inline const_iterator end() const { return Recipes.end(); } 2005 2006 inline reverse_iterator rbegin() { return Recipes.rbegin(); } 2007 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); } 2008 inline reverse_iterator rend() { return Recipes.rend(); } 2009 inline const_reverse_iterator rend() const { return Recipes.rend(); } 2010 2011 inline size_t size() const { return Recipes.size(); } 2012 inline bool empty() const { return Recipes.empty(); } 2013 inline const VPRecipeBase &front() const { return Recipes.front(); } 2014 inline VPRecipeBase &front() { return Recipes.front(); } 2015 inline const VPRecipeBase &back() const { return Recipes.back(); } 2016 inline VPRecipeBase &back() { return Recipes.back(); } 2017 2018 /// Returns a reference to the list of recipes. 2019 RecipeListTy &getRecipeList() { return Recipes; } 2020 2021 /// Returns a pointer to a member of the recipe list. 2022 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) { 2023 return &VPBasicBlock::Recipes; 2024 } 2025 2026 /// Method to support type inquiry through isa, cast, and dyn_cast. 2027 static inline bool classof(const VPBlockBase *V) { 2028 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC; 2029 } 2030 2031 void insert(VPRecipeBase *Recipe, iterator InsertPt) { 2032 assert(Recipe && "No recipe to append."); 2033 assert(!Recipe->Parent && "Recipe already in VPlan"); 2034 Recipe->Parent = this; 2035 Recipes.insert(InsertPt, Recipe); 2036 } 2037 2038 /// Augment the existing recipes of a VPBasicBlock with an additional 2039 /// \p Recipe as the last recipe. 2040 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); } 2041 2042 /// The method which generates the output IR instructions that correspond to 2043 /// this VPBasicBlock, thereby "executing" the VPlan. 2044 void execute(struct VPTransformState *State) override; 2045 2046 /// Return the position of the first non-phi node recipe in the block. 2047 iterator getFirstNonPhi(); 2048 2049 /// Returns an iterator range over the PHI-like recipes in the block. 2050 iterator_range<iterator> phis() { 2051 return make_range(begin(), getFirstNonPhi()); 2052 } 2053 2054 void dropAllReferences(VPValue *NewValue) override; 2055 2056 /// Split current block at \p SplitAt by inserting a new block between the 2057 /// current block and its successors and moving all recipes starting at 2058 /// SplitAt to the new block. Returns the new block. 2059 VPBasicBlock *splitAt(iterator SplitAt); 2060 2061 VPRegionBlock *getEnclosingLoopRegion(); 2062 2063 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2064 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p 2065 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers. 2066 /// 2067 /// Note that the numbering is applied to the whole VPlan, so printing 2068 /// individual blocks is consistent with the whole VPlan printing. 2069 void print(raw_ostream &O, const Twine &Indent, 2070 VPSlotTracker &SlotTracker) const override; 2071 using VPBlockBase::print; // Get the print(raw_stream &O) version. 2072 #endif 2073 2074 private: 2075 /// Create an IR BasicBlock to hold the output instructions generated by this 2076 /// VPBasicBlock, and return it. Update the CFGState accordingly. 2077 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG); 2078 }; 2079 2080 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks 2081 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG. 2082 /// A VPRegionBlock may indicate that its contents are to be replicated several 2083 /// times. This is designed to support predicated scalarization, in which a 2084 /// scalar if-then code structure needs to be generated VF * UF times. Having 2085 /// this replication indicator helps to keep a single model for multiple 2086 /// candidate VF's. The actual replication takes place only once the desired VF 2087 /// and UF have been determined. 2088 class VPRegionBlock : public VPBlockBase { 2089 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock. 2090 VPBlockBase *Entry; 2091 2092 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock. 2093 VPBlockBase *Exit; 2094 2095 /// An indicator whether this region is to generate multiple replicated 2096 /// instances of output IR corresponding to its VPBlockBases. 2097 bool IsReplicator; 2098 2099 public: 2100 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit, 2101 const std::string &Name = "", bool IsReplicator = false) 2102 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit), 2103 IsReplicator(IsReplicator) { 2104 assert(Entry->getPredecessors().empty() && "Entry block has predecessors."); 2105 assert(Exit->getSuccessors().empty() && "Exit block has successors."); 2106 Entry->setParent(this); 2107 Exit->setParent(this); 2108 } 2109 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false) 2110 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr), 2111 IsReplicator(IsReplicator) {} 2112 2113 ~VPRegionBlock() override { 2114 if (Entry) { 2115 VPValue DummyValue; 2116 Entry->dropAllReferences(&DummyValue); 2117 deleteCFG(Entry); 2118 } 2119 } 2120 2121 /// Method to support type inquiry through isa, cast, and dyn_cast. 2122 static inline bool classof(const VPBlockBase *V) { 2123 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC; 2124 } 2125 2126 const VPBlockBase *getEntry() const { return Entry; } 2127 VPBlockBase *getEntry() { return Entry; } 2128 2129 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p 2130 /// EntryBlock must have no predecessors. 2131 void setEntry(VPBlockBase *EntryBlock) { 2132 assert(EntryBlock->getPredecessors().empty() && 2133 "Entry block cannot have predecessors."); 2134 Entry = EntryBlock; 2135 EntryBlock->setParent(this); 2136 } 2137 2138 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a 2139 // specific interface of llvm::Function, instead of using 2140 // GraphTraints::getEntryNode. We should add a new template parameter to 2141 // DominatorTreeBase representing the Graph type. 2142 VPBlockBase &front() const { return *Entry; } 2143 2144 const VPBlockBase *getExit() const { return Exit; } 2145 VPBlockBase *getExit() { return Exit; } 2146 2147 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p 2148 /// ExitBlock must have no successors. 2149 void setExit(VPBlockBase *ExitBlock) { 2150 assert(ExitBlock->getSuccessors().empty() && 2151 "Exit block cannot have successors."); 2152 Exit = ExitBlock; 2153 ExitBlock->setParent(this); 2154 } 2155 2156 /// Returns the pre-header VPBasicBlock of the loop region. 2157 VPBasicBlock *getPreheaderVPBB() { 2158 assert(!isReplicator() && "should only get pre-header of loop regions"); 2159 return getSinglePredecessor()->getExitBasicBlock(); 2160 } 2161 2162 /// An indicator whether this region is to generate multiple replicated 2163 /// instances of output IR corresponding to its VPBlockBases. 2164 bool isReplicator() const { return IsReplicator; } 2165 2166 /// The method which generates the output IR instructions that correspond to 2167 /// this VPRegionBlock, thereby "executing" the VPlan. 2168 void execute(struct VPTransformState *State) override; 2169 2170 void dropAllReferences(VPValue *NewValue) override; 2171 2172 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2173 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with 2174 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using 2175 /// consequtive numbers. 2176 /// 2177 /// Note that the numbering is applied to the whole VPlan, so printing 2178 /// individual regions is consistent with the whole VPlan printing. 2179 void print(raw_ostream &O, const Twine &Indent, 2180 VPSlotTracker &SlotTracker) const override; 2181 using VPBlockBase::print; // Get the print(raw_stream &O) version. 2182 #endif 2183 }; 2184 2185 //===----------------------------------------------------------------------===// 2186 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs // 2187 //===----------------------------------------------------------------------===// 2188 2189 // The following set of template specializations implement GraphTraits to treat 2190 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note 2191 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the 2192 // VPBlockBase is a VPRegionBlock, this specialization provides access to its 2193 // successors/predecessors but not to the blocks inside the region. 2194 2195 template <> struct GraphTraits<VPBlockBase *> { 2196 using NodeRef = VPBlockBase *; 2197 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 2198 2199 static NodeRef getEntryNode(NodeRef N) { return N; } 2200 2201 static inline ChildIteratorType child_begin(NodeRef N) { 2202 return N->getSuccessors().begin(); 2203 } 2204 2205 static inline ChildIteratorType child_end(NodeRef N) { 2206 return N->getSuccessors().end(); 2207 } 2208 }; 2209 2210 template <> struct GraphTraits<const VPBlockBase *> { 2211 using NodeRef = const VPBlockBase *; 2212 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator; 2213 2214 static NodeRef getEntryNode(NodeRef N) { return N; } 2215 2216 static inline ChildIteratorType child_begin(NodeRef N) { 2217 return N->getSuccessors().begin(); 2218 } 2219 2220 static inline ChildIteratorType child_end(NodeRef N) { 2221 return N->getSuccessors().end(); 2222 } 2223 }; 2224 2225 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead 2226 // of successors for the inverse traversal. 2227 template <> struct GraphTraits<Inverse<VPBlockBase *>> { 2228 using NodeRef = VPBlockBase *; 2229 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator; 2230 2231 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; } 2232 2233 static inline ChildIteratorType child_begin(NodeRef N) { 2234 return N->getPredecessors().begin(); 2235 } 2236 2237 static inline ChildIteratorType child_end(NodeRef N) { 2238 return N->getPredecessors().end(); 2239 } 2240 }; 2241 2242 // The following set of template specializations implement GraphTraits to 2243 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important 2244 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases 2245 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so 2246 // there won't be automatic recursion into other VPBlockBases that turn to be 2247 // VPRegionBlocks. 2248 2249 template <> 2250 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> { 2251 using GraphRef = VPRegionBlock *; 2252 using nodes_iterator = df_iterator<NodeRef>; 2253 2254 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 2255 2256 static nodes_iterator nodes_begin(GraphRef N) { 2257 return nodes_iterator::begin(N->getEntry()); 2258 } 2259 2260 static nodes_iterator nodes_end(GraphRef N) { 2261 // df_iterator::end() returns an empty iterator so the node used doesn't 2262 // matter. 2263 return nodes_iterator::end(N); 2264 } 2265 }; 2266 2267 template <> 2268 struct GraphTraits<const VPRegionBlock *> 2269 : public GraphTraits<const VPBlockBase *> { 2270 using GraphRef = const VPRegionBlock *; 2271 using nodes_iterator = df_iterator<NodeRef>; 2272 2273 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); } 2274 2275 static nodes_iterator nodes_begin(GraphRef N) { 2276 return nodes_iterator::begin(N->getEntry()); 2277 } 2278 2279 static nodes_iterator nodes_end(GraphRef N) { 2280 // df_iterator::end() returns an empty iterator so the node used doesn't 2281 // matter. 2282 return nodes_iterator::end(N); 2283 } 2284 }; 2285 2286 template <> 2287 struct GraphTraits<Inverse<VPRegionBlock *>> 2288 : public GraphTraits<Inverse<VPBlockBase *>> { 2289 using GraphRef = VPRegionBlock *; 2290 using nodes_iterator = df_iterator<NodeRef>; 2291 2292 static NodeRef getEntryNode(Inverse<GraphRef> N) { 2293 return N.Graph->getExit(); 2294 } 2295 2296 static nodes_iterator nodes_begin(GraphRef N) { 2297 return nodes_iterator::begin(N->getExit()); 2298 } 2299 2300 static nodes_iterator nodes_end(GraphRef N) { 2301 // df_iterator::end() returns an empty iterator so the node used doesn't 2302 // matter. 2303 return nodes_iterator::end(N); 2304 } 2305 }; 2306 2307 /// Iterator to traverse all successors of a VPBlockBase node. This includes the 2308 /// entry node of VPRegionBlocks. Exit blocks of a region implicitly have their 2309 /// parent region's successors. This ensures all blocks in a region are visited 2310 /// before any blocks in a successor region when doing a reverse post-order 2311 // traversal of the graph. 2312 template <typename BlockPtrTy> 2313 class VPAllSuccessorsIterator 2314 : public iterator_facade_base<VPAllSuccessorsIterator<BlockPtrTy>, 2315 std::forward_iterator_tag, VPBlockBase> { 2316 BlockPtrTy Block; 2317 /// Index of the current successor. For VPBasicBlock nodes, this simply is the 2318 /// index for the successor array. For VPRegionBlock, SuccessorIdx == 0 is 2319 /// used for the region's entry block, and SuccessorIdx - 1 are the indices 2320 /// for the successor array. 2321 size_t SuccessorIdx; 2322 2323 static BlockPtrTy getBlockWithSuccs(BlockPtrTy Current) { 2324 while (Current && Current->getNumSuccessors() == 0) 2325 Current = Current->getParent(); 2326 return Current; 2327 } 2328 2329 /// Templated helper to dereference successor \p SuccIdx of \p Block. Used by 2330 /// both the const and non-const operator* implementations. 2331 template <typename T1> static T1 deref(T1 Block, unsigned SuccIdx) { 2332 if (auto *R = dyn_cast<VPRegionBlock>(Block)) { 2333 if (SuccIdx == 0) 2334 return R->getEntry(); 2335 SuccIdx--; 2336 } 2337 2338 // For exit blocks, use the next parent region with successors. 2339 return getBlockWithSuccs(Block)->getSuccessors()[SuccIdx]; 2340 } 2341 2342 public: 2343 VPAllSuccessorsIterator(BlockPtrTy Block, size_t Idx = 0) 2344 : Block(Block), SuccessorIdx(Idx) {} 2345 VPAllSuccessorsIterator(const VPAllSuccessorsIterator &Other) 2346 : Block(Other.Block), SuccessorIdx(Other.SuccessorIdx) {} 2347 2348 VPAllSuccessorsIterator &operator=(const VPAllSuccessorsIterator &R) { 2349 Block = R.Block; 2350 SuccessorIdx = R.SuccessorIdx; 2351 return *this; 2352 } 2353 2354 static VPAllSuccessorsIterator end(BlockPtrTy Block) { 2355 BlockPtrTy ParentWithSuccs = getBlockWithSuccs(Block); 2356 unsigned NumSuccessors = ParentWithSuccs 2357 ? ParentWithSuccs->getNumSuccessors() 2358 : Block->getNumSuccessors(); 2359 2360 if (auto *R = dyn_cast<VPRegionBlock>(Block)) 2361 return {R, NumSuccessors + 1}; 2362 return {Block, NumSuccessors}; 2363 } 2364 2365 bool operator==(const VPAllSuccessorsIterator &R) const { 2366 return Block == R.Block && SuccessorIdx == R.SuccessorIdx; 2367 } 2368 2369 const VPBlockBase *operator*() const { return deref(Block, SuccessorIdx); } 2370 2371 BlockPtrTy operator*() { return deref(Block, SuccessorIdx); } 2372 2373 VPAllSuccessorsIterator &operator++() { 2374 SuccessorIdx++; 2375 return *this; 2376 } 2377 2378 VPAllSuccessorsIterator operator++(int X) { 2379 VPAllSuccessorsIterator Orig = *this; 2380 SuccessorIdx++; 2381 return Orig; 2382 } 2383 }; 2384 2385 /// Helper for GraphTraits specialization that traverses through VPRegionBlocks. 2386 template <typename BlockTy> class VPBlockRecursiveTraversalWrapper { 2387 BlockTy Entry; 2388 2389 public: 2390 VPBlockRecursiveTraversalWrapper(BlockTy Entry) : Entry(Entry) {} 2391 BlockTy getEntry() { return Entry; } 2392 }; 2393 2394 /// GraphTraits specialization to recursively traverse VPBlockBase nodes, 2395 /// including traversing through VPRegionBlocks. Exit blocks of a region 2396 /// implicitly have their parent region's successors. This ensures all blocks in 2397 /// a region are visited before any blocks in a successor region when doing a 2398 /// reverse post-order traversal of the graph. 2399 template <> 2400 struct GraphTraits<VPBlockRecursiveTraversalWrapper<VPBlockBase *>> { 2401 using NodeRef = VPBlockBase *; 2402 using ChildIteratorType = VPAllSuccessorsIterator<VPBlockBase *>; 2403 2404 static NodeRef 2405 getEntryNode(VPBlockRecursiveTraversalWrapper<VPBlockBase *> N) { 2406 return N.getEntry(); 2407 } 2408 2409 static inline ChildIteratorType child_begin(NodeRef N) { 2410 return ChildIteratorType(N); 2411 } 2412 2413 static inline ChildIteratorType child_end(NodeRef N) { 2414 return ChildIteratorType::end(N); 2415 } 2416 }; 2417 2418 template <> 2419 struct GraphTraits<VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> { 2420 using NodeRef = const VPBlockBase *; 2421 using ChildIteratorType = VPAllSuccessorsIterator<const VPBlockBase *>; 2422 2423 static NodeRef 2424 getEntryNode(VPBlockRecursiveTraversalWrapper<const VPBlockBase *> N) { 2425 return N.getEntry(); 2426 } 2427 2428 static inline ChildIteratorType child_begin(NodeRef N) { 2429 return ChildIteratorType(N); 2430 } 2431 2432 static inline ChildIteratorType child_end(NodeRef N) { 2433 return ChildIteratorType::end(N); 2434 } 2435 }; 2436 2437 /// VPlan models a candidate for vectorization, encoding various decisions take 2438 /// to produce efficient output IR, including which branches, basic-blocks and 2439 /// output IR instructions to generate, and their cost. VPlan holds a 2440 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry 2441 /// VPBlock. 2442 class VPlan { 2443 friend class VPlanPrinter; 2444 friend class VPSlotTracker; 2445 2446 /// Hold the single entry to the Hierarchical CFG of the VPlan. 2447 VPBlockBase *Entry; 2448 2449 /// Holds the VFs applicable to this VPlan. 2450 SmallSetVector<ElementCount, 2> VFs; 2451 2452 /// Holds the name of the VPlan, for printing. 2453 std::string Name; 2454 2455 /// Holds all the external definitions created for this VPlan. External 2456 /// definitions must be immutable and hold a pointer to their underlying IR. 2457 DenseMap<Value *, VPValue *> VPExternalDefs; 2458 2459 /// Represents the trip count of the original loop, for folding 2460 /// the tail. 2461 VPValue *TripCount = nullptr; 2462 2463 /// Represents the backedge taken count of the original loop, for folding 2464 /// the tail. It equals TripCount - 1. 2465 VPValue *BackedgeTakenCount = nullptr; 2466 2467 /// Represents the vector trip count. 2468 VPValue VectorTripCount; 2469 2470 /// Holds a mapping between Values and their corresponding VPValue inside 2471 /// VPlan. 2472 Value2VPValueTy Value2VPValue; 2473 2474 /// Contains all VPValues that been allocated by addVPValue directly and need 2475 /// to be free when the plan's destructor is called. 2476 SmallVector<VPValue *, 16> VPValuesToFree; 2477 2478 /// Holds the VPLoopInfo analysis for this VPlan. 2479 VPLoopInfo VPLInfo; 2480 2481 /// Indicates whether it is safe use the Value2VPValue mapping or if the 2482 /// mapping cannot be used any longer, because it is stale. 2483 bool Value2VPValueEnabled = true; 2484 2485 public: 2486 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) { 2487 if (Entry) 2488 Entry->setPlan(this); 2489 } 2490 2491 ~VPlan() { 2492 if (Entry) { 2493 VPValue DummyValue; 2494 for (VPBlockBase *Block : depth_first(Entry)) 2495 Block->dropAllReferences(&DummyValue); 2496 2497 VPBlockBase::deleteCFG(Entry); 2498 } 2499 for (VPValue *VPV : VPValuesToFree) 2500 delete VPV; 2501 if (TripCount) 2502 delete TripCount; 2503 if (BackedgeTakenCount) 2504 delete BackedgeTakenCount; 2505 for (auto &P : VPExternalDefs) 2506 delete P.second; 2507 } 2508 2509 /// Prepare the plan for execution, setting up the required live-in values. 2510 void prepareToExecute(Value *TripCount, Value *VectorTripCount, 2511 Value *CanonicalIVStartValue, VPTransformState &State); 2512 2513 /// Generate the IR code for this VPlan. 2514 void execute(struct VPTransformState *State); 2515 2516 VPBlockBase *getEntry() { return Entry; } 2517 const VPBlockBase *getEntry() const { return Entry; } 2518 2519 VPBlockBase *setEntry(VPBlockBase *Block) { 2520 Entry = Block; 2521 Block->setPlan(this); 2522 return Entry; 2523 } 2524 2525 /// The trip count of the original loop. 2526 VPValue *getOrCreateTripCount() { 2527 if (!TripCount) 2528 TripCount = new VPValue(); 2529 return TripCount; 2530 } 2531 2532 /// The backedge taken count of the original loop. 2533 VPValue *getOrCreateBackedgeTakenCount() { 2534 if (!BackedgeTakenCount) 2535 BackedgeTakenCount = new VPValue(); 2536 return BackedgeTakenCount; 2537 } 2538 2539 /// The vector trip count. 2540 VPValue &getVectorTripCount() { return VectorTripCount; } 2541 2542 /// Mark the plan to indicate that using Value2VPValue is not safe any 2543 /// longer, because it may be stale. 2544 void disableValue2VPValue() { Value2VPValueEnabled = false; } 2545 2546 void addVF(ElementCount VF) { VFs.insert(VF); } 2547 2548 bool hasVF(ElementCount VF) { return VFs.count(VF); } 2549 2550 const std::string &getName() const { return Name; } 2551 2552 void setName(const Twine &newName) { Name = newName.str(); } 2553 2554 /// Get the existing or add a new external definition for \p V. 2555 VPValue *getOrAddExternalDef(Value *V) { 2556 auto I = VPExternalDefs.insert({V, nullptr}); 2557 if (I.second) 2558 I.first->second = new VPValue(V); 2559 return I.first->second; 2560 } 2561 2562 void addVPValue(Value *V) { 2563 assert(Value2VPValueEnabled && 2564 "IR value to VPValue mapping may be out of date!"); 2565 assert(V && "Trying to add a null Value to VPlan"); 2566 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2567 VPValue *VPV = new VPValue(V); 2568 Value2VPValue[V] = VPV; 2569 VPValuesToFree.push_back(VPV); 2570 } 2571 2572 void addVPValue(Value *V, VPValue *VPV) { 2573 assert(Value2VPValueEnabled && "Value2VPValue mapping may be out of date!"); 2574 assert(V && "Trying to add a null Value to VPlan"); 2575 assert(!Value2VPValue.count(V) && "Value already exists in VPlan"); 2576 Value2VPValue[V] = VPV; 2577 } 2578 2579 /// Returns the VPValue for \p V. \p OverrideAllowed can be used to disable 2580 /// checking whether it is safe to query VPValues using IR Values. 2581 VPValue *getVPValue(Value *V, bool OverrideAllowed = false) { 2582 assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) && 2583 "Value2VPValue mapping may be out of date!"); 2584 assert(V && "Trying to get the VPValue of a null Value"); 2585 assert(Value2VPValue.count(V) && "Value does not exist in VPlan"); 2586 return Value2VPValue[V]; 2587 } 2588 2589 /// Gets the VPValue or adds a new one (if none exists yet) for \p V. \p 2590 /// OverrideAllowed can be used to disable checking whether it is safe to 2591 /// query VPValues using IR Values. 2592 VPValue *getOrAddVPValue(Value *V, bool OverrideAllowed = false) { 2593 assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) && 2594 "Value2VPValue mapping may be out of date!"); 2595 assert(V && "Trying to get or add the VPValue of a null Value"); 2596 if (!Value2VPValue.count(V)) 2597 addVPValue(V); 2598 return getVPValue(V); 2599 } 2600 2601 void removeVPValueFor(Value *V) { 2602 assert(Value2VPValueEnabled && 2603 "IR value to VPValue mapping may be out of date!"); 2604 Value2VPValue.erase(V); 2605 } 2606 2607 /// Return the VPLoopInfo analysis for this VPlan. 2608 VPLoopInfo &getVPLoopInfo() { return VPLInfo; } 2609 const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; } 2610 2611 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2612 /// Print this VPlan to \p O. 2613 void print(raw_ostream &O) const; 2614 2615 /// Print this VPlan in DOT format to \p O. 2616 void printDOT(raw_ostream &O) const; 2617 2618 /// Dump the plan to stderr (for debugging). 2619 LLVM_DUMP_METHOD void dump() const; 2620 #endif 2621 2622 /// Returns a range mapping the values the range \p Operands to their 2623 /// corresponding VPValues. 2624 iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>> 2625 mapToVPValues(User::op_range Operands) { 2626 std::function<VPValue *(Value *)> Fn = [this](Value *Op) { 2627 return getOrAddVPValue(Op); 2628 }; 2629 return map_range(Operands, Fn); 2630 } 2631 2632 /// Returns true if \p VPV is uniform after vectorization. 2633 bool isUniformAfterVectorization(VPValue *VPV) const { 2634 auto RepR = dyn_cast_or_null<VPReplicateRecipe>(VPV->getDef()); 2635 return !VPV->getDef() || (RepR && RepR->isUniform()); 2636 } 2637 2638 /// Returns the VPRegionBlock of the vector loop. 2639 VPRegionBlock *getVectorLoopRegion() { 2640 if (auto *R = dyn_cast<VPRegionBlock>(getEntry())) 2641 return R; 2642 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor()); 2643 } 2644 const VPRegionBlock *getVectorLoopRegion() const { 2645 if (auto *R = dyn_cast<VPRegionBlock>(getEntry())) 2646 return R; 2647 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor()); 2648 } 2649 2650 /// Returns the canonical induction recipe of the vector loop. 2651 VPCanonicalIVPHIRecipe *getCanonicalIV() { 2652 VPBasicBlock *EntryVPBB = getVectorLoopRegion()->getEntryBasicBlock(); 2653 if (EntryVPBB->empty()) { 2654 // VPlan native path. 2655 EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor()); 2656 } 2657 return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin()); 2658 } 2659 2660 private: 2661 /// Add to the given dominator tree the header block and every new basic block 2662 /// that was created between it and the latch block, inclusive. 2663 static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB, 2664 BasicBlock *LoopPreHeaderBB, 2665 BasicBlock *LoopExitBB); 2666 }; 2667 2668 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2669 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is 2670 /// indented and follows the dot format. 2671 class VPlanPrinter { 2672 raw_ostream &OS; 2673 const VPlan &Plan; 2674 unsigned Depth = 0; 2675 unsigned TabWidth = 2; 2676 std::string Indent; 2677 unsigned BID = 0; 2678 SmallDenseMap<const VPBlockBase *, unsigned> BlockID; 2679 2680 VPSlotTracker SlotTracker; 2681 2682 /// Handle indentation. 2683 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); } 2684 2685 /// Print a given \p Block of the Plan. 2686 void dumpBlock(const VPBlockBase *Block); 2687 2688 /// Print the information related to the CFG edges going out of a given 2689 /// \p Block, followed by printing the successor blocks themselves. 2690 void dumpEdges(const VPBlockBase *Block); 2691 2692 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing 2693 /// its successor blocks. 2694 void dumpBasicBlock(const VPBasicBlock *BasicBlock); 2695 2696 /// Print a given \p Region of the Plan. 2697 void dumpRegion(const VPRegionBlock *Region); 2698 2699 unsigned getOrCreateBID(const VPBlockBase *Block) { 2700 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++; 2701 } 2702 2703 Twine getOrCreateName(const VPBlockBase *Block); 2704 2705 Twine getUID(const VPBlockBase *Block); 2706 2707 /// Print the information related to a CFG edge between two VPBlockBases. 2708 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden, 2709 const Twine &Label); 2710 2711 public: 2712 VPlanPrinter(raw_ostream &O, const VPlan &P) 2713 : OS(O), Plan(P), SlotTracker(&P) {} 2714 2715 LLVM_DUMP_METHOD void dump(); 2716 }; 2717 2718 struct VPlanIngredient { 2719 const Value *V; 2720 2721 VPlanIngredient(const Value *V) : V(V) {} 2722 2723 void print(raw_ostream &O) const; 2724 }; 2725 2726 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) { 2727 I.print(OS); 2728 return OS; 2729 } 2730 2731 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) { 2732 Plan.print(OS); 2733 return OS; 2734 } 2735 #endif 2736 2737 //===----------------------------------------------------------------------===// 2738 // VPlan Utilities 2739 //===----------------------------------------------------------------------===// 2740 2741 /// Class that provides utilities for VPBlockBases in VPlan. 2742 class VPBlockUtils { 2743 public: 2744 VPBlockUtils() = delete; 2745 2746 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p 2747 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p 2748 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's 2749 /// successors are moved from \p BlockPtr to \p NewBlock and \p BlockPtr's 2750 /// conditional bit is propagated to \p NewBlock. \p NewBlock must have 2751 /// neither successors nor predecessors. 2752 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) { 2753 assert(NewBlock->getSuccessors().empty() && 2754 NewBlock->getPredecessors().empty() && 2755 "Can't insert new block with predecessors or successors."); 2756 NewBlock->setParent(BlockPtr->getParent()); 2757 SmallVector<VPBlockBase *> Succs(BlockPtr->successors()); 2758 for (VPBlockBase *Succ : Succs) { 2759 disconnectBlocks(BlockPtr, Succ); 2760 connectBlocks(NewBlock, Succ); 2761 } 2762 NewBlock->setCondBit(BlockPtr->getCondBit()); 2763 BlockPtr->setCondBit(nullptr); 2764 connectBlocks(BlockPtr, NewBlock); 2765 } 2766 2767 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p 2768 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p 2769 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr 2770 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor 2771 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse 2772 /// must have neither successors nor predecessors. 2773 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, 2774 VPValue *Condition, VPBlockBase *BlockPtr) { 2775 assert(IfTrue->getSuccessors().empty() && 2776 "Can't insert IfTrue with successors."); 2777 assert(IfFalse->getSuccessors().empty() && 2778 "Can't insert IfFalse with successors."); 2779 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition); 2780 IfTrue->setPredecessors({BlockPtr}); 2781 IfFalse->setPredecessors({BlockPtr}); 2782 IfTrue->setParent(BlockPtr->getParent()); 2783 IfFalse->setParent(BlockPtr->getParent()); 2784 } 2785 2786 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to 2787 /// the successors of \p From and \p From to the predecessors of \p To. Both 2788 /// VPBlockBases must have the same parent, which can be null. Both 2789 /// VPBlockBases can be already connected to other VPBlockBases. 2790 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) { 2791 assert((From->getParent() == To->getParent()) && 2792 "Can't connect two block with different parents"); 2793 assert(From->getNumSuccessors() < 2 && 2794 "Blocks can't have more than two successors."); 2795 From->appendSuccessor(To); 2796 To->appendPredecessor(From); 2797 } 2798 2799 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To 2800 /// from the successors of \p From and \p From from the predecessors of \p To. 2801 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) { 2802 assert(To && "Successor to disconnect is null."); 2803 From->removeSuccessor(To); 2804 To->removePredecessor(From); 2805 } 2806 2807 /// Try to merge \p Block into its single predecessor, if \p Block is a 2808 /// VPBasicBlock and its predecessor has a single successor. Returns a pointer 2809 /// to the predecessor \p Block was merged into or nullptr otherwise. 2810 static VPBasicBlock *tryToMergeBlockIntoPredecessor(VPBlockBase *Block) { 2811 auto *VPBB = dyn_cast<VPBasicBlock>(Block); 2812 auto *PredVPBB = 2813 dyn_cast_or_null<VPBasicBlock>(Block->getSinglePredecessor()); 2814 if (!VPBB || !PredVPBB || PredVPBB->getNumSuccessors() != 1) 2815 return nullptr; 2816 2817 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) 2818 R.moveBefore(*PredVPBB, PredVPBB->end()); 2819 VPBlockUtils::disconnectBlocks(PredVPBB, VPBB); 2820 auto *ParentRegion = cast<VPRegionBlock>(Block->getParent()); 2821 if (ParentRegion->getExit() == Block) 2822 ParentRegion->setExit(PredVPBB); 2823 SmallVector<VPBlockBase *> Successors(Block->successors()); 2824 for (auto *Succ : Successors) { 2825 VPBlockUtils::disconnectBlocks(Block, Succ); 2826 VPBlockUtils::connectBlocks(PredVPBB, Succ); 2827 } 2828 delete Block; 2829 return PredVPBB; 2830 } 2831 2832 /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge. 2833 static bool isBackEdge(const VPBlockBase *FromBlock, 2834 const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) { 2835 assert(FromBlock->getParent() == ToBlock->getParent() && 2836 FromBlock->getParent() && "Must be in same region"); 2837 const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock); 2838 const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock); 2839 if (!FromLoop || !ToLoop || FromLoop != ToLoop) 2840 return false; 2841 2842 // A back-edge is a branch from the loop latch to its header. 2843 return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader(); 2844 } 2845 2846 /// Returns true if \p Block is a loop latch 2847 static bool blockIsLoopLatch(const VPBlockBase *Block, 2848 const VPLoopInfo *VPLInfo) { 2849 if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block)) 2850 return ParentVPL->isLoopLatch(Block); 2851 2852 return false; 2853 } 2854 2855 /// Count and return the number of succesors of \p PredBlock excluding any 2856 /// backedges. 2857 static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock, 2858 VPLoopInfo *VPLI) { 2859 unsigned Count = 0; 2860 for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) { 2861 if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI)) 2862 Count++; 2863 } 2864 return Count; 2865 } 2866 2867 /// Return an iterator range over \p Range which only includes \p BlockTy 2868 /// blocks. The accesses are casted to \p BlockTy. 2869 template <typename BlockTy, typename T> 2870 static auto blocksOnly(const T &Range) { 2871 // Create BaseTy with correct const-ness based on BlockTy. 2872 using BaseTy = 2873 typename std::conditional<std::is_const<BlockTy>::value, 2874 const VPBlockBase, VPBlockBase>::type; 2875 2876 // We need to first create an iterator range over (const) BlocktTy & instead 2877 // of (const) BlockTy * for filter_range to work properly. 2878 auto Mapped = 2879 map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; }); 2880 auto Filter = make_filter_range( 2881 Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); }); 2882 return map_range(Filter, [](BaseTy &Block) -> BlockTy * { 2883 return cast<BlockTy>(&Block); 2884 }); 2885 } 2886 }; 2887 2888 class VPInterleavedAccessInfo { 2889 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *> 2890 InterleaveGroupMap; 2891 2892 /// Type for mapping of instruction based interleave groups to VPInstruction 2893 /// interleave groups 2894 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *, 2895 InterleaveGroup<VPInstruction> *>; 2896 2897 /// Recursively \p Region and populate VPlan based interleave groups based on 2898 /// \p IAI. 2899 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New, 2900 InterleavedAccessInfo &IAI); 2901 /// Recursively traverse \p Block and populate VPlan based interleave groups 2902 /// based on \p IAI. 2903 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 2904 InterleavedAccessInfo &IAI); 2905 2906 public: 2907 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI); 2908 2909 ~VPInterleavedAccessInfo() { 2910 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet; 2911 // Avoid releasing a pointer twice. 2912 for (auto &I : InterleaveGroupMap) 2913 DelSet.insert(I.second); 2914 for (auto *Ptr : DelSet) 2915 delete Ptr; 2916 } 2917 2918 /// Get the interleave group that \p Instr belongs to. 2919 /// 2920 /// \returns nullptr if doesn't have such group. 2921 InterleaveGroup<VPInstruction> * 2922 getInterleaveGroup(VPInstruction *Instr) const { 2923 return InterleaveGroupMap.lookup(Instr); 2924 } 2925 }; 2926 2927 /// Class that maps (parts of) an existing VPlan to trees of combined 2928 /// VPInstructions. 2929 class VPlanSlp { 2930 enum class OpMode { Failed, Load, Opcode }; 2931 2932 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as 2933 /// DenseMap keys. 2934 struct BundleDenseMapInfo { 2935 static SmallVector<VPValue *, 4> getEmptyKey() { 2936 return {reinterpret_cast<VPValue *>(-1)}; 2937 } 2938 2939 static SmallVector<VPValue *, 4> getTombstoneKey() { 2940 return {reinterpret_cast<VPValue *>(-2)}; 2941 } 2942 2943 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) { 2944 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2945 } 2946 2947 static bool isEqual(const SmallVector<VPValue *, 4> &LHS, 2948 const SmallVector<VPValue *, 4> &RHS) { 2949 return LHS == RHS; 2950 } 2951 }; 2952 2953 /// Mapping of values in the original VPlan to a combined VPInstruction. 2954 DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo> 2955 BundleToCombined; 2956 2957 VPInterleavedAccessInfo &IAI; 2958 2959 /// Basic block to operate on. For now, only instructions in a single BB are 2960 /// considered. 2961 const VPBasicBlock &BB; 2962 2963 /// Indicates whether we managed to combine all visited instructions or not. 2964 bool CompletelySLP = true; 2965 2966 /// Width of the widest combined bundle in bits. 2967 unsigned WidestBundleBits = 0; 2968 2969 using MultiNodeOpTy = 2970 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>; 2971 2972 // Input operand bundles for the current multi node. Each multi node operand 2973 // bundle contains values not matching the multi node's opcode. They will 2974 // be reordered in reorderMultiNodeOps, once we completed building a 2975 // multi node. 2976 SmallVector<MultiNodeOpTy, 4> MultiNodeOps; 2977 2978 /// Indicates whether we are building a multi node currently. 2979 bool MultiNodeActive = false; 2980 2981 /// Check if we can vectorize Operands together. 2982 bool areVectorizable(ArrayRef<VPValue *> Operands) const; 2983 2984 /// Add combined instruction \p New for the bundle \p Operands. 2985 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New); 2986 2987 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now. 2988 VPInstruction *markFailed(); 2989 2990 /// Reorder operands in the multi node to maximize sequential memory access 2991 /// and commutative operations. 2992 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps(); 2993 2994 /// Choose the best candidate to use for the lane after \p Last. The set of 2995 /// candidates to choose from are values with an opcode matching \p Last's 2996 /// or loads consecutive to \p Last. 2997 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last, 2998 SmallPtrSetImpl<VPValue *> &Candidates, 2999 VPInterleavedAccessInfo &IAI); 3000 3001 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3002 /// Print bundle \p Values to dbgs(). 3003 void dumpBundle(ArrayRef<VPValue *> Values); 3004 #endif 3005 3006 public: 3007 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {} 3008 3009 ~VPlanSlp() = default; 3010 3011 /// Tries to build an SLP tree rooted at \p Operands and returns a 3012 /// VPInstruction combining \p Operands, if they can be combined. 3013 VPInstruction *buildGraph(ArrayRef<VPValue *> Operands); 3014 3015 /// Return the width of the widest combined bundle in bits. 3016 unsigned getWidestBundleBits() const { return WidestBundleBits; } 3017 3018 /// Return true if all visited instruction can be combined. 3019 bool isCompletelySLP() const { return CompletelySLP; } 3020 }; 3021 3022 namespace vputils { 3023 3024 /// Returns true if only the first lane of \p Def is used. 3025 bool onlyFirstLaneUsed(VPValue *Def); 3026 3027 /// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p 3028 /// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in 3029 /// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's 3030 /// pre-header already contains a recipe expanding \p Expr, return it. If not, 3031 /// create a new one. 3032 VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 3033 ScalarEvolution &SE); 3034 3035 } // end namespace vputils 3036 3037 } // end namespace llvm 3038 3039 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H 3040