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