blob: f039e21458a95120cee3507a1e523c0cfcf16980 [file] [log] [blame]
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001//===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
Ayal Zaks1f58dda2017-08-27 12:55:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko6cadde72017-10-17 21:27:42 +00009//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000010/// \file
11/// This file contains the declarations of the Vectorization Plan base classes:
12/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
13/// VPBlockBase, together implementing a Hierarchical CFG;
14/// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
15/// treated as proper graphs for generic algorithms;
16/// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
17/// within VPBasicBlocks;
18/// 4. The VPlan class holding a candidate for vectorization;
19/// 5. The VPlanPrinter class providing a way to print a plan in dot format.
20/// These are documented in docs/VectorizationPlan.rst.
Eugene Zelenko6cadde72017-10-17 21:27:42 +000021//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000022//===----------------------------------------------------------------------===//
23
24#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
25#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26
Eugene Zelenko6cadde72017-10-17 21:27:42 +000027#include "llvm/ADT/DenseMap.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000028#include "llvm/ADT/GraphTraits.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000029#include "llvm/ADT/Optional.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000030#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000031#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000033#include "llvm/ADT/ilist.h"
34#include "llvm/ADT/ilist_node.h"
35#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000036#include <algorithm>
37#include <cassert>
38#include <cstddef>
39#include <map>
40#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000041
42namespace llvm {
43
Ayal Zaks1f58dda2017-08-27 12:55:46 +000044class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000045class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000046class InnerLoopVectorizer;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000047class LoopInfo;
48class raw_ostream;
49class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000050class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000051class VPRegionBlock;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000052
53/// In what follows, the term "input IR" refers to code that is fed into the
54/// vectorizer whereas the term "output IR" refers to code that is generated by
55/// the vectorizer.
56
57/// VPIteration represents a single point in the iteration space of the output
58/// (vectorized and/or unrolled) IR loop.
59struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000060 /// in [0..UF)
61 unsigned Part;
62
63 /// in [0..VF)
64 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000065};
66
67/// This is a helper struct for maintaining vectorization state. It's used for
68/// mapping values from the original loop to their corresponding values in
69/// the new loop. Two mappings are maintained: one for vectorized values and
70/// one for scalarized values. Vectorized values are represented with UF
71/// vector values in the new loop, and scalarized values are represented with
72/// UF x VF scalar values in the new loop. UF and VF are the unroll and
73/// vectorization factors, respectively.
74///
75/// Entries can be added to either map with setVectorValue and setScalarValue,
76/// which assert that an entry was not already added before. If an entry is to
77/// replace an existing one, call resetVectorValue and resetScalarValue. This is
78/// currently needed to modify the mapped values during "fix-up" operations that
79/// occur once the first phase of widening is complete. These operations include
80/// type truncation and the second phase of recurrence widening.
81///
82/// Entries from either map can be retrieved using the getVectorValue and
83/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +000084struct VectorizerValueMap {
85private:
86 /// The unroll factor. Each entry in the vector map contains UF vector values.
87 unsigned UF;
88
89 /// The vectorization factor. Each entry in the scalar map contains UF x VF
90 /// scalar values.
91 unsigned VF;
92
93 /// The vector and scalar map storage. We use std::map and not DenseMap
94 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +000095 using VectorParts = SmallVector<Value *, 2>;
96 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000097 std::map<Value *, VectorParts> VectorMapStorage;
98 std::map<Value *, ScalarParts> ScalarMapStorage;
99
100public:
101 /// Construct an empty map with the given unroll and vectorization factors.
102 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
103
104 /// \return True if the map has any vector entry for \p Key.
105 bool hasAnyVectorValue(Value *Key) const {
106 return VectorMapStorage.count(Key);
107 }
108
109 /// \return True if the map has a vector entry for \p Key and \p Part.
110 bool hasVectorValue(Value *Key, unsigned Part) const {
111 assert(Part < UF && "Queried Vector Part is too large.");
112 if (!hasAnyVectorValue(Key))
113 return false;
114 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
115 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
116 return Entry[Part] != nullptr;
117 }
118
119 /// \return True if the map has any scalar entry for \p Key.
120 bool hasAnyScalarValue(Value *Key) const {
121 return ScalarMapStorage.count(Key);
122 }
123
124 /// \return True if the map has a scalar entry for \p Key and \p Instance.
125 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
126 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
127 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
128 if (!hasAnyScalarValue(Key))
129 return false;
130 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
131 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
132 assert(Entry[Instance.Part].size() == VF &&
133 "ScalarParts has wrong dimensions.");
134 return Entry[Instance.Part][Instance.Lane] != nullptr;
135 }
136
137 /// Retrieve the existing vector value that corresponds to \p Key and
138 /// \p Part.
139 Value *getVectorValue(Value *Key, unsigned Part) {
140 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
141 return VectorMapStorage[Key][Part];
142 }
143
144 /// Retrieve the existing scalar value that corresponds to \p Key and
145 /// \p Instance.
146 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
147 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
148 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
149 }
150
151 /// Set a vector value associated with \p Key and \p Part. Assumes such a
152 /// value is not already set. If it is, use resetVectorValue() instead.
153 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
154 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
155 if (!VectorMapStorage.count(Key)) {
156 VectorParts Entry(UF);
157 VectorMapStorage[Key] = Entry;
158 }
159 VectorMapStorage[Key][Part] = Vector;
160 }
161
162 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
163 /// value is not already set.
164 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
165 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
166 if (!ScalarMapStorage.count(Key)) {
167 ScalarParts Entry(UF);
168 // TODO: Consider storing uniform values only per-part, as they occupy
169 // lane 0 only, keeping the other VF-1 redundant entries null.
170 for (unsigned Part = 0; Part < UF; ++Part)
171 Entry[Part].resize(VF, nullptr);
172 ScalarMapStorage[Key] = Entry;
173 }
174 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
175 }
176
177 /// Reset the vector value associated with \p Key for the given \p Part.
178 /// This function can be used to update values that have already been
179 /// vectorized. This is the case for "fix-up" operations including type
180 /// truncation and the second phase of recurrence vectorization.
181 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
182 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
183 VectorMapStorage[Key][Part] = Vector;
184 }
185
186 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
187 /// This function can be used to update values that have already been
188 /// scalarized. This is the case for "fix-up" operations including scalar phi
189 /// nodes for scalarized and predicated instructions.
190 void resetScalarValue(Value *Key, const VPIteration &Instance,
191 Value *Scalar) {
192 assert(hasScalarValue(Key, Instance) &&
193 "Scalar value not set for part and lane");
194 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
195 }
196};
197
198/// VPTransformState holds information passed down when "executing" a VPlan,
199/// needed for generating the output IR.
200struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000201 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
202 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
203 InnerLoopVectorizer *ILV)
204 : VF(VF), UF(UF), LI(LI), DT(DT), Builder(Builder), ValueMap(ValueMap),
205 ILV(ILV) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000206
207 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
208 unsigned VF;
209 unsigned UF;
210
211 /// Hold the indices to generate specific scalar instructions. Null indicates
212 /// that all instances are to be generated, using either scalar or vector
213 /// instructions.
214 Optional<VPIteration> Instance;
215
216 /// Hold state information used when constructing the CFG of the output IR,
217 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
218 struct CFGState {
219 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000220 VPBasicBlock *PrevVPBB = nullptr;
221
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000222 /// The previous IR BasicBlock created or used. Initially set to the new
223 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000224 BasicBlock *PrevBB = nullptr;
225
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000226 /// The last IR BasicBlock in the output IR. Set to the new latch
227 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000228 BasicBlock *LastBB = nullptr;
229
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000230 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
231 /// of replication, maps the BasicBlock of the last replica created.
232 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
233
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000234 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000235 } CFG;
236
237 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000238 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000239
240 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000241 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000242
243 /// Hold a reference to the IRBuilder used to generate output IR code.
244 IRBuilder<> &Builder;
245
246 /// Hold a reference to the Value state information used when generating the
247 /// Values of the output IR.
248 VectorizerValueMap &ValueMap;
249
250 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000251 InnerLoopVectorizer *ILV;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000252};
253
254/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
255/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
256class VPBlockBase {
257private:
258 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
259
260 /// An optional name for the block.
261 std::string Name;
262
263 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
264 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000265 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000266
267 /// List of predecessor blocks.
268 SmallVector<VPBlockBase *, 1> Predecessors;
269
270 /// List of successor blocks.
271 SmallVector<VPBlockBase *, 1> Successors;
272
273 /// Add \p Successor as the last successor to this block.
274 void appendSuccessor(VPBlockBase *Successor) {
275 assert(Successor && "Cannot add nullptr successor!");
276 Successors.push_back(Successor);
277 }
278
279 /// Add \p Predecessor as the last predecessor to this block.
280 void appendPredecessor(VPBlockBase *Predecessor) {
281 assert(Predecessor && "Cannot add nullptr predecessor!");
282 Predecessors.push_back(Predecessor);
283 }
284
285 /// Remove \p Predecessor from the predecessors of this block.
286 void removePredecessor(VPBlockBase *Predecessor) {
287 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
288 assert(Pos && "Predecessor does not exist");
289 Predecessors.erase(Pos);
290 }
291
292 /// Remove \p Successor from the successors of this block.
293 void removeSuccessor(VPBlockBase *Successor) {
294 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
295 assert(Pos && "Successor does not exist");
296 Successors.erase(Pos);
297 }
298
299protected:
300 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000301 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000302
303public:
304 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
305 /// that are actually instantiated. Values of this enumeration are kept in the
306 /// SubclassID field of the VPBlockBase objects. They are used for concrete
307 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000308 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000309
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000310 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000311
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000312 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000313
314 const std::string &getName() const { return Name; }
315
316 void setName(const Twine &newName) { Name = newName.str(); }
317
318 /// \return an ID for the concrete type of this object.
319 /// This is used to implement the classof checks. This should not be used
320 /// for any other purpose, as the values may change as LLVM evolves.
321 unsigned getVPBlockID() const { return SubclassID; }
322
323 const VPRegionBlock *getParent() const { return Parent; }
324
325 void setParent(VPRegionBlock *P) { Parent = P; }
326
327 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
328 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
329 /// VPBlockBase is a VPBasicBlock, it is returned.
330 const VPBasicBlock *getEntryBasicBlock() const;
331 VPBasicBlock *getEntryBasicBlock();
332
333 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
334 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
335 /// VPBlockBase is a VPBasicBlock, it is returned.
336 const VPBasicBlock *getExitBasicBlock() const;
337 VPBasicBlock *getExitBasicBlock();
338
339 const VPBlocksTy &getSuccessors() const { return Successors; }
340 VPBlocksTy &getSuccessors() { return Successors; }
341
342 const VPBlocksTy &getPredecessors() const { return Predecessors; }
343 VPBlocksTy &getPredecessors() { return Predecessors; }
344
345 /// \return the successor of this VPBlockBase if it has a single successor.
346 /// Otherwise return a null pointer.
347 VPBlockBase *getSingleSuccessor() const {
348 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
349 }
350
351 /// \return the predecessor of this VPBlockBase if it has a single
352 /// predecessor. Otherwise return a null pointer.
353 VPBlockBase *getSinglePredecessor() const {
354 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
355 }
356
357 /// An Enclosing Block of a block B is any block containing B, including B
358 /// itself. \return the closest enclosing block starting from "this", which
359 /// has successors. \return the root enclosing block if all enclosing blocks
360 /// have no successors.
361 VPBlockBase *getEnclosingBlockWithSuccessors();
362
363 /// \return the closest enclosing block starting from "this", which has
364 /// predecessors. \return the root enclosing block if all enclosing blocks
365 /// have no predecessors.
366 VPBlockBase *getEnclosingBlockWithPredecessors();
367
368 /// \return the successors either attached directly to this VPBlockBase or, if
369 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
370 /// successors of its own, search recursively for the first enclosing
371 /// VPRegionBlock that has successors and return them. If no such
372 /// VPRegionBlock exists, return the (empty) successors of the topmost
373 /// VPBlockBase reached.
374 const VPBlocksTy &getHierarchicalSuccessors() {
375 return getEnclosingBlockWithSuccessors()->getSuccessors();
376 }
377
378 /// \return the hierarchical successor of this VPBlockBase if it has a single
379 /// hierarchical successor. Otherwise return a null pointer.
380 VPBlockBase *getSingleHierarchicalSuccessor() {
381 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
382 }
383
384 /// \return the predecessors either attached directly to this VPBlockBase or,
385 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
386 /// predecessors of its own, search recursively for the first enclosing
387 /// VPRegionBlock that has predecessors and return them. If no such
388 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
389 /// VPBlockBase reached.
390 const VPBlocksTy &getHierarchicalPredecessors() {
391 return getEnclosingBlockWithPredecessors()->getPredecessors();
392 }
393
394 /// \return the hierarchical predecessor of this VPBlockBase if it has a
395 /// single hierarchical predecessor. Otherwise return a null pointer.
396 VPBlockBase *getSingleHierarchicalPredecessor() {
397 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
398 }
399
400 /// Sets a given VPBlockBase \p Successor as the single successor and \return
401 /// \p Successor. The parent of this Block is copied to be the parent of
402 /// \p Successor.
403 VPBlockBase *setOneSuccessor(VPBlockBase *Successor) {
404 assert(Successors.empty() && "Setting one successor when others exist.");
405 appendSuccessor(Successor);
406 Successor->appendPredecessor(this);
407 Successor->Parent = Parent;
408 return Successor;
409 }
410
411 /// Sets two given VPBlockBases \p IfTrue and \p IfFalse to be the two
412 /// successors. The parent of this Block is copied to be the parent of both
413 /// \p IfTrue and \p IfFalse.
414 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
415 assert(Successors.empty() && "Setting two successors when others exist.");
416 appendSuccessor(IfTrue);
417 appendSuccessor(IfFalse);
418 IfTrue->appendPredecessor(this);
419 IfFalse->appendPredecessor(this);
420 IfTrue->Parent = Parent;
421 IfFalse->Parent = Parent;
422 }
423
424 void disconnectSuccessor(VPBlockBase *Successor) {
425 assert(Successor && "Successor to disconnect is null.");
426 removeSuccessor(Successor);
427 Successor->removePredecessor(this);
428 }
429
430 /// The method which generates the output IR that correspond to this
431 /// VPBlockBase, thereby "executing" the VPlan.
432 virtual void execute(struct VPTransformState *State) = 0;
433
434 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
435 static void deleteCFG(VPBlockBase *Entry);
436};
437
438/// VPRecipeBase is a base class modeling a sequence of one or more output IR
439/// instructions.
440class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
441 friend VPBasicBlock;
442
443private:
444 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
445
446 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000447 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000448
449public:
450 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
451 /// that is actually instantiated. Values of this enumeration are kept in the
452 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
453 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000454 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000455 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000456 VPBranchOnMaskSC,
457 VPInterleaveSC,
458 VPPredInstPHISC,
459 VPReplicateSC,
460 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000461 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000462 VPWidenPHISC,
463 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000464 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000465
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000466 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
467 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000468
469 /// \return an ID for the concrete type of this object.
470 /// This is used to implement the classof checks. This should not be used
471 /// for any other purpose, as the values may change as LLVM evolves.
472 unsigned getVPRecipeID() const { return SubclassID; }
473
474 /// \return the VPBasicBlock which this VPRecipe belongs to.
475 VPBasicBlock *getParent() { return Parent; }
476 const VPBasicBlock *getParent() const { return Parent; }
477
478 /// The method which generates the output IR instructions that correspond to
479 /// this VPRecipe, thereby "executing" the VPlan.
480 virtual void execute(struct VPTransformState &State) = 0;
481
482 /// Each recipe prints itself.
483 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
484};
485
486/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
487/// holds a sequence of zero or more VPRecipe's each representing a sequence of
488/// output IR instructions.
489class VPBasicBlock : public VPBlockBase {
490public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000491 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000492
493private:
494 /// The VPRecipes held in the order of output instructions to generate.
495 RecipeListTy Recipes;
496
497public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000498 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
499 : VPBlockBase(VPBasicBlockSC, Name.str()) {
500 if (Recipe)
501 appendRecipe(Recipe);
502 }
503
504 ~VPBasicBlock() override { Recipes.clear(); }
505
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000506 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000507 using iterator = RecipeListTy::iterator;
508 using const_iterator = RecipeListTy::const_iterator;
509 using reverse_iterator = RecipeListTy::reverse_iterator;
510 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000511
512 //===--------------------------------------------------------------------===//
513 /// Recipe iterator methods
514 ///
515 inline iterator begin() { return Recipes.begin(); }
516 inline const_iterator begin() const { return Recipes.begin(); }
517 inline iterator end() { return Recipes.end(); }
518 inline const_iterator end() const { return Recipes.end(); }
519
520 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
521 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
522 inline reverse_iterator rend() { return Recipes.rend(); }
523 inline const_reverse_iterator rend() const { return Recipes.rend(); }
524
525 inline size_t size() const { return Recipes.size(); }
526 inline bool empty() const { return Recipes.empty(); }
527 inline const VPRecipeBase &front() const { return Recipes.front(); }
528 inline VPRecipeBase &front() { return Recipes.front(); }
529 inline const VPRecipeBase &back() const { return Recipes.back(); }
530 inline VPRecipeBase &back() { return Recipes.back(); }
531
532 /// \brief Returns a pointer to a member of the recipe list.
533 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
534 return &VPBasicBlock::Recipes;
535 }
536
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000537 /// Method to support type inquiry through isa, cast, and dyn_cast.
538 static inline bool classof(const VPBlockBase *V) {
539 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
540 }
541
542 /// Augment the existing recipes of a VPBasicBlock with an additional
543 /// \p Recipe as the last recipe.
544 void appendRecipe(VPRecipeBase *Recipe) {
545 assert(Recipe && "No recipe to append.");
546 assert(!Recipe->Parent && "Recipe already in VPlan");
547 Recipe->Parent = this;
548 return Recipes.push_back(Recipe);
549 }
550
551 /// The method which generates the output IR instructions that correspond to
552 /// this VPBasicBlock, thereby "executing" the VPlan.
553 void execute(struct VPTransformState *State) override;
554
555private:
556 /// Create an IR BasicBlock to hold the output instructions generated by this
557 /// VPBasicBlock, and return it. Update the CFGState accordingly.
558 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
559};
560
561/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
562/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
563/// A VPRegionBlock may indicate that its contents are to be replicated several
564/// times. This is designed to support predicated scalarization, in which a
565/// scalar if-then code structure needs to be generated VF * UF times. Having
566/// this replication indicator helps to keep a single model for multiple
567/// candidate VF's. The actual replication takes place only once the desired VF
568/// and UF have been determined.
569class VPRegionBlock : public VPBlockBase {
570private:
571 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
572 VPBlockBase *Entry;
573
574 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
575 VPBlockBase *Exit;
576
577 /// An indicator whether this region is to generate multiple replicated
578 /// instances of output IR corresponding to its VPBlockBases.
579 bool IsReplicator;
580
581public:
582 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
583 const std::string &Name = "", bool IsReplicator = false)
584 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
585 IsReplicator(IsReplicator) {
586 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
587 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
588 Entry->setParent(this);
589 Exit->setParent(this);
590 }
591
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000592 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000593 if (Entry)
594 deleteCFG(Entry);
595 }
596
597 /// Method to support type inquiry through isa, cast, and dyn_cast.
598 static inline bool classof(const VPBlockBase *V) {
599 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
600 }
601
602 const VPBlockBase *getEntry() const { return Entry; }
603 VPBlockBase *getEntry() { return Entry; }
604
605 const VPBlockBase *getExit() const { return Exit; }
606 VPBlockBase *getExit() { return Exit; }
607
608 /// An indicator whether this region is to generate multiple replicated
609 /// instances of output IR corresponding to its VPBlockBases.
610 bool isReplicator() const { return IsReplicator; }
611
612 /// The method which generates the output IR instructions that correspond to
613 /// this VPRegionBlock, thereby "executing" the VPlan.
614 void execute(struct VPTransformState *State) override;
615};
616
617/// VPlan models a candidate for vectorization, encoding various decisions take
618/// to produce efficient output IR, including which branches, basic-blocks and
619/// output IR instructions to generate, and their cost. VPlan holds a
620/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
621/// VPBlock.
622class VPlan {
623private:
624 /// Hold the single entry to the Hierarchical CFG of the VPlan.
625 VPBlockBase *Entry;
626
627 /// Holds the VFs applicable to this VPlan.
628 SmallSet<unsigned, 2> VFs;
629
630 /// Holds the name of the VPlan, for printing.
631 std::string Name;
632
633public:
634 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
635
636 ~VPlan() {
637 if (Entry)
638 VPBlockBase::deleteCFG(Entry);
639 }
640
641 /// Generate the IR code for this VPlan.
642 void execute(struct VPTransformState *State);
643
644 VPBlockBase *getEntry() { return Entry; }
645 const VPBlockBase *getEntry() const { return Entry; }
646
647 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
648
649 void addVF(unsigned VF) { VFs.insert(VF); }
650
651 bool hasVF(unsigned VF) { return VFs.count(VF); }
652
653 const std::string &getName() const { return Name; }
654
655 void setName(const Twine &newName) { Name = newName.str(); }
656
657private:
658 /// Add to the given dominator tree the header block and every new basic block
659 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000660 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000661 BasicBlock *LoopPreHeaderBB,
662 BasicBlock *LoopLatchBB);
663};
664
665/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
666/// indented and follows the dot format.
667class VPlanPrinter {
668 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
669 friend inline raw_ostream &operator<<(raw_ostream &OS,
670 const struct VPlanIngredient &I);
671
672private:
673 raw_ostream &OS;
674 VPlan &Plan;
675 unsigned Depth;
676 unsigned TabWidth = 2;
677 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000678 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000679 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
680
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000681 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
682
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000683 /// Handle indentation.
684 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
685
686 /// Print a given \p Block of the Plan.
687 void dumpBlock(const VPBlockBase *Block);
688
689 /// Print the information related to the CFG edges going out of a given
690 /// \p Block, followed by printing the successor blocks themselves.
691 void dumpEdges(const VPBlockBase *Block);
692
693 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
694 /// its successor blocks.
695 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
696
697 /// Print a given \p Region of the Plan.
698 void dumpRegion(const VPRegionBlock *Region);
699
700 unsigned getOrCreateBID(const VPBlockBase *Block) {
701 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
702 }
703
704 const Twine getOrCreateName(const VPBlockBase *Block);
705
706 const Twine getUID(const VPBlockBase *Block);
707
708 /// Print the information related to a CFG edge between two VPBlockBases.
709 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
710 const Twine &Label);
711
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000712 void dump();
713
714 static void printAsIngredient(raw_ostream &O, Value *V);
715};
716
717struct VPlanIngredient {
718 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000719
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000720 VPlanIngredient(Value *V) : V(V) {}
721};
722
723inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
724 VPlanPrinter::printAsIngredient(OS, I.V);
725 return OS;
726}
727
728inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
729 VPlanPrinter Printer(OS, Plan);
730 Printer.dump();
731 return OS;
732}
733
734//===--------------------------------------------------------------------===//
735// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
736//===--------------------------------------------------------------------===//
737
738// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
739// graph of VPBlockBase nodes...
740
741template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000742 using NodeRef = VPBlockBase *;
743 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000744
745 static NodeRef getEntryNode(NodeRef N) { return N; }
746
747 static inline ChildIteratorType child_begin(NodeRef N) {
748 return N->getSuccessors().begin();
749 }
750
751 static inline ChildIteratorType child_end(NodeRef N) {
752 return N->getSuccessors().end();
753 }
754};
755
756template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000757 using NodeRef = const VPBlockBase *;
758 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000759
760 static NodeRef getEntryNode(NodeRef N) { return N; }
761
762 static inline ChildIteratorType child_begin(NodeRef N) {
763 return N->getSuccessors().begin();
764 }
765
766 static inline ChildIteratorType child_end(NodeRef N) {
767 return N->getSuccessors().end();
768 }
769};
770
771// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
772// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
773// for a VPBlockBase is considered to be when traversing the predecessors of a
774// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000775template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000776 using NodeRef = VPBlockBase *;
777 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000778
779 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
780 return B;
781 }
782
783 static inline ChildIteratorType child_begin(NodeRef N) {
784 return N->getPredecessors().begin();
785 }
786
787 static inline ChildIteratorType child_end(NodeRef N) {
788 return N->getPredecessors().end();
789 }
790};
791
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000792} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000793
794#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H