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