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