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