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