1 //===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file contains the declarations of the Vectorization Plan base classes:
12 /// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
13 /// VPBlockBase, together implementing a Hierarchical CFG;
14 /// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
15 /// treated as proper graphs for generic algorithms;
16 /// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
17 /// within VPBasicBlocks;
18 /// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
20 /// 5. The VPlan class holding a candidate for vectorization;
21 /// 6. The VPlanPrinter class providing a way to print a plan in dot format;
22 /// These are documented in docs/VectorizationPlan.rst.
24 //===----------------------------------------------------------------------===//
26 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
29 #include "VPlanLoopInfo.h"
30 #include "VPlanValue.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/DepthFirstIterator.h"
33 #include "llvm/ADT/GraphTraits.h"
34 #include "llvm/ADT/Optional.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/IR/IRBuilder.h"
50 class LoopVectorizationLegality;
51 class LoopVectorizationCostModel;
54 class InnerLoopVectorizer;
55 class InterleaveGroup;
62 /// A range of powers-of-2 vectorization factors with fixed start and
63 /// adjustable end. The range includes start and excludes end, e.g.,:
64 /// [1, 9) = {1, 2, 4, 8}
69 // Need not be a power of 2. If End <= Start range is empty.
73 using VPlanPtr = std::unique_ptr<VPlan>;
75 /// In what follows, the term "input IR" refers to code that is fed into the
76 /// vectorizer whereas the term "output IR" refers to code that is generated by
79 /// VPIteration represents a single point in the iteration space of the output
80 /// (vectorized and/or unrolled) IR loop.
89 /// This is a helper struct for maintaining vectorization state. It's used for
90 /// mapping values from the original loop to their corresponding values in
91 /// the new loop. Two mappings are maintained: one for vectorized values and
92 /// one for scalarized values. Vectorized values are represented with UF
93 /// vector values in the new loop, and scalarized values are represented with
94 /// UF x VF scalar values in the new loop. UF and VF are the unroll and
95 /// vectorization factors, respectively.
97 /// Entries can be added to either map with setVectorValue and setScalarValue,
98 /// which assert that an entry was not already added before. If an entry is to
99 /// replace an existing one, call resetVectorValue and resetScalarValue. This is
100 /// currently needed to modify the mapped values during "fix-up" operations that
101 /// occur once the first phase of widening is complete. These operations include
102 /// type truncation and the second phase of recurrence widening.
104 /// Entries from either map can be retrieved using the getVectorValue and
105 /// getScalarValue functions, which assert that the desired value exists.
106 struct VectorizerValueMap {
107 friend struct VPTransformState;
110 /// The unroll factor. Each entry in the vector map contains UF vector values.
113 /// The vectorization factor. Each entry in the scalar map contains UF x VF
117 /// The vector and scalar map storage. We use std::map and not DenseMap
118 /// because insertions to DenseMap invalidate its iterators.
119 using VectorParts = SmallVector<Value *, 2>;
120 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
121 std::map<Value *, VectorParts> VectorMapStorage;
122 std::map<Value *, ScalarParts> ScalarMapStorage;
125 /// Construct an empty map with the given unroll and vectorization factors.
126 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
128 /// \return True if the map has any vector entry for \p Key.
129 bool hasAnyVectorValue(Value *Key) const {
130 return VectorMapStorage.count(Key);
133 /// \return True if the map has a vector entry for \p Key and \p Part.
134 bool hasVectorValue(Value *Key, unsigned Part) const {
135 assert(Part < UF && "Queried Vector Part is too large.");
136 if (!hasAnyVectorValue(Key))
138 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
139 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
140 return Entry[Part] != nullptr;
143 /// \return True if the map has any scalar entry for \p Key.
144 bool hasAnyScalarValue(Value *Key) const {
145 return ScalarMapStorage.count(Key);
148 /// \return True if the map has a scalar entry for \p Key and \p Instance.
149 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
150 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
151 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
152 if (!hasAnyScalarValue(Key))
154 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
155 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
156 assert(Entry[Instance.Part].size() == VF &&
157 "ScalarParts has wrong dimensions.");
158 return Entry[Instance.Part][Instance.Lane] != nullptr;
161 /// Retrieve the existing vector value that corresponds to \p Key and
163 Value *getVectorValue(Value *Key, unsigned Part) {
164 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
165 return VectorMapStorage[Key][Part];
168 /// Retrieve the existing scalar value that corresponds to \p Key and
170 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
171 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
172 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
175 /// Set a vector value associated with \p Key and \p Part. Assumes such a
176 /// value is not already set. If it is, use resetVectorValue() instead.
177 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
178 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
179 if (!VectorMapStorage.count(Key)) {
180 VectorParts Entry(UF);
181 VectorMapStorage[Key] = Entry;
183 VectorMapStorage[Key][Part] = Vector;
186 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
187 /// value is not already set.
188 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
189 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
190 if (!ScalarMapStorage.count(Key)) {
191 ScalarParts Entry(UF);
192 // TODO: Consider storing uniform values only per-part, as they occupy
193 // lane 0 only, keeping the other VF-1 redundant entries null.
194 for (unsigned Part = 0; Part < UF; ++Part)
195 Entry[Part].resize(VF, nullptr);
196 ScalarMapStorage[Key] = Entry;
198 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
201 /// Reset the vector value associated with \p Key for the given \p Part.
202 /// This function can be used to update values that have already been
203 /// vectorized. This is the case for "fix-up" operations including type
204 /// truncation and the second phase of recurrence vectorization.
205 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
206 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
207 VectorMapStorage[Key][Part] = Vector;
210 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
211 /// This function can be used to update values that have already been
212 /// scalarized. This is the case for "fix-up" operations including scalar phi
213 /// nodes for scalarized and predicated instructions.
214 void resetScalarValue(Value *Key, const VPIteration &Instance,
216 assert(hasScalarValue(Key, Instance) &&
217 "Scalar value not set for part and lane");
218 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
222 /// This class is used to enable the VPlan to invoke a method of ILV. This is
223 /// needed until the method is refactored out of ILV and becomes reusable.
225 virtual ~VPCallback() {}
226 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
229 /// VPTransformState holds information passed down when "executing" a VPlan,
230 /// needed for generating the output IR.
231 struct VPTransformState {
232 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
233 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
234 InnerLoopVectorizer *ILV, VPCallback &Callback)
235 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
236 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
238 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
242 /// Hold the indices to generate specific scalar instructions. Null indicates
243 /// that all instances are to be generated, using either scalar or vector
245 Optional<VPIteration> Instance;
248 /// A type for vectorized values in the new loop. Each value from the
249 /// original loop, when vectorized, is represented by UF vector values in
250 /// the new unrolled loop, where UF is the unroll factor.
251 typedef SmallVector<Value *, 2> PerPartValuesTy;
253 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
256 /// Get the generated Value for a given VPValue and a given Part. Note that
257 /// as some Defs are still created by ILV and managed in its ValueMap, this
258 /// method will delegate the call to ILV in such cases in order to provide
259 /// callers a consistent API.
261 Value *get(VPValue *Def, unsigned Part) {
262 // If Values have been set for this Def return the one relevant for \p Part.
263 if (Data.PerPartOutput.count(Def))
264 return Data.PerPartOutput[Def][Part];
265 // Def is managed by ILV: bring the Values from ValueMap.
266 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
269 /// Set the generated Value for a given VPValue and a given Part.
270 void set(VPValue *Def, Value *V, unsigned Part) {
271 if (!Data.PerPartOutput.count(Def)) {
272 DataState::PerPartValuesTy Entry(UF);
273 Data.PerPartOutput[Def] = Entry;
275 Data.PerPartOutput[Def][Part] = V;
278 /// Hold state information used when constructing the CFG of the output IR,
279 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
281 /// The previous VPBasicBlock visited. Initially set to null.
282 VPBasicBlock *PrevVPBB = nullptr;
284 /// The previous IR BasicBlock created or used. Initially set to the new
285 /// header BasicBlock.
286 BasicBlock *PrevBB = nullptr;
288 /// The last IR BasicBlock in the output IR. Set to the new latch
289 /// BasicBlock, used for placing the newly created BasicBlocks.
290 BasicBlock *LastBB = nullptr;
292 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
293 /// of replication, maps the BasicBlock of the last replica created.
294 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
296 CFGState() = default;
299 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
302 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
305 /// Hold a reference to the IRBuilder used to generate output IR code.
306 IRBuilder<> &Builder;
308 /// Hold a reference to the Value state information used when generating the
309 /// Values of the output IR.
310 VectorizerValueMap &ValueMap;
312 /// Hold a reference to a mapping between VPValues in VPlan and original
313 /// Values they correspond to.
314 VPValue2ValueTy VPValue2Value;
316 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
317 InnerLoopVectorizer *ILV;
319 VPCallback &Callback;
322 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
323 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
325 friend class VPBlockUtils;
328 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
330 /// An optional name for the block.
333 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
334 /// it is a topmost VPBlockBase.
335 VPRegionBlock *Parent = nullptr;
337 /// List of predecessor blocks.
338 SmallVector<VPBlockBase *, 1> Predecessors;
340 /// List of successor blocks.
341 SmallVector<VPBlockBase *, 1> Successors;
343 /// Successor selector, null for zero or single successor blocks.
344 VPValue *CondBit = nullptr;
346 /// Add \p Successor as the last successor to this block.
347 void appendSuccessor(VPBlockBase *Successor) {
348 assert(Successor && "Cannot add nullptr successor!");
349 Successors.push_back(Successor);
352 /// Add \p Predecessor as the last predecessor to this block.
353 void appendPredecessor(VPBlockBase *Predecessor) {
354 assert(Predecessor && "Cannot add nullptr predecessor!");
355 Predecessors.push_back(Predecessor);
358 /// Remove \p Predecessor from the predecessors of this block.
359 void removePredecessor(VPBlockBase *Predecessor) {
360 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
361 assert(Pos && "Predecessor does not exist");
362 Predecessors.erase(Pos);
365 /// Remove \p Successor from the successors of this block.
366 void removeSuccessor(VPBlockBase *Successor) {
367 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
368 assert(Pos && "Successor does not exist");
369 Successors.erase(Pos);
373 VPBlockBase(const unsigned char SC, const std::string &N)
374 : SubclassID(SC), Name(N) {}
377 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
378 /// that are actually instantiated. Values of this enumeration are kept in the
379 /// SubclassID field of the VPBlockBase objects. They are used for concrete
380 /// type identification.
381 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
383 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
385 virtual ~VPBlockBase() = default;
387 const std::string &getName() const { return Name; }
389 void setName(const Twine &newName) { Name = newName.str(); }
391 /// \return an ID for the concrete type of this object.
392 /// This is used to implement the classof checks. This should not be used
393 /// for any other purpose, as the values may change as LLVM evolves.
394 unsigned getVPBlockID() const { return SubclassID; }
396 VPRegionBlock *getParent() { return Parent; }
397 const VPRegionBlock *getParent() const { return Parent; }
399 void setParent(VPRegionBlock *P) { Parent = P; }
401 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
402 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
403 /// VPBlockBase is a VPBasicBlock, it is returned.
404 const VPBasicBlock *getEntryBasicBlock() const;
405 VPBasicBlock *getEntryBasicBlock();
407 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
408 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
409 /// VPBlockBase is a VPBasicBlock, it is returned.
410 const VPBasicBlock *getExitBasicBlock() const;
411 VPBasicBlock *getExitBasicBlock();
413 const VPBlocksTy &getSuccessors() const { return Successors; }
414 VPBlocksTy &getSuccessors() { return Successors; }
416 const VPBlocksTy &getPredecessors() const { return Predecessors; }
417 VPBlocksTy &getPredecessors() { return Predecessors; }
419 /// \return the successor of this VPBlockBase if it has a single successor.
420 /// Otherwise return a null pointer.
421 VPBlockBase *getSingleSuccessor() const {
422 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
425 /// \return the predecessor of this VPBlockBase if it has a single
426 /// predecessor. Otherwise return a null pointer.
427 VPBlockBase *getSinglePredecessor() const {
428 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
431 size_t getNumSuccessors() const { return Successors.size(); }
432 size_t getNumPredecessors() const { return Predecessors.size(); }
434 /// An Enclosing Block of a block B is any block containing B, including B
435 /// itself. \return the closest enclosing block starting from "this", which
436 /// has successors. \return the root enclosing block if all enclosing blocks
437 /// have no successors.
438 VPBlockBase *getEnclosingBlockWithSuccessors();
440 /// \return the closest enclosing block starting from "this", which has
441 /// predecessors. \return the root enclosing block if all enclosing blocks
442 /// have no predecessors.
443 VPBlockBase *getEnclosingBlockWithPredecessors();
445 /// \return the successors either attached directly to this VPBlockBase or, if
446 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
447 /// successors of its own, search recursively for the first enclosing
448 /// VPRegionBlock that has successors and return them. If no such
449 /// VPRegionBlock exists, return the (empty) successors of the topmost
450 /// VPBlockBase reached.
451 const VPBlocksTy &getHierarchicalSuccessors() {
452 return getEnclosingBlockWithSuccessors()->getSuccessors();
455 /// \return the hierarchical successor of this VPBlockBase if it has a single
456 /// hierarchical successor. Otherwise return a null pointer.
457 VPBlockBase *getSingleHierarchicalSuccessor() {
458 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
461 /// \return the predecessors either attached directly to this VPBlockBase or,
462 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
463 /// predecessors of its own, search recursively for the first enclosing
464 /// VPRegionBlock that has predecessors and return them. If no such
465 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
466 /// VPBlockBase reached.
467 const VPBlocksTy &getHierarchicalPredecessors() {
468 return getEnclosingBlockWithPredecessors()->getPredecessors();
471 /// \return the hierarchical predecessor of this VPBlockBase if it has a
472 /// single hierarchical predecessor. Otherwise return a null pointer.
473 VPBlockBase *getSingleHierarchicalPredecessor() {
474 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
477 /// \return the condition bit selecting the successor.
478 VPValue *getCondBit() { return CondBit; }
480 const VPValue *getCondBit() const { return CondBit; }
482 void setCondBit(VPValue *CV) { CondBit = CV; }
484 /// Set a given VPBlockBase \p Successor as the single successor of this
485 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
486 /// This VPBlockBase must have no successors.
487 void setOneSuccessor(VPBlockBase *Successor) {
488 assert(Successors.empty() && "Setting one successor when others exist.");
489 appendSuccessor(Successor);
492 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
493 /// successors of this VPBlockBase. \p Condition is set as the successor
494 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
495 /// IfFalse. This VPBlockBase must have no successors.
496 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
497 VPValue *Condition) {
498 assert(Successors.empty() && "Setting two successors when others exist.");
499 assert(Condition && "Setting two successors without condition!");
501 appendSuccessor(IfTrue);
502 appendSuccessor(IfFalse);
505 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
506 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
507 /// as successor of any VPBasicBlock in \p NewPreds.
508 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
509 assert(Predecessors.empty() && "Block predecessors already set.");
510 for (auto *Pred : NewPreds)
511 appendPredecessor(Pred);
514 /// The method which generates the output IR that correspond to this
515 /// VPBlockBase, thereby "executing" the VPlan.
516 virtual void execute(struct VPTransformState *State) = 0;
518 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
519 static void deleteCFG(VPBlockBase *Entry);
521 void printAsOperand(raw_ostream &OS, bool PrintType) const {
525 void print(raw_ostream &OS) const {
526 // TODO: Only printing VPBB name for now since we only have dot printing
527 // support for VPInstructions/Recipes.
528 printAsOperand(OS, false);
531 /// Return true if it is legal to hoist instructions into this block.
532 bool isLegalToHoistInto() {
533 // There are currently no constraints that prevent an instruction to be
534 // hoisted into a VPBlockBase.
539 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
541 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
545 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
547 /// Each VPRecipe belongs to a single VPBasicBlock.
548 VPBasicBlock *Parent = nullptr;
551 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
552 /// that is actually instantiated. Values of this enumeration are kept in the
553 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
554 /// type identification.
555 using VPRecipeTy = enum {
562 VPWidenIntOrFpInductionSC,
563 VPWidenMemoryInstructionSC,
568 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
569 virtual ~VPRecipeBase() = default;
571 /// \return an ID for the concrete type of this object.
572 /// This is used to implement the classof checks. This should not be used
573 /// for any other purpose, as the values may change as LLVM evolves.
574 unsigned getVPRecipeID() const { return SubclassID; }
576 /// \return the VPBasicBlock which this VPRecipe belongs to.
577 VPBasicBlock *getParent() { return Parent; }
578 const VPBasicBlock *getParent() const { return Parent; }
580 /// The method which generates the output IR instructions that correspond to
581 /// this VPRecipe, thereby "executing" the VPlan.
582 virtual void execute(struct VPTransformState &State) = 0;
584 /// Each recipe prints itself.
585 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
587 /// Insert an unlinked recipe into a basic block immediately before
588 /// the specified recipe.
589 void insertBefore(VPRecipeBase *InsertPos);
591 /// This method unlinks 'this' from the containing basic block and deletes it.
593 /// \returns an iterator pointing to the element after the erased one
594 iplist<VPRecipeBase>::iterator eraseFromParent();
597 /// This is a concrete Recipe that models a single VPlan-level instruction.
598 /// While as any Recipe it may generate a sequence of IR instructions when
599 /// executed, these instructions would always form a single-def expression as
600 /// the VPInstruction is also a single def-use vertex.
601 class VPInstruction : public VPUser, public VPRecipeBase {
602 friend class VPlanHCFGTransforms;
605 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
606 enum { Not = Instruction::OtherOpsEnd + 1 };
609 typedef unsigned char OpcodeTy;
612 /// Utility method serving execute(): generates a single instance of the
613 /// modeled instruction.
614 void generateInstruction(VPTransformState &State, unsigned Part);
617 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
618 : VPUser(VPValue::VPInstructionSC, Operands),
619 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
621 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
622 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
624 /// Method to support type inquiry through isa, cast, and dyn_cast.
625 static inline bool classof(const VPValue *V) {
626 return V->getVPValueID() == VPValue::VPInstructionSC;
629 /// Method to support type inquiry through isa, cast, and dyn_cast.
630 static inline bool classof(const VPRecipeBase *R) {
631 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
634 unsigned getOpcode() const { return Opcode; }
636 /// Generate the instruction.
637 /// TODO: We currently execute only per-part unless a specific instance is
639 void execute(VPTransformState &State) override;
641 /// Print the Recipe.
642 void print(raw_ostream &O, const Twine &Indent) const override;
644 /// Print the VPInstruction.
645 void print(raw_ostream &O) const;
648 /// VPWidenRecipe is a recipe for producing a copy of vector type for each
649 /// Instruction in its ingredients independently, in order. This recipe covers
650 /// most of the traditional vectorization cases where each ingredient transforms
651 /// into a vectorized version of itself.
652 class VPWidenRecipe : public VPRecipeBase {
654 /// Hold the ingredients by pointing to their original BasicBlock location.
655 BasicBlock::iterator Begin;
656 BasicBlock::iterator End;
659 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
660 End = I->getIterator();
664 ~VPWidenRecipe() override = default;
666 /// Method to support type inquiry through isa, cast, and dyn_cast.
667 static inline bool classof(const VPRecipeBase *V) {
668 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
671 /// Produce widened copies of all Ingredients.
672 void execute(VPTransformState &State) override;
674 /// Augment the recipe to include Instr, if it lies at its End.
675 bool appendInstruction(Instruction *Instr) {
676 if (End != Instr->getIterator())
682 /// Print the recipe.
683 void print(raw_ostream &O, const Twine &Indent) const override;
686 /// A recipe for handling phi nodes of integer and floating-point inductions,
687 /// producing their vector and scalar values.
688 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
694 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
695 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
696 ~VPWidenIntOrFpInductionRecipe() override = default;
698 /// Method to support type inquiry through isa, cast, and dyn_cast.
699 static inline bool classof(const VPRecipeBase *V) {
700 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
703 /// Generate the vectorized and scalarized versions of the phi node as
704 /// needed by their users.
705 void execute(VPTransformState &State) override;
707 /// Print the recipe.
708 void print(raw_ostream &O, const Twine &Indent) const override;
711 /// A recipe for handling all phi nodes except for integer and FP inductions.
712 class VPWidenPHIRecipe : public VPRecipeBase {
717 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
718 ~VPWidenPHIRecipe() override = default;
720 /// Method to support type inquiry through isa, cast, and dyn_cast.
721 static inline bool classof(const VPRecipeBase *V) {
722 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
725 /// Generate the phi/select nodes.
726 void execute(VPTransformState &State) override;
728 /// Print the recipe.
729 void print(raw_ostream &O, const Twine &Indent) const override;
732 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
734 class VPBlendRecipe : public VPRecipeBase {
738 /// The blend operation is a User of a mask, if not null.
739 std::unique_ptr<VPUser> User;
742 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
743 : VPRecipeBase(VPBlendSC), Phi(Phi) {
744 assert((Phi->getNumIncomingValues() == 1 ||
745 Phi->getNumIncomingValues() == Masks.size()) &&
746 "Expected the same number of incoming values and masks");
748 User.reset(new VPUser(Masks));
751 /// Method to support type inquiry through isa, cast, and dyn_cast.
752 static inline bool classof(const VPRecipeBase *V) {
753 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
756 /// Generate the phi/select nodes.
757 void execute(VPTransformState &State) override;
759 /// Print the recipe.
760 void print(raw_ostream &O, const Twine &Indent) const override;
763 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
764 /// or stores into one wide load/store and shuffles.
765 class VPInterleaveRecipe : public VPRecipeBase {
767 const InterleaveGroup *IG;
770 VPInterleaveRecipe(const InterleaveGroup *IG)
771 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
772 ~VPInterleaveRecipe() override = default;
774 /// Method to support type inquiry through isa, cast, and dyn_cast.
775 static inline bool classof(const VPRecipeBase *V) {
776 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
779 /// Generate the wide load or store, and shuffles.
780 void execute(VPTransformState &State) override;
782 /// Print the recipe.
783 void print(raw_ostream &O, const Twine &Indent) const override;
785 const InterleaveGroup *getInterleaveGroup() { return IG; }
788 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
789 /// copies of the original scalar type, one per lane, instead of producing a
790 /// single copy of widened type for all lanes. If the instruction is known to be
791 /// uniform only one copy, per lane zero, will be generated.
792 class VPReplicateRecipe : public VPRecipeBase {
794 /// The instruction being replicated.
795 Instruction *Ingredient;
797 /// Indicator if only a single replica per lane is needed.
800 /// Indicator if the replicas are also predicated.
803 /// Indicator if the scalar values should also be packed into a vector.
807 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
808 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
809 IsPredicated(IsPredicated) {
810 // Retain the previous behavior of predicateInstructions(), where an
811 // insert-element of a predicated instruction got hoisted into the
812 // predicated basic block iff it was its only user. This is achieved by
813 // having predicated instructions also pack their values into a vector by
814 // default unless they have a replicated user which uses their scalar value.
815 AlsoPack = IsPredicated && !I->use_empty();
818 ~VPReplicateRecipe() override = default;
820 /// Method to support type inquiry through isa, cast, and dyn_cast.
821 static inline bool classof(const VPRecipeBase *V) {
822 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
825 /// Generate replicas of the desired Ingredient. Replicas will be generated
826 /// for all parts and lanes unless a specific part and lane are specified in
828 void execute(VPTransformState &State) override;
830 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
832 /// Print the recipe.
833 void print(raw_ostream &O, const Twine &Indent) const override;
836 /// A recipe for generating conditional branches on the bits of a mask.
837 class VPBranchOnMaskRecipe : public VPRecipeBase {
839 std::unique_ptr<VPUser> User;
842 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
843 if (BlockInMask) // nullptr means all-one mask.
844 User.reset(new VPUser({BlockInMask}));
847 /// Method to support type inquiry through isa, cast, and dyn_cast.
848 static inline bool classof(const VPRecipeBase *V) {
849 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
852 /// Generate the extraction of the appropriate bit from the block mask and the
853 /// conditional branch.
854 void execute(VPTransformState &State) override;
856 /// Print the recipe.
857 void print(raw_ostream &O, const Twine &Indent) const override {
858 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
860 O << *User->getOperand(0);
867 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
868 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
869 /// order to merge values that are set under such a branch and feed their uses.
870 /// The phi nodes can be scalar or vector depending on the users of the value.
871 /// This recipe works in concert with VPBranchOnMaskRecipe.
872 class VPPredInstPHIRecipe : public VPRecipeBase {
874 Instruction *PredInst;
877 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
878 /// nodes after merging back from a Branch-on-Mask.
879 VPPredInstPHIRecipe(Instruction *PredInst)
880 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
881 ~VPPredInstPHIRecipe() override = default;
883 /// Method to support type inquiry through isa, cast, and dyn_cast.
884 static inline bool classof(const VPRecipeBase *V) {
885 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
888 /// Generates phi nodes for live-outs as needed to retain SSA form.
889 void execute(VPTransformState &State) override;
891 /// Print the recipe.
892 void print(raw_ostream &O, const Twine &Indent) const override;
895 /// A Recipe for widening load/store operations.
896 /// TODO: We currently execute only per-part unless a specific instance is
898 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
901 std::unique_ptr<VPUser> User;
904 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
905 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
906 if (Mask) // Create a VPInstruction to register as a user of the mask.
907 User.reset(new VPUser({Mask}));
910 /// Method to support type inquiry through isa, cast, and dyn_cast.
911 static inline bool classof(const VPRecipeBase *V) {
912 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
915 /// Generate the wide load/store.
916 void execute(VPTransformState &State) override;
918 /// Print the recipe.
919 void print(raw_ostream &O, const Twine &Indent) const override;
922 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
923 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
924 /// output IR instructions.
925 class VPBasicBlock : public VPBlockBase {
927 using RecipeListTy = iplist<VPRecipeBase>;
930 /// The VPRecipes held in the order of output instructions to generate.
931 RecipeListTy Recipes;
934 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
935 : VPBlockBase(VPBasicBlockSC, Name.str()) {
937 appendRecipe(Recipe);
940 ~VPBasicBlock() override { Recipes.clear(); }
942 /// Instruction iterators...
943 using iterator = RecipeListTy::iterator;
944 using const_iterator = RecipeListTy::const_iterator;
945 using reverse_iterator = RecipeListTy::reverse_iterator;
946 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
948 //===--------------------------------------------------------------------===//
949 /// Recipe iterator methods
951 inline iterator begin() { return Recipes.begin(); }
952 inline const_iterator begin() const { return Recipes.begin(); }
953 inline iterator end() { return Recipes.end(); }
954 inline const_iterator end() const { return Recipes.end(); }
956 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
957 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
958 inline reverse_iterator rend() { return Recipes.rend(); }
959 inline const_reverse_iterator rend() const { return Recipes.rend(); }
961 inline size_t size() const { return Recipes.size(); }
962 inline bool empty() const { return Recipes.empty(); }
963 inline const VPRecipeBase &front() const { return Recipes.front(); }
964 inline VPRecipeBase &front() { return Recipes.front(); }
965 inline const VPRecipeBase &back() const { return Recipes.back(); }
966 inline VPRecipeBase &back() { return Recipes.back(); }
968 /// Returns a reference to the list of recipes.
969 RecipeListTy &getRecipeList() { return Recipes; }
971 /// Returns a pointer to a member of the recipe list.
972 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
973 return &VPBasicBlock::Recipes;
976 /// Method to support type inquiry through isa, cast, and dyn_cast.
977 static inline bool classof(const VPBlockBase *V) {
978 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
981 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
982 assert(Recipe && "No recipe to append.");
983 assert(!Recipe->Parent && "Recipe already in VPlan");
984 Recipe->Parent = this;
985 Recipes.insert(InsertPt, Recipe);
988 /// Augment the existing recipes of a VPBasicBlock with an additional
989 /// \p Recipe as the last recipe.
990 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
992 /// The method which generates the output IR instructions that correspond to
993 /// this VPBasicBlock, thereby "executing" the VPlan.
994 void execute(struct VPTransformState *State) override;
997 /// Create an IR BasicBlock to hold the output instructions generated by this
998 /// VPBasicBlock, and return it. Update the CFGState accordingly.
999 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1002 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1003 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1004 /// A VPRegionBlock may indicate that its contents are to be replicated several
1005 /// times. This is designed to support predicated scalarization, in which a
1006 /// scalar if-then code structure needs to be generated VF * UF times. Having
1007 /// this replication indicator helps to keep a single model for multiple
1008 /// candidate VF's. The actual replication takes place only once the desired VF
1009 /// and UF have been determined.
1010 class VPRegionBlock : public VPBlockBase {
1012 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1015 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1018 /// An indicator whether this region is to generate multiple replicated
1019 /// instances of output IR corresponding to its VPBlockBases.
1023 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1024 const std::string &Name = "", bool IsReplicator = false)
1025 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1026 IsReplicator(IsReplicator) {
1027 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1028 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1029 Entry->setParent(this);
1030 Exit->setParent(this);
1032 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1033 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1034 IsReplicator(IsReplicator) {}
1036 ~VPRegionBlock() override {
1041 /// Method to support type inquiry through isa, cast, and dyn_cast.
1042 static inline bool classof(const VPBlockBase *V) {
1043 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1046 const VPBlockBase *getEntry() const { return Entry; }
1047 VPBlockBase *getEntry() { return Entry; }
1049 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1050 /// EntryBlock must have no predecessors.
1051 void setEntry(VPBlockBase *EntryBlock) {
1052 assert(EntryBlock->getPredecessors().empty() &&
1053 "Entry block cannot have predecessors.");
1055 EntryBlock->setParent(this);
1058 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1059 // specific interface of llvm::Function, instead of using
1060 // GraphTraints::getEntryNode. We should add a new template parameter to
1061 // DominatorTreeBase representing the Graph type.
1062 VPBlockBase &front() const { return *Entry; }
1064 const VPBlockBase *getExit() const { return Exit; }
1065 VPBlockBase *getExit() { return Exit; }
1067 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1068 /// ExitBlock must have no successors.
1069 void setExit(VPBlockBase *ExitBlock) {
1070 assert(ExitBlock->getSuccessors().empty() &&
1071 "Exit block cannot have successors.");
1073 ExitBlock->setParent(this);
1076 /// An indicator whether this region is to generate multiple replicated
1077 /// instances of output IR corresponding to its VPBlockBases.
1078 bool isReplicator() const { return IsReplicator; }
1080 /// The method which generates the output IR instructions that correspond to
1081 /// this VPRegionBlock, thereby "executing" the VPlan.
1082 void execute(struct VPTransformState *State) override;
1085 /// VPlan models a candidate for vectorization, encoding various decisions take
1086 /// to produce efficient output IR, including which branches, basic-blocks and
1087 /// output IR instructions to generate, and their cost. VPlan holds a
1088 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1091 friend class VPlanPrinter;
1094 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1097 /// Holds the VFs applicable to this VPlan.
1098 SmallSet<unsigned, 2> VFs;
1100 /// Holds the name of the VPlan, for printing.
1103 /// Holds all the external definitions created for this VPlan.
1104 // TODO: Introduce a specific representation for external definitions in
1105 // VPlan. External definitions must be immutable and hold a pointer to its
1106 // underlying IR that will be used to implement its structural comparison
1107 // (operators '==' and '<').
1108 SmallPtrSet<VPValue *, 16> VPExternalDefs;
1110 /// Holds a mapping between Values and their corresponding VPValue inside
1112 Value2VPValueTy Value2VPValue;
1114 /// Holds the VPLoopInfo analysis for this VPlan.
1118 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1122 VPBlockBase::deleteCFG(Entry);
1123 for (auto &MapEntry : Value2VPValue)
1124 delete MapEntry.second;
1125 for (VPValue *Def : VPExternalDefs)
1129 /// Generate the IR code for this VPlan.
1130 void execute(struct VPTransformState *State);
1132 VPBlockBase *getEntry() { return Entry; }
1133 const VPBlockBase *getEntry() const { return Entry; }
1135 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1137 void addVF(unsigned VF) { VFs.insert(VF); }
1139 bool hasVF(unsigned VF) { return VFs.count(VF); }
1141 const std::string &getName() const { return Name; }
1143 void setName(const Twine &newName) { Name = newName.str(); }
1145 /// Add \p VPVal to the pool of external definitions if it's not already
1147 void addExternalDef(VPValue *VPVal) {
1148 VPExternalDefs.insert(VPVal);
1151 void addVPValue(Value *V) {
1152 assert(V && "Trying to add a null Value to VPlan");
1153 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1154 Value2VPValue[V] = new VPValue();
1157 VPValue *getVPValue(Value *V) {
1158 assert(V && "Trying to get the VPValue of a null Value");
1159 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1160 return Value2VPValue[V];
1163 /// Return the VPLoopInfo analysis for this VPlan.
1164 VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1165 const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1168 /// Add to the given dominator tree the header block and every new basic block
1169 /// that was created between it and the latch block, inclusive.
1170 static void updateDominatorTree(DominatorTree *DT,
1171 BasicBlock *LoopPreHeaderBB,
1172 BasicBlock *LoopLatchBB);
1175 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1176 /// indented and follows the dot format.
1177 class VPlanPrinter {
1178 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1179 friend inline raw_ostream &operator<<(raw_ostream &OS,
1180 const struct VPlanIngredient &I);
1186 unsigned TabWidth = 2;
1189 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1191 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1193 /// Handle indentation.
1194 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1196 /// Print a given \p Block of the Plan.
1197 void dumpBlock(const VPBlockBase *Block);
1199 /// Print the information related to the CFG edges going out of a given
1200 /// \p Block, followed by printing the successor blocks themselves.
1201 void dumpEdges(const VPBlockBase *Block);
1203 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1204 /// its successor blocks.
1205 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1207 /// Print a given \p Region of the Plan.
1208 void dumpRegion(const VPRegionBlock *Region);
1210 unsigned getOrCreateBID(const VPBlockBase *Block) {
1211 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1214 const Twine getOrCreateName(const VPBlockBase *Block);
1216 const Twine getUID(const VPBlockBase *Block);
1218 /// Print the information related to a CFG edge between two VPBlockBases.
1219 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1220 const Twine &Label);
1224 static void printAsIngredient(raw_ostream &O, Value *V);
1227 struct VPlanIngredient {
1230 VPlanIngredient(Value *V) : V(V) {}
1233 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1234 VPlanPrinter::printAsIngredient(OS, I.V);
1238 inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1239 VPlanPrinter Printer(OS, Plan);
1244 //===----------------------------------------------------------------------===//
1245 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs //
1246 //===----------------------------------------------------------------------===//
1248 // The following set of template specializations implement GraphTraits to treat
1249 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1250 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1251 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
1252 // successors/predecessors but not to the blocks inside the region.
1254 template <> struct GraphTraits<VPBlockBase *> {
1255 using NodeRef = VPBlockBase *;
1256 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1258 static NodeRef getEntryNode(NodeRef N) { return N; }
1260 static inline ChildIteratorType child_begin(NodeRef N) {
1261 return N->getSuccessors().begin();
1264 static inline ChildIteratorType child_end(NodeRef N) {
1265 return N->getSuccessors().end();
1269 template <> struct GraphTraits<const VPBlockBase *> {
1270 using NodeRef = const VPBlockBase *;
1271 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1273 static NodeRef getEntryNode(NodeRef N) { return N; }
1275 static inline ChildIteratorType child_begin(NodeRef N) {
1276 return N->getSuccessors().begin();
1279 static inline ChildIteratorType child_end(NodeRef N) {
1280 return N->getSuccessors().end();
1284 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1285 // of successors for the inverse traversal.
1286 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1287 using NodeRef = VPBlockBase *;
1288 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1290 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1292 static inline ChildIteratorType child_begin(NodeRef N) {
1293 return N->getPredecessors().begin();
1296 static inline ChildIteratorType child_end(NodeRef N) {
1297 return N->getPredecessors().end();
1301 // The following set of template specializations implement GraphTraits to
1302 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1303 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1304 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1305 // there won't be automatic recursion into other VPBlockBases that turn to be
1309 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1310 using GraphRef = VPRegionBlock *;
1311 using nodes_iterator = df_iterator<NodeRef>;
1313 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1315 static nodes_iterator nodes_begin(GraphRef N) {
1316 return nodes_iterator::begin(N->getEntry());
1319 static nodes_iterator nodes_end(GraphRef N) {
1320 // df_iterator::end() returns an empty iterator so the node used doesn't
1322 return nodes_iterator::end(N);
1327 struct GraphTraits<const VPRegionBlock *>
1328 : public GraphTraits<const VPBlockBase *> {
1329 using GraphRef = const VPRegionBlock *;
1330 using nodes_iterator = df_iterator<NodeRef>;
1332 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1334 static nodes_iterator nodes_begin(GraphRef N) {
1335 return nodes_iterator::begin(N->getEntry());
1338 static nodes_iterator nodes_end(GraphRef N) {
1339 // df_iterator::end() returns an empty iterator so the node used doesn't
1341 return nodes_iterator::end(N);
1346 struct GraphTraits<Inverse<VPRegionBlock *>>
1347 : public GraphTraits<Inverse<VPBlockBase *>> {
1348 using GraphRef = VPRegionBlock *;
1349 using nodes_iterator = df_iterator<NodeRef>;
1351 static NodeRef getEntryNode(Inverse<GraphRef> N) {
1352 return N.Graph->getExit();
1355 static nodes_iterator nodes_begin(GraphRef N) {
1356 return nodes_iterator::begin(N->getExit());
1359 static nodes_iterator nodes_end(GraphRef N) {
1360 // df_iterator::end() returns an empty iterator so the node used doesn't
1362 return nodes_iterator::end(N);
1366 //===----------------------------------------------------------------------===//
1368 //===----------------------------------------------------------------------===//
1370 /// Class that provides utilities for VPBlockBases in VPlan.
1371 class VPBlockUtils {
1373 VPBlockUtils() = delete;
1375 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1376 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1377 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1378 /// has more than one successor, its conditional bit is propagated to \p
1379 /// NewBlock. \p NewBlock must have neither successors nor predecessors.
1380 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1381 assert(NewBlock->getSuccessors().empty() &&
1382 "Can't insert new block with successors.");
1383 // TODO: move successors from BlockPtr to NewBlock when this functionality
1384 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1385 // already has successors.
1386 BlockPtr->setOneSuccessor(NewBlock);
1387 NewBlock->setPredecessors({BlockPtr});
1388 NewBlock->setParent(BlockPtr->getParent());
1391 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1392 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1393 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1394 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1395 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1396 /// must have neither successors nor predecessors.
1397 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1398 VPValue *Condition, VPBlockBase *BlockPtr) {
1399 assert(IfTrue->getSuccessors().empty() &&
1400 "Can't insert IfTrue with successors.");
1401 assert(IfFalse->getSuccessors().empty() &&
1402 "Can't insert IfFalse with successors.");
1403 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
1404 IfTrue->setPredecessors({BlockPtr});
1405 IfFalse->setPredecessors({BlockPtr});
1406 IfTrue->setParent(BlockPtr->getParent());
1407 IfFalse->setParent(BlockPtr->getParent());
1410 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1411 /// the successors of \p From and \p From to the predecessors of \p To. Both
1412 /// VPBlockBases must have the same parent, which can be null. Both
1413 /// VPBlockBases can be already connected to other VPBlockBases.
1414 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1415 assert((From->getParent() == To->getParent()) &&
1416 "Can't connect two block with different parents");
1417 assert(From->getNumSuccessors() < 2 &&
1418 "Blocks can't have more than two successors.");
1419 From->appendSuccessor(To);
1420 To->appendPredecessor(From);
1423 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1424 /// from the successors of \p From and \p From from the predecessors of \p To.
1425 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1426 assert(To && "Successor to disconnect is null.");
1427 From->removeSuccessor(To);
1428 To->removePredecessor(From);
1432 } // end namespace llvm
1434 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H