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() && all_of(getStoredValues(), [Op](VPValue *StoredV) {
1511              return Op != StoredV;
1512            });
1513   }
1514 };
1515 
1516 /// A recipe to represent inloop reduction operations, performing a reduction on
1517 /// a vector operand into a scalar value, and adding the result to a chain.
1518 /// The Operands are {ChainOp, VecOp, [Condition]}.
1519 class VPReductionRecipe : public VPRecipeBase, public VPValue {
1520   /// The recurrence decriptor for the reduction in question.
1521   const RecurrenceDescriptor *RdxDesc;
1522   /// Pointer to the TTI, needed to create the target reduction
1523   const TargetTransformInfo *TTI;
1524 
1525 public:
1526   VPReductionRecipe(const RecurrenceDescriptor *R, Instruction *I,
1527                     VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
1528                     const TargetTransformInfo *TTI)
1529       : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}),
1530         VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) {
1531     if (CondOp)
1532       addOperand(CondOp);
1533   }
1534 
1535   ~VPReductionRecipe() override = default;
1536 
1537   /// Method to support type inquiry through isa, cast, and dyn_cast.
1538   static inline bool classof(const VPValue *V) {
1539     return V->getVPValueID() == VPValue::VPVReductionSC;
1540   }
1541 
1542   /// Generate the reduction in the loop
1543   void execute(VPTransformState &State) override;
1544 
1545 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1546   /// Print the recipe.
1547   void print(raw_ostream &O, const Twine &Indent,
1548              VPSlotTracker &SlotTracker) const override;
1549 #endif
1550 
1551   /// The VPValue of the scalar Chain being accumulated.
1552   VPValue *getChainOp() const { return getOperand(0); }
1553   /// The VPValue of the vector value to be reduced.
1554   VPValue *getVecOp() const { return getOperand(1); }
1555   /// The VPValue of the condition for the block.
1556   VPValue *getCondOp() const {
1557     return getNumOperands() > 2 ? getOperand(2) : nullptr;
1558   }
1559 };
1560 
1561 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
1562 /// copies of the original scalar type, one per lane, instead of producing a
1563 /// single copy of widened type for all lanes. If the instruction is known to be
1564 /// uniform only one copy, per lane zero, will be generated.
1565 class VPReplicateRecipe : public VPRecipeBase, public VPValue {
1566   /// Indicator if only a single replica per lane is needed.
1567   bool IsUniform;
1568 
1569   /// Indicator if the replicas are also predicated.
1570   bool IsPredicated;
1571 
1572   /// Indicator if the scalar values should also be packed into a vector.
1573   bool AlsoPack;
1574 
1575 public:
1576   template <typename IterT>
1577   VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands,
1578                     bool IsUniform, bool IsPredicated = false)
1579       : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this),
1580         IsUniform(IsUniform), IsPredicated(IsPredicated) {
1581     // Retain the previous behavior of predicateInstructions(), where an
1582     // insert-element of a predicated instruction got hoisted into the
1583     // predicated basic block iff it was its only user. This is achieved by
1584     // having predicated instructions also pack their values into a vector by
1585     // default unless they have a replicated user which uses their scalar value.
1586     AlsoPack = IsPredicated && !I->use_empty();
1587   }
1588 
1589   ~VPReplicateRecipe() override = default;
1590 
1591   /// Method to support type inquiry through isa, cast, and dyn_cast.
1592   static inline bool classof(const VPDef *D) {
1593     return D->getVPDefID() == VPRecipeBase::VPReplicateSC;
1594   }
1595 
1596   static inline bool classof(const VPValue *V) {
1597     return V->getVPValueID() == VPValue::VPVReplicateSC;
1598   }
1599 
1600   /// Generate replicas of the desired Ingredient. Replicas will be generated
1601   /// for all parts and lanes unless a specific part and lane are specified in
1602   /// the \p State.
1603   void execute(VPTransformState &State) override;
1604 
1605   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
1606 
1607 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1608   /// Print the recipe.
1609   void print(raw_ostream &O, const Twine &Indent,
1610              VPSlotTracker &SlotTracker) const override;
1611 #endif
1612 
1613   bool isUniform() const { return IsUniform; }
1614 
1615   bool isPacked() const { return AlsoPack; }
1616 
1617   bool isPredicated() const { return IsPredicated; }
1618 
1619   /// Returns true if the recipe only uses the first lane of operand \p Op.
1620   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1621     assert(is_contained(operands(), Op) &&
1622            "Op must be an operand of the recipe");
1623     return isUniform();
1624   }
1625 
1626   /// Returns true if the recipe uses scalars of operand \p Op.
1627   bool usesScalars(const VPValue *Op) const override {
1628     assert(is_contained(operands(), Op) &&
1629            "Op must be an operand of the recipe");
1630     return true;
1631   }
1632 };
1633 
1634 /// A recipe for generating conditional branches on the bits of a mask.
1635 class VPBranchOnMaskRecipe : public VPRecipeBase {
1636 public:
1637   VPBranchOnMaskRecipe(VPValue *BlockInMask)
1638       : VPRecipeBase(VPBranchOnMaskSC, {}) {
1639     if (BlockInMask) // nullptr means all-one mask.
1640       addOperand(BlockInMask);
1641   }
1642 
1643   /// Method to support type inquiry through isa, cast, and dyn_cast.
1644   static inline bool classof(const VPDef *D) {
1645     return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC;
1646   }
1647 
1648   /// Generate the extraction of the appropriate bit from the block mask and the
1649   /// conditional branch.
1650   void execute(VPTransformState &State) override;
1651 
1652 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1653   /// Print the recipe.
1654   void print(raw_ostream &O, const Twine &Indent,
1655              VPSlotTracker &SlotTracker) const override {
1656     O << Indent << "BRANCH-ON-MASK ";
1657     if (VPValue *Mask = getMask())
1658       Mask->printAsOperand(O, SlotTracker);
1659     else
1660       O << " All-One";
1661   }
1662 #endif
1663 
1664   /// Return the mask used by this recipe. Note that a full mask is represented
1665   /// by a nullptr.
1666   VPValue *getMask() const {
1667     assert(getNumOperands() <= 1 && "should have either 0 or 1 operands");
1668     // Mask is optional.
1669     return getNumOperands() == 1 ? getOperand(0) : nullptr;
1670   }
1671 };
1672 
1673 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
1674 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
1675 /// order to merge values that are set under such a branch and feed their uses.
1676 /// The phi nodes can be scalar or vector depending on the users of the value.
1677 /// This recipe works in concert with VPBranchOnMaskRecipe.
1678 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue {
1679 public:
1680   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
1681   /// nodes after merging back from a Branch-on-Mask.
1682   VPPredInstPHIRecipe(VPValue *PredV)
1683       : VPRecipeBase(VPPredInstPHISC, PredV),
1684         VPValue(VPValue::VPVPredInstPHI, nullptr, this) {}
1685   ~VPPredInstPHIRecipe() override = default;
1686 
1687   /// Method to support type inquiry through isa, cast, and dyn_cast.
1688   static inline bool classof(const VPDef *D) {
1689     return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC;
1690   }
1691 
1692   /// Generates phi nodes for live-outs as needed to retain SSA form.
1693   void execute(VPTransformState &State) override;
1694 
1695 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1696   /// Print the recipe.
1697   void print(raw_ostream &O, const Twine &Indent,
1698              VPSlotTracker &SlotTracker) const override;
1699 #endif
1700 
1701   /// Returns true if the recipe uses scalars of operand \p Op.
1702   bool usesScalars(const VPValue *Op) const override {
1703     assert(is_contained(operands(), Op) &&
1704            "Op must be an operand of the recipe");
1705     return true;
1706   }
1707 };
1708 
1709 /// A Recipe for widening load/store operations.
1710 /// The recipe uses the following VPValues:
1711 /// - For load: Address, optional mask
1712 /// - For store: Address, stored value, optional mask
1713 /// TODO: We currently execute only per-part unless a specific instance is
1714 /// provided.
1715 class VPWidenMemoryInstructionRecipe : public VPRecipeBase, public VPValue {
1716   Instruction &Ingredient;
1717 
1718   // Whether the loaded-from / stored-to addresses are consecutive.
1719   bool Consecutive;
1720 
1721   // Whether the consecutive loaded/stored addresses are in reverse order.
1722   bool Reverse;
1723 
1724   void setMask(VPValue *Mask) {
1725     if (!Mask)
1726       return;
1727     addOperand(Mask);
1728   }
1729 
1730   bool isMasked() const {
1731     return isStore() ? getNumOperands() == 3 : getNumOperands() == 2;
1732   }
1733 
1734 public:
1735   VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask,
1736                                  bool Consecutive, bool Reverse)
1737       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}),
1738         VPValue(VPValue::VPVMemoryInstructionSC, &Load, this), Ingredient(Load),
1739         Consecutive(Consecutive), Reverse(Reverse) {
1740     assert((Consecutive || !Reverse) && "Reverse implies consecutive");
1741     setMask(Mask);
1742   }
1743 
1744   VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr,
1745                                  VPValue *StoredValue, VPValue *Mask,
1746                                  bool Consecutive, bool Reverse)
1747       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}),
1748         VPValue(VPValue::VPVMemoryInstructionSC, &Store, this),
1749         Ingredient(Store), Consecutive(Consecutive), Reverse(Reverse) {
1750     assert((Consecutive || !Reverse) && "Reverse implies consecutive");
1751     setMask(Mask);
1752   }
1753 
1754   /// Method to support type inquiry through isa, cast, and dyn_cast.
1755   static inline bool classof(const VPDef *D) {
1756     return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1757   }
1758 
1759   /// Return the address accessed by this recipe.
1760   VPValue *getAddr() const {
1761     return getOperand(0); // Address is the 1st, mandatory operand.
1762   }
1763 
1764   /// Return the mask used by this recipe. Note that a full mask is represented
1765   /// by a nullptr.
1766   VPValue *getMask() const {
1767     // Mask is optional and therefore the last operand.
1768     return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
1769   }
1770 
1771   /// Returns true if this recipe is a store.
1772   bool isStore() const { return isa<StoreInst>(Ingredient); }
1773 
1774   /// Return the address accessed by this recipe.
1775   VPValue *getStoredValue() const {
1776     assert(isStore() && "Stored value only available for store instructions");
1777     return getOperand(1); // Stored value is the 2nd, mandatory operand.
1778   }
1779 
1780   // Return whether the loaded-from / stored-to addresses are consecutive.
1781   bool isConsecutive() const { return Consecutive; }
1782 
1783   // Return whether the consecutive loaded/stored addresses are in reverse
1784   // order.
1785   bool isReverse() const { return Reverse; }
1786 
1787   /// Generate the wide load/store.
1788   void execute(VPTransformState &State) override;
1789 
1790 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1791   /// Print the recipe.
1792   void print(raw_ostream &O, const Twine &Indent,
1793              VPSlotTracker &SlotTracker) const override;
1794 #endif
1795 
1796   /// Returns true if the recipe only uses the first lane of operand \p Op.
1797   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1798     assert(is_contained(operands(), Op) &&
1799            "Op must be an operand of the recipe");
1800 
1801     // Widened, consecutive memory operations only demand the first lane of
1802     // their address, unless the same operand is also stored. That latter can
1803     // happen with opaque pointers.
1804     return Op == getAddr() && isConsecutive() &&
1805            (!isStore() || Op != getStoredValue());
1806   }
1807 };
1808 
1809 /// Recipe to expand a SCEV expression.
1810 class VPExpandSCEVRecipe : public VPRecipeBase, public VPValue {
1811   const SCEV *Expr;
1812   ScalarEvolution &SE;
1813 
1814 public:
1815   VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE)
1816       : VPRecipeBase(VPExpandSCEVSC, {}), VPValue(nullptr, this), Expr(Expr),
1817         SE(SE) {}
1818 
1819   ~VPExpandSCEVRecipe() override = default;
1820 
1821   /// Method to support type inquiry through isa, cast, and dyn_cast.
1822   static inline bool classof(const VPDef *D) {
1823     return D->getVPDefID() == VPExpandSCEVSC;
1824   }
1825 
1826   /// Generate a canonical vector induction variable of the vector loop, with
1827   void execute(VPTransformState &State) override;
1828 
1829 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1830   /// Print the recipe.
1831   void print(raw_ostream &O, const Twine &Indent,
1832              VPSlotTracker &SlotTracker) const override;
1833 #endif
1834 
1835   const SCEV *getSCEV() const { return Expr; }
1836 };
1837 
1838 /// Canonical scalar induction phi of the vector loop. Starting at the specified
1839 /// start value (either 0 or the resume value when vectorizing the epilogue
1840 /// loop). VPWidenCanonicalIVRecipe represents the vector version of the
1841 /// canonical induction variable.
1842 class VPCanonicalIVPHIRecipe : public VPHeaderPHIRecipe {
1843   DebugLoc DL;
1844 
1845 public:
1846   VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL)
1847       : VPHeaderPHIRecipe(VPValue::VPVCanonicalIVPHISC, VPCanonicalIVPHISC,
1848                           nullptr, StartV),
1849         DL(DL) {}
1850 
1851   ~VPCanonicalIVPHIRecipe() override = default;
1852 
1853   /// Method to support type inquiry through isa, cast, and dyn_cast.
1854   static inline bool classof(const VPDef *D) {
1855     return D->getVPDefID() == VPCanonicalIVPHISC;
1856   }
1857   static inline bool classof(const VPHeaderPHIRecipe *D) {
1858     return D->getVPDefID() == VPCanonicalIVPHISC;
1859   }
1860   static inline bool classof(const VPValue *V) {
1861     return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC;
1862   }
1863 
1864   /// Generate the canonical scalar induction phi of the vector loop.
1865   void execute(VPTransformState &State) override;
1866 
1867 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1868   /// Print the recipe.
1869   void print(raw_ostream &O, const Twine &Indent,
1870              VPSlotTracker &SlotTracker) const override;
1871 #endif
1872 
1873   /// Returns the scalar type of the induction.
1874   const Type *getScalarType() const {
1875     return getOperand(0)->getLiveInIRValue()->getType();
1876   }
1877 
1878   /// Returns true if the recipe only uses the first lane of operand \p Op.
1879   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1880     assert(is_contained(operands(), Op) &&
1881            "Op must be an operand of the recipe");
1882     return true;
1883   }
1884 };
1885 
1886 /// A Recipe for widening the canonical induction variable of the vector loop.
1887 class VPWidenCanonicalIVRecipe : public VPRecipeBase, public VPValue {
1888 public:
1889   VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV)
1890       : VPRecipeBase(VPWidenCanonicalIVSC, {CanonicalIV}),
1891         VPValue(VPValue::VPVWidenCanonicalIVSC, nullptr, this) {}
1892 
1893   ~VPWidenCanonicalIVRecipe() override = default;
1894 
1895   /// Method to support type inquiry through isa, cast, and dyn_cast.
1896   static inline bool classof(const VPDef *D) {
1897     return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1898   }
1899 
1900   /// Extra classof implementations to allow directly casting from VPUser ->
1901   /// VPWidenCanonicalIVRecipe.
1902   static inline bool classof(const VPUser *U) {
1903     auto *R = dyn_cast<VPRecipeBase>(U);
1904     return R && R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1905   }
1906   static inline bool classof(const VPRecipeBase *R) {
1907     return R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1908   }
1909 
1910   /// Generate a canonical vector induction variable of the vector loop, with
1911   /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
1912   /// step = <VF*UF, VF*UF, ..., VF*UF>.
1913   void execute(VPTransformState &State) override;
1914 
1915 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1916   /// Print the recipe.
1917   void print(raw_ostream &O, const Twine &Indent,
1918              VPSlotTracker &SlotTracker) const override;
1919 #endif
1920 
1921   /// Returns the scalar type of the induction.
1922   const Type *getScalarType() const {
1923     return cast<VPCanonicalIVPHIRecipe>(getOperand(0)->getDef())
1924         ->getScalarType();
1925   }
1926 };
1927 
1928 /// A recipe for handling phi nodes of integer and floating-point inductions,
1929 /// producing their scalar values.
1930 class VPScalarIVStepsRecipe : public VPRecipeBase, public VPValue {
1931   /// Scalar type to use for the generated values.
1932   Type *Ty;
1933   /// If not nullptr, truncate the generated values to TruncToTy.
1934   Type *TruncToTy;
1935   const InductionDescriptor &IndDesc;
1936 
1937 public:
1938   VPScalarIVStepsRecipe(Type *Ty, const InductionDescriptor &IndDesc,
1939                         VPValue *CanonicalIV, VPValue *Start, VPValue *Step,
1940                         Type *TruncToTy)
1941       : VPRecipeBase(VPScalarIVStepsSC, {CanonicalIV, Start, Step}),
1942         VPValue(nullptr, this), Ty(Ty), TruncToTy(TruncToTy), IndDesc(IndDesc) {
1943   }
1944 
1945   ~VPScalarIVStepsRecipe() override = default;
1946 
1947   /// Method to support type inquiry through isa, cast, and dyn_cast.
1948   static inline bool classof(const VPDef *D) {
1949     return D->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1950   }
1951   /// Extra classof implementations to allow directly casting from VPUser ->
1952   /// VPScalarIVStepsRecipe.
1953   static inline bool classof(const VPUser *U) {
1954     auto *R = dyn_cast<VPRecipeBase>(U);
1955     return R && R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1956   }
1957   static inline bool classof(const VPRecipeBase *R) {
1958     return R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1959   }
1960 
1961   /// Generate the scalarized versions of the phi node as needed by their users.
1962   void execute(VPTransformState &State) override;
1963 
1964 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1965   /// Print the recipe.
1966   void print(raw_ostream &O, const Twine &Indent,
1967              VPSlotTracker &SlotTracker) const override;
1968 #endif
1969 
1970   /// Returns true if the induction is canonical, i.e. starting at 0 and
1971   /// incremented by UF * VF (= the original IV is incremented by 1).
1972   bool isCanonical() const;
1973 
1974   VPCanonicalIVPHIRecipe *getCanonicalIV() const;
1975   VPValue *getStartValue() const { return getOperand(1); }
1976   VPValue *getStepValue() const { return getOperand(2); }
1977 
1978   /// Returns true if the recipe only uses the first lane of operand \p Op.
1979   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1980     assert(is_contained(operands(), Op) &&
1981            "Op must be an operand of the recipe");
1982     return true;
1983   }
1984 };
1985 
1986 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1987 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1988 /// output IR instructions. All PHI-like recipes must come before any non-PHI recipes.
1989 class VPBasicBlock : public VPBlockBase {
1990 public:
1991   using RecipeListTy = iplist<VPRecipeBase>;
1992 
1993 private:
1994   /// The VPRecipes held in the order of output instructions to generate.
1995   RecipeListTy Recipes;
1996 
1997 public:
1998   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1999       : VPBlockBase(VPBasicBlockSC, Name.str()) {
2000     if (Recipe)
2001       appendRecipe(Recipe);
2002   }
2003 
2004   ~VPBasicBlock() override {
2005     while (!Recipes.empty())
2006       Recipes.pop_back();
2007   }
2008 
2009   /// Instruction iterators...
2010   using iterator = RecipeListTy::iterator;
2011   using const_iterator = RecipeListTy::const_iterator;
2012   using reverse_iterator = RecipeListTy::reverse_iterator;
2013   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
2014 
2015   //===--------------------------------------------------------------------===//
2016   /// Recipe iterator methods
2017   ///
2018   inline iterator begin() { return Recipes.begin(); }
2019   inline const_iterator begin() const { return Recipes.begin(); }
2020   inline iterator end() { return Recipes.end(); }
2021   inline const_iterator end() const { return Recipes.end(); }
2022 
2023   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
2024   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
2025   inline reverse_iterator rend() { return Recipes.rend(); }
2026   inline const_reverse_iterator rend() const { return Recipes.rend(); }
2027 
2028   inline size_t size() const { return Recipes.size(); }
2029   inline bool empty() const { return Recipes.empty(); }
2030   inline const VPRecipeBase &front() const { return Recipes.front(); }
2031   inline VPRecipeBase &front() { return Recipes.front(); }
2032   inline const VPRecipeBase &back() const { return Recipes.back(); }
2033   inline VPRecipeBase &back() { return Recipes.back(); }
2034 
2035   /// Returns a reference to the list of recipes.
2036   RecipeListTy &getRecipeList() { return Recipes; }
2037 
2038   /// Returns a pointer to a member of the recipe list.
2039   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
2040     return &VPBasicBlock::Recipes;
2041   }
2042 
2043   /// Method to support type inquiry through isa, cast, and dyn_cast.
2044   static inline bool classof(const VPBlockBase *V) {
2045     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
2046   }
2047 
2048   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
2049     assert(Recipe && "No recipe to append.");
2050     assert(!Recipe->Parent && "Recipe already in VPlan");
2051     Recipe->Parent = this;
2052     Recipes.insert(InsertPt, Recipe);
2053   }
2054 
2055   /// Augment the existing recipes of a VPBasicBlock with an additional
2056   /// \p Recipe as the last recipe.
2057   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
2058 
2059   /// The method which generates the output IR instructions that correspond to
2060   /// this VPBasicBlock, thereby "executing" the VPlan.
2061   void execute(struct VPTransformState *State) override;
2062 
2063   /// Return the position of the first non-phi node recipe in the block.
2064   iterator getFirstNonPhi();
2065 
2066   /// Returns an iterator range over the PHI-like recipes in the block.
2067   iterator_range<iterator> phis() {
2068     return make_range(begin(), getFirstNonPhi());
2069   }
2070 
2071   void dropAllReferences(VPValue *NewValue) override;
2072 
2073   /// Split current block at \p SplitAt by inserting a new block between the
2074   /// current block and its successors and moving all recipes starting at
2075   /// SplitAt to the new block. Returns the new block.
2076   VPBasicBlock *splitAt(iterator SplitAt);
2077 
2078   VPRegionBlock *getEnclosingLoopRegion();
2079 
2080 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2081   /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
2082   /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
2083   ///
2084   /// Note that the numbering is applied to the whole VPlan, so printing
2085   /// individual blocks is consistent with the whole VPlan printing.
2086   void print(raw_ostream &O, const Twine &Indent,
2087              VPSlotTracker &SlotTracker) const override;
2088   using VPBlockBase::print; // Get the print(raw_stream &O) version.
2089 #endif
2090 
2091 private:
2092   /// Create an IR BasicBlock to hold the output instructions generated by this
2093   /// VPBasicBlock, and return it. Update the CFGState accordingly.
2094   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
2095 };
2096 
2097 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
2098 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
2099 /// A VPRegionBlock may indicate that its contents are to be replicated several
2100 /// times. This is designed to support predicated scalarization, in which a
2101 /// scalar if-then code structure needs to be generated VF * UF times. Having
2102 /// this replication indicator helps to keep a single model for multiple
2103 /// candidate VF's. The actual replication takes place only once the desired VF
2104 /// and UF have been determined.
2105 class VPRegionBlock : public VPBlockBase {
2106   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
2107   VPBlockBase *Entry;
2108 
2109   /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
2110   VPBlockBase *Exit;
2111 
2112   /// An indicator whether this region is to generate multiple replicated
2113   /// instances of output IR corresponding to its VPBlockBases.
2114   bool IsReplicator;
2115 
2116 public:
2117   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
2118                 const std::string &Name = "", bool IsReplicator = false)
2119       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
2120         IsReplicator(IsReplicator) {
2121     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
2122     assert(Exit->getSuccessors().empty() && "Exit block has successors.");
2123     Entry->setParent(this);
2124     Exit->setParent(this);
2125   }
2126   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
2127       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
2128         IsReplicator(IsReplicator) {}
2129 
2130   ~VPRegionBlock() override {
2131     if (Entry) {
2132       VPValue DummyValue;
2133       Entry->dropAllReferences(&DummyValue);
2134       deleteCFG(Entry);
2135     }
2136   }
2137 
2138   /// Method to support type inquiry through isa, cast, and dyn_cast.
2139   static inline bool classof(const VPBlockBase *V) {
2140     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
2141   }
2142 
2143   const VPBlockBase *getEntry() const { return Entry; }
2144   VPBlockBase *getEntry() { return Entry; }
2145 
2146   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
2147   /// EntryBlock must have no predecessors.
2148   void setEntry(VPBlockBase *EntryBlock) {
2149     assert(EntryBlock->getPredecessors().empty() &&
2150            "Entry block cannot have predecessors.");
2151     Entry = EntryBlock;
2152     EntryBlock->setParent(this);
2153   }
2154 
2155   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
2156   // specific interface of llvm::Function, instead of using
2157   // GraphTraints::getEntryNode. We should add a new template parameter to
2158   // DominatorTreeBase representing the Graph type.
2159   VPBlockBase &front() const { return *Entry; }
2160 
2161   const VPBlockBase *getExit() const { return Exit; }
2162   VPBlockBase *getExit() { return Exit; }
2163 
2164   /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
2165   /// ExitBlock must have no successors.
2166   void setExit(VPBlockBase *ExitBlock) {
2167     assert(ExitBlock->getSuccessors().empty() &&
2168            "Exit block cannot have successors.");
2169     Exit = ExitBlock;
2170     ExitBlock->setParent(this);
2171   }
2172 
2173   /// Returns the pre-header VPBasicBlock of the loop region.
2174   VPBasicBlock *getPreheaderVPBB() {
2175     assert(!isReplicator() && "should only get pre-header of loop regions");
2176     return getSinglePredecessor()->getExitBasicBlock();
2177   }
2178 
2179   /// An indicator whether this region is to generate multiple replicated
2180   /// instances of output IR corresponding to its VPBlockBases.
2181   bool isReplicator() const { return IsReplicator; }
2182 
2183   /// The method which generates the output IR instructions that correspond to
2184   /// this VPRegionBlock, thereby "executing" the VPlan.
2185   void execute(struct VPTransformState *State) override;
2186 
2187   void dropAllReferences(VPValue *NewValue) override;
2188 
2189 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2190   /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
2191   /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
2192   /// consequtive numbers.
2193   ///
2194   /// Note that the numbering is applied to the whole VPlan, so printing
2195   /// individual regions is consistent with the whole VPlan printing.
2196   void print(raw_ostream &O, const Twine &Indent,
2197              VPSlotTracker &SlotTracker) const override;
2198   using VPBlockBase::print; // Get the print(raw_stream &O) version.
2199 #endif
2200 };
2201 
2202 //===----------------------------------------------------------------------===//
2203 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
2204 //===----------------------------------------------------------------------===//
2205 
2206 // The following set of template specializations implement GraphTraits to treat
2207 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
2208 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
2209 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
2210 // successors/predecessors but not to the blocks inside the region.
2211 
2212 template <> struct GraphTraits<VPBlockBase *> {
2213   using NodeRef = VPBlockBase *;
2214   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
2215 
2216   static NodeRef getEntryNode(NodeRef N) { return N; }
2217 
2218   static inline ChildIteratorType child_begin(NodeRef N) {
2219     return N->getSuccessors().begin();
2220   }
2221 
2222   static inline ChildIteratorType child_end(NodeRef N) {
2223     return N->getSuccessors().end();
2224   }
2225 };
2226 
2227 template <> struct GraphTraits<const VPBlockBase *> {
2228   using NodeRef = const VPBlockBase *;
2229   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
2230 
2231   static NodeRef getEntryNode(NodeRef N) { return N; }
2232 
2233   static inline ChildIteratorType child_begin(NodeRef N) {
2234     return N->getSuccessors().begin();
2235   }
2236 
2237   static inline ChildIteratorType child_end(NodeRef N) {
2238     return N->getSuccessors().end();
2239   }
2240 };
2241 
2242 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
2243 // of successors for the inverse traversal.
2244 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
2245   using NodeRef = VPBlockBase *;
2246   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
2247 
2248   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
2249 
2250   static inline ChildIteratorType child_begin(NodeRef N) {
2251     return N->getPredecessors().begin();
2252   }
2253 
2254   static inline ChildIteratorType child_end(NodeRef N) {
2255     return N->getPredecessors().end();
2256   }
2257 };
2258 
2259 // The following set of template specializations implement GraphTraits to
2260 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
2261 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
2262 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
2263 // there won't be automatic recursion into other VPBlockBases that turn to be
2264 // VPRegionBlocks.
2265 
2266 template <>
2267 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
2268   using GraphRef = VPRegionBlock *;
2269   using nodes_iterator = df_iterator<NodeRef>;
2270 
2271   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
2272 
2273   static nodes_iterator nodes_begin(GraphRef N) {
2274     return nodes_iterator::begin(N->getEntry());
2275   }
2276 
2277   static nodes_iterator nodes_end(GraphRef N) {
2278     // df_iterator::end() returns an empty iterator so the node used doesn't
2279     // matter.
2280     return nodes_iterator::end(N);
2281   }
2282 };
2283 
2284 template <>
2285 struct GraphTraits<const VPRegionBlock *>
2286     : public GraphTraits<const VPBlockBase *> {
2287   using GraphRef = const VPRegionBlock *;
2288   using nodes_iterator = df_iterator<NodeRef>;
2289 
2290   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
2291 
2292   static nodes_iterator nodes_begin(GraphRef N) {
2293     return nodes_iterator::begin(N->getEntry());
2294   }
2295 
2296   static nodes_iterator nodes_end(GraphRef N) {
2297     // df_iterator::end() returns an empty iterator so the node used doesn't
2298     // matter.
2299     return nodes_iterator::end(N);
2300   }
2301 };
2302 
2303 template <>
2304 struct GraphTraits<Inverse<VPRegionBlock *>>
2305     : public GraphTraits<Inverse<VPBlockBase *>> {
2306   using GraphRef = VPRegionBlock *;
2307   using nodes_iterator = df_iterator<NodeRef>;
2308 
2309   static NodeRef getEntryNode(Inverse<GraphRef> N) {
2310     return N.Graph->getExit();
2311   }
2312 
2313   static nodes_iterator nodes_begin(GraphRef N) {
2314     return nodes_iterator::begin(N->getExit());
2315   }
2316 
2317   static nodes_iterator nodes_end(GraphRef N) {
2318     // df_iterator::end() returns an empty iterator so the node used doesn't
2319     // matter.
2320     return nodes_iterator::end(N);
2321   }
2322 };
2323 
2324 /// Iterator to traverse all successors of a VPBlockBase node. This includes the
2325 /// entry node of VPRegionBlocks. Exit blocks of a region implicitly have their
2326 /// parent region's successors. This ensures all blocks in a region are visited
2327 /// before any blocks in a successor region when doing a reverse post-order
2328 // traversal of the graph.
2329 template <typename BlockPtrTy>
2330 class VPAllSuccessorsIterator
2331     : public iterator_facade_base<VPAllSuccessorsIterator<BlockPtrTy>,
2332                                   std::forward_iterator_tag, VPBlockBase> {
2333   BlockPtrTy Block;
2334   /// Index of the current successor. For VPBasicBlock nodes, this simply is the
2335   /// index for the successor array. For VPRegionBlock, SuccessorIdx == 0 is
2336   /// used for the region's entry block, and SuccessorIdx - 1 are the indices
2337   /// for the successor array.
2338   size_t SuccessorIdx;
2339 
2340   static BlockPtrTy getBlockWithSuccs(BlockPtrTy Current) {
2341     while (Current && Current->getNumSuccessors() == 0)
2342       Current = Current->getParent();
2343     return Current;
2344   }
2345 
2346   /// Templated helper to dereference successor \p SuccIdx of \p Block. Used by
2347   /// both the const and non-const operator* implementations.
2348   template <typename T1> static T1 deref(T1 Block, unsigned SuccIdx) {
2349     if (auto *R = dyn_cast<VPRegionBlock>(Block)) {
2350       if (SuccIdx == 0)
2351         return R->getEntry();
2352       SuccIdx--;
2353     }
2354 
2355     // For exit blocks, use the next parent region with successors.
2356     return getBlockWithSuccs(Block)->getSuccessors()[SuccIdx];
2357   }
2358 
2359 public:
2360   VPAllSuccessorsIterator(BlockPtrTy Block, size_t Idx = 0)
2361       : Block(Block), SuccessorIdx(Idx) {}
2362   VPAllSuccessorsIterator(const VPAllSuccessorsIterator &Other)
2363       : Block(Other.Block), SuccessorIdx(Other.SuccessorIdx) {}
2364 
2365   VPAllSuccessorsIterator &operator=(const VPAllSuccessorsIterator &R) {
2366     Block = R.Block;
2367     SuccessorIdx = R.SuccessorIdx;
2368     return *this;
2369   }
2370 
2371   static VPAllSuccessorsIterator end(BlockPtrTy Block) {
2372     BlockPtrTy ParentWithSuccs = getBlockWithSuccs(Block);
2373     unsigned NumSuccessors = ParentWithSuccs
2374                                  ? ParentWithSuccs->getNumSuccessors()
2375                                  : Block->getNumSuccessors();
2376 
2377     if (auto *R = dyn_cast<VPRegionBlock>(Block))
2378       return {R, NumSuccessors + 1};
2379     return {Block, NumSuccessors};
2380   }
2381 
2382   bool operator==(const VPAllSuccessorsIterator &R) const {
2383     return Block == R.Block && SuccessorIdx == R.SuccessorIdx;
2384   }
2385 
2386   const VPBlockBase *operator*() const { return deref(Block, SuccessorIdx); }
2387 
2388   BlockPtrTy operator*() { return deref(Block, SuccessorIdx); }
2389 
2390   VPAllSuccessorsIterator &operator++() {
2391     SuccessorIdx++;
2392     return *this;
2393   }
2394 
2395   VPAllSuccessorsIterator operator++(int X) {
2396     VPAllSuccessorsIterator Orig = *this;
2397     SuccessorIdx++;
2398     return Orig;
2399   }
2400 };
2401 
2402 /// Helper for GraphTraits specialization that traverses through VPRegionBlocks.
2403 template <typename BlockTy> class VPBlockRecursiveTraversalWrapper {
2404   BlockTy Entry;
2405 
2406 public:
2407   VPBlockRecursiveTraversalWrapper(BlockTy Entry) : Entry(Entry) {}
2408   BlockTy getEntry() { return Entry; }
2409 };
2410 
2411 /// GraphTraits specialization to recursively traverse VPBlockBase nodes,
2412 /// including traversing through VPRegionBlocks.  Exit blocks of a region
2413 /// implicitly have their parent region's successors. This ensures all blocks in
2414 /// a region are visited before any blocks in a successor region when doing a
2415 /// reverse post-order traversal of the graph.
2416 template <>
2417 struct GraphTraits<VPBlockRecursiveTraversalWrapper<VPBlockBase *>> {
2418   using NodeRef = VPBlockBase *;
2419   using ChildIteratorType = VPAllSuccessorsIterator<VPBlockBase *>;
2420 
2421   static NodeRef
2422   getEntryNode(VPBlockRecursiveTraversalWrapper<VPBlockBase *> N) {
2423     return N.getEntry();
2424   }
2425 
2426   static inline ChildIteratorType child_begin(NodeRef N) {
2427     return ChildIteratorType(N);
2428   }
2429 
2430   static inline ChildIteratorType child_end(NodeRef N) {
2431     return ChildIteratorType::end(N);
2432   }
2433 };
2434 
2435 template <>
2436 struct GraphTraits<VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> {
2437   using NodeRef = const VPBlockBase *;
2438   using ChildIteratorType = VPAllSuccessorsIterator<const VPBlockBase *>;
2439 
2440   static NodeRef
2441   getEntryNode(VPBlockRecursiveTraversalWrapper<const VPBlockBase *> N) {
2442     return N.getEntry();
2443   }
2444 
2445   static inline ChildIteratorType child_begin(NodeRef N) {
2446     return ChildIteratorType(N);
2447   }
2448 
2449   static inline ChildIteratorType child_end(NodeRef N) {
2450     return ChildIteratorType::end(N);
2451   }
2452 };
2453 
2454 /// VPlan models a candidate for vectorization, encoding various decisions take
2455 /// to produce efficient output IR, including which branches, basic-blocks and
2456 /// output IR instructions to generate, and their cost. VPlan holds a
2457 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
2458 /// VPBlock.
2459 class VPlan {
2460   friend class VPlanPrinter;
2461   friend class VPSlotTracker;
2462 
2463   /// Hold the single entry to the Hierarchical CFG of the VPlan.
2464   VPBlockBase *Entry;
2465 
2466   /// Holds the VFs applicable to this VPlan.
2467   SmallSetVector<ElementCount, 2> VFs;
2468 
2469   /// Holds the name of the VPlan, for printing.
2470   std::string Name;
2471 
2472   /// Holds all the external definitions created for this VPlan. External
2473   /// definitions must be immutable and hold a pointer to their underlying IR.
2474   DenseMap<Value *, VPValue *> VPExternalDefs;
2475 
2476   /// Represents the trip count of the original loop, for folding
2477   /// the tail.
2478   VPValue *TripCount = nullptr;
2479 
2480   /// Represents the backedge taken count of the original loop, for folding
2481   /// the tail. It equals TripCount - 1.
2482   VPValue *BackedgeTakenCount = nullptr;
2483 
2484   /// Represents the vector trip count.
2485   VPValue VectorTripCount;
2486 
2487   /// Holds a mapping between Values and their corresponding VPValue inside
2488   /// VPlan.
2489   Value2VPValueTy Value2VPValue;
2490 
2491   /// Contains all VPValues that been allocated by addVPValue directly and need
2492   /// to be free when the plan's destructor is called.
2493   SmallVector<VPValue *, 16> VPValuesToFree;
2494 
2495   /// Holds the VPLoopInfo analysis for this VPlan.
2496   VPLoopInfo VPLInfo;
2497 
2498   /// Indicates whether it is safe use the Value2VPValue mapping or if the
2499   /// mapping cannot be used any longer, because it is stale.
2500   bool Value2VPValueEnabled = true;
2501 
2502 public:
2503   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {
2504     if (Entry)
2505       Entry->setPlan(this);
2506   }
2507 
2508   ~VPlan() {
2509     if (Entry) {
2510       VPValue DummyValue;
2511       for (VPBlockBase *Block : depth_first(Entry))
2512         Block->dropAllReferences(&DummyValue);
2513 
2514       VPBlockBase::deleteCFG(Entry);
2515     }
2516     for (VPValue *VPV : VPValuesToFree)
2517       delete VPV;
2518     if (TripCount)
2519       delete TripCount;
2520     if (BackedgeTakenCount)
2521       delete BackedgeTakenCount;
2522     for (auto &P : VPExternalDefs)
2523       delete P.second;
2524   }
2525 
2526   /// Prepare the plan for execution, setting up the required live-in values.
2527   void prepareToExecute(Value *TripCount, Value *VectorTripCount,
2528                         Value *CanonicalIVStartValue, VPTransformState &State);
2529 
2530   /// Generate the IR code for this VPlan.
2531   void execute(struct VPTransformState *State);
2532 
2533   VPBlockBase *getEntry() { return Entry; }
2534   const VPBlockBase *getEntry() const { return Entry; }
2535 
2536   VPBlockBase *setEntry(VPBlockBase *Block) {
2537     Entry = Block;
2538     Block->setPlan(this);
2539     return Entry;
2540   }
2541 
2542   /// The trip count of the original loop.
2543   VPValue *getOrCreateTripCount() {
2544     if (!TripCount)
2545       TripCount = new VPValue();
2546     return TripCount;
2547   }
2548 
2549   /// The backedge taken count of the original loop.
2550   VPValue *getOrCreateBackedgeTakenCount() {
2551     if (!BackedgeTakenCount)
2552       BackedgeTakenCount = new VPValue();
2553     return BackedgeTakenCount;
2554   }
2555 
2556   /// The vector trip count.
2557   VPValue &getVectorTripCount() { return VectorTripCount; }
2558 
2559   /// Mark the plan to indicate that using Value2VPValue is not safe any
2560   /// longer, because it may be stale.
2561   void disableValue2VPValue() { Value2VPValueEnabled = false; }
2562 
2563   void addVF(ElementCount VF) { VFs.insert(VF); }
2564 
2565   bool hasVF(ElementCount VF) { return VFs.count(VF); }
2566 
2567   const std::string &getName() const { return Name; }
2568 
2569   void setName(const Twine &newName) { Name = newName.str(); }
2570 
2571   /// Get the existing or add a new external definition for \p V.
2572   VPValue *getOrAddExternalDef(Value *V) {
2573     auto I = VPExternalDefs.insert({V, nullptr});
2574     if (I.second)
2575       I.first->second = new VPValue(V);
2576     return I.first->second;
2577   }
2578 
2579   void addVPValue(Value *V) {
2580     assert(Value2VPValueEnabled &&
2581            "IR value to VPValue mapping may be out of date!");
2582     assert(V && "Trying to add a null Value to VPlan");
2583     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
2584     VPValue *VPV = new VPValue(V);
2585     Value2VPValue[V] = VPV;
2586     VPValuesToFree.push_back(VPV);
2587   }
2588 
2589   void addVPValue(Value *V, VPValue *VPV) {
2590     assert(Value2VPValueEnabled && "Value2VPValue mapping may be out of date!");
2591     assert(V && "Trying to add a null Value to VPlan");
2592     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
2593     Value2VPValue[V] = VPV;
2594   }
2595 
2596   /// Returns the VPValue for \p V. \p OverrideAllowed can be used to disable
2597   /// checking whether it is safe to query VPValues using IR Values.
2598   VPValue *getVPValue(Value *V, bool OverrideAllowed = false) {
2599     assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) &&
2600            "Value2VPValue mapping may be out of date!");
2601     assert(V && "Trying to get the VPValue of a null Value");
2602     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
2603     return Value2VPValue[V];
2604   }
2605 
2606   /// Gets the VPValue or adds a new one (if none exists yet) for \p V. \p
2607   /// OverrideAllowed can be used to disable checking whether it is safe to
2608   /// query VPValues using IR Values.
2609   VPValue *getOrAddVPValue(Value *V, bool OverrideAllowed = false) {
2610     assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) &&
2611            "Value2VPValue mapping may be out of date!");
2612     assert(V && "Trying to get or add the VPValue of a null Value");
2613     if (!Value2VPValue.count(V))
2614       addVPValue(V);
2615     return getVPValue(V);
2616   }
2617 
2618   void removeVPValueFor(Value *V) {
2619     assert(Value2VPValueEnabled &&
2620            "IR value to VPValue mapping may be out of date!");
2621     Value2VPValue.erase(V);
2622   }
2623 
2624   /// Return the VPLoopInfo analysis for this VPlan.
2625   VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
2626   const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
2627 
2628 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2629   /// Print this VPlan to \p O.
2630   void print(raw_ostream &O) const;
2631 
2632   /// Print this VPlan in DOT format to \p O.
2633   void printDOT(raw_ostream &O) const;
2634 
2635   /// Dump the plan to stderr (for debugging).
2636   LLVM_DUMP_METHOD void dump() const;
2637 #endif
2638 
2639   /// Returns a range mapping the values the range \p Operands to their
2640   /// corresponding VPValues.
2641   iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>>
2642   mapToVPValues(User::op_range Operands) {
2643     std::function<VPValue *(Value *)> Fn = [this](Value *Op) {
2644       return getOrAddVPValue(Op);
2645     };
2646     return map_range(Operands, Fn);
2647   }
2648 
2649   /// Returns true if \p VPV is uniform after vectorization.
2650   bool isUniformAfterVectorization(VPValue *VPV) const {
2651     auto RepR = dyn_cast_or_null<VPReplicateRecipe>(VPV->getDef());
2652     return !VPV->getDef() || (RepR && RepR->isUniform());
2653   }
2654 
2655   /// Returns the VPRegionBlock of the vector loop.
2656   VPRegionBlock *getVectorLoopRegion() {
2657     if (auto *R = dyn_cast<VPRegionBlock>(getEntry()))
2658       return R;
2659     return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
2660   }
2661   const VPRegionBlock *getVectorLoopRegion() const {
2662     if (auto *R = dyn_cast<VPRegionBlock>(getEntry()))
2663       return R;
2664     return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
2665   }
2666 
2667   /// Returns the canonical induction recipe of the vector loop.
2668   VPCanonicalIVPHIRecipe *getCanonicalIV() {
2669     VPBasicBlock *EntryVPBB = getVectorLoopRegion()->getEntryBasicBlock();
2670     if (EntryVPBB->empty()) {
2671       // VPlan native path.
2672       EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor());
2673     }
2674     return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin());
2675   }
2676 
2677 private:
2678   /// Add to the given dominator tree the header block and every new basic block
2679   /// that was created between it and the latch block, inclusive.
2680   static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB,
2681                                   BasicBlock *LoopPreHeaderBB,
2682                                   BasicBlock *LoopExitBB);
2683 };
2684 
2685 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2686 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
2687 /// indented and follows the dot format.
2688 class VPlanPrinter {
2689   raw_ostream &OS;
2690   const VPlan &Plan;
2691   unsigned Depth = 0;
2692   unsigned TabWidth = 2;
2693   std::string Indent;
2694   unsigned BID = 0;
2695   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
2696 
2697   VPSlotTracker SlotTracker;
2698 
2699   /// Handle indentation.
2700   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
2701 
2702   /// Print a given \p Block of the Plan.
2703   void dumpBlock(const VPBlockBase *Block);
2704 
2705   /// Print the information related to the CFG edges going out of a given
2706   /// \p Block, followed by printing the successor blocks themselves.
2707   void dumpEdges(const VPBlockBase *Block);
2708 
2709   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
2710   /// its successor blocks.
2711   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
2712 
2713   /// Print a given \p Region of the Plan.
2714   void dumpRegion(const VPRegionBlock *Region);
2715 
2716   unsigned getOrCreateBID(const VPBlockBase *Block) {
2717     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
2718   }
2719 
2720   Twine getOrCreateName(const VPBlockBase *Block);
2721 
2722   Twine getUID(const VPBlockBase *Block);
2723 
2724   /// Print the information related to a CFG edge between two VPBlockBases.
2725   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
2726                 const Twine &Label);
2727 
2728 public:
2729   VPlanPrinter(raw_ostream &O, const VPlan &P)
2730       : OS(O), Plan(P), SlotTracker(&P) {}
2731 
2732   LLVM_DUMP_METHOD void dump();
2733 };
2734 
2735 struct VPlanIngredient {
2736   const Value *V;
2737 
2738   VPlanIngredient(const Value *V) : V(V) {}
2739 
2740   void print(raw_ostream &O) const;
2741 };
2742 
2743 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
2744   I.print(OS);
2745   return OS;
2746 }
2747 
2748 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
2749   Plan.print(OS);
2750   return OS;
2751 }
2752 #endif
2753 
2754 //===----------------------------------------------------------------------===//
2755 // VPlan Utilities
2756 //===----------------------------------------------------------------------===//
2757 
2758 /// Class that provides utilities for VPBlockBases in VPlan.
2759 class VPBlockUtils {
2760 public:
2761   VPBlockUtils() = delete;
2762 
2763   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
2764   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
2765   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's
2766   /// successors are moved from \p BlockPtr to \p NewBlock and \p BlockPtr's
2767   /// conditional bit is propagated to \p NewBlock. \p NewBlock must have
2768   /// neither successors nor predecessors.
2769   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
2770     assert(NewBlock->getSuccessors().empty() &&
2771            NewBlock->getPredecessors().empty() &&
2772            "Can't insert new block with predecessors or successors.");
2773     NewBlock->setParent(BlockPtr->getParent());
2774     SmallVector<VPBlockBase *> Succs(BlockPtr->successors());
2775     for (VPBlockBase *Succ : Succs) {
2776       disconnectBlocks(BlockPtr, Succ);
2777       connectBlocks(NewBlock, Succ);
2778     }
2779     NewBlock->setCondBit(BlockPtr->getCondBit());
2780     BlockPtr->setCondBit(nullptr);
2781     connectBlocks(BlockPtr, NewBlock);
2782   }
2783 
2784   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
2785   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
2786   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
2787   /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
2788   /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
2789   /// must have neither successors nor predecessors.
2790   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
2791                                    VPValue *Condition, VPBlockBase *BlockPtr) {
2792     assert(IfTrue->getSuccessors().empty() &&
2793            "Can't insert IfTrue with successors.");
2794     assert(IfFalse->getSuccessors().empty() &&
2795            "Can't insert IfFalse with successors.");
2796     BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
2797     IfTrue->setPredecessors({BlockPtr});
2798     IfFalse->setPredecessors({BlockPtr});
2799     IfTrue->setParent(BlockPtr->getParent());
2800     IfFalse->setParent(BlockPtr->getParent());
2801   }
2802 
2803   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
2804   /// the successors of \p From and \p From to the predecessors of \p To. Both
2805   /// VPBlockBases must have the same parent, which can be null. Both
2806   /// VPBlockBases can be already connected to other VPBlockBases.
2807   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
2808     assert((From->getParent() == To->getParent()) &&
2809            "Can't connect two block with different parents");
2810     assert(From->getNumSuccessors() < 2 &&
2811            "Blocks can't have more than two successors.");
2812     From->appendSuccessor(To);
2813     To->appendPredecessor(From);
2814   }
2815 
2816   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
2817   /// from the successors of \p From and \p From from the predecessors of \p To.
2818   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
2819     assert(To && "Successor to disconnect is null.");
2820     From->removeSuccessor(To);
2821     To->removePredecessor(From);
2822   }
2823 
2824   /// Try to merge \p Block into its single predecessor, if \p Block is a
2825   /// VPBasicBlock and its predecessor has a single successor. Returns a pointer
2826   /// to the predecessor \p Block was merged into or nullptr otherwise.
2827   static VPBasicBlock *tryToMergeBlockIntoPredecessor(VPBlockBase *Block) {
2828     auto *VPBB = dyn_cast<VPBasicBlock>(Block);
2829     auto *PredVPBB =
2830         dyn_cast_or_null<VPBasicBlock>(Block->getSinglePredecessor());
2831     if (!VPBB || !PredVPBB || PredVPBB->getNumSuccessors() != 1)
2832       return nullptr;
2833 
2834     for (VPRecipeBase &R : make_early_inc_range(*VPBB))
2835       R.moveBefore(*PredVPBB, PredVPBB->end());
2836     VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
2837     auto *ParentRegion = cast<VPRegionBlock>(Block->getParent());
2838     if (ParentRegion->getExit() == Block)
2839       ParentRegion->setExit(PredVPBB);
2840     SmallVector<VPBlockBase *> Successors(Block->successors());
2841     for (auto *Succ : Successors) {
2842       VPBlockUtils::disconnectBlocks(Block, Succ);
2843       VPBlockUtils::connectBlocks(PredVPBB, Succ);
2844     }
2845     delete Block;
2846     return PredVPBB;
2847   }
2848 
2849   /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
2850   static bool isBackEdge(const VPBlockBase *FromBlock,
2851                          const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
2852     assert(FromBlock->getParent() == ToBlock->getParent() &&
2853            FromBlock->getParent() && "Must be in same region");
2854     const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
2855     const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
2856     if (!FromLoop || !ToLoop || FromLoop != ToLoop)
2857       return false;
2858 
2859     // A back-edge is a branch from the loop latch to its header.
2860     return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
2861   }
2862 
2863   /// Returns true if \p Block is a loop latch
2864   static bool blockIsLoopLatch(const VPBlockBase *Block,
2865                                const VPLoopInfo *VPLInfo) {
2866     if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
2867       return ParentVPL->isLoopLatch(Block);
2868 
2869     return false;
2870   }
2871 
2872   /// Count and return the number of succesors of \p PredBlock excluding any
2873   /// backedges.
2874   static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
2875                                       VPLoopInfo *VPLI) {
2876     unsigned Count = 0;
2877     for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
2878       if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
2879         Count++;
2880     }
2881     return Count;
2882   }
2883 
2884   /// Return an iterator range over \p Range which only includes \p BlockTy
2885   /// blocks. The accesses are casted to \p BlockTy.
2886   template <typename BlockTy, typename T>
2887   static auto blocksOnly(const T &Range) {
2888     // Create BaseTy with correct const-ness based on BlockTy.
2889     using BaseTy =
2890         typename std::conditional<std::is_const<BlockTy>::value,
2891                                   const VPBlockBase, VPBlockBase>::type;
2892 
2893     // We need to first create an iterator range over (const) BlocktTy & instead
2894     // of (const) BlockTy * for filter_range to work properly.
2895     auto Mapped =
2896         map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; });
2897     auto Filter = make_filter_range(
2898         Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); });
2899     return map_range(Filter, [](BaseTy &Block) -> BlockTy * {
2900       return cast<BlockTy>(&Block);
2901     });
2902   }
2903 };
2904 
2905 class VPInterleavedAccessInfo {
2906   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
2907       InterleaveGroupMap;
2908 
2909   /// Type for mapping of instruction based interleave groups to VPInstruction
2910   /// interleave groups
2911   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
2912                              InterleaveGroup<VPInstruction> *>;
2913 
2914   /// Recursively \p Region and populate VPlan based interleave groups based on
2915   /// \p IAI.
2916   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
2917                    InterleavedAccessInfo &IAI);
2918   /// Recursively traverse \p Block and populate VPlan based interleave groups
2919   /// based on \p IAI.
2920   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
2921                   InterleavedAccessInfo &IAI);
2922 
2923 public:
2924   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
2925 
2926   ~VPInterleavedAccessInfo() {
2927     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
2928     // Avoid releasing a pointer twice.
2929     for (auto &I : InterleaveGroupMap)
2930       DelSet.insert(I.second);
2931     for (auto *Ptr : DelSet)
2932       delete Ptr;
2933   }
2934 
2935   /// Get the interleave group that \p Instr belongs to.
2936   ///
2937   /// \returns nullptr if doesn't have such group.
2938   InterleaveGroup<VPInstruction> *
2939   getInterleaveGroup(VPInstruction *Instr) const {
2940     return InterleaveGroupMap.lookup(Instr);
2941   }
2942 };
2943 
2944 /// Class that maps (parts of) an existing VPlan to trees of combined
2945 /// VPInstructions.
2946 class VPlanSlp {
2947   enum class OpMode { Failed, Load, Opcode };
2948 
2949   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
2950   /// DenseMap keys.
2951   struct BundleDenseMapInfo {
2952     static SmallVector<VPValue *, 4> getEmptyKey() {
2953       return {reinterpret_cast<VPValue *>(-1)};
2954     }
2955 
2956     static SmallVector<VPValue *, 4> getTombstoneKey() {
2957       return {reinterpret_cast<VPValue *>(-2)};
2958     }
2959 
2960     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
2961       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2962     }
2963 
2964     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
2965                         const SmallVector<VPValue *, 4> &RHS) {
2966       return LHS == RHS;
2967     }
2968   };
2969 
2970   /// Mapping of values in the original VPlan to a combined VPInstruction.
2971   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
2972       BundleToCombined;
2973 
2974   VPInterleavedAccessInfo &IAI;
2975 
2976   /// Basic block to operate on. For now, only instructions in a single BB are
2977   /// considered.
2978   const VPBasicBlock &BB;
2979 
2980   /// Indicates whether we managed to combine all visited instructions or not.
2981   bool CompletelySLP = true;
2982 
2983   /// Width of the widest combined bundle in bits.
2984   unsigned WidestBundleBits = 0;
2985 
2986   using MultiNodeOpTy =
2987       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
2988 
2989   // Input operand bundles for the current multi node. Each multi node operand
2990   // bundle contains values not matching the multi node's opcode. They will
2991   // be reordered in reorderMultiNodeOps, once we completed building a
2992   // multi node.
2993   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
2994 
2995   /// Indicates whether we are building a multi node currently.
2996   bool MultiNodeActive = false;
2997 
2998   /// Check if we can vectorize Operands together.
2999   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
3000 
3001   /// Add combined instruction \p New for the bundle \p Operands.
3002   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
3003 
3004   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
3005   VPInstruction *markFailed();
3006 
3007   /// Reorder operands in the multi node to maximize sequential memory access
3008   /// and commutative operations.
3009   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
3010 
3011   /// Choose the best candidate to use for the lane after \p Last. The set of
3012   /// candidates to choose from are values with an opcode matching \p Last's
3013   /// or loads consecutive to \p Last.
3014   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
3015                                        SmallPtrSetImpl<VPValue *> &Candidates,
3016                                        VPInterleavedAccessInfo &IAI);
3017 
3018 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3019   /// Print bundle \p Values to dbgs().
3020   void dumpBundle(ArrayRef<VPValue *> Values);
3021 #endif
3022 
3023 public:
3024   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
3025 
3026   ~VPlanSlp() = default;
3027 
3028   /// Tries to build an SLP tree rooted at \p Operands and returns a
3029   /// VPInstruction combining \p Operands, if they can be combined.
3030   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
3031 
3032   /// Return the width of the widest combined bundle in bits.
3033   unsigned getWidestBundleBits() const { return WidestBundleBits; }
3034 
3035   /// Return true if all visited instruction can be combined.
3036   bool isCompletelySLP() const { return CompletelySLP; }
3037 };
3038 
3039 namespace vputils {
3040 
3041 /// Returns true if only the first lane of \p Def is used.
3042 bool onlyFirstLaneUsed(VPValue *Def);
3043 
3044 /// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p
3045 /// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in
3046 /// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's
3047 /// pre-header already contains a recipe expanding \p Expr, return it. If not,
3048 /// create a new one.
3049 VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
3050                                        ScalarEvolution &SE);
3051 
3052 } // end namespace vputils
3053 
3054 } // end namespace llvm
3055 
3056 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
3057