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