blob: a39eda0c08c9432d6a48e1ce214d213ea91b2ccf [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"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000033#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000036#include "llvm/ADT/ilist.h"
37#include "llvm/ADT/ilist_node.h"
38#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000039#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <map>
43#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000044
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000045// The (re)use of existing LoopVectorize classes is subject to future VPlan
46// refactoring.
47namespace {
48class LoopVectorizationLegality;
49class LoopVectorizationCostModel;
50} // namespace
51
Ayal Zaks1f58dda2017-08-27 12:55:46 +000052namespace llvm {
53
Ayal Zaks1f58dda2017-08-27 12:55:46 +000054class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000055class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000056class InnerLoopVectorizer;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000057class LoopInfo;
58class raw_ostream;
59class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000060class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000061class VPRegionBlock;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000062
63/// In what follows, the term "input IR" refers to code that is fed into the
64/// vectorizer whereas the term "output IR" refers to code that is generated by
65/// the vectorizer.
66
67/// VPIteration represents a single point in the iteration space of the output
68/// (vectorized and/or unrolled) IR loop.
69struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000070 /// in [0..UF)
71 unsigned Part;
72
73 /// in [0..VF)
74 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000075};
76
77/// This is a helper struct for maintaining vectorization state. It's used for
78/// mapping values from the original loop to their corresponding values in
79/// the new loop. Two mappings are maintained: one for vectorized values and
80/// one for scalarized values. Vectorized values are represented with UF
81/// vector values in the new loop, and scalarized values are represented with
82/// UF x VF scalar values in the new loop. UF and VF are the unroll and
83/// vectorization factors, respectively.
84///
85/// Entries can be added to either map with setVectorValue and setScalarValue,
86/// which assert that an entry was not already added before. If an entry is to
87/// replace an existing one, call resetVectorValue and resetScalarValue. This is
88/// currently needed to modify the mapped values during "fix-up" operations that
89/// occur once the first phase of widening is complete. These operations include
90/// type truncation and the second phase of recurrence widening.
91///
92/// Entries from either map can be retrieved using the getVectorValue and
93/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +000094struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000095 friend struct VPTransformState;
96
Ayal Zaks1f58dda2017-08-27 12:55:46 +000097private:
98 /// The unroll factor. Each entry in the vector map contains UF vector values.
99 unsigned UF;
100
101 /// The vectorization factor. Each entry in the scalar map contains UF x VF
102 /// scalar values.
103 unsigned VF;
104
105 /// The vector and scalar map storage. We use std::map and not DenseMap
106 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000107 using VectorParts = SmallVector<Value *, 2>;
108 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000109 std::map<Value *, VectorParts> VectorMapStorage;
110 std::map<Value *, ScalarParts> ScalarMapStorage;
111
112public:
113 /// Construct an empty map with the given unroll and vectorization factors.
114 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
115
116 /// \return True if the map has any vector entry for \p Key.
117 bool hasAnyVectorValue(Value *Key) const {
118 return VectorMapStorage.count(Key);
119 }
120
121 /// \return True if the map has a vector entry for \p Key and \p Part.
122 bool hasVectorValue(Value *Key, unsigned Part) const {
123 assert(Part < UF && "Queried Vector Part is too large.");
124 if (!hasAnyVectorValue(Key))
125 return false;
126 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
127 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
128 return Entry[Part] != nullptr;
129 }
130
131 /// \return True if the map has any scalar entry for \p Key.
132 bool hasAnyScalarValue(Value *Key) const {
133 return ScalarMapStorage.count(Key);
134 }
135
136 /// \return True if the map has a scalar entry for \p Key and \p Instance.
137 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
138 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
139 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
140 if (!hasAnyScalarValue(Key))
141 return false;
142 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
143 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
144 assert(Entry[Instance.Part].size() == VF &&
145 "ScalarParts has wrong dimensions.");
146 return Entry[Instance.Part][Instance.Lane] != nullptr;
147 }
148
149 /// Retrieve the existing vector value that corresponds to \p Key and
150 /// \p Part.
151 Value *getVectorValue(Value *Key, unsigned Part) {
152 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
153 return VectorMapStorage[Key][Part];
154 }
155
156 /// Retrieve the existing scalar value that corresponds to \p Key and
157 /// \p Instance.
158 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
159 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
160 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
161 }
162
163 /// Set a vector value associated with \p Key and \p Part. Assumes such a
164 /// value is not already set. If it is, use resetVectorValue() instead.
165 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
166 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
167 if (!VectorMapStorage.count(Key)) {
168 VectorParts Entry(UF);
169 VectorMapStorage[Key] = Entry;
170 }
171 VectorMapStorage[Key][Part] = Vector;
172 }
173
174 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
175 /// value is not already set.
176 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
177 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
178 if (!ScalarMapStorage.count(Key)) {
179 ScalarParts Entry(UF);
180 // TODO: Consider storing uniform values only per-part, as they occupy
181 // lane 0 only, keeping the other VF-1 redundant entries null.
182 for (unsigned Part = 0; Part < UF; ++Part)
183 Entry[Part].resize(VF, nullptr);
184 ScalarMapStorage[Key] = Entry;
185 }
186 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
187 }
188
189 /// Reset the vector value associated with \p Key for the given \p Part.
190 /// This function can be used to update values that have already been
191 /// vectorized. This is the case for "fix-up" operations including type
192 /// truncation and the second phase of recurrence vectorization.
193 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
194 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
195 VectorMapStorage[Key][Part] = Vector;
196 }
197
198 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
199 /// This function can be used to update values that have already been
200 /// scalarized. This is the case for "fix-up" operations including scalar phi
201 /// nodes for scalarized and predicated instructions.
202 void resetScalarValue(Value *Key, const VPIteration &Instance,
203 Value *Scalar) {
204 assert(hasScalarValue(Key, Instance) &&
205 "Scalar value not set for part and lane");
206 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
207 }
208};
209
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000210/// This class is used to enable the VPlan to invoke a method of ILV. This is
211/// needed until the method is refactored out of ILV and becomes reusable.
212struct VPCallback {
213 virtual ~VPCallback() {}
214 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
215};
216
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000217/// VPTransformState holds information passed down when "executing" a VPlan,
218/// needed for generating the output IR.
219struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000220 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
221 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000222 InnerLoopVectorizer *ILV, VPCallback &Callback)
223 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
224 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000225
226 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
227 unsigned VF;
228 unsigned UF;
229
230 /// Hold the indices to generate specific scalar instructions. Null indicates
231 /// that all instances are to be generated, using either scalar or vector
232 /// instructions.
233 Optional<VPIteration> Instance;
234
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000235 struct DataState {
236 /// A type for vectorized values in the new loop. Each value from the
237 /// original loop, when vectorized, is represented by UF vector values in
238 /// the new unrolled loop, where UF is the unroll factor.
239 typedef SmallVector<Value *, 2> PerPartValuesTy;
240
241 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
242 } Data;
243
244 /// Get the generated Value for a given VPValue and a given Part. Note that
245 /// as some Defs are still created by ILV and managed in its ValueMap, this
246 /// method will delegate the call to ILV in such cases in order to provide
247 /// callers a consistent API.
248 /// \see set.
249 Value *get(VPValue *Def, unsigned Part) {
250 // If Values have been set for this Def return the one relevant for \p Part.
251 if (Data.PerPartOutput.count(Def))
252 return Data.PerPartOutput[Def][Part];
253 // Def is managed by ILV: bring the Values from ValueMap.
254 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
255 }
256
257 /// Set the generated Value for a given VPValue and a given Part.
258 void set(VPValue *Def, Value *V, unsigned Part) {
259 if (!Data.PerPartOutput.count(Def)) {
260 DataState::PerPartValuesTy Entry(UF);
261 Data.PerPartOutput[Def] = Entry;
262 }
263 Data.PerPartOutput[Def][Part] = V;
264 }
265
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000266 /// Hold state information used when constructing the CFG of the output IR,
267 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
268 struct CFGState {
269 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000270 VPBasicBlock *PrevVPBB = nullptr;
271
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000272 /// The previous IR BasicBlock created or used. Initially set to the new
273 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000274 BasicBlock *PrevBB = nullptr;
275
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000276 /// The last IR BasicBlock in the output IR. Set to the new latch
277 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000278 BasicBlock *LastBB = nullptr;
279
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000280 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
281 /// of replication, maps the BasicBlock of the last replica created.
282 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
283
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000284 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000285 } CFG;
286
287 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000288 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000289
290 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000291 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000292
293 /// Hold a reference to the IRBuilder used to generate output IR code.
294 IRBuilder<> &Builder;
295
296 /// Hold a reference to the Value state information used when generating the
297 /// Values of the output IR.
298 VectorizerValueMap &ValueMap;
299
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000300 /// Hold a reference to a mapping between VPValues in VPlan and original
301 /// Values they correspond to.
302 VPValue2ValueTy VPValue2Value;
303
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000304 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000305 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000306
307 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000308};
309
310/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
311/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
312class VPBlockBase {
313private:
314 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
315
316 /// An optional name for the block.
317 std::string Name;
318
319 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
320 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000321 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000322
323 /// List of predecessor blocks.
324 SmallVector<VPBlockBase *, 1> Predecessors;
325
326 /// List of successor blocks.
327 SmallVector<VPBlockBase *, 1> Successors;
328
329 /// Add \p Successor as the last successor to this block.
330 void appendSuccessor(VPBlockBase *Successor) {
331 assert(Successor && "Cannot add nullptr successor!");
332 Successors.push_back(Successor);
333 }
334
335 /// Add \p Predecessor as the last predecessor to this block.
336 void appendPredecessor(VPBlockBase *Predecessor) {
337 assert(Predecessor && "Cannot add nullptr predecessor!");
338 Predecessors.push_back(Predecessor);
339 }
340
341 /// Remove \p Predecessor from the predecessors of this block.
342 void removePredecessor(VPBlockBase *Predecessor) {
343 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
344 assert(Pos && "Predecessor does not exist");
345 Predecessors.erase(Pos);
346 }
347
348 /// Remove \p Successor from the successors of this block.
349 void removeSuccessor(VPBlockBase *Successor) {
350 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
351 assert(Pos && "Successor does not exist");
352 Successors.erase(Pos);
353 }
354
355protected:
356 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000357 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000358
359public:
360 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
361 /// that are actually instantiated. Values of this enumeration are kept in the
362 /// SubclassID field of the VPBlockBase objects. They are used for concrete
363 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000364 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000365
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000366 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000367
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000368 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000369
370 const std::string &getName() const { return Name; }
371
372 void setName(const Twine &newName) { Name = newName.str(); }
373
374 /// \return an ID for the concrete type of this object.
375 /// This is used to implement the classof checks. This should not be used
376 /// for any other purpose, as the values may change as LLVM evolves.
377 unsigned getVPBlockID() const { return SubclassID; }
378
379 const VPRegionBlock *getParent() const { return Parent; }
380
381 void setParent(VPRegionBlock *P) { Parent = P; }
382
383 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
384 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
385 /// VPBlockBase is a VPBasicBlock, it is returned.
386 const VPBasicBlock *getEntryBasicBlock() const;
387 VPBasicBlock *getEntryBasicBlock();
388
389 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
390 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
391 /// VPBlockBase is a VPBasicBlock, it is returned.
392 const VPBasicBlock *getExitBasicBlock() const;
393 VPBasicBlock *getExitBasicBlock();
394
395 const VPBlocksTy &getSuccessors() const { return Successors; }
396 VPBlocksTy &getSuccessors() { return Successors; }
397
398 const VPBlocksTy &getPredecessors() const { return Predecessors; }
399 VPBlocksTy &getPredecessors() { return Predecessors; }
400
401 /// \return the successor of this VPBlockBase if it has a single successor.
402 /// Otherwise return a null pointer.
403 VPBlockBase *getSingleSuccessor() const {
404 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
405 }
406
407 /// \return the predecessor of this VPBlockBase if it has a single
408 /// predecessor. Otherwise return a null pointer.
409 VPBlockBase *getSinglePredecessor() const {
410 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
411 }
412
413 /// An Enclosing Block of a block B is any block containing B, including B
414 /// itself. \return the closest enclosing block starting from "this", which
415 /// has successors. \return the root enclosing block if all enclosing blocks
416 /// have no successors.
417 VPBlockBase *getEnclosingBlockWithSuccessors();
418
419 /// \return the closest enclosing block starting from "this", which has
420 /// predecessors. \return the root enclosing block if all enclosing blocks
421 /// have no predecessors.
422 VPBlockBase *getEnclosingBlockWithPredecessors();
423
424 /// \return the successors either attached directly to this VPBlockBase or, if
425 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
426 /// successors of its own, search recursively for the first enclosing
427 /// VPRegionBlock that has successors and return them. If no such
428 /// VPRegionBlock exists, return the (empty) successors of the topmost
429 /// VPBlockBase reached.
430 const VPBlocksTy &getHierarchicalSuccessors() {
431 return getEnclosingBlockWithSuccessors()->getSuccessors();
432 }
433
434 /// \return the hierarchical successor of this VPBlockBase if it has a single
435 /// hierarchical successor. Otherwise return a null pointer.
436 VPBlockBase *getSingleHierarchicalSuccessor() {
437 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
438 }
439
440 /// \return the predecessors either attached directly to this VPBlockBase or,
441 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
442 /// predecessors of its own, search recursively for the first enclosing
443 /// VPRegionBlock that has predecessors and return them. If no such
444 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
445 /// VPBlockBase reached.
446 const VPBlocksTy &getHierarchicalPredecessors() {
447 return getEnclosingBlockWithPredecessors()->getPredecessors();
448 }
449
450 /// \return the hierarchical predecessor of this VPBlockBase if it has a
451 /// single hierarchical predecessor. Otherwise return a null pointer.
452 VPBlockBase *getSingleHierarchicalPredecessor() {
453 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
454 }
455
456 /// Sets a given VPBlockBase \p Successor as the single successor and \return
457 /// \p Successor. The parent of this Block is copied to be the parent of
458 /// \p Successor.
459 VPBlockBase *setOneSuccessor(VPBlockBase *Successor) {
460 assert(Successors.empty() && "Setting one successor when others exist.");
461 appendSuccessor(Successor);
462 Successor->appendPredecessor(this);
463 Successor->Parent = Parent;
464 return Successor;
465 }
466
467 /// Sets two given VPBlockBases \p IfTrue and \p IfFalse to be the two
468 /// successors. The parent of this Block is copied to be the parent of both
469 /// \p IfTrue and \p IfFalse.
470 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
471 assert(Successors.empty() && "Setting two successors when others exist.");
472 appendSuccessor(IfTrue);
473 appendSuccessor(IfFalse);
474 IfTrue->appendPredecessor(this);
475 IfFalse->appendPredecessor(this);
476 IfTrue->Parent = Parent;
477 IfFalse->Parent = Parent;
478 }
479
480 void disconnectSuccessor(VPBlockBase *Successor) {
481 assert(Successor && "Successor to disconnect is null.");
482 removeSuccessor(Successor);
483 Successor->removePredecessor(this);
484 }
485
486 /// The method which generates the output IR that correspond to this
487 /// VPBlockBase, thereby "executing" the VPlan.
488 virtual void execute(struct VPTransformState *State) = 0;
489
490 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
491 static void deleteCFG(VPBlockBase *Entry);
492};
493
494/// VPRecipeBase is a base class modeling a sequence of one or more output IR
495/// instructions.
496class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
497 friend VPBasicBlock;
498
499private:
500 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
501
502 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000503 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000504
505public:
506 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
507 /// that is actually instantiated. Values of this enumeration are kept in the
508 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
509 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000510 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000511 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000512 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000513 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000514 VPInterleaveSC,
515 VPPredInstPHISC,
516 VPReplicateSC,
517 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000518 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000519 VPWidenPHISC,
520 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000521 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000522
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000523 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
524 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000525
526 /// \return an ID for the concrete type of this object.
527 /// This is used to implement the classof checks. This should not be used
528 /// for any other purpose, as the values may change as LLVM evolves.
529 unsigned getVPRecipeID() const { return SubclassID; }
530
531 /// \return the VPBasicBlock which this VPRecipe belongs to.
532 VPBasicBlock *getParent() { return Parent; }
533 const VPBasicBlock *getParent() const { return Parent; }
534
535 /// The method which generates the output IR instructions that correspond to
536 /// this VPRecipe, thereby "executing" the VPlan.
537 virtual void execute(struct VPTransformState &State) = 0;
538
539 /// Each recipe prints itself.
540 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
541};
542
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000543/// This is a concrete Recipe that models a single VPlan-level instruction.
544/// While as any Recipe it may generate a sequence of IR instructions when
545/// executed, these instructions would always form a single-def expression as
546/// the VPInstruction is also a single def-use vertex.
547class VPInstruction : public VPUser, public VPRecipeBase {
548public:
549 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
550 enum { Not = Instruction::OtherOpsEnd + 1 };
551
552private:
553 typedef unsigned char OpcodeTy;
554 OpcodeTy Opcode;
555
556 /// Utility method serving execute(): generates a single instance of the
557 /// modeled instruction.
558 void generateInstruction(VPTransformState &State, unsigned Part);
559
560public:
561 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
562 : VPUser(VPValue::VPInstructionSC, Operands),
563 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
564
565 /// Method to support type inquiry through isa, cast, and dyn_cast.
566 static inline bool classof(const VPValue *V) {
567 return V->getVPValueID() == VPValue::VPInstructionSC;
568 }
569
570 /// Method to support type inquiry through isa, cast, and dyn_cast.
571 static inline bool classof(const VPRecipeBase *R) {
572 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
573 }
574
575 unsigned getOpcode() const { return Opcode; }
576
577 /// Generate the instruction.
578 /// TODO: We currently execute only per-part unless a specific instance is
579 /// provided.
580 void execute(VPTransformState &State) override;
581
582 /// Print the Recipe.
583 void print(raw_ostream &O, const Twine &Indent) const override;
584
585 /// Print the VPInstruction.
586 void print(raw_ostream &O) const;
587};
588
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000589/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
590/// holds a sequence of zero or more VPRecipe's each representing a sequence of
591/// output IR instructions.
592class VPBasicBlock : public VPBlockBase {
593public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000594 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000595
596private:
597 /// The VPRecipes held in the order of output instructions to generate.
598 RecipeListTy Recipes;
599
600public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000601 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
602 : VPBlockBase(VPBasicBlockSC, Name.str()) {
603 if (Recipe)
604 appendRecipe(Recipe);
605 }
606
607 ~VPBasicBlock() override { Recipes.clear(); }
608
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000609 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000610 using iterator = RecipeListTy::iterator;
611 using const_iterator = RecipeListTy::const_iterator;
612 using reverse_iterator = RecipeListTy::reverse_iterator;
613 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000614
615 //===--------------------------------------------------------------------===//
616 /// Recipe iterator methods
617 ///
618 inline iterator begin() { return Recipes.begin(); }
619 inline const_iterator begin() const { return Recipes.begin(); }
620 inline iterator end() { return Recipes.end(); }
621 inline const_iterator end() const { return Recipes.end(); }
622
623 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
624 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
625 inline reverse_iterator rend() { return Recipes.rend(); }
626 inline const_reverse_iterator rend() const { return Recipes.rend(); }
627
628 inline size_t size() const { return Recipes.size(); }
629 inline bool empty() const { return Recipes.empty(); }
630 inline const VPRecipeBase &front() const { return Recipes.front(); }
631 inline VPRecipeBase &front() { return Recipes.front(); }
632 inline const VPRecipeBase &back() const { return Recipes.back(); }
633 inline VPRecipeBase &back() { return Recipes.back(); }
634
635 /// \brief Returns a pointer to a member of the recipe list.
636 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
637 return &VPBasicBlock::Recipes;
638 }
639
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000640 /// Method to support type inquiry through isa, cast, and dyn_cast.
641 static inline bool classof(const VPBlockBase *V) {
642 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
643 }
644
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000645 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000646 assert(Recipe && "No recipe to append.");
647 assert(!Recipe->Parent && "Recipe already in VPlan");
648 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000649 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000650 }
651
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000652 /// Augment the existing recipes of a VPBasicBlock with an additional
653 /// \p Recipe as the last recipe.
654 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
655
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000656 /// The method which generates the output IR instructions that correspond to
657 /// this VPBasicBlock, thereby "executing" the VPlan.
658 void execute(struct VPTransformState *State) override;
659
660private:
661 /// Create an IR BasicBlock to hold the output instructions generated by this
662 /// VPBasicBlock, and return it. Update the CFGState accordingly.
663 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
664};
665
666/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
667/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
668/// A VPRegionBlock may indicate that its contents are to be replicated several
669/// times. This is designed to support predicated scalarization, in which a
670/// scalar if-then code structure needs to be generated VF * UF times. Having
671/// this replication indicator helps to keep a single model for multiple
672/// candidate VF's. The actual replication takes place only once the desired VF
673/// and UF have been determined.
674class VPRegionBlock : public VPBlockBase {
675private:
676 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
677 VPBlockBase *Entry;
678
679 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
680 VPBlockBase *Exit;
681
682 /// An indicator whether this region is to generate multiple replicated
683 /// instances of output IR corresponding to its VPBlockBases.
684 bool IsReplicator;
685
686public:
687 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
688 const std::string &Name = "", bool IsReplicator = false)
689 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
690 IsReplicator(IsReplicator) {
691 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
692 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
693 Entry->setParent(this);
694 Exit->setParent(this);
695 }
696
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000697 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000698 if (Entry)
699 deleteCFG(Entry);
700 }
701
702 /// Method to support type inquiry through isa, cast, and dyn_cast.
703 static inline bool classof(const VPBlockBase *V) {
704 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
705 }
706
707 const VPBlockBase *getEntry() const { return Entry; }
708 VPBlockBase *getEntry() { return Entry; }
709
710 const VPBlockBase *getExit() const { return Exit; }
711 VPBlockBase *getExit() { return Exit; }
712
713 /// An indicator whether this region is to generate multiple replicated
714 /// instances of output IR corresponding to its VPBlockBases.
715 bool isReplicator() const { return IsReplicator; }
716
717 /// The method which generates the output IR instructions that correspond to
718 /// this VPRegionBlock, thereby "executing" the VPlan.
719 void execute(struct VPTransformState *State) override;
720};
721
722/// VPlan models a candidate for vectorization, encoding various decisions take
723/// to produce efficient output IR, including which branches, basic-blocks and
724/// output IR instructions to generate, and their cost. VPlan holds a
725/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
726/// VPBlock.
727class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000728 friend class VPlanPrinter;
729
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000730private:
731 /// Hold the single entry to the Hierarchical CFG of the VPlan.
732 VPBlockBase *Entry;
733
734 /// Holds the VFs applicable to this VPlan.
735 SmallSet<unsigned, 2> VFs;
736
737 /// Holds the name of the VPlan, for printing.
738 std::string Name;
739
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000740 /// Holds a mapping between Values and their corresponding VPValue inside
741 /// VPlan.
742 Value2VPValueTy Value2VPValue;
743
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000744public:
745 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
746
747 ~VPlan() {
748 if (Entry)
749 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000750 for (auto &MapEntry : Value2VPValue)
751 delete MapEntry.second;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000752 }
753
754 /// Generate the IR code for this VPlan.
755 void execute(struct VPTransformState *State);
756
757 VPBlockBase *getEntry() { return Entry; }
758 const VPBlockBase *getEntry() const { return Entry; }
759
760 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
761
762 void addVF(unsigned VF) { VFs.insert(VF); }
763
764 bool hasVF(unsigned VF) { return VFs.count(VF); }
765
766 const std::string &getName() const { return Name; }
767
768 void setName(const Twine &newName) { Name = newName.str(); }
769
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000770 void addVPValue(Value *V) {
771 assert(V && "Trying to add a null Value to VPlan");
772 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
773 Value2VPValue[V] = new VPValue();
774 }
775
776 VPValue *getVPValue(Value *V) {
777 assert(V && "Trying to get the VPValue of a null Value");
778 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
779 return Value2VPValue[V];
780 }
781
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000782private:
783 /// Add to the given dominator tree the header block and every new basic block
784 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000785 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000786 BasicBlock *LoopPreHeaderBB,
787 BasicBlock *LoopLatchBB);
788};
789
790/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
791/// indented and follows the dot format.
792class VPlanPrinter {
793 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
794 friend inline raw_ostream &operator<<(raw_ostream &OS,
795 const struct VPlanIngredient &I);
796
797private:
798 raw_ostream &OS;
799 VPlan &Plan;
800 unsigned Depth;
801 unsigned TabWidth = 2;
802 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000803 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000804 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
805
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000806 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
807
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000808 /// Handle indentation.
809 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
810
811 /// Print a given \p Block of the Plan.
812 void dumpBlock(const VPBlockBase *Block);
813
814 /// Print the information related to the CFG edges going out of a given
815 /// \p Block, followed by printing the successor blocks themselves.
816 void dumpEdges(const VPBlockBase *Block);
817
818 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
819 /// its successor blocks.
820 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
821
822 /// Print a given \p Region of the Plan.
823 void dumpRegion(const VPRegionBlock *Region);
824
825 unsigned getOrCreateBID(const VPBlockBase *Block) {
826 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
827 }
828
829 const Twine getOrCreateName(const VPBlockBase *Block);
830
831 const Twine getUID(const VPBlockBase *Block);
832
833 /// Print the information related to a CFG edge between two VPBlockBases.
834 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
835 const Twine &Label);
836
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000837 void dump();
838
839 static void printAsIngredient(raw_ostream &O, Value *V);
840};
841
842struct VPlanIngredient {
843 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000844
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000845 VPlanIngredient(Value *V) : V(V) {}
846};
847
848inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
849 VPlanPrinter::printAsIngredient(OS, I.V);
850 return OS;
851}
852
853inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
854 VPlanPrinter Printer(OS, Plan);
855 Printer.dump();
856 return OS;
857}
858
859//===--------------------------------------------------------------------===//
860// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
861//===--------------------------------------------------------------------===//
862
863// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
864// graph of VPBlockBase nodes...
865
866template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000867 using NodeRef = VPBlockBase *;
868 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000869
870 static NodeRef getEntryNode(NodeRef N) { return N; }
871
872 static inline ChildIteratorType child_begin(NodeRef N) {
873 return N->getSuccessors().begin();
874 }
875
876 static inline ChildIteratorType child_end(NodeRef N) {
877 return N->getSuccessors().end();
878 }
879};
880
881template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000882 using NodeRef = const VPBlockBase *;
883 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000884
885 static NodeRef getEntryNode(NodeRef N) { return N; }
886
887 static inline ChildIteratorType child_begin(NodeRef N) {
888 return N->getSuccessors().begin();
889 }
890
891 static inline ChildIteratorType child_end(NodeRef N) {
892 return N->getSuccessors().end();
893 }
894};
895
896// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
897// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
898// for a VPBlockBase is considered to be when traversing the predecessors of a
899// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000900template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000901 using NodeRef = VPBlockBase *;
902 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000903
904 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
905 return B;
906 }
907
908 static inline ChildIteratorType child_begin(NodeRef N) {
909 return N->getPredecessors().begin();
910 }
911
912 static inline ChildIteratorType child_end(NodeRef N) {
913 return N->getPredecessors().end();
914 }
915};
916
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000917} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000918
919#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H