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