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