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