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