1 //===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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
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.
23 //===----------------------------------------------------------------------===//
25 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
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/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/ADT/ilist.h"
39 #include "llvm/ADT/ilist_node.h"
40 #include "llvm/Analysis/VectorUtils.h"
41 #include "llvm/IR/IRBuilder.h"
50 class LoopVectorizationLegality
;
51 class LoopVectorizationCostModel
;
54 class InnerLoopVectorizer
;
55 template <class T
> class InterleaveGroup
;
64 /// A range of powers-of-2 vectorization factors with fixed start and
65 /// adjustable end. The range includes start and excludes end, e.g.,:
66 /// [1, 9) = {1, 2, 4, 8}
71 // Need not be a power of 2. If End <= Start range is empty.
75 using VPlanPtr
= std::unique_ptr
<VPlan
>;
77 /// In what follows, the term "input IR" refers to code that is fed into the
78 /// vectorizer whereas the term "output IR" refers to code that is generated by
81 /// VPIteration represents a single point in the iteration space of the output
82 /// (vectorized and/or unrolled) IR loop.
91 /// This is a helper struct for maintaining vectorization state. It's used for
92 /// mapping values from the original loop to their corresponding values in
93 /// the new loop. Two mappings are maintained: one for vectorized values and
94 /// one for scalarized values. Vectorized values are represented with UF
95 /// vector values in the new loop, and scalarized values are represented with
96 /// UF x VF scalar values in the new loop. UF and VF are the unroll and
97 /// vectorization factors, respectively.
99 /// Entries can be added to either map with setVectorValue and setScalarValue,
100 /// which assert that an entry was not already added before. If an entry is to
101 /// replace an existing one, call resetVectorValue and resetScalarValue. This is
102 /// currently needed to modify the mapped values during "fix-up" operations that
103 /// occur once the first phase of widening is complete. These operations include
104 /// type truncation and the second phase of recurrence widening.
106 /// Entries from either map can be retrieved using the getVectorValue and
107 /// getScalarValue functions, which assert that the desired value exists.
108 struct VectorizerValueMap
{
109 friend struct VPTransformState
;
112 /// The unroll factor. Each entry in the vector map contains UF vector values.
115 /// The vectorization factor. Each entry in the scalar map contains UF x VF
119 /// The vector and scalar map storage. We use std::map and not DenseMap
120 /// because insertions to DenseMap invalidate its iterators.
121 using VectorParts
= SmallVector
<Value
*, 2>;
122 using ScalarParts
= SmallVector
<SmallVector
<Value
*, 4>, 2>;
123 std::map
<Value
*, VectorParts
> VectorMapStorage
;
124 std::map
<Value
*, ScalarParts
> ScalarMapStorage
;
127 /// Construct an empty map with the given unroll and vectorization factors.
128 VectorizerValueMap(unsigned UF
, unsigned VF
) : UF(UF
), VF(VF
) {}
130 /// \return True if the map has any vector entry for \p Key.
131 bool hasAnyVectorValue(Value
*Key
) const {
132 return VectorMapStorage
.count(Key
);
135 /// \return True if the map has a vector entry for \p Key and \p Part.
136 bool hasVectorValue(Value
*Key
, unsigned Part
) const {
137 assert(Part
< UF
&& "Queried Vector Part is too large.");
138 if (!hasAnyVectorValue(Key
))
140 const VectorParts
&Entry
= VectorMapStorage
.find(Key
)->second
;
141 assert(Entry
.size() == UF
&& "VectorParts has wrong dimensions.");
142 return Entry
[Part
] != nullptr;
145 /// \return True if the map has any scalar entry for \p Key.
146 bool hasAnyScalarValue(Value
*Key
) const {
147 return ScalarMapStorage
.count(Key
);
150 /// \return True if the map has a scalar entry for \p Key and \p Instance.
151 bool hasScalarValue(Value
*Key
, const VPIteration
&Instance
) const {
152 assert(Instance
.Part
< UF
&& "Queried Scalar Part is too large.");
153 assert(Instance
.Lane
< VF
&& "Queried Scalar Lane is too large.");
154 if (!hasAnyScalarValue(Key
))
156 const ScalarParts
&Entry
= ScalarMapStorage
.find(Key
)->second
;
157 assert(Entry
.size() == UF
&& "ScalarParts has wrong dimensions.");
158 assert(Entry
[Instance
.Part
].size() == VF
&&
159 "ScalarParts has wrong dimensions.");
160 return Entry
[Instance
.Part
][Instance
.Lane
] != nullptr;
163 /// Retrieve the existing vector value that corresponds to \p Key and
165 Value
*getVectorValue(Value
*Key
, unsigned Part
) {
166 assert(hasVectorValue(Key
, Part
) && "Getting non-existent value.");
167 return VectorMapStorage
[Key
][Part
];
170 /// Retrieve the existing scalar value that corresponds to \p Key and
172 Value
*getScalarValue(Value
*Key
, const VPIteration
&Instance
) {
173 assert(hasScalarValue(Key
, Instance
) && "Getting non-existent value.");
174 return ScalarMapStorage
[Key
][Instance
.Part
][Instance
.Lane
];
177 /// Set a vector value associated with \p Key and \p Part. Assumes such a
178 /// value is not already set. If it is, use resetVectorValue() instead.
179 void setVectorValue(Value
*Key
, unsigned Part
, Value
*Vector
) {
180 assert(!hasVectorValue(Key
, Part
) && "Vector value already set for part");
181 if (!VectorMapStorage
.count(Key
)) {
182 VectorParts
Entry(UF
);
183 VectorMapStorage
[Key
] = Entry
;
185 VectorMapStorage
[Key
][Part
] = Vector
;
188 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
189 /// value is not already set.
190 void setScalarValue(Value
*Key
, const VPIteration
&Instance
, Value
*Scalar
) {
191 assert(!hasScalarValue(Key
, Instance
) && "Scalar value already set");
192 if (!ScalarMapStorage
.count(Key
)) {
193 ScalarParts
Entry(UF
);
194 // TODO: Consider storing uniform values only per-part, as they occupy
195 // lane 0 only, keeping the other VF-1 redundant entries null.
196 for (unsigned Part
= 0; Part
< UF
; ++Part
)
197 Entry
[Part
].resize(VF
, nullptr);
198 ScalarMapStorage
[Key
] = Entry
;
200 ScalarMapStorage
[Key
][Instance
.Part
][Instance
.Lane
] = Scalar
;
203 /// Reset the vector value associated with \p Key for the given \p Part.
204 /// This function can be used to update values that have already been
205 /// vectorized. This is the case for "fix-up" operations including type
206 /// truncation and the second phase of recurrence vectorization.
207 void resetVectorValue(Value
*Key
, unsigned Part
, Value
*Vector
) {
208 assert(hasVectorValue(Key
, Part
) && "Vector value not set for part");
209 VectorMapStorage
[Key
][Part
] = Vector
;
212 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
213 /// This function can be used to update values that have already been
214 /// scalarized. This is the case for "fix-up" operations including scalar phi
215 /// nodes for scalarized and predicated instructions.
216 void resetScalarValue(Value
*Key
, const VPIteration
&Instance
,
218 assert(hasScalarValue(Key
, Instance
) &&
219 "Scalar value not set for part and lane");
220 ScalarMapStorage
[Key
][Instance
.Part
][Instance
.Lane
] = Scalar
;
224 /// This class is used to enable the VPlan to invoke a method of ILV. This is
225 /// needed until the method is refactored out of ILV and becomes reusable.
227 virtual ~VPCallback() {}
228 virtual Value
*getOrCreateVectorValues(Value
*V
, unsigned Part
) = 0;
231 /// VPTransformState holds information passed down when "executing" a VPlan,
232 /// needed for generating the output IR.
233 struct VPTransformState
{
234 VPTransformState(unsigned VF
, unsigned UF
, LoopInfo
*LI
, DominatorTree
*DT
,
235 IRBuilder
<> &Builder
, VectorizerValueMap
&ValueMap
,
236 InnerLoopVectorizer
*ILV
, VPCallback
&Callback
)
237 : VF(VF
), UF(UF
), Instance(), LI(LI
), DT(DT
), Builder(Builder
),
238 ValueMap(ValueMap
), ILV(ILV
), Callback(Callback
) {}
240 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
244 /// Hold the indices to generate specific scalar instructions. Null indicates
245 /// that all instances are to be generated, using either scalar or vector
247 Optional
<VPIteration
> Instance
;
250 /// A type for vectorized values in the new loop. Each value from the
251 /// original loop, when vectorized, is represented by UF vector values in
252 /// the new unrolled loop, where UF is the unroll factor.
253 typedef SmallVector
<Value
*, 2> PerPartValuesTy
;
255 DenseMap
<VPValue
*, PerPartValuesTy
> PerPartOutput
;
258 /// Get the generated Value for a given VPValue and a given Part. Note that
259 /// as some Defs are still created by ILV and managed in its ValueMap, this
260 /// method will delegate the call to ILV in such cases in order to provide
261 /// callers a consistent API.
263 Value
*get(VPValue
*Def
, unsigned Part
) {
264 // If Values have been set for this Def return the one relevant for \p Part.
265 if (Data
.PerPartOutput
.count(Def
))
266 return Data
.PerPartOutput
[Def
][Part
];
267 // Def is managed by ILV: bring the Values from ValueMap.
268 return Callback
.getOrCreateVectorValues(VPValue2Value
[Def
], Part
);
271 /// Set the generated Value for a given VPValue and a given Part.
272 void set(VPValue
*Def
, Value
*V
, unsigned Part
) {
273 if (!Data
.PerPartOutput
.count(Def
)) {
274 DataState::PerPartValuesTy
Entry(UF
);
275 Data
.PerPartOutput
[Def
] = Entry
;
277 Data
.PerPartOutput
[Def
][Part
] = V
;
280 /// Hold state information used when constructing the CFG of the output IR,
281 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
283 /// The previous VPBasicBlock visited. Initially set to null.
284 VPBasicBlock
*PrevVPBB
= nullptr;
286 /// The previous IR BasicBlock created or used. Initially set to the new
287 /// header BasicBlock.
288 BasicBlock
*PrevBB
= nullptr;
290 /// The last IR BasicBlock in the output IR. Set to the new latch
291 /// BasicBlock, used for placing the newly created BasicBlocks.
292 BasicBlock
*LastBB
= nullptr;
294 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
295 /// of replication, maps the BasicBlock of the last replica created.
296 SmallDenseMap
<VPBasicBlock
*, BasicBlock
*> VPBB2IRBB
;
298 /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
299 /// up at the end of vector code generation.
300 SmallVector
<VPBasicBlock
*, 8> VPBBsToFix
;
302 CFGState() = default;
305 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
308 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
311 /// Hold a reference to the IRBuilder used to generate output IR code.
312 IRBuilder
<> &Builder
;
314 /// Hold a reference to the Value state information used when generating the
315 /// Values of the output IR.
316 VectorizerValueMap
&ValueMap
;
318 /// Hold a reference to a mapping between VPValues in VPlan and original
319 /// Values they correspond to.
320 VPValue2ValueTy VPValue2Value
;
322 /// Hold the trip count of the scalar loop.
323 Value
*TripCount
= nullptr;
325 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
326 InnerLoopVectorizer
*ILV
;
328 VPCallback
&Callback
;
331 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
332 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
334 friend class VPBlockUtils
;
337 const unsigned char SubclassID
; ///< Subclass identifier (for isa/dyn_cast).
339 /// An optional name for the block.
342 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
343 /// it is a topmost VPBlockBase.
344 VPRegionBlock
*Parent
= nullptr;
346 /// List of predecessor blocks.
347 SmallVector
<VPBlockBase
*, 1> Predecessors
;
349 /// List of successor blocks.
350 SmallVector
<VPBlockBase
*, 1> Successors
;
352 /// Successor selector, null for zero or single successor blocks.
353 VPValue
*CondBit
= nullptr;
355 /// Current block predicate - null if the block does not need a predicate.
356 VPValue
*Predicate
= nullptr;
358 /// Add \p Successor as the last successor to this block.
359 void appendSuccessor(VPBlockBase
*Successor
) {
360 assert(Successor
&& "Cannot add nullptr successor!");
361 Successors
.push_back(Successor
);
364 /// Add \p Predecessor as the last predecessor to this block.
365 void appendPredecessor(VPBlockBase
*Predecessor
) {
366 assert(Predecessor
&& "Cannot add nullptr predecessor!");
367 Predecessors
.push_back(Predecessor
);
370 /// Remove \p Predecessor from the predecessors of this block.
371 void removePredecessor(VPBlockBase
*Predecessor
) {
372 auto Pos
= std::find(Predecessors
.begin(), Predecessors
.end(), Predecessor
);
373 assert(Pos
&& "Predecessor does not exist");
374 Predecessors
.erase(Pos
);
377 /// Remove \p Successor from the successors of this block.
378 void removeSuccessor(VPBlockBase
*Successor
) {
379 auto Pos
= std::find(Successors
.begin(), Successors
.end(), Successor
);
380 assert(Pos
&& "Successor does not exist");
381 Successors
.erase(Pos
);
385 VPBlockBase(const unsigned char SC
, const std::string
&N
)
386 : SubclassID(SC
), Name(N
) {}
389 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
390 /// that are actually instantiated. Values of this enumeration are kept in the
391 /// SubclassID field of the VPBlockBase objects. They are used for concrete
392 /// type identification.
393 using VPBlockTy
= enum { VPBasicBlockSC
, VPRegionBlockSC
};
395 using VPBlocksTy
= SmallVectorImpl
<VPBlockBase
*>;
397 virtual ~VPBlockBase() = default;
399 const std::string
&getName() const { return Name
; }
401 void setName(const Twine
&newName
) { Name
= newName
.str(); }
403 /// \return an ID for the concrete type of this object.
404 /// This is used to implement the classof checks. This should not be used
405 /// for any other purpose, as the values may change as LLVM evolves.
406 unsigned getVPBlockID() const { return SubclassID
; }
408 VPRegionBlock
*getParent() { return Parent
; }
409 const VPRegionBlock
*getParent() const { return Parent
; }
411 void setParent(VPRegionBlock
*P
) { Parent
= P
; }
413 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
414 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
415 /// VPBlockBase is a VPBasicBlock, it is returned.
416 const VPBasicBlock
*getEntryBasicBlock() const;
417 VPBasicBlock
*getEntryBasicBlock();
419 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
420 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
421 /// VPBlockBase is a VPBasicBlock, it is returned.
422 const VPBasicBlock
*getExitBasicBlock() const;
423 VPBasicBlock
*getExitBasicBlock();
425 const VPBlocksTy
&getSuccessors() const { return Successors
; }
426 VPBlocksTy
&getSuccessors() { return Successors
; }
428 const VPBlocksTy
&getPredecessors() const { return Predecessors
; }
429 VPBlocksTy
&getPredecessors() { return Predecessors
; }
431 /// \return the successor of this VPBlockBase if it has a single successor.
432 /// Otherwise return a null pointer.
433 VPBlockBase
*getSingleSuccessor() const {
434 return (Successors
.size() == 1 ? *Successors
.begin() : nullptr);
437 /// \return the predecessor of this VPBlockBase if it has a single
438 /// predecessor. Otherwise return a null pointer.
439 VPBlockBase
*getSinglePredecessor() const {
440 return (Predecessors
.size() == 1 ? *Predecessors
.begin() : nullptr);
443 size_t getNumSuccessors() const { return Successors
.size(); }
444 size_t getNumPredecessors() const { return Predecessors
.size(); }
446 /// An Enclosing Block of a block B is any block containing B, including B
447 /// itself. \return the closest enclosing block starting from "this", which
448 /// has successors. \return the root enclosing block if all enclosing blocks
449 /// have no successors.
450 VPBlockBase
*getEnclosingBlockWithSuccessors();
452 /// \return the closest enclosing block starting from "this", which has
453 /// predecessors. \return the root enclosing block if all enclosing blocks
454 /// have no predecessors.
455 VPBlockBase
*getEnclosingBlockWithPredecessors();
457 /// \return the successors either attached directly to this VPBlockBase or, if
458 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
459 /// successors of its own, search recursively for the first enclosing
460 /// VPRegionBlock that has successors and return them. If no such
461 /// VPRegionBlock exists, return the (empty) successors of the topmost
462 /// VPBlockBase reached.
463 const VPBlocksTy
&getHierarchicalSuccessors() {
464 return getEnclosingBlockWithSuccessors()->getSuccessors();
467 /// \return the hierarchical successor of this VPBlockBase if it has a single
468 /// hierarchical successor. Otherwise return a null pointer.
469 VPBlockBase
*getSingleHierarchicalSuccessor() {
470 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
473 /// \return the predecessors either attached directly to this VPBlockBase or,
474 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
475 /// predecessors of its own, search recursively for the first enclosing
476 /// VPRegionBlock that has predecessors and return them. If no such
477 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
478 /// VPBlockBase reached.
479 const VPBlocksTy
&getHierarchicalPredecessors() {
480 return getEnclosingBlockWithPredecessors()->getPredecessors();
483 /// \return the hierarchical predecessor of this VPBlockBase if it has a
484 /// single hierarchical predecessor. Otherwise return a null pointer.
485 VPBlockBase
*getSingleHierarchicalPredecessor() {
486 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
489 /// \return the condition bit selecting the successor.
490 VPValue
*getCondBit() { return CondBit
; }
492 const VPValue
*getCondBit() const { return CondBit
; }
494 void setCondBit(VPValue
*CV
) { CondBit
= CV
; }
496 VPValue
*getPredicate() { return Predicate
; }
498 const VPValue
*getPredicate() const { return Predicate
; }
500 void setPredicate(VPValue
*Pred
) { Predicate
= Pred
; }
502 /// Set a given VPBlockBase \p Successor as the single successor of this
503 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
504 /// This VPBlockBase must have no successors.
505 void setOneSuccessor(VPBlockBase
*Successor
) {
506 assert(Successors
.empty() && "Setting one successor when others exist.");
507 appendSuccessor(Successor
);
510 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
511 /// successors of this VPBlockBase. \p Condition is set as the successor
512 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
513 /// IfFalse. This VPBlockBase must have no successors.
514 void setTwoSuccessors(VPBlockBase
*IfTrue
, VPBlockBase
*IfFalse
,
515 VPValue
*Condition
) {
516 assert(Successors
.empty() && "Setting two successors when others exist.");
517 assert(Condition
&& "Setting two successors without condition!");
519 appendSuccessor(IfTrue
);
520 appendSuccessor(IfFalse
);
523 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
524 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
525 /// as successor of any VPBasicBlock in \p NewPreds.
526 void setPredecessors(ArrayRef
<VPBlockBase
*> NewPreds
) {
527 assert(Predecessors
.empty() && "Block predecessors already set.");
528 for (auto *Pred
: NewPreds
)
529 appendPredecessor(Pred
);
532 /// Remove all the predecessor of this block.
533 void clearPredecessors() { Predecessors
.clear(); }
535 /// Remove all the successors of this block and set to null its condition bit
536 void clearSuccessors() {
541 /// The method which generates the output IR that correspond to this
542 /// VPBlockBase, thereby "executing" the VPlan.
543 virtual void execute(struct VPTransformState
*State
) = 0;
545 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
546 static void deleteCFG(VPBlockBase
*Entry
);
548 void printAsOperand(raw_ostream
&OS
, bool PrintType
) const {
552 void print(raw_ostream
&OS
) const {
553 // TODO: Only printing VPBB name for now since we only have dot printing
554 // support for VPInstructions/Recipes.
555 printAsOperand(OS
, false);
558 /// Return true if it is legal to hoist instructions into this block.
559 bool isLegalToHoistInto() {
560 // There are currently no constraints that prevent an instruction to be
561 // hoisted into a VPBlockBase.
566 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
568 class VPRecipeBase
: public ilist_node_with_parent
<VPRecipeBase
, VPBasicBlock
> {
572 const unsigned char SubclassID
; ///< Subclass identifier (for isa/dyn_cast).
574 /// Each VPRecipe belongs to a single VPBasicBlock.
575 VPBasicBlock
*Parent
= nullptr;
578 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
579 /// that is actually instantiated. Values of this enumeration are kept in the
580 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
581 /// type identification.
582 using VPRecipeTy
= enum {
589 VPWidenIntOrFpInductionSC
,
590 VPWidenMemoryInstructionSC
,
595 VPRecipeBase(const unsigned char SC
) : SubclassID(SC
) {}
596 virtual ~VPRecipeBase() = default;
598 /// \return an ID for the concrete type of this object.
599 /// This is used to implement the classof checks. This should not be used
600 /// for any other purpose, as the values may change as LLVM evolves.
601 unsigned getVPRecipeID() const { return SubclassID
; }
603 /// \return the VPBasicBlock which this VPRecipe belongs to.
604 VPBasicBlock
*getParent() { return Parent
; }
605 const VPBasicBlock
*getParent() const { return Parent
; }
607 /// The method which generates the output IR instructions that correspond to
608 /// this VPRecipe, thereby "executing" the VPlan.
609 virtual void execute(struct VPTransformState
&State
) = 0;
611 /// Each recipe prints itself.
612 virtual void print(raw_ostream
&O
, const Twine
&Indent
) const = 0;
614 /// Insert an unlinked recipe into a basic block immediately before
615 /// the specified recipe.
616 void insertBefore(VPRecipeBase
*InsertPos
);
618 /// Unlink this recipe from its current VPBasicBlock and insert it into
619 /// the VPBasicBlock that MovePos lives in, right after MovePos.
620 void moveAfter(VPRecipeBase
*MovePos
);
622 /// This method unlinks 'this' from the containing basic block and deletes it.
624 /// \returns an iterator pointing to the element after the erased one
625 iplist
<VPRecipeBase
>::iterator
eraseFromParent();
628 /// This is a concrete Recipe that models a single VPlan-level instruction.
629 /// While as any Recipe it may generate a sequence of IR instructions when
630 /// executed, these instructions would always form a single-def expression as
631 /// the VPInstruction is also a single def-use vertex.
632 class VPInstruction
: public VPUser
, public VPRecipeBase
{
633 friend class VPlanHCFGTransforms
;
634 friend class VPlanSlp
;
637 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
639 Not
= Instruction::OtherOpsEnd
+ 1,
646 typedef unsigned char OpcodeTy
;
649 /// Utility method serving execute(): generates a single instance of the
650 /// modeled instruction.
651 void generateInstruction(VPTransformState
&State
, unsigned Part
);
654 Instruction
*getUnderlyingInstr() {
655 return cast_or_null
<Instruction
>(getUnderlyingValue());
658 void setUnderlyingInstr(Instruction
*I
) { setUnderlyingValue(I
); }
661 VPInstruction(unsigned Opcode
, ArrayRef
<VPValue
*> Operands
)
662 : VPUser(VPValue::VPInstructionSC
, Operands
),
663 VPRecipeBase(VPRecipeBase::VPInstructionSC
), Opcode(Opcode
) {}
665 VPInstruction(unsigned Opcode
, std::initializer_list
<VPValue
*> Operands
)
666 : VPInstruction(Opcode
, ArrayRef
<VPValue
*>(Operands
)) {}
668 /// Method to support type inquiry through isa, cast, and dyn_cast.
669 static inline bool classof(const VPValue
*V
) {
670 return V
->getVPValueID() == VPValue::VPInstructionSC
;
673 VPInstruction
*clone() const {
674 SmallVector
<VPValue
*, 2> Operands(operands());
675 return new VPInstruction(Opcode
, Operands
);
678 /// Method to support type inquiry through isa, cast, and dyn_cast.
679 static inline bool classof(const VPRecipeBase
*R
) {
680 return R
->getVPRecipeID() == VPRecipeBase::VPInstructionSC
;
683 unsigned getOpcode() const { return Opcode
; }
685 /// Generate the instruction.
686 /// TODO: We currently execute only per-part unless a specific instance is
688 void execute(VPTransformState
&State
) override
;
690 /// Print the Recipe.
691 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
693 /// Print the VPInstruction.
694 void print(raw_ostream
&O
) const;
696 /// Return true if this instruction may modify memory.
697 bool mayWriteToMemory() const {
698 // TODO: we can use attributes of the called function to rule out memory
700 return Opcode
== Instruction::Store
|| Opcode
== Instruction::Call
||
701 Opcode
== Instruction::Invoke
|| Opcode
== SLPStore
;
705 /// VPWidenRecipe is a recipe for producing a copy of vector type for each
706 /// Instruction in its ingredients independently, in order. This recipe covers
707 /// most of the traditional vectorization cases where each ingredient transforms
708 /// into a vectorized version of itself.
709 class VPWidenRecipe
: public VPRecipeBase
{
711 /// Hold the ingredients by pointing to their original BasicBlock location.
712 BasicBlock::iterator Begin
;
713 BasicBlock::iterator End
;
716 VPWidenRecipe(Instruction
*I
) : VPRecipeBase(VPWidenSC
) {
717 End
= I
->getIterator();
721 ~VPWidenRecipe() override
= default;
723 /// Method to support type inquiry through isa, cast, and dyn_cast.
724 static inline bool classof(const VPRecipeBase
*V
) {
725 return V
->getVPRecipeID() == VPRecipeBase::VPWidenSC
;
728 /// Produce widened copies of all Ingredients.
729 void execute(VPTransformState
&State
) override
;
731 /// Augment the recipe to include Instr, if it lies at its End.
732 bool appendInstruction(Instruction
*Instr
) {
733 if (End
!= Instr
->getIterator())
739 /// Print the recipe.
740 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
743 /// A recipe for handling phi nodes of integer and floating-point inductions,
744 /// producing their vector and scalar values.
745 class VPWidenIntOrFpInductionRecipe
: public VPRecipeBase
{
751 VPWidenIntOrFpInductionRecipe(PHINode
*IV
, TruncInst
*Trunc
= nullptr)
752 : VPRecipeBase(VPWidenIntOrFpInductionSC
), IV(IV
), Trunc(Trunc
) {}
753 ~VPWidenIntOrFpInductionRecipe() override
= default;
755 /// Method to support type inquiry through isa, cast, and dyn_cast.
756 static inline bool classof(const VPRecipeBase
*V
) {
757 return V
->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC
;
760 /// Generate the vectorized and scalarized versions of the phi node as
761 /// needed by their users.
762 void execute(VPTransformState
&State
) override
;
764 /// Print the recipe.
765 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
768 /// A recipe for handling all phi nodes except for integer and FP inductions.
769 class VPWidenPHIRecipe
: public VPRecipeBase
{
774 VPWidenPHIRecipe(PHINode
*Phi
) : VPRecipeBase(VPWidenPHISC
), Phi(Phi
) {}
775 ~VPWidenPHIRecipe() override
= default;
777 /// Method to support type inquiry through isa, cast, and dyn_cast.
778 static inline bool classof(const VPRecipeBase
*V
) {
779 return V
->getVPRecipeID() == VPRecipeBase::VPWidenPHISC
;
782 /// Generate the phi/select nodes.
783 void execute(VPTransformState
&State
) override
;
785 /// Print the recipe.
786 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
789 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
791 class VPBlendRecipe
: public VPRecipeBase
{
795 /// The blend operation is a User of a mask, if not null.
796 std::unique_ptr
<VPUser
> User
;
799 VPBlendRecipe(PHINode
*Phi
, ArrayRef
<VPValue
*> Masks
)
800 : VPRecipeBase(VPBlendSC
), Phi(Phi
) {
801 assert((Phi
->getNumIncomingValues() == 1 ||
802 Phi
->getNumIncomingValues() == Masks
.size()) &&
803 "Expected the same number of incoming values and masks");
805 User
.reset(new VPUser(Masks
));
808 /// Method to support type inquiry through isa, cast, and dyn_cast.
809 static inline bool classof(const VPRecipeBase
*V
) {
810 return V
->getVPRecipeID() == VPRecipeBase::VPBlendSC
;
813 /// Generate the phi/select nodes.
814 void execute(VPTransformState
&State
) override
;
816 /// Print the recipe.
817 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
820 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
821 /// or stores into one wide load/store and shuffles.
822 class VPInterleaveRecipe
: public VPRecipeBase
{
824 const InterleaveGroup
<Instruction
> *IG
;
825 std::unique_ptr
<VPUser
> User
;
828 VPInterleaveRecipe(const InterleaveGroup
<Instruction
> *IG
, VPValue
*Mask
)
829 : VPRecipeBase(VPInterleaveSC
), IG(IG
) {
830 if (Mask
) // Create a VPInstruction to register as a user of the mask.
831 User
.reset(new VPUser({Mask
}));
833 ~VPInterleaveRecipe() override
= default;
835 /// Method to support type inquiry through isa, cast, and dyn_cast.
836 static inline bool classof(const VPRecipeBase
*V
) {
837 return V
->getVPRecipeID() == VPRecipeBase::VPInterleaveSC
;
840 /// Generate the wide load or store, and shuffles.
841 void execute(VPTransformState
&State
) override
;
843 /// Print the recipe.
844 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
846 const InterleaveGroup
<Instruction
> *getInterleaveGroup() { return IG
; }
849 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
850 /// copies of the original scalar type, one per lane, instead of producing a
851 /// single copy of widened type for all lanes. If the instruction is known to be
852 /// uniform only one copy, per lane zero, will be generated.
853 class VPReplicateRecipe
: public VPRecipeBase
{
855 /// The instruction being replicated.
856 Instruction
*Ingredient
;
858 /// Indicator if only a single replica per lane is needed.
861 /// Indicator if the replicas are also predicated.
864 /// Indicator if the scalar values should also be packed into a vector.
868 VPReplicateRecipe(Instruction
*I
, bool IsUniform
, bool IsPredicated
= false)
869 : VPRecipeBase(VPReplicateSC
), Ingredient(I
), IsUniform(IsUniform
),
870 IsPredicated(IsPredicated
) {
871 // Retain the previous behavior of predicateInstructions(), where an
872 // insert-element of a predicated instruction got hoisted into the
873 // predicated basic block iff it was its only user. This is achieved by
874 // having predicated instructions also pack their values into a vector by
875 // default unless they have a replicated user which uses their scalar value.
876 AlsoPack
= IsPredicated
&& !I
->use_empty();
879 ~VPReplicateRecipe() override
= default;
881 /// Method to support type inquiry through isa, cast, and dyn_cast.
882 static inline bool classof(const VPRecipeBase
*V
) {
883 return V
->getVPRecipeID() == VPRecipeBase::VPReplicateSC
;
886 /// Generate replicas of the desired Ingredient. Replicas will be generated
887 /// for all parts and lanes unless a specific part and lane are specified in
889 void execute(VPTransformState
&State
) override
;
891 void setAlsoPack(bool Pack
) { AlsoPack
= Pack
; }
893 /// Print the recipe.
894 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
897 /// A recipe for generating conditional branches on the bits of a mask.
898 class VPBranchOnMaskRecipe
: public VPRecipeBase
{
900 std::unique_ptr
<VPUser
> User
;
903 VPBranchOnMaskRecipe(VPValue
*BlockInMask
) : VPRecipeBase(VPBranchOnMaskSC
) {
904 if (BlockInMask
) // nullptr means all-one mask.
905 User
.reset(new VPUser({BlockInMask
}));
908 /// Method to support type inquiry through isa, cast, and dyn_cast.
909 static inline bool classof(const VPRecipeBase
*V
) {
910 return V
->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC
;
913 /// Generate the extraction of the appropriate bit from the block mask and the
914 /// conditional branch.
915 void execute(VPTransformState
&State
) override
;
917 /// Print the recipe.
918 void print(raw_ostream
&O
, const Twine
&Indent
) const override
{
919 O
<< " +\n" << Indent
<< "\"BRANCH-ON-MASK ";
921 O
<< *User
->getOperand(0);
928 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
929 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
930 /// order to merge values that are set under such a branch and feed their uses.
931 /// The phi nodes can be scalar or vector depending on the users of the value.
932 /// This recipe works in concert with VPBranchOnMaskRecipe.
933 class VPPredInstPHIRecipe
: public VPRecipeBase
{
935 Instruction
*PredInst
;
938 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
939 /// nodes after merging back from a Branch-on-Mask.
940 VPPredInstPHIRecipe(Instruction
*PredInst
)
941 : VPRecipeBase(VPPredInstPHISC
), PredInst(PredInst
) {}
942 ~VPPredInstPHIRecipe() override
= default;
944 /// Method to support type inquiry through isa, cast, and dyn_cast.
945 static inline bool classof(const VPRecipeBase
*V
) {
946 return V
->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC
;
949 /// Generates phi nodes for live-outs as needed to retain SSA form.
950 void execute(VPTransformState
&State
) override
;
952 /// Print the recipe.
953 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
956 /// A Recipe for widening load/store operations.
957 /// TODO: We currently execute only per-part unless a specific instance is
959 class VPWidenMemoryInstructionRecipe
: public VPRecipeBase
{
962 std::unique_ptr
<VPUser
> User
;
965 VPWidenMemoryInstructionRecipe(Instruction
&Instr
, VPValue
*Mask
)
966 : VPRecipeBase(VPWidenMemoryInstructionSC
), Instr(Instr
) {
967 if (Mask
) // Create a VPInstruction to register as a user of the mask.
968 User
.reset(new VPUser({Mask
}));
971 /// Method to support type inquiry through isa, cast, and dyn_cast.
972 static inline bool classof(const VPRecipeBase
*V
) {
973 return V
->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC
;
976 /// Generate the wide load/store.
977 void execute(VPTransformState
&State
) override
;
979 /// Print the recipe.
980 void print(raw_ostream
&O
, const Twine
&Indent
) const override
;
983 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
984 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
985 /// output IR instructions.
986 class VPBasicBlock
: public VPBlockBase
{
988 using RecipeListTy
= iplist
<VPRecipeBase
>;
991 /// The VPRecipes held in the order of output instructions to generate.
992 RecipeListTy Recipes
;
995 VPBasicBlock(const Twine
&Name
= "", VPRecipeBase
*Recipe
= nullptr)
996 : VPBlockBase(VPBasicBlockSC
, Name
.str()) {
998 appendRecipe(Recipe
);
1001 ~VPBasicBlock() override
{ Recipes
.clear(); }
1003 /// Instruction iterators...
1004 using iterator
= RecipeListTy::iterator
;
1005 using const_iterator
= RecipeListTy::const_iterator
;
1006 using reverse_iterator
= RecipeListTy::reverse_iterator
;
1007 using const_reverse_iterator
= RecipeListTy::const_reverse_iterator
;
1009 //===--------------------------------------------------------------------===//
1010 /// Recipe iterator methods
1012 inline iterator
begin() { return Recipes
.begin(); }
1013 inline const_iterator
begin() const { return Recipes
.begin(); }
1014 inline iterator
end() { return Recipes
.end(); }
1015 inline const_iterator
end() const { return Recipes
.end(); }
1017 inline reverse_iterator
rbegin() { return Recipes
.rbegin(); }
1018 inline const_reverse_iterator
rbegin() const { return Recipes
.rbegin(); }
1019 inline reverse_iterator
rend() { return Recipes
.rend(); }
1020 inline const_reverse_iterator
rend() const { return Recipes
.rend(); }
1022 inline size_t size() const { return Recipes
.size(); }
1023 inline bool empty() const { return Recipes
.empty(); }
1024 inline const VPRecipeBase
&front() const { return Recipes
.front(); }
1025 inline VPRecipeBase
&front() { return Recipes
.front(); }
1026 inline const VPRecipeBase
&back() const { return Recipes
.back(); }
1027 inline VPRecipeBase
&back() { return Recipes
.back(); }
1029 /// Returns a reference to the list of recipes.
1030 RecipeListTy
&getRecipeList() { return Recipes
; }
1032 /// Returns a pointer to a member of the recipe list.
1033 static RecipeListTy
VPBasicBlock::*getSublistAccess(VPRecipeBase
*) {
1034 return &VPBasicBlock::Recipes
;
1037 /// Method to support type inquiry through isa, cast, and dyn_cast.
1038 static inline bool classof(const VPBlockBase
*V
) {
1039 return V
->getVPBlockID() == VPBlockBase::VPBasicBlockSC
;
1042 void insert(VPRecipeBase
*Recipe
, iterator InsertPt
) {
1043 assert(Recipe
&& "No recipe to append.");
1044 assert(!Recipe
->Parent
&& "Recipe already in VPlan");
1045 Recipe
->Parent
= this;
1046 Recipes
.insert(InsertPt
, Recipe
);
1049 /// Augment the existing recipes of a VPBasicBlock with an additional
1050 /// \p Recipe as the last recipe.
1051 void appendRecipe(VPRecipeBase
*Recipe
) { insert(Recipe
, end()); }
1053 /// The method which generates the output IR instructions that correspond to
1054 /// this VPBasicBlock, thereby "executing" the VPlan.
1055 void execute(struct VPTransformState
*State
) override
;
1058 /// Create an IR BasicBlock to hold the output instructions generated by this
1059 /// VPBasicBlock, and return it. Update the CFGState accordingly.
1060 BasicBlock
*createEmptyBasicBlock(VPTransformState::CFGState
&CFG
);
1063 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1064 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1065 /// A VPRegionBlock may indicate that its contents are to be replicated several
1066 /// times. This is designed to support predicated scalarization, in which a
1067 /// scalar if-then code structure needs to be generated VF * UF times. Having
1068 /// this replication indicator helps to keep a single model for multiple
1069 /// candidate VF's. The actual replication takes place only once the desired VF
1070 /// and UF have been determined.
1071 class VPRegionBlock
: public VPBlockBase
{
1073 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1076 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1079 /// An indicator whether this region is to generate multiple replicated
1080 /// instances of output IR corresponding to its VPBlockBases.
1084 VPRegionBlock(VPBlockBase
*Entry
, VPBlockBase
*Exit
,
1085 const std::string
&Name
= "", bool IsReplicator
= false)
1086 : VPBlockBase(VPRegionBlockSC
, Name
), Entry(Entry
), Exit(Exit
),
1087 IsReplicator(IsReplicator
) {
1088 assert(Entry
->getPredecessors().empty() && "Entry block has predecessors.");
1089 assert(Exit
->getSuccessors().empty() && "Exit block has successors.");
1090 Entry
->setParent(this);
1091 Exit
->setParent(this);
1093 VPRegionBlock(const std::string
&Name
= "", bool IsReplicator
= false)
1094 : VPBlockBase(VPRegionBlockSC
, Name
), Entry(nullptr), Exit(nullptr),
1095 IsReplicator(IsReplicator
) {}
1097 ~VPRegionBlock() override
{
1102 /// Method to support type inquiry through isa, cast, and dyn_cast.
1103 static inline bool classof(const VPBlockBase
*V
) {
1104 return V
->getVPBlockID() == VPBlockBase::VPRegionBlockSC
;
1107 const VPBlockBase
*getEntry() const { return Entry
; }
1108 VPBlockBase
*getEntry() { return Entry
; }
1110 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1111 /// EntryBlock must have no predecessors.
1112 void setEntry(VPBlockBase
*EntryBlock
) {
1113 assert(EntryBlock
->getPredecessors().empty() &&
1114 "Entry block cannot have predecessors.");
1116 EntryBlock
->setParent(this);
1119 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1120 // specific interface of llvm::Function, instead of using
1121 // GraphTraints::getEntryNode. We should add a new template parameter to
1122 // DominatorTreeBase representing the Graph type.
1123 VPBlockBase
&front() const { return *Entry
; }
1125 const VPBlockBase
*getExit() const { return Exit
; }
1126 VPBlockBase
*getExit() { return Exit
; }
1128 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1129 /// ExitBlock must have no successors.
1130 void setExit(VPBlockBase
*ExitBlock
) {
1131 assert(ExitBlock
->getSuccessors().empty() &&
1132 "Exit block cannot have successors.");
1134 ExitBlock
->setParent(this);
1137 /// An indicator whether this region is to generate multiple replicated
1138 /// instances of output IR corresponding to its VPBlockBases.
1139 bool isReplicator() const { return IsReplicator
; }
1141 /// The method which generates the output IR instructions that correspond to
1142 /// this VPRegionBlock, thereby "executing" the VPlan.
1143 void execute(struct VPTransformState
*State
) override
;
1146 /// VPlan models a candidate for vectorization, encoding various decisions take
1147 /// to produce efficient output IR, including which branches, basic-blocks and
1148 /// output IR instructions to generate, and their cost. VPlan holds a
1149 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1152 friend class VPlanPrinter
;
1155 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1158 /// Holds the VFs applicable to this VPlan.
1159 SmallSet
<unsigned, 2> VFs
;
1161 /// Holds the name of the VPlan, for printing.
1164 /// Holds all the external definitions created for this VPlan.
1165 // TODO: Introduce a specific representation for external definitions in
1166 // VPlan. External definitions must be immutable and hold a pointer to its
1167 // underlying IR that will be used to implement its structural comparison
1168 // (operators '==' and '<').
1169 SmallPtrSet
<VPValue
*, 16> VPExternalDefs
;
1171 /// Represents the backedge taken count of the original loop, for folding
1173 VPValue
*BackedgeTakenCount
= nullptr;
1175 /// Holds a mapping between Values and their corresponding VPValue inside
1177 Value2VPValueTy Value2VPValue
;
1179 /// Holds the VPLoopInfo analysis for this VPlan.
1182 /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1183 SmallVector
<VPValue
*, 4> VPCBVs
;
1186 VPlan(VPBlockBase
*Entry
= nullptr) : Entry(Entry
) {}
1190 VPBlockBase::deleteCFG(Entry
);
1191 for (auto &MapEntry
: Value2VPValue
)
1192 if (MapEntry
.second
!= BackedgeTakenCount
)
1193 delete MapEntry
.second
;
1194 if (BackedgeTakenCount
)
1195 delete BackedgeTakenCount
; // Delete once, if in Value2VPValue or not.
1196 for (VPValue
*Def
: VPExternalDefs
)
1198 for (VPValue
*CBV
: VPCBVs
)
1202 /// Generate the IR code for this VPlan.
1203 void execute(struct VPTransformState
*State
);
1205 VPBlockBase
*getEntry() { return Entry
; }
1206 const VPBlockBase
*getEntry() const { return Entry
; }
1208 VPBlockBase
*setEntry(VPBlockBase
*Block
) { return Entry
= Block
; }
1210 /// The backedge taken count of the original loop.
1211 VPValue
*getOrCreateBackedgeTakenCount() {
1212 if (!BackedgeTakenCount
)
1213 BackedgeTakenCount
= new VPValue();
1214 return BackedgeTakenCount
;
1217 void addVF(unsigned VF
) { VFs
.insert(VF
); }
1219 bool hasVF(unsigned VF
) { return VFs
.count(VF
); }
1221 const std::string
&getName() const { return Name
; }
1223 void setName(const Twine
&newName
) { Name
= newName
.str(); }
1225 /// Add \p VPVal to the pool of external definitions if it's not already
1227 void addExternalDef(VPValue
*VPVal
) {
1228 VPExternalDefs
.insert(VPVal
);
1231 /// Add \p CBV to the vector of condition bit values.
1232 void addCBV(VPValue
*CBV
) {
1233 VPCBVs
.push_back(CBV
);
1236 void addVPValue(Value
*V
) {
1237 assert(V
&& "Trying to add a null Value to VPlan");
1238 assert(!Value2VPValue
.count(V
) && "Value already exists in VPlan");
1239 Value2VPValue
[V
] = new VPValue();
1242 VPValue
*getVPValue(Value
*V
) {
1243 assert(V
&& "Trying to get the VPValue of a null Value");
1244 assert(Value2VPValue
.count(V
) && "Value does not exist in VPlan");
1245 return Value2VPValue
[V
];
1248 /// Return the VPLoopInfo analysis for this VPlan.
1249 VPLoopInfo
&getVPLoopInfo() { return VPLInfo
; }
1250 const VPLoopInfo
&getVPLoopInfo() const { return VPLInfo
; }
1253 /// Add to the given dominator tree the header block and every new basic block
1254 /// that was created between it and the latch block, inclusive.
1255 static void updateDominatorTree(DominatorTree
*DT
,
1256 BasicBlock
*LoopPreHeaderBB
,
1257 BasicBlock
*LoopLatchBB
);
1260 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1261 /// indented and follows the dot format.
1262 class VPlanPrinter
{
1263 friend inline raw_ostream
&operator<<(raw_ostream
&OS
, VPlan
&Plan
);
1264 friend inline raw_ostream
&operator<<(raw_ostream
&OS
,
1265 const struct VPlanIngredient
&I
);
1271 unsigned TabWidth
= 2;
1274 SmallDenseMap
<const VPBlockBase
*, unsigned> BlockID
;
1276 VPlanPrinter(raw_ostream
&O
, VPlan
&P
) : OS(O
), Plan(P
) {}
1278 /// Handle indentation.
1279 void bumpIndent(int b
) { Indent
= std::string((Depth
+= b
) * TabWidth
, ' '); }
1281 /// Print a given \p Block of the Plan.
1282 void dumpBlock(const VPBlockBase
*Block
);
1284 /// Print the information related to the CFG edges going out of a given
1285 /// \p Block, followed by printing the successor blocks themselves.
1286 void dumpEdges(const VPBlockBase
*Block
);
1288 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1289 /// its successor blocks.
1290 void dumpBasicBlock(const VPBasicBlock
*BasicBlock
);
1292 /// Print a given \p Region of the Plan.
1293 void dumpRegion(const VPRegionBlock
*Region
);
1295 unsigned getOrCreateBID(const VPBlockBase
*Block
) {
1296 return BlockID
.count(Block
) ? BlockID
[Block
] : BlockID
[Block
] = BID
++;
1299 const Twine
getOrCreateName(const VPBlockBase
*Block
);
1301 const Twine
getUID(const VPBlockBase
*Block
);
1303 /// Print the information related to a CFG edge between two VPBlockBases.
1304 void drawEdge(const VPBlockBase
*From
, const VPBlockBase
*To
, bool Hidden
,
1305 const Twine
&Label
);
1309 static void printAsIngredient(raw_ostream
&O
, Value
*V
);
1312 struct VPlanIngredient
{
1315 VPlanIngredient(Value
*V
) : V(V
) {}
1318 inline raw_ostream
&operator<<(raw_ostream
&OS
, const VPlanIngredient
&I
) {
1319 VPlanPrinter::printAsIngredient(OS
, I
.V
);
1323 inline raw_ostream
&operator<<(raw_ostream
&OS
, VPlan
&Plan
) {
1324 VPlanPrinter
Printer(OS
, Plan
);
1329 //===----------------------------------------------------------------------===//
1330 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs //
1331 //===----------------------------------------------------------------------===//
1333 // The following set of template specializations implement GraphTraits to treat
1334 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1335 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1336 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
1337 // successors/predecessors but not to the blocks inside the region.
1339 template <> struct GraphTraits
<VPBlockBase
*> {
1340 using NodeRef
= VPBlockBase
*;
1341 using ChildIteratorType
= SmallVectorImpl
<VPBlockBase
*>::iterator
;
1343 static NodeRef
getEntryNode(NodeRef N
) { return N
; }
1345 static inline ChildIteratorType
child_begin(NodeRef N
) {
1346 return N
->getSuccessors().begin();
1349 static inline ChildIteratorType
child_end(NodeRef N
) {
1350 return N
->getSuccessors().end();
1354 template <> struct GraphTraits
<const VPBlockBase
*> {
1355 using NodeRef
= const VPBlockBase
*;
1356 using ChildIteratorType
= SmallVectorImpl
<VPBlockBase
*>::const_iterator
;
1358 static NodeRef
getEntryNode(NodeRef N
) { return N
; }
1360 static inline ChildIteratorType
child_begin(NodeRef N
) {
1361 return N
->getSuccessors().begin();
1364 static inline ChildIteratorType
child_end(NodeRef N
) {
1365 return N
->getSuccessors().end();
1369 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1370 // of successors for the inverse traversal.
1371 template <> struct GraphTraits
<Inverse
<VPBlockBase
*>> {
1372 using NodeRef
= VPBlockBase
*;
1373 using ChildIteratorType
= SmallVectorImpl
<VPBlockBase
*>::iterator
;
1375 static NodeRef
getEntryNode(Inverse
<NodeRef
> B
) { return B
.Graph
; }
1377 static inline ChildIteratorType
child_begin(NodeRef N
) {
1378 return N
->getPredecessors().begin();
1381 static inline ChildIteratorType
child_end(NodeRef N
) {
1382 return N
->getPredecessors().end();
1386 // The following set of template specializations implement GraphTraits to
1387 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1388 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1389 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1390 // there won't be automatic recursion into other VPBlockBases that turn to be
1394 struct GraphTraits
<VPRegionBlock
*> : public GraphTraits
<VPBlockBase
*> {
1395 using GraphRef
= VPRegionBlock
*;
1396 using nodes_iterator
= df_iterator
<NodeRef
>;
1398 static NodeRef
getEntryNode(GraphRef N
) { return N
->getEntry(); }
1400 static nodes_iterator
nodes_begin(GraphRef N
) {
1401 return nodes_iterator::begin(N
->getEntry());
1404 static nodes_iterator
nodes_end(GraphRef N
) {
1405 // df_iterator::end() returns an empty iterator so the node used doesn't
1407 return nodes_iterator::end(N
);
1412 struct GraphTraits
<const VPRegionBlock
*>
1413 : public GraphTraits
<const VPBlockBase
*> {
1414 using GraphRef
= const VPRegionBlock
*;
1415 using nodes_iterator
= df_iterator
<NodeRef
>;
1417 static NodeRef
getEntryNode(GraphRef N
) { return N
->getEntry(); }
1419 static nodes_iterator
nodes_begin(GraphRef N
) {
1420 return nodes_iterator::begin(N
->getEntry());
1423 static nodes_iterator
nodes_end(GraphRef N
) {
1424 // df_iterator::end() returns an empty iterator so the node used doesn't
1426 return nodes_iterator::end(N
);
1431 struct GraphTraits
<Inverse
<VPRegionBlock
*>>
1432 : public GraphTraits
<Inverse
<VPBlockBase
*>> {
1433 using GraphRef
= VPRegionBlock
*;
1434 using nodes_iterator
= df_iterator
<NodeRef
>;
1436 static NodeRef
getEntryNode(Inverse
<GraphRef
> N
) {
1437 return N
.Graph
->getExit();
1440 static nodes_iterator
nodes_begin(GraphRef N
) {
1441 return nodes_iterator::begin(N
->getExit());
1444 static nodes_iterator
nodes_end(GraphRef N
) {
1445 // df_iterator::end() returns an empty iterator so the node used doesn't
1447 return nodes_iterator::end(N
);
1451 //===----------------------------------------------------------------------===//
1453 //===----------------------------------------------------------------------===//
1455 /// Class that provides utilities for VPBlockBases in VPlan.
1456 class VPBlockUtils
{
1458 VPBlockUtils() = delete;
1460 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1461 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1462 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1463 /// has more than one successor, its conditional bit is propagated to \p
1464 /// NewBlock. \p NewBlock must have neither successors nor predecessors.
1465 static void insertBlockAfter(VPBlockBase
*NewBlock
, VPBlockBase
*BlockPtr
) {
1466 assert(NewBlock
->getSuccessors().empty() &&
1467 "Can't insert new block with successors.");
1468 // TODO: move successors from BlockPtr to NewBlock when this functionality
1469 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1470 // already has successors.
1471 BlockPtr
->setOneSuccessor(NewBlock
);
1472 NewBlock
->setPredecessors({BlockPtr
});
1473 NewBlock
->setParent(BlockPtr
->getParent());
1476 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1477 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1478 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1479 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1480 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1481 /// must have neither successors nor predecessors.
1482 static void insertTwoBlocksAfter(VPBlockBase
*IfTrue
, VPBlockBase
*IfFalse
,
1483 VPValue
*Condition
, VPBlockBase
*BlockPtr
) {
1484 assert(IfTrue
->getSuccessors().empty() &&
1485 "Can't insert IfTrue with successors.");
1486 assert(IfFalse
->getSuccessors().empty() &&
1487 "Can't insert IfFalse with successors.");
1488 BlockPtr
->setTwoSuccessors(IfTrue
, IfFalse
, Condition
);
1489 IfTrue
->setPredecessors({BlockPtr
});
1490 IfFalse
->setPredecessors({BlockPtr
});
1491 IfTrue
->setParent(BlockPtr
->getParent());
1492 IfFalse
->setParent(BlockPtr
->getParent());
1495 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1496 /// the successors of \p From and \p From to the predecessors of \p To. Both
1497 /// VPBlockBases must have the same parent, which can be null. Both
1498 /// VPBlockBases can be already connected to other VPBlockBases.
1499 static void connectBlocks(VPBlockBase
*From
, VPBlockBase
*To
) {
1500 assert((From
->getParent() == To
->getParent()) &&
1501 "Can't connect two block with different parents");
1502 assert(From
->getNumSuccessors() < 2 &&
1503 "Blocks can't have more than two successors.");
1504 From
->appendSuccessor(To
);
1505 To
->appendPredecessor(From
);
1508 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1509 /// from the successors of \p From and \p From from the predecessors of \p To.
1510 static void disconnectBlocks(VPBlockBase
*From
, VPBlockBase
*To
) {
1511 assert(To
&& "Successor to disconnect is null.");
1512 From
->removeSuccessor(To
);
1513 To
->removePredecessor(From
);
1516 /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
1517 static bool isBackEdge(const VPBlockBase
*FromBlock
,
1518 const VPBlockBase
*ToBlock
, const VPLoopInfo
*VPLI
) {
1519 assert(FromBlock
->getParent() == ToBlock
->getParent() &&
1520 FromBlock
->getParent() && "Must be in same region");
1521 const VPLoop
*FromLoop
= VPLI
->getLoopFor(FromBlock
);
1522 const VPLoop
*ToLoop
= VPLI
->getLoopFor(ToBlock
);
1523 if (!FromLoop
|| !ToLoop
|| FromLoop
!= ToLoop
)
1526 // A back-edge is a branch from the loop latch to its header.
1527 return ToLoop
->isLoopLatch(FromBlock
) && ToBlock
== ToLoop
->getHeader();
1530 /// Returns true if \p Block is a loop latch
1531 static bool blockIsLoopLatch(const VPBlockBase
*Block
,
1532 const VPLoopInfo
*VPLInfo
) {
1533 if (const VPLoop
*ParentVPL
= VPLInfo
->getLoopFor(Block
))
1534 return ParentVPL
->isLoopLatch(Block
);
1539 /// Count and return the number of succesors of \p PredBlock excluding any
1541 static unsigned countSuccessorsNoBE(VPBlockBase
*PredBlock
,
1544 for (VPBlockBase
*SuccBlock
: PredBlock
->getSuccessors()) {
1545 if (!VPBlockUtils::isBackEdge(PredBlock
, SuccBlock
, VPLI
))
1552 class VPInterleavedAccessInfo
{
1554 DenseMap
<VPInstruction
*, InterleaveGroup
<VPInstruction
> *>
1557 /// Type for mapping of instruction based interleave groups to VPInstruction
1558 /// interleave groups
1559 using Old2NewTy
= DenseMap
<InterleaveGroup
<Instruction
> *,
1560 InterleaveGroup
<VPInstruction
> *>;
1562 /// Recursively \p Region and populate VPlan based interleave groups based on
1564 void visitRegion(VPRegionBlock
*Region
, Old2NewTy
&Old2New
,
1565 InterleavedAccessInfo
&IAI
);
1566 /// Recursively traverse \p Block and populate VPlan based interleave groups
1567 /// based on \p IAI.
1568 void visitBlock(VPBlockBase
*Block
, Old2NewTy
&Old2New
,
1569 InterleavedAccessInfo
&IAI
);
1572 VPInterleavedAccessInfo(VPlan
&Plan
, InterleavedAccessInfo
&IAI
);
1574 ~VPInterleavedAccessInfo() {
1575 SmallPtrSet
<InterleaveGroup
<VPInstruction
> *, 4> DelSet
;
1576 // Avoid releasing a pointer twice.
1577 for (auto &I
: InterleaveGroupMap
)
1578 DelSet
.insert(I
.second
);
1579 for (auto *Ptr
: DelSet
)
1583 /// Get the interleave group that \p Instr belongs to.
1585 /// \returns nullptr if doesn't have such group.
1586 InterleaveGroup
<VPInstruction
> *
1587 getInterleaveGroup(VPInstruction
*Instr
) const {
1588 if (InterleaveGroupMap
.count(Instr
))
1589 return InterleaveGroupMap
.find(Instr
)->second
;
1594 /// Class that maps (parts of) an existing VPlan to trees of combined
1598 enum class OpMode
{ Failed
, Load
, Opcode
};
1600 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
1602 struct BundleDenseMapInfo
{
1603 static SmallVector
<VPValue
*, 4> getEmptyKey() {
1604 return {reinterpret_cast<VPValue
*>(-1)};
1607 static SmallVector
<VPValue
*, 4> getTombstoneKey() {
1608 return {reinterpret_cast<VPValue
*>(-2)};
1611 static unsigned getHashValue(const SmallVector
<VPValue
*, 4> &V
) {
1612 return static_cast<unsigned>(hash_combine_range(V
.begin(), V
.end()));
1615 static bool isEqual(const SmallVector
<VPValue
*, 4> &LHS
,
1616 const SmallVector
<VPValue
*, 4> &RHS
) {
1621 /// Mapping of values in the original VPlan to a combined VPInstruction.
1622 DenseMap
<SmallVector
<VPValue
*, 4>, VPInstruction
*, BundleDenseMapInfo
>
1625 VPInterleavedAccessInfo
&IAI
;
1627 /// Basic block to operate on. For now, only instructions in a single BB are
1629 const VPBasicBlock
&BB
;
1631 /// Indicates whether we managed to combine all visited instructions or not.
1632 bool CompletelySLP
= true;
1634 /// Width of the widest combined bundle in bits.
1635 unsigned WidestBundleBits
= 0;
1637 using MultiNodeOpTy
=
1638 typename
std::pair
<VPInstruction
*, SmallVector
<VPValue
*, 4>>;
1640 // Input operand bundles for the current multi node. Each multi node operand
1641 // bundle contains values not matching the multi node's opcode. They will
1642 // be reordered in reorderMultiNodeOps, once we completed building a
1644 SmallVector
<MultiNodeOpTy
, 4> MultiNodeOps
;
1646 /// Indicates whether we are building a multi node currently.
1647 bool MultiNodeActive
= false;
1649 /// Check if we can vectorize Operands together.
1650 bool areVectorizable(ArrayRef
<VPValue
*> Operands
) const;
1652 /// Add combined instruction \p New for the bundle \p Operands.
1653 void addCombined(ArrayRef
<VPValue
*> Operands
, VPInstruction
*New
);
1655 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
1656 VPInstruction
*markFailed();
1658 /// Reorder operands in the multi node to maximize sequential memory access
1659 /// and commutative operations.
1660 SmallVector
<MultiNodeOpTy
, 4> reorderMultiNodeOps();
1662 /// Choose the best candidate to use for the lane after \p Last. The set of
1663 /// candidates to choose from are values with an opcode matching \p Last's
1664 /// or loads consecutive to \p Last.
1665 std::pair
<OpMode
, VPValue
*> getBest(OpMode Mode
, VPValue
*Last
,
1666 SmallPtrSetImpl
<VPValue
*> &Candidates
,
1667 VPInterleavedAccessInfo
&IAI
);
1669 /// Print bundle \p Values to dbgs().
1670 void dumpBundle(ArrayRef
<VPValue
*> Values
);
1673 VPlanSlp(VPInterleavedAccessInfo
&IAI
, VPBasicBlock
&BB
) : IAI(IAI
), BB(BB
) {}
1676 for (auto &KV
: BundleToCombined
)
1680 /// Tries to build an SLP tree rooted at \p Operands and returns a
1681 /// VPInstruction combining \p Operands, if they can be combined.
1682 VPInstruction
*buildGraph(ArrayRef
<VPValue
*> Operands
);
1684 /// Return the width of the widest combined bundle in bits.
1685 unsigned getWidestBundleBits() const { return WidestBundleBits
; }
1687 /// Return true if all visited instruction can be combined.
1688 bool isCompletelySLP() const { return CompletelySLP
; }
1690 } // end namespace llvm
1692 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H