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