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