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