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