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