blob: 6bc49dbbcb601445b0adb28dcdad4eb494ecf676 [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;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000018/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
19/// instruction;
20/// 5. The VPlan class holding a candidate for vectorization;
21/// 6. The VPlanPrinter class providing a way to print a plan in dot format;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000022/// These are documented in docs/VectorizationPlan.rst.
Eugene Zelenko6cadde72017-10-17 21:27:42 +000023//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000024//===----------------------------------------------------------------------===//
25
26#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
28
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000029#include "VPlanValue.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000030#include "llvm/ADT/DenseMap.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000031#include "llvm/ADT/GraphTraits.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000032#include "llvm/ADT/Optional.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000033#include "llvm/ADT/SmallPtrSet.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000034#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000035#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000037#include "llvm/ADT/ilist.h"
38#include "llvm/ADT/ilist_node.h"
39#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000040#include <algorithm>
41#include <cassert>
42#include <cstddef>
43#include <map>
44#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000045
46namespace llvm {
47
Hal Finkel0f1314c2018-01-07 16:02:58 +000048class LoopVectorizationLegality;
49class LoopVectorizationCostModel;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000050class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000051class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000052class InnerLoopVectorizer;
Hal Finkel7333aa92017-12-16 01:12:50 +000053class InterleaveGroup;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000054class LoopInfo;
55class raw_ostream;
56class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000057class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000058class VPRegionBlock;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000059class VPlan;
60
61/// A range of powers-of-2 vectorization factors with fixed start and
62/// adjustable end. The range includes start and excludes end, e.g.,:
63/// [1, 9) = {1, 2, 4, 8}
64struct VFRange {
65 // A power of 2.
66 const unsigned Start;
67
68 // Need not be a power of 2. If End <= Start range is empty.
69 unsigned End;
70};
71
72using VPlanPtr = std::unique_ptr<VPlan>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000073
74/// In what follows, the term "input IR" refers to code that is fed into the
75/// vectorizer whereas the term "output IR" refers to code that is generated by
76/// the vectorizer.
77
78/// VPIteration represents a single point in the iteration space of the output
79/// (vectorized and/or unrolled) IR loop.
80struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000081 /// in [0..UF)
82 unsigned Part;
83
84 /// in [0..VF)
85 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000086};
87
88/// This is a helper struct for maintaining vectorization state. It's used for
89/// mapping values from the original loop to their corresponding values in
90/// the new loop. Two mappings are maintained: one for vectorized values and
91/// one for scalarized values. Vectorized values are represented with UF
92/// vector values in the new loop, and scalarized values are represented with
93/// UF x VF scalar values in the new loop. UF and VF are the unroll and
94/// vectorization factors, respectively.
95///
96/// Entries can be added to either map with setVectorValue and setScalarValue,
97/// which assert that an entry was not already added before. If an entry is to
98/// replace an existing one, call resetVectorValue and resetScalarValue. This is
99/// currently needed to modify the mapped values during "fix-up" operations that
100/// occur once the first phase of widening is complete. These operations include
101/// type truncation and the second phase of recurrence widening.
102///
103/// Entries from either map can be retrieved using the getVectorValue and
104/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000105struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000106 friend struct VPTransformState;
107
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000108private:
109 /// The unroll factor. Each entry in the vector map contains UF vector values.
110 unsigned UF;
111
112 /// The vectorization factor. Each entry in the scalar map contains UF x VF
113 /// scalar values.
114 unsigned VF;
115
116 /// The vector and scalar map storage. We use std::map and not DenseMap
117 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000118 using VectorParts = SmallVector<Value *, 2>;
119 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000120 std::map<Value *, VectorParts> VectorMapStorage;
121 std::map<Value *, ScalarParts> ScalarMapStorage;
122
123public:
124 /// Construct an empty map with the given unroll and vectorization factors.
125 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
126
127 /// \return True if the map has any vector entry for \p Key.
128 bool hasAnyVectorValue(Value *Key) const {
129 return VectorMapStorage.count(Key);
130 }
131
132 /// \return True if the map has a vector entry for \p Key and \p Part.
133 bool hasVectorValue(Value *Key, unsigned Part) const {
134 assert(Part < UF && "Queried Vector Part is too large.");
135 if (!hasAnyVectorValue(Key))
136 return false;
137 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
138 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
139 return Entry[Part] != nullptr;
140 }
141
142 /// \return True if the map has any scalar entry for \p Key.
143 bool hasAnyScalarValue(Value *Key) const {
144 return ScalarMapStorage.count(Key);
145 }
146
147 /// \return True if the map has a scalar entry for \p Key and \p Instance.
148 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
149 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
150 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
151 if (!hasAnyScalarValue(Key))
152 return false;
153 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
154 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
155 assert(Entry[Instance.Part].size() == VF &&
156 "ScalarParts has wrong dimensions.");
157 return Entry[Instance.Part][Instance.Lane] != nullptr;
158 }
159
160 /// Retrieve the existing vector value that corresponds to \p Key and
161 /// \p Part.
162 Value *getVectorValue(Value *Key, unsigned Part) {
163 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
164 return VectorMapStorage[Key][Part];
165 }
166
167 /// Retrieve the existing scalar value that corresponds to \p Key and
168 /// \p Instance.
169 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
170 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
171 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
172 }
173
174 /// Set a vector value associated with \p Key and \p Part. Assumes such a
175 /// value is not already set. If it is, use resetVectorValue() instead.
176 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
177 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
178 if (!VectorMapStorage.count(Key)) {
179 VectorParts Entry(UF);
180 VectorMapStorage[Key] = Entry;
181 }
182 VectorMapStorage[Key][Part] = Vector;
183 }
184
185 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
186 /// value is not already set.
187 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
188 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
189 if (!ScalarMapStorage.count(Key)) {
190 ScalarParts Entry(UF);
191 // TODO: Consider storing uniform values only per-part, as they occupy
192 // lane 0 only, keeping the other VF-1 redundant entries null.
193 for (unsigned Part = 0; Part < UF; ++Part)
194 Entry[Part].resize(VF, nullptr);
195 ScalarMapStorage[Key] = Entry;
196 }
197 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
198 }
199
200 /// Reset the vector value associated with \p Key for the given \p Part.
201 /// This function can be used to update values that have already been
202 /// vectorized. This is the case for "fix-up" operations including type
203 /// truncation and the second phase of recurrence vectorization.
204 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
205 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
206 VectorMapStorage[Key][Part] = Vector;
207 }
208
209 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
210 /// This function can be used to update values that have already been
211 /// scalarized. This is the case for "fix-up" operations including scalar phi
212 /// nodes for scalarized and predicated instructions.
213 void resetScalarValue(Value *Key, const VPIteration &Instance,
214 Value *Scalar) {
215 assert(hasScalarValue(Key, Instance) &&
216 "Scalar value not set for part and lane");
217 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
218 }
219};
220
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000221/// This class is used to enable the VPlan to invoke a method of ILV. This is
222/// needed until the method is refactored out of ILV and becomes reusable.
223struct VPCallback {
224 virtual ~VPCallback() {}
225 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
226};
227
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000228/// VPTransformState holds information passed down when "executing" a VPlan,
229/// needed for generating the output IR.
230struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000231 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
232 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000233 InnerLoopVectorizer *ILV, VPCallback &Callback)
234 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
235 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000236
237 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
238 unsigned VF;
239 unsigned UF;
240
241 /// Hold the indices to generate specific scalar instructions. Null indicates
242 /// that all instances are to be generated, using either scalar or vector
243 /// instructions.
244 Optional<VPIteration> Instance;
245
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000246 struct DataState {
247 /// A type for vectorized values in the new loop. Each value from the
248 /// original loop, when vectorized, is represented by UF vector values in
249 /// the new unrolled loop, where UF is the unroll factor.
250 typedef SmallVector<Value *, 2> PerPartValuesTy;
251
252 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
253 } Data;
254
255 /// Get the generated Value for a given VPValue and a given Part. Note that
256 /// as some Defs are still created by ILV and managed in its ValueMap, this
257 /// method will delegate the call to ILV in such cases in order to provide
258 /// callers a consistent API.
259 /// \see set.
260 Value *get(VPValue *Def, unsigned Part) {
261 // If Values have been set for this Def return the one relevant for \p Part.
262 if (Data.PerPartOutput.count(Def))
263 return Data.PerPartOutput[Def][Part];
264 // Def is managed by ILV: bring the Values from ValueMap.
265 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
266 }
267
268 /// Set the generated Value for a given VPValue and a given Part.
269 void set(VPValue *Def, Value *V, unsigned Part) {
270 if (!Data.PerPartOutput.count(Def)) {
271 DataState::PerPartValuesTy Entry(UF);
272 Data.PerPartOutput[Def] = Entry;
273 }
274 Data.PerPartOutput[Def][Part] = V;
275 }
276
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000277 /// Hold state information used when constructing the CFG of the output IR,
278 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
279 struct CFGState {
280 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000281 VPBasicBlock *PrevVPBB = nullptr;
282
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000283 /// The previous IR BasicBlock created or used. Initially set to the new
284 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000285 BasicBlock *PrevBB = nullptr;
286
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000287 /// The last IR BasicBlock in the output IR. Set to the new latch
288 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000289 BasicBlock *LastBB = nullptr;
290
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000291 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
292 /// of replication, maps the BasicBlock of the last replica created.
293 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
294
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000295 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000296 } CFG;
297
298 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000299 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000300
301 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000302 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000303
304 /// Hold a reference to the IRBuilder used to generate output IR code.
305 IRBuilder<> &Builder;
306
307 /// Hold a reference to the Value state information used when generating the
308 /// Values of the output IR.
309 VectorizerValueMap &ValueMap;
310
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000311 /// Hold a reference to a mapping between VPValues in VPlan and original
312 /// Values they correspond to.
313 VPValue2ValueTy VPValue2Value;
314
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000315 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000316 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000317
318 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000319};
320
321/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
322/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
323class VPBlockBase {
Diego Caballero168d04d2018-05-21 18:14:23 +0000324 friend class VPBlockUtils;
325
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000326private:
327 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
328
329 /// An optional name for the block.
330 std::string Name;
331
332 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
333 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000334 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000335
336 /// List of predecessor blocks.
337 SmallVector<VPBlockBase *, 1> Predecessors;
338
339 /// List of successor blocks.
340 SmallVector<VPBlockBase *, 1> Successors;
341
342 /// Add \p Successor as the last successor to this block.
343 void appendSuccessor(VPBlockBase *Successor) {
344 assert(Successor && "Cannot add nullptr successor!");
345 Successors.push_back(Successor);
346 }
347
348 /// Add \p Predecessor as the last predecessor to this block.
349 void appendPredecessor(VPBlockBase *Predecessor) {
350 assert(Predecessor && "Cannot add nullptr predecessor!");
351 Predecessors.push_back(Predecessor);
352 }
353
354 /// Remove \p Predecessor from the predecessors of this block.
355 void removePredecessor(VPBlockBase *Predecessor) {
356 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
357 assert(Pos && "Predecessor does not exist");
358 Predecessors.erase(Pos);
359 }
360
361 /// Remove \p Successor from the successors of this block.
362 void removeSuccessor(VPBlockBase *Successor) {
363 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
364 assert(Pos && "Successor does not exist");
365 Successors.erase(Pos);
366 }
367
368protected:
369 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000370 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000371
372public:
373 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
374 /// that are actually instantiated. Values of this enumeration are kept in the
375 /// SubclassID field of the VPBlockBase objects. They are used for concrete
376 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000377 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000378
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000379 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000380
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000381 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000382
383 const std::string &getName() const { return Name; }
384
385 void setName(const Twine &newName) { Name = newName.str(); }
386
387 /// \return an ID for the concrete type of this object.
388 /// This is used to implement the classof checks. This should not be used
389 /// for any other purpose, as the values may change as LLVM evolves.
390 unsigned getVPBlockID() const { return SubclassID; }
391
Diego Caballero168d04d2018-05-21 18:14:23 +0000392 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000393 const VPRegionBlock *getParent() const { return Parent; }
394
395 void setParent(VPRegionBlock *P) { Parent = P; }
396
397 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
398 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
399 /// VPBlockBase is a VPBasicBlock, it is returned.
400 const VPBasicBlock *getEntryBasicBlock() const;
401 VPBasicBlock *getEntryBasicBlock();
402
403 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
404 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
405 /// VPBlockBase is a VPBasicBlock, it is returned.
406 const VPBasicBlock *getExitBasicBlock() const;
407 VPBasicBlock *getExitBasicBlock();
408
409 const VPBlocksTy &getSuccessors() const { return Successors; }
410 VPBlocksTy &getSuccessors() { return Successors; }
411
412 const VPBlocksTy &getPredecessors() const { return Predecessors; }
413 VPBlocksTy &getPredecessors() { return Predecessors; }
414
415 /// \return the successor of this VPBlockBase if it has a single successor.
416 /// Otherwise return a null pointer.
417 VPBlockBase *getSingleSuccessor() const {
418 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
419 }
420
421 /// \return the predecessor of this VPBlockBase if it has a single
422 /// predecessor. Otherwise return a null pointer.
423 VPBlockBase *getSinglePredecessor() const {
424 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
425 }
426
Diego Caballero168d04d2018-05-21 18:14:23 +0000427 size_t getNumSuccessors() const { return Successors.size(); }
428 size_t getNumPredecessors() const { return Predecessors.size(); }
429
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000430 /// An Enclosing Block of a block B is any block containing B, including B
431 /// itself. \return the closest enclosing block starting from "this", which
432 /// has successors. \return the root enclosing block if all enclosing blocks
433 /// have no successors.
434 VPBlockBase *getEnclosingBlockWithSuccessors();
435
436 /// \return the closest enclosing block starting from "this", which has
437 /// predecessors. \return the root enclosing block if all enclosing blocks
438 /// have no predecessors.
439 VPBlockBase *getEnclosingBlockWithPredecessors();
440
441 /// \return the successors either attached directly to this VPBlockBase or, if
442 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
443 /// successors of its own, search recursively for the first enclosing
444 /// VPRegionBlock that has successors and return them. If no such
445 /// VPRegionBlock exists, return the (empty) successors of the topmost
446 /// VPBlockBase reached.
447 const VPBlocksTy &getHierarchicalSuccessors() {
448 return getEnclosingBlockWithSuccessors()->getSuccessors();
449 }
450
451 /// \return the hierarchical successor of this VPBlockBase if it has a single
452 /// hierarchical successor. Otherwise return a null pointer.
453 VPBlockBase *getSingleHierarchicalSuccessor() {
454 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
455 }
456
457 /// \return the predecessors either attached directly to this VPBlockBase or,
458 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
459 /// predecessors of its own, search recursively for the first enclosing
460 /// VPRegionBlock that has predecessors and return them. If no such
461 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
462 /// VPBlockBase reached.
463 const VPBlocksTy &getHierarchicalPredecessors() {
464 return getEnclosingBlockWithPredecessors()->getPredecessors();
465 }
466
467 /// \return the hierarchical predecessor of this VPBlockBase if it has a
468 /// single hierarchical predecessor. Otherwise return a null pointer.
469 VPBlockBase *getSingleHierarchicalPredecessor() {
470 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
471 }
472
Diego Caballero168d04d2018-05-21 18:14:23 +0000473 /// Set a given VPBlockBase \p Successor as the single successor of this
474 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
475 /// This VPBlockBase must have no successors.
476 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000477 assert(Successors.empty() && "Setting one successor when others exist.");
478 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000479 }
480
Diego Caballero168d04d2018-05-21 18:14:23 +0000481 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
482 /// successors of this VPBlockBase. This VPBlockBase is not added as
483 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
484 /// successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000485 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
486 assert(Successors.empty() && "Setting two successors when others exist.");
487 appendSuccessor(IfTrue);
488 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000489 }
490
Diego Caballero168d04d2018-05-21 18:14:23 +0000491 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
492 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
493 /// as successor of any VPBasicBlock in \p NewPreds.
494 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
495 assert(Predecessors.empty() && "Block predecessors already set.");
496 for (auto *Pred : NewPreds)
497 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000498 }
499
500 /// The method which generates the output IR that correspond to this
501 /// VPBlockBase, thereby "executing" the VPlan.
502 virtual void execute(struct VPTransformState *State) = 0;
503
504 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
505 static void deleteCFG(VPBlockBase *Entry);
506};
507
508/// VPRecipeBase is a base class modeling a sequence of one or more output IR
509/// instructions.
510class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
511 friend VPBasicBlock;
512
513private:
514 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
515
516 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000517 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000518
519public:
520 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
521 /// that is actually instantiated. Values of this enumeration are kept in the
522 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
523 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000524 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000525 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000526 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000527 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000528 VPInterleaveSC,
529 VPPredInstPHISC,
530 VPReplicateSC,
531 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000532 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000533 VPWidenPHISC,
534 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000535 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000536
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000537 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
538 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000539
540 /// \return an ID for the concrete type of this object.
541 /// This is used to implement the classof checks. This should not be used
542 /// for any other purpose, as the values may change as LLVM evolves.
543 unsigned getVPRecipeID() const { return SubclassID; }
544
545 /// \return the VPBasicBlock which this VPRecipe belongs to.
546 VPBasicBlock *getParent() { return Parent; }
547 const VPBasicBlock *getParent() const { return Parent; }
548
549 /// The method which generates the output IR instructions that correspond to
550 /// this VPRecipe, thereby "executing" the VPlan.
551 virtual void execute(struct VPTransformState &State) = 0;
552
553 /// Each recipe prints itself.
554 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
555};
556
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000557/// This is a concrete Recipe that models a single VPlan-level instruction.
558/// While as any Recipe it may generate a sequence of IR instructions when
559/// executed, these instructions would always form a single-def expression as
560/// the VPInstruction is also a single def-use vertex.
561class VPInstruction : public VPUser, public VPRecipeBase {
562public:
563 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
564 enum { Not = Instruction::OtherOpsEnd + 1 };
565
566private:
567 typedef unsigned char OpcodeTy;
568 OpcodeTy Opcode;
569
570 /// Utility method serving execute(): generates a single instance of the
571 /// modeled instruction.
572 void generateInstruction(VPTransformState &State, unsigned Part);
573
574public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000575 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000576 : VPUser(VPValue::VPInstructionSC, Operands),
577 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
578
Diego Caballero168d04d2018-05-21 18:14:23 +0000579 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
580 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
581
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000582 /// Method to support type inquiry through isa, cast, and dyn_cast.
583 static inline bool classof(const VPValue *V) {
584 return V->getVPValueID() == VPValue::VPInstructionSC;
585 }
586
587 /// Method to support type inquiry through isa, cast, and dyn_cast.
588 static inline bool classof(const VPRecipeBase *R) {
589 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
590 }
591
592 unsigned getOpcode() const { return Opcode; }
593
594 /// Generate the instruction.
595 /// TODO: We currently execute only per-part unless a specific instance is
596 /// provided.
597 void execute(VPTransformState &State) override;
598
599 /// Print the Recipe.
600 void print(raw_ostream &O, const Twine &Indent) const override;
601
602 /// Print the VPInstruction.
603 void print(raw_ostream &O) const;
604};
605
Hal Finkel7333aa92017-12-16 01:12:50 +0000606/// VPWidenRecipe is a recipe for producing a copy of vector type for each
607/// Instruction in its ingredients independently, in order. This recipe covers
608/// most of the traditional vectorization cases where each ingredient transforms
609/// into a vectorized version of itself.
610class VPWidenRecipe : public VPRecipeBase {
611private:
612 /// Hold the ingredients by pointing to their original BasicBlock location.
613 BasicBlock::iterator Begin;
614 BasicBlock::iterator End;
615
616public:
617 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
618 End = I->getIterator();
619 Begin = End++;
620 }
621
622 ~VPWidenRecipe() override = default;
623
624 /// Method to support type inquiry through isa, cast, and dyn_cast.
625 static inline bool classof(const VPRecipeBase *V) {
626 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
627 }
628
629 /// Produce widened copies of all Ingredients.
630 void execute(VPTransformState &State) override;
631
632 /// Augment the recipe to include Instr, if it lies at its End.
633 bool appendInstruction(Instruction *Instr) {
634 if (End != Instr->getIterator())
635 return false;
636 End++;
637 return true;
638 }
639
640 /// Print the recipe.
641 void print(raw_ostream &O, const Twine &Indent) const override;
642};
643
644/// A recipe for handling phi nodes of integer and floating-point inductions,
645/// producing their vector and scalar values.
646class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
647private:
648 PHINode *IV;
649 TruncInst *Trunc;
650
651public:
652 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
653 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
654 ~VPWidenIntOrFpInductionRecipe() override = default;
655
656 /// Method to support type inquiry through isa, cast, and dyn_cast.
657 static inline bool classof(const VPRecipeBase *V) {
658 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
659 }
660
661 /// Generate the vectorized and scalarized versions of the phi node as
662 /// needed by their users.
663 void execute(VPTransformState &State) override;
664
665 /// Print the recipe.
666 void print(raw_ostream &O, const Twine &Indent) const override;
667};
668
669/// A recipe for handling all phi nodes except for integer and FP inductions.
670class VPWidenPHIRecipe : public VPRecipeBase {
671private:
672 PHINode *Phi;
673
674public:
675 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
676 ~VPWidenPHIRecipe() override = default;
677
678 /// Method to support type inquiry through isa, cast, and dyn_cast.
679 static inline bool classof(const VPRecipeBase *V) {
680 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
681 }
682
683 /// Generate the phi/select nodes.
684 void execute(VPTransformState &State) override;
685
686 /// Print the recipe.
687 void print(raw_ostream &O, const Twine &Indent) const override;
688};
689
690/// A recipe for vectorizing a phi-node as a sequence of mask-based select
691/// instructions.
692class VPBlendRecipe : public VPRecipeBase {
693private:
694 PHINode *Phi;
695
696 /// The blend operation is a User of a mask, if not null.
697 std::unique_ptr<VPUser> User;
698
699public:
700 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
701 : VPRecipeBase(VPBlendSC), Phi(Phi) {
702 assert((Phi->getNumIncomingValues() == 1 ||
703 Phi->getNumIncomingValues() == Masks.size()) &&
704 "Expected the same number of incoming values and masks");
705 if (!Masks.empty())
706 User.reset(new VPUser(Masks));
707 }
708
709 /// Method to support type inquiry through isa, cast, and dyn_cast.
710 static inline bool classof(const VPRecipeBase *V) {
711 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
712 }
713
714 /// Generate the phi/select nodes.
715 void execute(VPTransformState &State) override;
716
717 /// Print the recipe.
718 void print(raw_ostream &O, const Twine &Indent) const override;
719};
720
721/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
722/// or stores into one wide load/store and shuffles.
723class VPInterleaveRecipe : public VPRecipeBase {
724private:
725 const InterleaveGroup *IG;
726
727public:
728 VPInterleaveRecipe(const InterleaveGroup *IG)
729 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
730 ~VPInterleaveRecipe() override = default;
731
732 /// Method to support type inquiry through isa, cast, and dyn_cast.
733 static inline bool classof(const VPRecipeBase *V) {
734 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
735 }
736
737 /// Generate the wide load or store, and shuffles.
738 void execute(VPTransformState &State) override;
739
740 /// Print the recipe.
741 void print(raw_ostream &O, const Twine &Indent) const override;
742
743 const InterleaveGroup *getInterleaveGroup() { return IG; }
744};
745
746/// VPReplicateRecipe replicates a given instruction producing multiple scalar
747/// copies of the original scalar type, one per lane, instead of producing a
748/// single copy of widened type for all lanes. If the instruction is known to be
749/// uniform only one copy, per lane zero, will be generated.
750class VPReplicateRecipe : public VPRecipeBase {
751private:
752 /// The instruction being replicated.
753 Instruction *Ingredient;
754
755 /// Indicator if only a single replica per lane is needed.
756 bool IsUniform;
757
758 /// Indicator if the replicas are also predicated.
759 bool IsPredicated;
760
761 /// Indicator if the scalar values should also be packed into a vector.
762 bool AlsoPack;
763
764public:
765 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
766 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
767 IsPredicated(IsPredicated) {
768 // Retain the previous behavior of predicateInstructions(), where an
769 // insert-element of a predicated instruction got hoisted into the
770 // predicated basic block iff it was its only user. This is achieved by
771 // having predicated instructions also pack their values into a vector by
772 // default unless they have a replicated user which uses their scalar value.
773 AlsoPack = IsPredicated && !I->use_empty();
774 }
775
776 ~VPReplicateRecipe() override = default;
777
778 /// Method to support type inquiry through isa, cast, and dyn_cast.
779 static inline bool classof(const VPRecipeBase *V) {
780 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
781 }
782
783 /// Generate replicas of the desired Ingredient. Replicas will be generated
784 /// for all parts and lanes unless a specific part and lane are specified in
785 /// the \p State.
786 void execute(VPTransformState &State) override;
787
788 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
789
790 /// Print the recipe.
791 void print(raw_ostream &O, const Twine &Indent) const override;
792};
793
794/// A recipe for generating conditional branches on the bits of a mask.
795class VPBranchOnMaskRecipe : public VPRecipeBase {
796private:
797 std::unique_ptr<VPUser> User;
798
799public:
800 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
801 if (BlockInMask) // nullptr means all-one mask.
802 User.reset(new VPUser({BlockInMask}));
803 }
804
805 /// Method to support type inquiry through isa, cast, and dyn_cast.
806 static inline bool classof(const VPRecipeBase *V) {
807 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
808 }
809
810 /// Generate the extraction of the appropriate bit from the block mask and the
811 /// conditional branch.
812 void execute(VPTransformState &State) override;
813
814 /// Print the recipe.
815 void print(raw_ostream &O, const Twine &Indent) const override {
816 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
817 if (User)
818 O << *User->getOperand(0);
819 else
820 O << " All-One";
821 O << "\\l\"";
822 }
823};
824
825/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
826/// control converges back from a Branch-on-Mask. The phi nodes are needed in
827/// order to merge values that are set under such a branch and feed their uses.
828/// The phi nodes can be scalar or vector depending on the users of the value.
829/// This recipe works in concert with VPBranchOnMaskRecipe.
830class VPPredInstPHIRecipe : public VPRecipeBase {
831private:
832 Instruction *PredInst;
833
834public:
835 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
836 /// nodes after merging back from a Branch-on-Mask.
837 VPPredInstPHIRecipe(Instruction *PredInst)
838 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
839 ~VPPredInstPHIRecipe() override = default;
840
841 /// Method to support type inquiry through isa, cast, and dyn_cast.
842 static inline bool classof(const VPRecipeBase *V) {
843 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
844 }
845
846 /// Generates phi nodes for live-outs as needed to retain SSA form.
847 void execute(VPTransformState &State) override;
848
849 /// Print the recipe.
850 void print(raw_ostream &O, const Twine &Indent) const override;
851};
852
853/// A Recipe for widening load/store operations.
854/// TODO: We currently execute only per-part unless a specific instance is
855/// provided.
856class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
857private:
858 Instruction &Instr;
859 std::unique_ptr<VPUser> User;
860
861public:
862 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
863 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
864 if (Mask) // Create a VPInstruction to register as a user of the mask.
865 User.reset(new VPUser({Mask}));
866 }
867
868 /// Method to support type inquiry through isa, cast, and dyn_cast.
869 static inline bool classof(const VPRecipeBase *V) {
870 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
871 }
872
873 /// Generate the wide load/store.
874 void execute(VPTransformState &State) override;
875
876 /// Print the recipe.
877 void print(raw_ostream &O, const Twine &Indent) const override;
878};
879
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000880/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
881/// holds a sequence of zero or more VPRecipe's each representing a sequence of
882/// output IR instructions.
883class VPBasicBlock : public VPBlockBase {
884public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000885 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000886
887private:
888 /// The VPRecipes held in the order of output instructions to generate.
889 RecipeListTy Recipes;
890
891public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000892 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
893 : VPBlockBase(VPBasicBlockSC, Name.str()) {
894 if (Recipe)
895 appendRecipe(Recipe);
896 }
897
898 ~VPBasicBlock() override { Recipes.clear(); }
899
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000900 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000901 using iterator = RecipeListTy::iterator;
902 using const_iterator = RecipeListTy::const_iterator;
903 using reverse_iterator = RecipeListTy::reverse_iterator;
904 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000905
906 //===--------------------------------------------------------------------===//
907 /// Recipe iterator methods
908 ///
909 inline iterator begin() { return Recipes.begin(); }
910 inline const_iterator begin() const { return Recipes.begin(); }
911 inline iterator end() { return Recipes.end(); }
912 inline const_iterator end() const { return Recipes.end(); }
913
914 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
915 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
916 inline reverse_iterator rend() { return Recipes.rend(); }
917 inline const_reverse_iterator rend() const { return Recipes.rend(); }
918
919 inline size_t size() const { return Recipes.size(); }
920 inline bool empty() const { return Recipes.empty(); }
921 inline const VPRecipeBase &front() const { return Recipes.front(); }
922 inline VPRecipeBase &front() { return Recipes.front(); }
923 inline const VPRecipeBase &back() const { return Recipes.back(); }
924 inline VPRecipeBase &back() { return Recipes.back(); }
925
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000926 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000927 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
928 return &VPBasicBlock::Recipes;
929 }
930
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000931 /// Method to support type inquiry through isa, cast, and dyn_cast.
932 static inline bool classof(const VPBlockBase *V) {
933 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
934 }
935
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000936 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000937 assert(Recipe && "No recipe to append.");
938 assert(!Recipe->Parent && "Recipe already in VPlan");
939 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000940 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000941 }
942
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000943 /// Augment the existing recipes of a VPBasicBlock with an additional
944 /// \p Recipe as the last recipe.
945 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
946
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000947 /// The method which generates the output IR instructions that correspond to
948 /// this VPBasicBlock, thereby "executing" the VPlan.
949 void execute(struct VPTransformState *State) override;
950
951private:
952 /// Create an IR BasicBlock to hold the output instructions generated by this
953 /// VPBasicBlock, and return it. Update the CFGState accordingly.
954 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
955};
956
957/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
958/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
959/// A VPRegionBlock may indicate that its contents are to be replicated several
960/// times. This is designed to support predicated scalarization, in which a
961/// scalar if-then code structure needs to be generated VF * UF times. Having
962/// this replication indicator helps to keep a single model for multiple
963/// candidate VF's. The actual replication takes place only once the desired VF
964/// and UF have been determined.
965class VPRegionBlock : public VPBlockBase {
966private:
967 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
968 VPBlockBase *Entry;
969
970 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
971 VPBlockBase *Exit;
972
973 /// An indicator whether this region is to generate multiple replicated
974 /// instances of output IR corresponding to its VPBlockBases.
975 bool IsReplicator;
976
977public:
978 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
979 const std::string &Name = "", bool IsReplicator = false)
980 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
981 IsReplicator(IsReplicator) {
982 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
983 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
984 Entry->setParent(this);
985 Exit->setParent(this);
986 }
Diego Caballero168d04d2018-05-21 18:14:23 +0000987 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
988 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
989 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000990
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000991 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000992 if (Entry)
993 deleteCFG(Entry);
994 }
995
996 /// Method to support type inquiry through isa, cast, and dyn_cast.
997 static inline bool classof(const VPBlockBase *V) {
998 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
999 }
1000
1001 const VPBlockBase *getEntry() const { return Entry; }
1002 VPBlockBase *getEntry() { return Entry; }
1003
Diego Caballero168d04d2018-05-21 18:14:23 +00001004 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1005 /// EntryBlock must have no predecessors.
1006 void setEntry(VPBlockBase *EntryBlock) {
1007 assert(EntryBlock->getPredecessors().empty() &&
1008 "Entry block cannot have predecessors.");
1009 Entry = EntryBlock;
1010 EntryBlock->setParent(this);
1011 }
1012
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001013 const VPBlockBase *getExit() const { return Exit; }
1014 VPBlockBase *getExit() { return Exit; }
1015
Diego Caballero168d04d2018-05-21 18:14:23 +00001016 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1017 /// ExitBlock must have no successors.
1018 void setExit(VPBlockBase *ExitBlock) {
1019 assert(ExitBlock->getSuccessors().empty() &&
1020 "Exit block cannot have successors.");
1021 Exit = ExitBlock;
1022 ExitBlock->setParent(this);
1023 }
1024
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001025 /// An indicator whether this region is to generate multiple replicated
1026 /// instances of output IR corresponding to its VPBlockBases.
1027 bool isReplicator() const { return IsReplicator; }
1028
1029 /// The method which generates the output IR instructions that correspond to
1030 /// this VPRegionBlock, thereby "executing" the VPlan.
1031 void execute(struct VPTransformState *State) override;
1032};
1033
1034/// VPlan models a candidate for vectorization, encoding various decisions take
1035/// to produce efficient output IR, including which branches, basic-blocks and
1036/// output IR instructions to generate, and their cost. VPlan holds a
1037/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1038/// VPBlock.
1039class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001040 friend class VPlanPrinter;
1041
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001042private:
1043 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1044 VPBlockBase *Entry;
1045
1046 /// Holds the VFs applicable to this VPlan.
1047 SmallSet<unsigned, 2> VFs;
1048
1049 /// Holds the name of the VPlan, for printing.
1050 std::string Name;
1051
Diego Caballero168d04d2018-05-21 18:14:23 +00001052 /// Holds all the external definitions created for this VPlan.
1053 // TODO: Introduce a specific representation for external definitions in
1054 // VPlan. External definitions must be immutable and hold a pointer to its
1055 // underlying IR that will be used to implement its structural comparison
1056 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001057 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001058
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001059 /// Holds a mapping between Values and their corresponding VPValue inside
1060 /// VPlan.
1061 Value2VPValueTy Value2VPValue;
1062
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001063public:
1064 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1065
1066 ~VPlan() {
1067 if (Entry)
1068 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001069 for (auto &MapEntry : Value2VPValue)
1070 delete MapEntry.second;
Diego Caballero168d04d2018-05-21 18:14:23 +00001071 for (VPValue *Def : VPExternalDefs)
1072 delete Def;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001073 }
1074
1075 /// Generate the IR code for this VPlan.
1076 void execute(struct VPTransformState *State);
1077
1078 VPBlockBase *getEntry() { return Entry; }
1079 const VPBlockBase *getEntry() const { return Entry; }
1080
1081 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1082
1083 void addVF(unsigned VF) { VFs.insert(VF); }
1084
1085 bool hasVF(unsigned VF) { return VFs.count(VF); }
1086
1087 const std::string &getName() const { return Name; }
1088
1089 void setName(const Twine &newName) { Name = newName.str(); }
1090
Diego Caballero168d04d2018-05-21 18:14:23 +00001091 /// Add \p VPVal to the pool of external definitions if it's not already
1092 /// in the pool.
1093 void addExternalDef(VPValue *VPVal) {
1094 VPExternalDefs.insert(VPVal);
1095 }
1096
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001097 void addVPValue(Value *V) {
1098 assert(V && "Trying to add a null Value to VPlan");
1099 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1100 Value2VPValue[V] = new VPValue();
1101 }
1102
1103 VPValue *getVPValue(Value *V) {
1104 assert(V && "Trying to get the VPValue of a null Value");
1105 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1106 return Value2VPValue[V];
1107 }
1108
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001109private:
1110 /// Add to the given dominator tree the header block and every new basic block
1111 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001112 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001113 BasicBlock *LoopPreHeaderBB,
1114 BasicBlock *LoopLatchBB);
1115};
1116
1117/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1118/// indented and follows the dot format.
1119class VPlanPrinter {
1120 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1121 friend inline raw_ostream &operator<<(raw_ostream &OS,
1122 const struct VPlanIngredient &I);
1123
1124private:
1125 raw_ostream &OS;
1126 VPlan &Plan;
1127 unsigned Depth;
1128 unsigned TabWidth = 2;
1129 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001130 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001131 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1132
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001133 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1134
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001135 /// Handle indentation.
1136 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1137
1138 /// Print a given \p Block of the Plan.
1139 void dumpBlock(const VPBlockBase *Block);
1140
1141 /// Print the information related to the CFG edges going out of a given
1142 /// \p Block, followed by printing the successor blocks themselves.
1143 void dumpEdges(const VPBlockBase *Block);
1144
1145 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1146 /// its successor blocks.
1147 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1148
1149 /// Print a given \p Region of the Plan.
1150 void dumpRegion(const VPRegionBlock *Region);
1151
1152 unsigned getOrCreateBID(const VPBlockBase *Block) {
1153 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1154 }
1155
1156 const Twine getOrCreateName(const VPBlockBase *Block);
1157
1158 const Twine getUID(const VPBlockBase *Block);
1159
1160 /// Print the information related to a CFG edge between two VPBlockBases.
1161 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1162 const Twine &Label);
1163
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001164 void dump();
1165
1166 static void printAsIngredient(raw_ostream &O, Value *V);
1167};
1168
1169struct VPlanIngredient {
1170 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001171
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001172 VPlanIngredient(Value *V) : V(V) {}
1173};
1174
1175inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1176 VPlanPrinter::printAsIngredient(OS, I.V);
1177 return OS;
1178}
1179
1180inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1181 VPlanPrinter Printer(OS, Plan);
1182 Printer.dump();
1183 return OS;
1184}
1185
1186//===--------------------------------------------------------------------===//
1187// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
1188//===--------------------------------------------------------------------===//
1189
1190// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1191// graph of VPBlockBase nodes...
1192
1193template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001194 using NodeRef = VPBlockBase *;
1195 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001196
1197 static NodeRef getEntryNode(NodeRef N) { return N; }
1198
1199 static inline ChildIteratorType child_begin(NodeRef N) {
1200 return N->getSuccessors().begin();
1201 }
1202
1203 static inline ChildIteratorType child_end(NodeRef N) {
1204 return N->getSuccessors().end();
1205 }
1206};
1207
1208template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001209 using NodeRef = const VPBlockBase *;
1210 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001211
1212 static NodeRef getEntryNode(NodeRef N) { return N; }
1213
1214 static inline ChildIteratorType child_begin(NodeRef N) {
1215 return N->getSuccessors().begin();
1216 }
1217
1218 static inline ChildIteratorType child_end(NodeRef N) {
1219 return N->getSuccessors().end();
1220 }
1221};
1222
1223// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1224// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
1225// for a VPBlockBase is considered to be when traversing the predecessors of a
1226// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001227template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001228 using NodeRef = VPBlockBase *;
1229 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001230
1231 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
1232 return B;
1233 }
1234
1235 static inline ChildIteratorType child_begin(NodeRef N) {
1236 return N->getPredecessors().begin();
1237 }
1238
1239 static inline ChildIteratorType child_end(NodeRef N) {
1240 return N->getPredecessors().end();
1241 }
1242};
1243
Diego Caballero168d04d2018-05-21 18:14:23 +00001244//===----------------------------------------------------------------------===//
1245// VPlan Utilities
1246//===----------------------------------------------------------------------===//
1247
1248/// Class that provides utilities for VPBlockBases in VPlan.
1249class VPBlockUtils {
1250public:
1251 VPBlockUtils() = delete;
1252
1253 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1254 /// NewBlock as successor of \p BlockPtr and \p Block as predecessor of \p
1255 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p NewBlock
1256 /// must have neither successors nor predecessors.
1257 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1258 assert(NewBlock->getSuccessors().empty() &&
1259 "Can't insert new block with successors.");
1260 // TODO: move successors from BlockPtr to NewBlock when this functionality
1261 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1262 // already has successors.
1263 BlockPtr->setOneSuccessor(NewBlock);
1264 NewBlock->setPredecessors({BlockPtr});
1265 NewBlock->setParent(BlockPtr->getParent());
1266 }
1267
1268 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1269 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1270 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1271 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
1272 /// and \p IfTrue and \p IfFalse must have neither successors nor
1273 /// predecessors.
1274 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1275 VPBlockBase *BlockPtr) {
1276 assert(IfTrue->getSuccessors().empty() &&
1277 "Can't insert IfTrue with successors.");
1278 assert(IfFalse->getSuccessors().empty() &&
1279 "Can't insert IfFalse with successors.");
1280 BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
1281 IfTrue->setPredecessors({BlockPtr});
1282 IfFalse->setPredecessors({BlockPtr});
1283 IfTrue->setParent(BlockPtr->getParent());
1284 IfFalse->setParent(BlockPtr->getParent());
1285 }
1286
1287 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1288 /// the successors of \p From and \p From to the predecessors of \p To. Both
1289 /// VPBlockBases must have the same parent, which can be null. Both
1290 /// VPBlockBases can be already connected to other VPBlockBases.
1291 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1292 assert((From->getParent() == To->getParent()) &&
1293 "Can't connect two block with different parents");
1294 assert(From->getNumSuccessors() < 2 &&
1295 "Blocks can't have more than two successors.");
1296 From->appendSuccessor(To);
1297 To->appendPredecessor(From);
1298 }
1299
1300 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1301 /// from the successors of \p From and \p From from the predecessors of \p To.
1302 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1303 assert(To && "Successor to disconnect is null.");
1304 From->removeSuccessor(To);
1305 To->removePredecessor(From);
1306 }
1307};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001308
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001309} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001310
1311#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H