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