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