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