blob: 2ccabfd6af252f733aeed99960effdf71f89de1a [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;
Hal Finkel7333aa92017-12-16 01:12:50 +000057class InterleaveGroup;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000058class LoopInfo;
59class raw_ostream;
60class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000061class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000062class VPRegionBlock;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000063
64/// In what follows, the term "input IR" refers to code that is fed into the
65/// vectorizer whereas the term "output IR" refers to code that is generated by
66/// the vectorizer.
67
68/// VPIteration represents a single point in the iteration space of the output
69/// (vectorized and/or unrolled) IR loop.
70struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000071 /// in [0..UF)
72 unsigned Part;
73
74 /// in [0..VF)
75 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000076};
77
78/// This is a helper struct for maintaining vectorization state. It's used for
79/// mapping values from the original loop to their corresponding values in
80/// the new loop. Two mappings are maintained: one for vectorized values and
81/// one for scalarized values. Vectorized values are represented with UF
82/// vector values in the new loop, and scalarized values are represented with
83/// UF x VF scalar values in the new loop. UF and VF are the unroll and
84/// vectorization factors, respectively.
85///
86/// Entries can be added to either map with setVectorValue and setScalarValue,
87/// which assert that an entry was not already added before. If an entry is to
88/// replace an existing one, call resetVectorValue and resetScalarValue. This is
89/// currently needed to modify the mapped values during "fix-up" operations that
90/// occur once the first phase of widening is complete. These operations include
91/// type truncation and the second phase of recurrence widening.
92///
93/// Entries from either map can be retrieved using the getVectorValue and
94/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +000095struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000096 friend struct VPTransformState;
97
Ayal Zaks1f58dda2017-08-27 12:55:46 +000098private:
99 /// The unroll factor. Each entry in the vector map contains UF vector values.
100 unsigned UF;
101
102 /// The vectorization factor. Each entry in the scalar map contains UF x VF
103 /// scalar values.
104 unsigned VF;
105
106 /// The vector and scalar map storage. We use std::map and not DenseMap
107 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000108 using VectorParts = SmallVector<Value *, 2>;
109 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000110 std::map<Value *, VectorParts> VectorMapStorage;
111 std::map<Value *, ScalarParts> ScalarMapStorage;
112
113public:
114 /// Construct an empty map with the given unroll and vectorization factors.
115 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
116
117 /// \return True if the map has any vector entry for \p Key.
118 bool hasAnyVectorValue(Value *Key) const {
119 return VectorMapStorage.count(Key);
120 }
121
122 /// \return True if the map has a vector entry for \p Key and \p Part.
123 bool hasVectorValue(Value *Key, unsigned Part) const {
124 assert(Part < UF && "Queried Vector Part is too large.");
125 if (!hasAnyVectorValue(Key))
126 return false;
127 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
128 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
129 return Entry[Part] != nullptr;
130 }
131
132 /// \return True if the map has any scalar entry for \p Key.
133 bool hasAnyScalarValue(Value *Key) const {
134 return ScalarMapStorage.count(Key);
135 }
136
137 /// \return True if the map has a scalar entry for \p Key and \p Instance.
138 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
139 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
140 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
141 if (!hasAnyScalarValue(Key))
142 return false;
143 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
144 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
145 assert(Entry[Instance.Part].size() == VF &&
146 "ScalarParts has wrong dimensions.");
147 return Entry[Instance.Part][Instance.Lane] != nullptr;
148 }
149
150 /// Retrieve the existing vector value that corresponds to \p Key and
151 /// \p Part.
152 Value *getVectorValue(Value *Key, unsigned Part) {
153 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
154 return VectorMapStorage[Key][Part];
155 }
156
157 /// Retrieve the existing scalar value that corresponds to \p Key and
158 /// \p Instance.
159 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
160 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
161 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
162 }
163
164 /// Set a vector value associated with \p Key and \p Part. Assumes such a
165 /// value is not already set. If it is, use resetVectorValue() instead.
166 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
167 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
168 if (!VectorMapStorage.count(Key)) {
169 VectorParts Entry(UF);
170 VectorMapStorage[Key] = Entry;
171 }
172 VectorMapStorage[Key][Part] = Vector;
173 }
174
175 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
176 /// value is not already set.
177 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
178 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
179 if (!ScalarMapStorage.count(Key)) {
180 ScalarParts Entry(UF);
181 // TODO: Consider storing uniform values only per-part, as they occupy
182 // lane 0 only, keeping the other VF-1 redundant entries null.
183 for (unsigned Part = 0; Part < UF; ++Part)
184 Entry[Part].resize(VF, nullptr);
185 ScalarMapStorage[Key] = Entry;
186 }
187 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
188 }
189
190 /// Reset the vector value associated with \p Key for the given \p Part.
191 /// This function can be used to update values that have already been
192 /// vectorized. This is the case for "fix-up" operations including type
193 /// truncation and the second phase of recurrence vectorization.
194 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
195 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
196 VectorMapStorage[Key][Part] = Vector;
197 }
198
199 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
200 /// This function can be used to update values that have already been
201 /// scalarized. This is the case for "fix-up" operations including scalar phi
202 /// nodes for scalarized and predicated instructions.
203 void resetScalarValue(Value *Key, const VPIteration &Instance,
204 Value *Scalar) {
205 assert(hasScalarValue(Key, Instance) &&
206 "Scalar value not set for part and lane");
207 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
208 }
209};
210
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000211/// This class is used to enable the VPlan to invoke a method of ILV. This is
212/// needed until the method is refactored out of ILV and becomes reusable.
213struct VPCallback {
214 virtual ~VPCallback() {}
215 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
216};
217
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000218/// VPTransformState holds information passed down when "executing" a VPlan,
219/// needed for generating the output IR.
220struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000221 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
222 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000223 InnerLoopVectorizer *ILV, VPCallback &Callback)
224 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
225 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000226
227 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
228 unsigned VF;
229 unsigned UF;
230
231 /// Hold the indices to generate specific scalar instructions. Null indicates
232 /// that all instances are to be generated, using either scalar or vector
233 /// instructions.
234 Optional<VPIteration> Instance;
235
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000236 struct DataState {
237 /// A type for vectorized values in the new loop. Each value from the
238 /// original loop, when vectorized, is represented by UF vector values in
239 /// the new unrolled loop, where UF is the unroll factor.
240 typedef SmallVector<Value *, 2> PerPartValuesTy;
241
242 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
243 } Data;
244
245 /// Get the generated Value for a given VPValue and a given Part. Note that
246 /// as some Defs are still created by ILV and managed in its ValueMap, this
247 /// method will delegate the call to ILV in such cases in order to provide
248 /// callers a consistent API.
249 /// \see set.
250 Value *get(VPValue *Def, unsigned Part) {
251 // If Values have been set for this Def return the one relevant for \p Part.
252 if (Data.PerPartOutput.count(Def))
253 return Data.PerPartOutput[Def][Part];
254 // Def is managed by ILV: bring the Values from ValueMap.
255 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
256 }
257
258 /// Set the generated Value for a given VPValue and a given Part.
259 void set(VPValue *Def, Value *V, unsigned Part) {
260 if (!Data.PerPartOutput.count(Def)) {
261 DataState::PerPartValuesTy Entry(UF);
262 Data.PerPartOutput[Def] = Entry;
263 }
264 Data.PerPartOutput[Def][Part] = V;
265 }
266
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000267 /// Hold state information used when constructing the CFG of the output IR,
268 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
269 struct CFGState {
270 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000271 VPBasicBlock *PrevVPBB = nullptr;
272
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000273 /// The previous IR BasicBlock created or used. Initially set to the new
274 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000275 BasicBlock *PrevBB = nullptr;
276
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000277 /// The last IR BasicBlock in the output IR. Set to the new latch
278 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000279 BasicBlock *LastBB = nullptr;
280
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000281 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
282 /// of replication, maps the BasicBlock of the last replica created.
283 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
284
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000285 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000286 } CFG;
287
288 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000289 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000290
291 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000292 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000293
294 /// Hold a reference to the IRBuilder used to generate output IR code.
295 IRBuilder<> &Builder;
296
297 /// Hold a reference to the Value state information used when generating the
298 /// Values of the output IR.
299 VectorizerValueMap &ValueMap;
300
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000301 /// Hold a reference to a mapping between VPValues in VPlan and original
302 /// Values they correspond to.
303 VPValue2ValueTy VPValue2Value;
304
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000305 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000306 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000307
308 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000309};
310
311/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
312/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
313class VPBlockBase {
314private:
315 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
316
317 /// An optional name for the block.
318 std::string Name;
319
320 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
321 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000322 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000323
324 /// List of predecessor blocks.
325 SmallVector<VPBlockBase *, 1> Predecessors;
326
327 /// List of successor blocks.
328 SmallVector<VPBlockBase *, 1> Successors;
329
330 /// Add \p Successor as the last successor to this block.
331 void appendSuccessor(VPBlockBase *Successor) {
332 assert(Successor && "Cannot add nullptr successor!");
333 Successors.push_back(Successor);
334 }
335
336 /// Add \p Predecessor as the last predecessor to this block.
337 void appendPredecessor(VPBlockBase *Predecessor) {
338 assert(Predecessor && "Cannot add nullptr predecessor!");
339 Predecessors.push_back(Predecessor);
340 }
341
342 /// Remove \p Predecessor from the predecessors of this block.
343 void removePredecessor(VPBlockBase *Predecessor) {
344 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
345 assert(Pos && "Predecessor does not exist");
346 Predecessors.erase(Pos);
347 }
348
349 /// Remove \p Successor from the successors of this block.
350 void removeSuccessor(VPBlockBase *Successor) {
351 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
352 assert(Pos && "Successor does not exist");
353 Successors.erase(Pos);
354 }
355
356protected:
357 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000358 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000359
360public:
361 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
362 /// that are actually instantiated. Values of this enumeration are kept in the
363 /// SubclassID field of the VPBlockBase objects. They are used for concrete
364 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000365 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000366
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000367 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000368
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000369 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000370
371 const std::string &getName() const { return Name; }
372
373 void setName(const Twine &newName) { Name = newName.str(); }
374
375 /// \return an ID for the concrete type of this object.
376 /// This is used to implement the classof checks. This should not be used
377 /// for any other purpose, as the values may change as LLVM evolves.
378 unsigned getVPBlockID() const { return SubclassID; }
379
380 const VPRegionBlock *getParent() const { return Parent; }
381
382 void setParent(VPRegionBlock *P) { Parent = P; }
383
384 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
385 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
386 /// VPBlockBase is a VPBasicBlock, it is returned.
387 const VPBasicBlock *getEntryBasicBlock() const;
388 VPBasicBlock *getEntryBasicBlock();
389
390 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
391 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
392 /// VPBlockBase is a VPBasicBlock, it is returned.
393 const VPBasicBlock *getExitBasicBlock() const;
394 VPBasicBlock *getExitBasicBlock();
395
396 const VPBlocksTy &getSuccessors() const { return Successors; }
397 VPBlocksTy &getSuccessors() { return Successors; }
398
399 const VPBlocksTy &getPredecessors() const { return Predecessors; }
400 VPBlocksTy &getPredecessors() { return Predecessors; }
401
402 /// \return the successor of this VPBlockBase if it has a single successor.
403 /// Otherwise return a null pointer.
404 VPBlockBase *getSingleSuccessor() const {
405 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
406 }
407
408 /// \return the predecessor of this VPBlockBase if it has a single
409 /// predecessor. Otherwise return a null pointer.
410 VPBlockBase *getSinglePredecessor() const {
411 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
412 }
413
414 /// An Enclosing Block of a block B is any block containing B, including B
415 /// itself. \return the closest enclosing block starting from "this", which
416 /// has successors. \return the root enclosing block if all enclosing blocks
417 /// have no successors.
418 VPBlockBase *getEnclosingBlockWithSuccessors();
419
420 /// \return the closest enclosing block starting from "this", which has
421 /// predecessors. \return the root enclosing block if all enclosing blocks
422 /// have no predecessors.
423 VPBlockBase *getEnclosingBlockWithPredecessors();
424
425 /// \return the successors either attached directly to this VPBlockBase or, if
426 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
427 /// successors of its own, search recursively for the first enclosing
428 /// VPRegionBlock that has successors and return them. If no such
429 /// VPRegionBlock exists, return the (empty) successors of the topmost
430 /// VPBlockBase reached.
431 const VPBlocksTy &getHierarchicalSuccessors() {
432 return getEnclosingBlockWithSuccessors()->getSuccessors();
433 }
434
435 /// \return the hierarchical successor of this VPBlockBase if it has a single
436 /// hierarchical successor. Otherwise return a null pointer.
437 VPBlockBase *getSingleHierarchicalSuccessor() {
438 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
439 }
440
441 /// \return the predecessors either attached directly to this VPBlockBase or,
442 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
443 /// predecessors of its own, search recursively for the first enclosing
444 /// VPRegionBlock that has predecessors and return them. If no such
445 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
446 /// VPBlockBase reached.
447 const VPBlocksTy &getHierarchicalPredecessors() {
448 return getEnclosingBlockWithPredecessors()->getPredecessors();
449 }
450
451 /// \return the hierarchical predecessor of this VPBlockBase if it has a
452 /// single hierarchical predecessor. Otherwise return a null pointer.
453 VPBlockBase *getSingleHierarchicalPredecessor() {
454 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
455 }
456
457 /// Sets a given VPBlockBase \p Successor as the single successor and \return
458 /// \p Successor. The parent of this Block is copied to be the parent of
459 /// \p Successor.
460 VPBlockBase *setOneSuccessor(VPBlockBase *Successor) {
461 assert(Successors.empty() && "Setting one successor when others exist.");
462 appendSuccessor(Successor);
463 Successor->appendPredecessor(this);
464 Successor->Parent = Parent;
465 return Successor;
466 }
467
468 /// Sets two given VPBlockBases \p IfTrue and \p IfFalse to be the two
469 /// successors. The parent of this Block is copied to be the parent of both
470 /// \p IfTrue and \p IfFalse.
471 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
472 assert(Successors.empty() && "Setting two successors when others exist.");
473 appendSuccessor(IfTrue);
474 appendSuccessor(IfFalse);
475 IfTrue->appendPredecessor(this);
476 IfFalse->appendPredecessor(this);
477 IfTrue->Parent = Parent;
478 IfFalse->Parent = Parent;
479 }
480
481 void disconnectSuccessor(VPBlockBase *Successor) {
482 assert(Successor && "Successor to disconnect is null.");
483 removeSuccessor(Successor);
484 Successor->removePredecessor(this);
485 }
486
487 /// The method which generates the output IR that correspond to this
488 /// VPBlockBase, thereby "executing" the VPlan.
489 virtual void execute(struct VPTransformState *State) = 0;
490
491 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
492 static void deleteCFG(VPBlockBase *Entry);
493};
494
495/// VPRecipeBase is a base class modeling a sequence of one or more output IR
496/// instructions.
497class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
498 friend VPBasicBlock;
499
500private:
501 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
502
503 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000504 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000505
506public:
507 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
508 /// that is actually instantiated. Values of this enumeration are kept in the
509 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
510 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000511 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000512 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000513 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000514 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000515 VPInterleaveSC,
516 VPPredInstPHISC,
517 VPReplicateSC,
518 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000519 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000520 VPWidenPHISC,
521 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000522 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000523
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000524 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
525 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000526
527 /// \return an ID for the concrete type of this object.
528 /// This is used to implement the classof checks. This should not be used
529 /// for any other purpose, as the values may change as LLVM evolves.
530 unsigned getVPRecipeID() const { return SubclassID; }
531
532 /// \return the VPBasicBlock which this VPRecipe belongs to.
533 VPBasicBlock *getParent() { return Parent; }
534 const VPBasicBlock *getParent() const { return Parent; }
535
536 /// The method which generates the output IR instructions that correspond to
537 /// this VPRecipe, thereby "executing" the VPlan.
538 virtual void execute(struct VPTransformState &State) = 0;
539
540 /// Each recipe prints itself.
541 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
542};
543
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000544/// This is a concrete Recipe that models a single VPlan-level instruction.
545/// While as any Recipe it may generate a sequence of IR instructions when
546/// executed, these instructions would always form a single-def expression as
547/// the VPInstruction is also a single def-use vertex.
548class VPInstruction : public VPUser, public VPRecipeBase {
549public:
550 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
551 enum { Not = Instruction::OtherOpsEnd + 1 };
552
553private:
554 typedef unsigned char OpcodeTy;
555 OpcodeTy Opcode;
556
557 /// Utility method serving execute(): generates a single instance of the
558 /// modeled instruction.
559 void generateInstruction(VPTransformState &State, unsigned Part);
560
561public:
562 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
563 : VPUser(VPValue::VPInstructionSC, Operands),
564 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
565
566 /// Method to support type inquiry through isa, cast, and dyn_cast.
567 static inline bool classof(const VPValue *V) {
568 return V->getVPValueID() == VPValue::VPInstructionSC;
569 }
570
571 /// Method to support type inquiry through isa, cast, and dyn_cast.
572 static inline bool classof(const VPRecipeBase *R) {
573 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
574 }
575
576 unsigned getOpcode() const { return Opcode; }
577
578 /// Generate the instruction.
579 /// TODO: We currently execute only per-part unless a specific instance is
580 /// provided.
581 void execute(VPTransformState &State) override;
582
583 /// Print the Recipe.
584 void print(raw_ostream &O, const Twine &Indent) const override;
585
586 /// Print the VPInstruction.
587 void print(raw_ostream &O) const;
588};
589
Hal Finkel7333aa92017-12-16 01:12:50 +0000590/// VPWidenRecipe is a recipe for producing a copy of vector type for each
591/// Instruction in its ingredients independently, in order. This recipe covers
592/// most of the traditional vectorization cases where each ingredient transforms
593/// into a vectorized version of itself.
594class VPWidenRecipe : public VPRecipeBase {
595private:
596 /// Hold the ingredients by pointing to their original BasicBlock location.
597 BasicBlock::iterator Begin;
598 BasicBlock::iterator End;
599
600public:
601 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
602 End = I->getIterator();
603 Begin = End++;
604 }
605
606 ~VPWidenRecipe() override = default;
607
608 /// Method to support type inquiry through isa, cast, and dyn_cast.
609 static inline bool classof(const VPRecipeBase *V) {
610 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
611 }
612
613 /// Produce widened copies of all Ingredients.
614 void execute(VPTransformState &State) override;
615
616 /// Augment the recipe to include Instr, if it lies at its End.
617 bool appendInstruction(Instruction *Instr) {
618 if (End != Instr->getIterator())
619 return false;
620 End++;
621 return true;
622 }
623
624 /// Print the recipe.
625 void print(raw_ostream &O, const Twine &Indent) const override;
626};
627
628/// A recipe for handling phi nodes of integer and floating-point inductions,
629/// producing their vector and scalar values.
630class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
631private:
632 PHINode *IV;
633 TruncInst *Trunc;
634
635public:
636 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
637 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
638 ~VPWidenIntOrFpInductionRecipe() override = default;
639
640 /// Method to support type inquiry through isa, cast, and dyn_cast.
641 static inline bool classof(const VPRecipeBase *V) {
642 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
643 }
644
645 /// Generate the vectorized and scalarized versions of the phi node as
646 /// needed by their users.
647 void execute(VPTransformState &State) override;
648
649 /// Print the recipe.
650 void print(raw_ostream &O, const Twine &Indent) const override;
651};
652
653/// A recipe for handling all phi nodes except for integer and FP inductions.
654class VPWidenPHIRecipe : public VPRecipeBase {
655private:
656 PHINode *Phi;
657
658public:
659 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
660 ~VPWidenPHIRecipe() override = default;
661
662 /// Method to support type inquiry through isa, cast, and dyn_cast.
663 static inline bool classof(const VPRecipeBase *V) {
664 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
665 }
666
667 /// Generate the phi/select nodes.
668 void execute(VPTransformState &State) override;
669
670 /// Print the recipe.
671 void print(raw_ostream &O, const Twine &Indent) const override;
672};
673
674/// A recipe for vectorizing a phi-node as a sequence of mask-based select
675/// instructions.
676class VPBlendRecipe : public VPRecipeBase {
677private:
678 PHINode *Phi;
679
680 /// The blend operation is a User of a mask, if not null.
681 std::unique_ptr<VPUser> User;
682
683public:
684 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
685 : VPRecipeBase(VPBlendSC), Phi(Phi) {
686 assert((Phi->getNumIncomingValues() == 1 ||
687 Phi->getNumIncomingValues() == Masks.size()) &&
688 "Expected the same number of incoming values and masks");
689 if (!Masks.empty())
690 User.reset(new VPUser(Masks));
691 }
692
693 /// Method to support type inquiry through isa, cast, and dyn_cast.
694 static inline bool classof(const VPRecipeBase *V) {
695 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
696 }
697
698 /// Generate the phi/select nodes.
699 void execute(VPTransformState &State) override;
700
701 /// Print the recipe.
702 void print(raw_ostream &O, const Twine &Indent) const override;
703};
704
705/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
706/// or stores into one wide load/store and shuffles.
707class VPInterleaveRecipe : public VPRecipeBase {
708private:
709 const InterleaveGroup *IG;
710
711public:
712 VPInterleaveRecipe(const InterleaveGroup *IG)
713 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
714 ~VPInterleaveRecipe() override = default;
715
716 /// Method to support type inquiry through isa, cast, and dyn_cast.
717 static inline bool classof(const VPRecipeBase *V) {
718 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
719 }
720
721 /// Generate the wide load or store, and shuffles.
722 void execute(VPTransformState &State) override;
723
724 /// Print the recipe.
725 void print(raw_ostream &O, const Twine &Indent) const override;
726
727 const InterleaveGroup *getInterleaveGroup() { return IG; }
728};
729
730/// VPReplicateRecipe replicates a given instruction producing multiple scalar
731/// copies of the original scalar type, one per lane, instead of producing a
732/// single copy of widened type for all lanes. If the instruction is known to be
733/// uniform only one copy, per lane zero, will be generated.
734class VPReplicateRecipe : public VPRecipeBase {
735private:
736 /// The instruction being replicated.
737 Instruction *Ingredient;
738
739 /// Indicator if only a single replica per lane is needed.
740 bool IsUniform;
741
742 /// Indicator if the replicas are also predicated.
743 bool IsPredicated;
744
745 /// Indicator if the scalar values should also be packed into a vector.
746 bool AlsoPack;
747
748public:
749 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
750 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
751 IsPredicated(IsPredicated) {
752 // Retain the previous behavior of predicateInstructions(), where an
753 // insert-element of a predicated instruction got hoisted into the
754 // predicated basic block iff it was its only user. This is achieved by
755 // having predicated instructions also pack their values into a vector by
756 // default unless they have a replicated user which uses their scalar value.
757 AlsoPack = IsPredicated && !I->use_empty();
758 }
759
760 ~VPReplicateRecipe() override = default;
761
762 /// Method to support type inquiry through isa, cast, and dyn_cast.
763 static inline bool classof(const VPRecipeBase *V) {
764 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
765 }
766
767 /// Generate replicas of the desired Ingredient. Replicas will be generated
768 /// for all parts and lanes unless a specific part and lane are specified in
769 /// the \p State.
770 void execute(VPTransformState &State) override;
771
772 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
773
774 /// Print the recipe.
775 void print(raw_ostream &O, const Twine &Indent) const override;
776};
777
778/// A recipe for generating conditional branches on the bits of a mask.
779class VPBranchOnMaskRecipe : public VPRecipeBase {
780private:
781 std::unique_ptr<VPUser> User;
782
783public:
784 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
785 if (BlockInMask) // nullptr means all-one mask.
786 User.reset(new VPUser({BlockInMask}));
787 }
788
789 /// Method to support type inquiry through isa, cast, and dyn_cast.
790 static inline bool classof(const VPRecipeBase *V) {
791 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
792 }
793
794 /// Generate the extraction of the appropriate bit from the block mask and the
795 /// conditional branch.
796 void execute(VPTransformState &State) override;
797
798 /// Print the recipe.
799 void print(raw_ostream &O, const Twine &Indent) const override {
800 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
801 if (User)
802 O << *User->getOperand(0);
803 else
804 O << " All-One";
805 O << "\\l\"";
806 }
807};
808
809/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
810/// control converges back from a Branch-on-Mask. The phi nodes are needed in
811/// order to merge values that are set under such a branch and feed their uses.
812/// The phi nodes can be scalar or vector depending on the users of the value.
813/// This recipe works in concert with VPBranchOnMaskRecipe.
814class VPPredInstPHIRecipe : public VPRecipeBase {
815private:
816 Instruction *PredInst;
817
818public:
819 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
820 /// nodes after merging back from a Branch-on-Mask.
821 VPPredInstPHIRecipe(Instruction *PredInst)
822 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
823 ~VPPredInstPHIRecipe() override = default;
824
825 /// Method to support type inquiry through isa, cast, and dyn_cast.
826 static inline bool classof(const VPRecipeBase *V) {
827 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
828 }
829
830 /// Generates phi nodes for live-outs as needed to retain SSA form.
831 void execute(VPTransformState &State) override;
832
833 /// Print the recipe.
834 void print(raw_ostream &O, const Twine &Indent) const override;
835};
836
837/// A Recipe for widening load/store operations.
838/// TODO: We currently execute only per-part unless a specific instance is
839/// provided.
840class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
841private:
842 Instruction &Instr;
843 std::unique_ptr<VPUser> User;
844
845public:
846 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
847 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
848 if (Mask) // Create a VPInstruction to register as a user of the mask.
849 User.reset(new VPUser({Mask}));
850 }
851
852 /// Method to support type inquiry through isa, cast, and dyn_cast.
853 static inline bool classof(const VPRecipeBase *V) {
854 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
855 }
856
857 /// Generate the wide load/store.
858 void execute(VPTransformState &State) override;
859
860 /// Print the recipe.
861 void print(raw_ostream &O, const Twine &Indent) const override;
862};
863
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000864/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
865/// holds a sequence of zero or more VPRecipe's each representing a sequence of
866/// output IR instructions.
867class VPBasicBlock : public VPBlockBase {
868public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000869 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000870
871private:
872 /// The VPRecipes held in the order of output instructions to generate.
873 RecipeListTy Recipes;
874
875public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000876 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
877 : VPBlockBase(VPBasicBlockSC, Name.str()) {
878 if (Recipe)
879 appendRecipe(Recipe);
880 }
881
882 ~VPBasicBlock() override { Recipes.clear(); }
883
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000884 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000885 using iterator = RecipeListTy::iterator;
886 using const_iterator = RecipeListTy::const_iterator;
887 using reverse_iterator = RecipeListTy::reverse_iterator;
888 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000889
890 //===--------------------------------------------------------------------===//
891 /// Recipe iterator methods
892 ///
893 inline iterator begin() { return Recipes.begin(); }
894 inline const_iterator begin() const { return Recipes.begin(); }
895 inline iterator end() { return Recipes.end(); }
896 inline const_iterator end() const { return Recipes.end(); }
897
898 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
899 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
900 inline reverse_iterator rend() { return Recipes.rend(); }
901 inline const_reverse_iterator rend() const { return Recipes.rend(); }
902
903 inline size_t size() const { return Recipes.size(); }
904 inline bool empty() const { return Recipes.empty(); }
905 inline const VPRecipeBase &front() const { return Recipes.front(); }
906 inline VPRecipeBase &front() { return Recipes.front(); }
907 inline const VPRecipeBase &back() const { return Recipes.back(); }
908 inline VPRecipeBase &back() { return Recipes.back(); }
909
910 /// \brief Returns a pointer to a member of the recipe list.
911 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
912 return &VPBasicBlock::Recipes;
913 }
914
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000915 /// Method to support type inquiry through isa, cast, and dyn_cast.
916 static inline bool classof(const VPBlockBase *V) {
917 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
918 }
919
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000920 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000921 assert(Recipe && "No recipe to append.");
922 assert(!Recipe->Parent && "Recipe already in VPlan");
923 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000924 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000925 }
926
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000927 /// Augment the existing recipes of a VPBasicBlock with an additional
928 /// \p Recipe as the last recipe.
929 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
930
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000931 /// The method which generates the output IR instructions that correspond to
932 /// this VPBasicBlock, thereby "executing" the VPlan.
933 void execute(struct VPTransformState *State) override;
934
935private:
936 /// Create an IR BasicBlock to hold the output instructions generated by this
937 /// VPBasicBlock, and return it. Update the CFGState accordingly.
938 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
939};
940
941/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
942/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
943/// A VPRegionBlock may indicate that its contents are to be replicated several
944/// times. This is designed to support predicated scalarization, in which a
945/// scalar if-then code structure needs to be generated VF * UF times. Having
946/// this replication indicator helps to keep a single model for multiple
947/// candidate VF's. The actual replication takes place only once the desired VF
948/// and UF have been determined.
949class VPRegionBlock : public VPBlockBase {
950private:
951 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
952 VPBlockBase *Entry;
953
954 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
955 VPBlockBase *Exit;
956
957 /// An indicator whether this region is to generate multiple replicated
958 /// instances of output IR corresponding to its VPBlockBases.
959 bool IsReplicator;
960
961public:
962 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
963 const std::string &Name = "", bool IsReplicator = false)
964 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
965 IsReplicator(IsReplicator) {
966 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
967 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
968 Entry->setParent(this);
969 Exit->setParent(this);
970 }
971
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000972 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000973 if (Entry)
974 deleteCFG(Entry);
975 }
976
977 /// Method to support type inquiry through isa, cast, and dyn_cast.
978 static inline bool classof(const VPBlockBase *V) {
979 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
980 }
981
982 const VPBlockBase *getEntry() const { return Entry; }
983 VPBlockBase *getEntry() { return Entry; }
984
985 const VPBlockBase *getExit() const { return Exit; }
986 VPBlockBase *getExit() { return Exit; }
987
988 /// An indicator whether this region is to generate multiple replicated
989 /// instances of output IR corresponding to its VPBlockBases.
990 bool isReplicator() const { return IsReplicator; }
991
992 /// The method which generates the output IR instructions that correspond to
993 /// this VPRegionBlock, thereby "executing" the VPlan.
994 void execute(struct VPTransformState *State) override;
995};
996
997/// VPlan models a candidate for vectorization, encoding various decisions take
998/// to produce efficient output IR, including which branches, basic-blocks and
999/// output IR instructions to generate, and their cost. VPlan holds a
1000/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1001/// VPBlock.
1002class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001003 friend class VPlanPrinter;
1004
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001005private:
1006 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1007 VPBlockBase *Entry;
1008
1009 /// Holds the VFs applicable to this VPlan.
1010 SmallSet<unsigned, 2> VFs;
1011
1012 /// Holds the name of the VPlan, for printing.
1013 std::string Name;
1014
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001015 /// Holds a mapping between Values and their corresponding VPValue inside
1016 /// VPlan.
1017 Value2VPValueTy Value2VPValue;
1018
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001019public:
1020 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1021
1022 ~VPlan() {
1023 if (Entry)
1024 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001025 for (auto &MapEntry : Value2VPValue)
1026 delete MapEntry.second;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001027 }
1028
1029 /// Generate the IR code for this VPlan.
1030 void execute(struct VPTransformState *State);
1031
1032 VPBlockBase *getEntry() { return Entry; }
1033 const VPBlockBase *getEntry() const { return Entry; }
1034
1035 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1036
1037 void addVF(unsigned VF) { VFs.insert(VF); }
1038
1039 bool hasVF(unsigned VF) { return VFs.count(VF); }
1040
1041 const std::string &getName() const { return Name; }
1042
1043 void setName(const Twine &newName) { Name = newName.str(); }
1044
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001045 void addVPValue(Value *V) {
1046 assert(V && "Trying to add a null Value to VPlan");
1047 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1048 Value2VPValue[V] = new VPValue();
1049 }
1050
1051 VPValue *getVPValue(Value *V) {
1052 assert(V && "Trying to get the VPValue of a null Value");
1053 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1054 return Value2VPValue[V];
1055 }
1056
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001057private:
1058 /// Add to the given dominator tree the header block and every new basic block
1059 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001060 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001061 BasicBlock *LoopPreHeaderBB,
1062 BasicBlock *LoopLatchBB);
1063};
1064
1065/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1066/// indented and follows the dot format.
1067class VPlanPrinter {
1068 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1069 friend inline raw_ostream &operator<<(raw_ostream &OS,
1070 const struct VPlanIngredient &I);
1071
1072private:
1073 raw_ostream &OS;
1074 VPlan &Plan;
1075 unsigned Depth;
1076 unsigned TabWidth = 2;
1077 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001078 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001079 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1080
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001081 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1082
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001083 /// Handle indentation.
1084 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1085
1086 /// Print a given \p Block of the Plan.
1087 void dumpBlock(const VPBlockBase *Block);
1088
1089 /// Print the information related to the CFG edges going out of a given
1090 /// \p Block, followed by printing the successor blocks themselves.
1091 void dumpEdges(const VPBlockBase *Block);
1092
1093 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1094 /// its successor blocks.
1095 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1096
1097 /// Print a given \p Region of the Plan.
1098 void dumpRegion(const VPRegionBlock *Region);
1099
1100 unsigned getOrCreateBID(const VPBlockBase *Block) {
1101 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1102 }
1103
1104 const Twine getOrCreateName(const VPBlockBase *Block);
1105
1106 const Twine getUID(const VPBlockBase *Block);
1107
1108 /// Print the information related to a CFG edge between two VPBlockBases.
1109 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1110 const Twine &Label);
1111
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001112 void dump();
1113
1114 static void printAsIngredient(raw_ostream &O, Value *V);
1115};
1116
1117struct VPlanIngredient {
1118 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001119
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001120 VPlanIngredient(Value *V) : V(V) {}
1121};
1122
1123inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1124 VPlanPrinter::printAsIngredient(OS, I.V);
1125 return OS;
1126}
1127
1128inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1129 VPlanPrinter Printer(OS, Plan);
1130 Printer.dump();
1131 return OS;
1132}
1133
1134//===--------------------------------------------------------------------===//
1135// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
1136//===--------------------------------------------------------------------===//
1137
1138// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1139// graph of VPBlockBase nodes...
1140
1141template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001142 using NodeRef = VPBlockBase *;
1143 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001144
1145 static NodeRef getEntryNode(NodeRef N) { return N; }
1146
1147 static inline ChildIteratorType child_begin(NodeRef N) {
1148 return N->getSuccessors().begin();
1149 }
1150
1151 static inline ChildIteratorType child_end(NodeRef N) {
1152 return N->getSuccessors().end();
1153 }
1154};
1155
1156template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001157 using NodeRef = const VPBlockBase *;
1158 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001159
1160 static NodeRef getEntryNode(NodeRef N) { return N; }
1161
1162 static inline ChildIteratorType child_begin(NodeRef N) {
1163 return N->getSuccessors().begin();
1164 }
1165
1166 static inline ChildIteratorType child_end(NodeRef N) {
1167 return N->getSuccessors().end();
1168 }
1169};
1170
1171// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1172// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
1173// for a VPBlockBase is considered to be when traversing the predecessors of a
1174// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001175template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001176 using NodeRef = VPBlockBase *;
1177 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001178
1179 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
1180 return B;
1181 }
1182
1183 static inline ChildIteratorType child_begin(NodeRef N) {
1184 return N->getPredecessors().begin();
1185 }
1186
1187 static inline ChildIteratorType child_end(NodeRef N) {
1188 return N->getPredecessors().end();
1189 }
1190};
1191
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001192} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001193
1194#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H