1 //===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
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
19 ///    instruction;
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.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
28 
29 #include "VPlanValue.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/GraphTraits.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Twine.h"
36 #include "llvm/ADT/ilist.h"
37 #include "llvm/ADT/ilist_node.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstddef>
42 #include <map>
43 #include <string>
44 
45 // The (re)use of existing LoopVectorize classes is subject to future VPlan
46 // refactoring.
47 namespace {
48 class LoopVectorizationLegality;
49 class LoopVectorizationCostModel;
50 } // namespace
51 
52 namespace llvm {
53 
54 class BasicBlock;
55 class DominatorTree;
56 class InnerLoopVectorizer;
57 class InterleaveGroup;
58 class LoopInfo;
59 class raw_ostream;
60 class Value;
61 class VPBasicBlock;
62 class VPRegionBlock;
63 
64 /// In what follows, the term "input IR" refers to code that is fed into the
65 /// vectorizer whereas the term "output IR" refers to code that is generated by
66 /// the vectorizer.
67 
68 /// VPIteration represents a single point in the iteration space of the output
69 /// (vectorized and/or unrolled) IR loop.
70 struct VPIteration {
71   /// in [0..UF)
72   unsigned Part;
73 
74   /// in [0..VF)
75   unsigned Lane;
76 };
77 
78 /// This is a helper struct for maintaining vectorization state. It's used for
79 /// mapping values from the original loop to their corresponding values in
80 /// the new loop. Two mappings are maintained: one for vectorized values and
81 /// one for scalarized values. Vectorized values are represented with UF
82 /// vector values in the new loop, and scalarized values are represented with
83 /// UF x VF scalar values in the new loop. UF and VF are the unroll and
84 /// vectorization factors, respectively.
85 ///
86 /// Entries can be added to either map with setVectorValue and setScalarValue,
87 /// which assert that an entry was not already added before. If an entry is to
88 /// replace an existing one, call resetVectorValue and resetScalarValue. This is
89 /// currently needed to modify the mapped values during "fix-up" operations that
90 /// occur once the first phase of widening is complete. These operations include
91 /// type truncation and the second phase of recurrence widening.
92 ///
93 /// Entries from either map can be retrieved using the getVectorValue and
94 /// getScalarValue functions, which assert that the desired value exists.
95 struct VectorizerValueMap {
96   friend struct VPTransformState;
97 
98 private:
99   /// The unroll factor. Each entry in the vector map contains UF vector values.
100   unsigned UF;
101 
102   /// The vectorization factor. Each entry in the scalar map contains UF x VF
103   /// scalar values.
104   unsigned VF;
105 
106   /// The vector and scalar map storage. We use std::map and not DenseMap
107   /// because insertions to DenseMap invalidate its iterators.
108   using VectorParts = SmallVector<Value *, 2>;
109   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
110   std::map<Value *, VectorParts> VectorMapStorage;
111   std::map<Value *, ScalarParts> ScalarMapStorage;
112 
113 public:
114   /// Construct an empty map with the given unroll and vectorization factors.
115   VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
116 
117   /// \return True if the map has any vector entry for \p Key.
118   bool hasAnyVectorValue(Value *Key) const {
119     return VectorMapStorage.count(Key);
120   }
121 
122   /// \return True if the map has a vector entry for \p Key and \p Part.
123   bool hasVectorValue(Value *Key, unsigned Part) const {
124     assert(Part < UF && "Queried Vector Part is too large.");
125     if (!hasAnyVectorValue(Key))
126       return false;
127     const VectorParts &Entry = VectorMapStorage.find(Key)->second;
128     assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
129     return Entry[Part] != nullptr;
130   }
131 
132   /// \return True if the map has any scalar entry for \p Key.
133   bool hasAnyScalarValue(Value *Key) const {
134     return ScalarMapStorage.count(Key);
135   }
136 
137   /// \return True if the map has a scalar entry for \p Key and \p Instance.
138   bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
139     assert(Instance.Part < UF && "Queried Scalar Part is too large.");
140     assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
141     if (!hasAnyScalarValue(Key))
142       return false;
143     const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
144     assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
145     assert(Entry[Instance.Part].size() == VF &&
146            "ScalarParts has wrong dimensions.");
147     return Entry[Instance.Part][Instance.Lane] != nullptr;
148   }
149 
150   /// Retrieve the existing vector value that corresponds to \p Key and
151   /// \p Part.
152   Value *getVectorValue(Value *Key, unsigned Part) {
153     assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
154     return VectorMapStorage[Key][Part];
155   }
156 
157   /// Retrieve the existing scalar value that corresponds to \p Key and
158   /// \p Instance.
159   Value *getScalarValue(Value *Key, const VPIteration &Instance) {
160     assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
161     return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
162   }
163 
164   /// Set a vector value associated with \p Key and \p Part. Assumes such a
165   /// value is not already set. If it is, use resetVectorValue() instead.
166   void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
167     assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
168     if (!VectorMapStorage.count(Key)) {
169       VectorParts Entry(UF);
170       VectorMapStorage[Key] = Entry;
171     }
172     VectorMapStorage[Key][Part] = Vector;
173   }
174 
175   /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
176   /// value is not already set.
177   void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
178     assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
179     if (!ScalarMapStorage.count(Key)) {
180       ScalarParts Entry(UF);
181       // TODO: Consider storing uniform values only per-part, as they occupy
182       //       lane 0 only, keeping the other VF-1 redundant entries null.
183       for (unsigned Part = 0; Part < UF; ++Part)
184         Entry[Part].resize(VF, nullptr);
185       ScalarMapStorage[Key] = Entry;
186     }
187     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
188   }
189 
190   /// Reset the vector value associated with \p Key for the given \p Part.
191   /// This function can be used to update values that have already been
192   /// vectorized. This is the case for "fix-up" operations including type
193   /// truncation and the second phase of recurrence vectorization.
194   void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
195     assert(hasVectorValue(Key, Part) && "Vector value not set for part");
196     VectorMapStorage[Key][Part] = Vector;
197   }
198 
199   /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
200   /// This function can be used to update values that have already been
201   /// scalarized. This is the case for "fix-up" operations including scalar phi
202   /// nodes for scalarized and predicated instructions.
203   void resetScalarValue(Value *Key, const VPIteration &Instance,
204                         Value *Scalar) {
205     assert(hasScalarValue(Key, Instance) &&
206            "Scalar value not set for part and lane");
207     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
208   }
209 };
210 
211 /// This class is used to enable the VPlan to invoke a method of ILV. This is
212 /// needed until the method is refactored out of ILV and becomes reusable.
213 struct VPCallback {
214   virtual ~VPCallback() {}
215   virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
216 };
217 
218 /// VPTransformState holds information passed down when "executing" a VPlan,
219 /// needed for generating the output IR.
220 struct VPTransformState {
221   VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
222                    IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
223                    InnerLoopVectorizer *ILV, VPCallback &Callback)
224       : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
225         ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
226 
227   /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
228   unsigned VF;
229   unsigned UF;
230 
231   /// Hold the indices to generate specific scalar instructions. Null indicates
232   /// that all instances are to be generated, using either scalar or vector
233   /// instructions.
234   Optional<VPIteration> Instance;
235 
236   struct DataState {
237     /// A type for vectorized values in the new loop. Each value from the
238     /// original loop, when vectorized, is represented by UF vector values in
239     /// the new unrolled loop, where UF is the unroll factor.
240     typedef SmallVector<Value *, 2> PerPartValuesTy;
241 
242     DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
243   } Data;
244 
245   /// Get the generated Value for a given VPValue and a given Part. Note that
246   /// as some Defs are still created by ILV and managed in its ValueMap, this
247   /// method will delegate the call to ILV in such cases in order to provide
248   /// callers a consistent API.
249   /// \see set.
250   Value *get(VPValue *Def, unsigned Part) {
251     // If Values have been set for this Def return the one relevant for \p Part.
252     if (Data.PerPartOutput.count(Def))
253       return Data.PerPartOutput[Def][Part];
254     // Def is managed by ILV: bring the Values from ValueMap.
255     return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
256   }
257 
258   /// Set the generated Value for a given VPValue and a given Part.
259   void set(VPValue *Def, Value *V, unsigned Part) {
260     if (!Data.PerPartOutput.count(Def)) {
261       DataState::PerPartValuesTy Entry(UF);
262       Data.PerPartOutput[Def] = Entry;
263     }
264     Data.PerPartOutput[Def][Part] = V;
265   }
266 
267   /// Hold state information used when constructing the CFG of the output IR,
268   /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
269   struct CFGState {
270     /// The previous VPBasicBlock visited. Initially set to null.
271     VPBasicBlock *PrevVPBB = nullptr;
272 
273     /// The previous IR BasicBlock created or used. Initially set to the new
274     /// header BasicBlock.
275     BasicBlock *PrevBB = nullptr;
276 
277     /// The last IR BasicBlock in the output IR. Set to the new latch
278     /// BasicBlock, used for placing the newly created BasicBlocks.
279     BasicBlock *LastBB = nullptr;
280 
281     /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
282     /// of replication, maps the BasicBlock of the last replica created.
283     SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
284 
285     CFGState() = default;
286   } CFG;
287 
288   /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
289   LoopInfo *LI;
290 
291   /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
292   DominatorTree *DT;
293 
294   /// Hold a reference to the IRBuilder used to generate output IR code.
295   IRBuilder<> &Builder;
296 
297   /// Hold a reference to the Value state information used when generating the
298   /// Values of the output IR.
299   VectorizerValueMap &ValueMap;
300 
301   /// Hold a reference to a mapping between VPValues in VPlan and original
302   /// Values they correspond to.
303   VPValue2ValueTy VPValue2Value;
304 
305   /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
306   InnerLoopVectorizer *ILV;
307 
308   VPCallback &Callback;
309 };
310 
311 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
312 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
313 class VPBlockBase {
314 private:
315   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
316 
317   /// An optional name for the block.
318   std::string Name;
319 
320   /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
321   /// it is a topmost VPBlockBase.
322   VPRegionBlock *Parent = nullptr;
323 
324   /// List of predecessor blocks.
325   SmallVector<VPBlockBase *, 1> Predecessors;
326 
327   /// List of successor blocks.
328   SmallVector<VPBlockBase *, 1> Successors;
329 
330   /// Add \p Successor as the last successor to this block.
331   void appendSuccessor(VPBlockBase *Successor) {
332     assert(Successor && "Cannot add nullptr successor!");
333     Successors.push_back(Successor);
334   }
335 
336   /// Add \p Predecessor as the last predecessor to this block.
337   void appendPredecessor(VPBlockBase *Predecessor) {
338     assert(Predecessor && "Cannot add nullptr predecessor!");
339     Predecessors.push_back(Predecessor);
340   }
341 
342   /// Remove \p Predecessor from the predecessors of this block.
343   void removePredecessor(VPBlockBase *Predecessor) {
344     auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
345     assert(Pos && "Predecessor does not exist");
346     Predecessors.erase(Pos);
347   }
348 
349   /// Remove \p Successor from the successors of this block.
350   void removeSuccessor(VPBlockBase *Successor) {
351     auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
352     assert(Pos && "Successor does not exist");
353     Successors.erase(Pos);
354   }
355 
356 protected:
357   VPBlockBase(const unsigned char SC, const std::string &N)
358       : SubclassID(SC), Name(N) {}
359 
360 public:
361   /// An enumeration for keeping track of the concrete subclass of VPBlockBase
362   /// that are actually instantiated. Values of this enumeration are kept in the
363   /// SubclassID field of the VPBlockBase objects. They are used for concrete
364   /// type identification.
365   using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
366 
367   using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
368 
369   virtual ~VPBlockBase() = default;
370 
371   const std::string &getName() const { return Name; }
372 
373   void setName(const Twine &newName) { Name = newName.str(); }
374 
375   /// \return an ID for the concrete type of this object.
376   /// This is used to implement the classof checks. This should not be used
377   /// for any other purpose, as the values may change as LLVM evolves.
378   unsigned getVPBlockID() const { return SubclassID; }
379 
380   const VPRegionBlock *getParent() const { return Parent; }
381 
382   void setParent(VPRegionBlock *P) { Parent = P; }
383 
384   /// \return the VPBasicBlock that is the entry of this VPBlockBase,
385   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
386   /// VPBlockBase is a VPBasicBlock, it is returned.
387   const VPBasicBlock *getEntryBasicBlock() const;
388   VPBasicBlock *getEntryBasicBlock();
389 
390   /// \return the VPBasicBlock that is the exit of this VPBlockBase,
391   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
392   /// VPBlockBase is a VPBasicBlock, it is returned.
393   const VPBasicBlock *getExitBasicBlock() const;
394   VPBasicBlock *getExitBasicBlock();
395 
396   const VPBlocksTy &getSuccessors() const { return Successors; }
397   VPBlocksTy &getSuccessors() { return Successors; }
398 
399   const VPBlocksTy &getPredecessors() const { return Predecessors; }
400   VPBlocksTy &getPredecessors() { return Predecessors; }
401 
402   /// \return the successor of this VPBlockBase if it has a single successor.
403   /// Otherwise return a null pointer.
404   VPBlockBase *getSingleSuccessor() const {
405     return (Successors.size() == 1 ? *Successors.begin() : nullptr);
406   }
407 
408   /// \return the predecessor of this VPBlockBase if it has a single
409   /// predecessor. Otherwise return a null pointer.
410   VPBlockBase *getSinglePredecessor() const {
411     return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
412   }
413 
414   /// An Enclosing Block of a block B is any block containing B, including B
415   /// itself. \return the closest enclosing block starting from "this", which
416   /// has successors. \return the root enclosing block if all enclosing blocks
417   /// have no successors.
418   VPBlockBase *getEnclosingBlockWithSuccessors();
419 
420   /// \return the closest enclosing block starting from "this", which has
421   /// predecessors. \return the root enclosing block if all enclosing blocks
422   /// have no predecessors.
423   VPBlockBase *getEnclosingBlockWithPredecessors();
424 
425   /// \return the successors either attached directly to this VPBlockBase or, if
426   /// this VPBlockBase is the exit block of a VPRegionBlock and has no
427   /// successors of its own, search recursively for the first enclosing
428   /// VPRegionBlock that has successors and return them. If no such
429   /// VPRegionBlock exists, return the (empty) successors of the topmost
430   /// VPBlockBase reached.
431   const VPBlocksTy &getHierarchicalSuccessors() {
432     return getEnclosingBlockWithSuccessors()->getSuccessors();
433   }
434 
435   /// \return the hierarchical successor of this VPBlockBase if it has a single
436   /// hierarchical successor. Otherwise return a null pointer.
437   VPBlockBase *getSingleHierarchicalSuccessor() {
438     return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
439   }
440 
441   /// \return the predecessors either attached directly to this VPBlockBase or,
442   /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
443   /// predecessors of its own, search recursively for the first enclosing
444   /// VPRegionBlock that has predecessors and return them. If no such
445   /// VPRegionBlock exists, return the (empty) predecessors of the topmost
446   /// VPBlockBase reached.
447   const VPBlocksTy &getHierarchicalPredecessors() {
448     return getEnclosingBlockWithPredecessors()->getPredecessors();
449   }
450 
451   /// \return the hierarchical predecessor of this VPBlockBase if it has a
452   /// single hierarchical predecessor. Otherwise return a null pointer.
453   VPBlockBase *getSingleHierarchicalPredecessor() {
454     return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
455   }
456 
457   /// Sets a given VPBlockBase \p Successor as the single successor and \return
458   /// \p Successor. The parent of this Block is copied to be the parent of
459   /// \p Successor.
460   VPBlockBase *setOneSuccessor(VPBlockBase *Successor) {
461     assert(Successors.empty() && "Setting one successor when others exist.");
462     appendSuccessor(Successor);
463     Successor->appendPredecessor(this);
464     Successor->Parent = Parent;
465     return Successor;
466   }
467 
468   /// Sets two given VPBlockBases \p IfTrue and \p IfFalse to be the two
469   /// successors. The parent of this Block is copied to be the parent of both
470   /// \p IfTrue and \p IfFalse.
471   void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
472     assert(Successors.empty() && "Setting two successors when others exist.");
473     appendSuccessor(IfTrue);
474     appendSuccessor(IfFalse);
475     IfTrue->appendPredecessor(this);
476     IfFalse->appendPredecessor(this);
477     IfTrue->Parent = Parent;
478     IfFalse->Parent = Parent;
479   }
480 
481   void disconnectSuccessor(VPBlockBase *Successor) {
482     assert(Successor && "Successor to disconnect is null.");
483     removeSuccessor(Successor);
484     Successor->removePredecessor(this);
485   }
486 
487   /// The method which generates the output IR that correspond to this
488   /// VPBlockBase, thereby "executing" the VPlan.
489   virtual void execute(struct VPTransformState *State) = 0;
490 
491   /// Delete all blocks reachable from a given VPBlockBase, inclusive.
492   static void deleteCFG(VPBlockBase *Entry);
493 };
494 
495 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
496 /// instructions.
497 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
498   friend VPBasicBlock;
499 
500 private:
501   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
502 
503   /// Each VPRecipe belongs to a single VPBasicBlock.
504   VPBasicBlock *Parent = nullptr;
505 
506 public:
507   /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
508   /// that is actually instantiated. Values of this enumeration are kept in the
509   /// SubclassID field of the VPRecipeBase objects. They are used for concrete
510   /// type identification.
511   using VPRecipeTy = enum {
512     VPBlendSC,
513     VPBranchOnMaskSC,
514     VPInstructionSC,
515     VPInterleaveSC,
516     VPPredInstPHISC,
517     VPReplicateSC,
518     VPWidenIntOrFpInductionSC,
519     VPWidenMemoryInstructionSC,
520     VPWidenPHISC,
521     VPWidenSC,
522   };
523 
524   VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
525   virtual ~VPRecipeBase() = default;
526 
527   /// \return an ID for the concrete type of this object.
528   /// This is used to implement the classof checks. This should not be used
529   /// for any other purpose, as the values may change as LLVM evolves.
530   unsigned getVPRecipeID() const { return SubclassID; }
531 
532   /// \return the VPBasicBlock which this VPRecipe belongs to.
533   VPBasicBlock *getParent() { return Parent; }
534   const VPBasicBlock *getParent() const { return Parent; }
535 
536   /// The method which generates the output IR instructions that correspond to
537   /// this VPRecipe, thereby "executing" the VPlan.
538   virtual void execute(struct VPTransformState &State) = 0;
539 
540   /// Each recipe prints itself.
541   virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
542 };
543 
544 /// This is a concrete Recipe that models a single VPlan-level instruction.
545 /// While as any Recipe it may generate a sequence of IR instructions when
546 /// executed, these instructions would always form a single-def expression as
547 /// the VPInstruction is also a single def-use vertex.
548 class VPInstruction : public VPUser, public VPRecipeBase {
549 public:
550   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
551   enum { Not = Instruction::OtherOpsEnd + 1 };
552 
553 private:
554   typedef unsigned char OpcodeTy;
555   OpcodeTy Opcode;
556 
557   /// Utility method serving execute(): generates a single instance of the
558   /// modeled instruction.
559   void generateInstruction(VPTransformState &State, unsigned Part);
560 
561 public:
562   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
563       : VPUser(VPValue::VPInstructionSC, Operands),
564         VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
565 
566   /// Method to support type inquiry through isa, cast, and dyn_cast.
567   static inline bool classof(const VPValue *V) {
568     return V->getVPValueID() == VPValue::VPInstructionSC;
569   }
570 
571   /// Method to support type inquiry through isa, cast, and dyn_cast.
572   static inline bool classof(const VPRecipeBase *R) {
573     return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
574   }
575 
576   unsigned getOpcode() const { return Opcode; }
577 
578   /// Generate the instruction.
579   /// TODO: We currently execute only per-part unless a specific instance is
580   /// provided.
581   void execute(VPTransformState &State) override;
582 
583   /// Print the Recipe.
584   void print(raw_ostream &O, const Twine &Indent) const override;
585 
586   /// Print the VPInstruction.
587   void print(raw_ostream &O) const;
588 };
589 
590 /// VPWidenRecipe is a recipe for producing a copy of vector type for each
591 /// Instruction in its ingredients independently, in order. This recipe covers
592 /// most of the traditional vectorization cases where each ingredient transforms
593 /// into a vectorized version of itself.
594 class VPWidenRecipe : public VPRecipeBase {
595 private:
596   /// Hold the ingredients by pointing to their original BasicBlock location.
597   BasicBlock::iterator Begin;
598   BasicBlock::iterator End;
599 
600 public:
601   VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
602     End = I->getIterator();
603     Begin = End++;
604   }
605 
606   ~VPWidenRecipe() override = default;
607 
608   /// Method to support type inquiry through isa, cast, and dyn_cast.
609   static inline bool classof(const VPRecipeBase *V) {
610     return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
611   }
612 
613   /// Produce widened copies of all Ingredients.
614   void execute(VPTransformState &State) override;
615 
616   /// Augment the recipe to include Instr, if it lies at its End.
617   bool appendInstruction(Instruction *Instr) {
618     if (End != Instr->getIterator())
619       return false;
620     End++;
621     return true;
622   }
623 
624   /// Print the recipe.
625   void print(raw_ostream &O, const Twine &Indent) const override;
626 };
627 
628 /// A recipe for handling phi nodes of integer and floating-point inductions,
629 /// producing their vector and scalar values.
630 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
631 private:
632   PHINode *IV;
633   TruncInst *Trunc;
634 
635 public:
636   VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
637       : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
638   ~VPWidenIntOrFpInductionRecipe() override = default;
639 
640   /// Method to support type inquiry through isa, cast, and dyn_cast.
641   static inline bool classof(const VPRecipeBase *V) {
642     return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
643   }
644 
645   /// Generate the vectorized and scalarized versions of the phi node as
646   /// needed by their users.
647   void execute(VPTransformState &State) override;
648 
649   /// Print the recipe.
650   void print(raw_ostream &O, const Twine &Indent) const override;
651 };
652 
653 /// A recipe for handling all phi nodes except for integer and FP inductions.
654 class VPWidenPHIRecipe : public VPRecipeBase {
655 private:
656   PHINode *Phi;
657 
658 public:
659   VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
660   ~VPWidenPHIRecipe() override = default;
661 
662   /// Method to support type inquiry through isa, cast, and dyn_cast.
663   static inline bool classof(const VPRecipeBase *V) {
664     return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
665   }
666 
667   /// Generate the phi/select nodes.
668   void execute(VPTransformState &State) override;
669 
670   /// Print the recipe.
671   void print(raw_ostream &O, const Twine &Indent) const override;
672 };
673 
674 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
675 /// instructions.
676 class VPBlendRecipe : public VPRecipeBase {
677 private:
678   PHINode *Phi;
679 
680   /// The blend operation is a User of a mask, if not null.
681   std::unique_ptr<VPUser> User;
682 
683 public:
684   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
685       : VPRecipeBase(VPBlendSC), Phi(Phi) {
686     assert((Phi->getNumIncomingValues() == 1 ||
687             Phi->getNumIncomingValues() == Masks.size()) &&
688            "Expected the same number of incoming values and masks");
689     if (!Masks.empty())
690       User.reset(new VPUser(Masks));
691   }
692 
693   /// Method to support type inquiry through isa, cast, and dyn_cast.
694   static inline bool classof(const VPRecipeBase *V) {
695     return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
696   }
697 
698   /// Generate the phi/select nodes.
699   void execute(VPTransformState &State) override;
700 
701   /// Print the recipe.
702   void print(raw_ostream &O, const Twine &Indent) const override;
703 };
704 
705 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
706 /// or stores into one wide load/store and shuffles.
707 class VPInterleaveRecipe : public VPRecipeBase {
708 private:
709   const InterleaveGroup *IG;
710 
711 public:
712   VPInterleaveRecipe(const InterleaveGroup *IG)
713       : VPRecipeBase(VPInterleaveSC), IG(IG) {}
714   ~VPInterleaveRecipe() override = default;
715 
716   /// Method to support type inquiry through isa, cast, and dyn_cast.
717   static inline bool classof(const VPRecipeBase *V) {
718     return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
719   }
720 
721   /// Generate the wide load or store, and shuffles.
722   void execute(VPTransformState &State) override;
723 
724   /// Print the recipe.
725   void print(raw_ostream &O, const Twine &Indent) const override;
726 
727   const InterleaveGroup *getInterleaveGroup() { return IG; }
728 };
729 
730 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
731 /// copies of the original scalar type, one per lane, instead of producing a
732 /// single copy of widened type for all lanes. If the instruction is known to be
733 /// uniform only one copy, per lane zero, will be generated.
734 class VPReplicateRecipe : public VPRecipeBase {
735 private:
736   /// The instruction being replicated.
737   Instruction *Ingredient;
738 
739   /// Indicator if only a single replica per lane is needed.
740   bool IsUniform;
741 
742   /// Indicator if the replicas are also predicated.
743   bool IsPredicated;
744 
745   /// Indicator if the scalar values should also be packed into a vector.
746   bool AlsoPack;
747 
748 public:
749   VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
750       : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
751         IsPredicated(IsPredicated) {
752     // Retain the previous behavior of predicateInstructions(), where an
753     // insert-element of a predicated instruction got hoisted into the
754     // predicated basic block iff it was its only user. This is achieved by
755     // having predicated instructions also pack their values into a vector by
756     // default unless they have a replicated user which uses their scalar value.
757     AlsoPack = IsPredicated && !I->use_empty();
758   }
759 
760   ~VPReplicateRecipe() override = default;
761 
762   /// Method to support type inquiry through isa, cast, and dyn_cast.
763   static inline bool classof(const VPRecipeBase *V) {
764     return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
765   }
766 
767   /// Generate replicas of the desired Ingredient. Replicas will be generated
768   /// for all parts and lanes unless a specific part and lane are specified in
769   /// the \p State.
770   void execute(VPTransformState &State) override;
771 
772   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
773 
774   /// Print the recipe.
775   void print(raw_ostream &O, const Twine &Indent) const override;
776 };
777 
778 /// A recipe for generating conditional branches on the bits of a mask.
779 class VPBranchOnMaskRecipe : public VPRecipeBase {
780 private:
781   std::unique_ptr<VPUser> User;
782 
783 public:
784   VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
785     if (BlockInMask) // nullptr means all-one mask.
786       User.reset(new VPUser({BlockInMask}));
787   }
788 
789   /// Method to support type inquiry through isa, cast, and dyn_cast.
790   static inline bool classof(const VPRecipeBase *V) {
791     return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
792   }
793 
794   /// Generate the extraction of the appropriate bit from the block mask and the
795   /// conditional branch.
796   void execute(VPTransformState &State) override;
797 
798   /// Print the recipe.
799   void print(raw_ostream &O, const Twine &Indent) const override {
800     O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
801     if (User)
802       O << *User->getOperand(0);
803     else
804       O << " All-One";
805     O << "\\l\"";
806   }
807 };
808 
809 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
810 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
811 /// order to merge values that are set under such a branch and feed their uses.
812 /// The phi nodes can be scalar or vector depending on the users of the value.
813 /// This recipe works in concert with VPBranchOnMaskRecipe.
814 class VPPredInstPHIRecipe : public VPRecipeBase {
815 private:
816   Instruction *PredInst;
817 
818 public:
819   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
820   /// nodes after merging back from a Branch-on-Mask.
821   VPPredInstPHIRecipe(Instruction *PredInst)
822       : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
823   ~VPPredInstPHIRecipe() override = default;
824 
825   /// Method to support type inquiry through isa, cast, and dyn_cast.
826   static inline bool classof(const VPRecipeBase *V) {
827     return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
828   }
829 
830   /// Generates phi nodes for live-outs as needed to retain SSA form.
831   void execute(VPTransformState &State) override;
832 
833   /// Print the recipe.
834   void print(raw_ostream &O, const Twine &Indent) const override;
835 };
836 
837 /// A Recipe for widening load/store operations.
838 /// TODO: We currently execute only per-part unless a specific instance is
839 /// provided.
840 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
841 private:
842   Instruction &Instr;
843   std::unique_ptr<VPUser> User;
844 
845 public:
846   VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
847       : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
848     if (Mask) // Create a VPInstruction to register as a user of the mask.
849       User.reset(new VPUser({Mask}));
850   }
851 
852   /// Method to support type inquiry through isa, cast, and dyn_cast.
853   static inline bool classof(const VPRecipeBase *V) {
854     return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
855   }
856 
857   /// Generate the wide load/store.
858   void execute(VPTransformState &State) override;
859 
860   /// Print the recipe.
861   void print(raw_ostream &O, const Twine &Indent) const override;
862 };
863 
864 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
865 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
866 /// output IR instructions.
867 class VPBasicBlock : public VPBlockBase {
868 public:
869   using RecipeListTy = iplist<VPRecipeBase>;
870 
871 private:
872   /// The VPRecipes held in the order of output instructions to generate.
873   RecipeListTy Recipes;
874 
875 public:
876   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
877       : VPBlockBase(VPBasicBlockSC, Name.str()) {
878     if (Recipe)
879       appendRecipe(Recipe);
880   }
881 
882   ~VPBasicBlock() override { Recipes.clear(); }
883 
884   /// Instruction iterators...
885   using iterator = RecipeListTy::iterator;
886   using const_iterator = RecipeListTy::const_iterator;
887   using reverse_iterator = RecipeListTy::reverse_iterator;
888   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
889 
890   //===--------------------------------------------------------------------===//
891   /// Recipe iterator methods
892   ///
893   inline iterator begin() { return Recipes.begin(); }
894   inline const_iterator begin() const { return Recipes.begin(); }
895   inline iterator end() { return Recipes.end(); }
896   inline const_iterator end() const { return Recipes.end(); }
897 
898   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
899   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
900   inline reverse_iterator rend() { return Recipes.rend(); }
901   inline const_reverse_iterator rend() const { return Recipes.rend(); }
902 
903   inline size_t size() const { return Recipes.size(); }
904   inline bool empty() const { return Recipes.empty(); }
905   inline const VPRecipeBase &front() const { return Recipes.front(); }
906   inline VPRecipeBase &front() { return Recipes.front(); }
907   inline const VPRecipeBase &back() const { return Recipes.back(); }
908   inline VPRecipeBase &back() { return Recipes.back(); }
909 
910   /// \brief Returns a pointer to a member of the recipe list.
911   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
912     return &VPBasicBlock::Recipes;
913   }
914 
915   /// Method to support type inquiry through isa, cast, and dyn_cast.
916   static inline bool classof(const VPBlockBase *V) {
917     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
918   }
919 
920   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
921     assert(Recipe && "No recipe to append.");
922     assert(!Recipe->Parent && "Recipe already in VPlan");
923     Recipe->Parent = this;
924     Recipes.insert(InsertPt, Recipe);
925   }
926 
927   /// Augment the existing recipes of a VPBasicBlock with an additional
928   /// \p Recipe as the last recipe.
929   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
930 
931   /// The method which generates the output IR instructions that correspond to
932   /// this VPBasicBlock, thereby "executing" the VPlan.
933   void execute(struct VPTransformState *State) override;
934 
935 private:
936   /// Create an IR BasicBlock to hold the output instructions generated by this
937   /// VPBasicBlock, and return it. Update the CFGState accordingly.
938   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
939 };
940 
941 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
942 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
943 /// A VPRegionBlock may indicate that its contents are to be replicated several
944 /// times. This is designed to support predicated scalarization, in which a
945 /// scalar if-then code structure needs to be generated VF * UF times. Having
946 /// this replication indicator helps to keep a single model for multiple
947 /// candidate VF's. The actual replication takes place only once the desired VF
948 /// and UF have been determined.
949 class VPRegionBlock : public VPBlockBase {
950 private:
951   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
952   VPBlockBase *Entry;
953 
954   /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
955   VPBlockBase *Exit;
956 
957   /// An indicator whether this region is to generate multiple replicated
958   /// instances of output IR corresponding to its VPBlockBases.
959   bool IsReplicator;
960 
961 public:
962   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
963                 const std::string &Name = "", bool IsReplicator = false)
964       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
965         IsReplicator(IsReplicator) {
966     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
967     assert(Exit->getSuccessors().empty() && "Exit block has successors.");
968     Entry->setParent(this);
969     Exit->setParent(this);
970   }
971 
972   ~VPRegionBlock() override {
973     if (Entry)
974       deleteCFG(Entry);
975   }
976 
977   /// Method to support type inquiry through isa, cast, and dyn_cast.
978   static inline bool classof(const VPBlockBase *V) {
979     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
980   }
981 
982   const VPBlockBase *getEntry() const { return Entry; }
983   VPBlockBase *getEntry() { return Entry; }
984 
985   const VPBlockBase *getExit() const { return Exit; }
986   VPBlockBase *getExit() { return Exit; }
987 
988   /// An indicator whether this region is to generate multiple replicated
989   /// instances of output IR corresponding to its VPBlockBases.
990   bool isReplicator() const { return IsReplicator; }
991 
992   /// The method which generates the output IR instructions that correspond to
993   /// this VPRegionBlock, thereby "executing" the VPlan.
994   void execute(struct VPTransformState *State) override;
995 };
996 
997 /// VPlan models a candidate for vectorization, encoding various decisions take
998 /// to produce efficient output IR, including which branches, basic-blocks and
999 /// output IR instructions to generate, and their cost. VPlan holds a
1000 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1001 /// VPBlock.
1002 class VPlan {
1003   friend class VPlanPrinter;
1004 
1005 private:
1006   /// Hold the single entry to the Hierarchical CFG of the VPlan.
1007   VPBlockBase *Entry;
1008 
1009   /// Holds the VFs applicable to this VPlan.
1010   SmallSet<unsigned, 2> VFs;
1011 
1012   /// Holds the name of the VPlan, for printing.
1013   std::string Name;
1014 
1015   /// Holds a mapping between Values and their corresponding VPValue inside
1016   /// VPlan.
1017   Value2VPValueTy Value2VPValue;
1018 
1019 public:
1020   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1021 
1022   ~VPlan() {
1023     if (Entry)
1024       VPBlockBase::deleteCFG(Entry);
1025     for (auto &MapEntry : Value2VPValue)
1026       delete MapEntry.second;
1027   }
1028 
1029   /// Generate the IR code for this VPlan.
1030   void execute(struct VPTransformState *State);
1031 
1032   VPBlockBase *getEntry() { return Entry; }
1033   const VPBlockBase *getEntry() const { return Entry; }
1034 
1035   VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1036 
1037   void addVF(unsigned VF) { VFs.insert(VF); }
1038 
1039   bool hasVF(unsigned VF) { return VFs.count(VF); }
1040 
1041   const std::string &getName() const { return Name; }
1042 
1043   void setName(const Twine &newName) { Name = newName.str(); }
1044 
1045   void addVPValue(Value *V) {
1046     assert(V && "Trying to add a null Value to VPlan");
1047     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1048     Value2VPValue[V] = new VPValue();
1049   }
1050 
1051   VPValue *getVPValue(Value *V) {
1052     assert(V && "Trying to get the VPValue of a null Value");
1053     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1054     return Value2VPValue[V];
1055   }
1056 
1057 private:
1058   /// Add to the given dominator tree the header block and every new basic block
1059   /// that was created between it and the latch block, inclusive.
1060   static void updateDominatorTree(DominatorTree *DT,
1061                                   BasicBlock *LoopPreHeaderBB,
1062                                   BasicBlock *LoopLatchBB);
1063 };
1064 
1065 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1066 /// indented and follows the dot format.
1067 class VPlanPrinter {
1068   friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1069   friend inline raw_ostream &operator<<(raw_ostream &OS,
1070                                         const struct VPlanIngredient &I);
1071 
1072 private:
1073   raw_ostream &OS;
1074   VPlan &Plan;
1075   unsigned Depth;
1076   unsigned TabWidth = 2;
1077   std::string Indent;
1078   unsigned BID = 0;
1079   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1080 
1081   VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1082 
1083   /// Handle indentation.
1084   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1085 
1086   /// Print a given \p Block of the Plan.
1087   void dumpBlock(const VPBlockBase *Block);
1088 
1089   /// Print the information related to the CFG edges going out of a given
1090   /// \p Block, followed by printing the successor blocks themselves.
1091   void dumpEdges(const VPBlockBase *Block);
1092 
1093   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1094   /// its successor blocks.
1095   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1096 
1097   /// Print a given \p Region of the Plan.
1098   void dumpRegion(const VPRegionBlock *Region);
1099 
1100   unsigned getOrCreateBID(const VPBlockBase *Block) {
1101     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1102   }
1103 
1104   const Twine getOrCreateName(const VPBlockBase *Block);
1105 
1106   const Twine getUID(const VPBlockBase *Block);
1107 
1108   /// Print the information related to a CFG edge between two VPBlockBases.
1109   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1110                 const Twine &Label);
1111 
1112   void dump();
1113 
1114   static void printAsIngredient(raw_ostream &O, Value *V);
1115 };
1116 
1117 struct VPlanIngredient {
1118   Value *V;
1119 
1120   VPlanIngredient(Value *V) : V(V) {}
1121 };
1122 
1123 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1124   VPlanPrinter::printAsIngredient(OS, I.V);
1125   return OS;
1126 }
1127 
1128 inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1129   VPlanPrinter Printer(OS, Plan);
1130   Printer.dump();
1131   return OS;
1132 }
1133 
1134 //===--------------------------------------------------------------------===//
1135 // GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs  //
1136 //===--------------------------------------------------------------------===//
1137 
1138 // Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1139 // graph of VPBlockBase nodes...
1140 
1141 template <> struct GraphTraits<VPBlockBase *> {
1142   using NodeRef = VPBlockBase *;
1143   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1144 
1145   static NodeRef getEntryNode(NodeRef N) { return N; }
1146 
1147   static inline ChildIteratorType child_begin(NodeRef N) {
1148     return N->getSuccessors().begin();
1149   }
1150 
1151   static inline ChildIteratorType child_end(NodeRef N) {
1152     return N->getSuccessors().end();
1153   }
1154 };
1155 
1156 template <> struct GraphTraits<const VPBlockBase *> {
1157   using NodeRef = const VPBlockBase *;
1158   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1159 
1160   static NodeRef getEntryNode(NodeRef N) { return N; }
1161 
1162   static inline ChildIteratorType child_begin(NodeRef N) {
1163     return N->getSuccessors().begin();
1164   }
1165 
1166   static inline ChildIteratorType child_end(NodeRef N) {
1167     return N->getSuccessors().end();
1168   }
1169 };
1170 
1171 // Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1172 // graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
1173 // for a VPBlockBase is considered to be when traversing the predecessors of a
1174 // VPBlockBase instead of its successors.
1175 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1176   using NodeRef = VPBlockBase *;
1177   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1178 
1179   static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
1180     return B;
1181   }
1182 
1183   static inline ChildIteratorType child_begin(NodeRef N) {
1184     return N->getPredecessors().begin();
1185   }
1186 
1187   static inline ChildIteratorType child_end(NodeRef N) {
1188     return N->getPredecessors().end();
1189   }
1190 };
1191 
1192 } // end namespace llvm
1193 
1194 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
1195