blob: 193d7a906216797cdf107f052fad01487abb03ed [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"
Diego Caballero2a34ac82018-07-30 21:33:31 +000031#include "llvm/ADT/DepthFirstIterator.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000032#include "llvm/ADT/GraphTraits.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000033#include "llvm/ADT/Optional.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000034#include "llvm/ADT/SmallPtrSet.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000035#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000036#include "llvm/ADT/SmallVector.h"
37#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000038#include "llvm/ADT/ilist.h"
39#include "llvm/ADT/ilist_node.h"
40#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000041#include <algorithm>
42#include <cassert>
43#include <cstddef>
44#include <map>
45#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000046
47namespace llvm {
48
Hal Finkel0f1314c2018-01-07 16:02:58 +000049class LoopVectorizationLegality;
50class LoopVectorizationCostModel;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000051class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000052class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000053class InnerLoopVectorizer;
Hal Finkel7333aa92017-12-16 01:12:50 +000054class InterleaveGroup;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000055class LoopInfo;
56class raw_ostream;
57class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000058class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000059class VPRegionBlock;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000060class VPlan;
61
62/// A range of powers-of-2 vectorization factors with fixed start and
63/// adjustable end. The range includes start and excludes end, e.g.,:
64/// [1, 9) = {1, 2, 4, 8}
65struct VFRange {
66 // A power of 2.
67 const unsigned Start;
68
69 // Need not be a power of 2. If End <= Start range is empty.
70 unsigned End;
71};
72
73using VPlanPtr = std::unique_ptr<VPlan>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000074
75/// In what follows, the term "input IR" refers to code that is fed into the
76/// vectorizer whereas the term "output IR" refers to code that is generated by
77/// the vectorizer.
78
79/// VPIteration represents a single point in the iteration space of the output
80/// (vectorized and/or unrolled) IR loop.
81struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000082 /// in [0..UF)
83 unsigned Part;
84
85 /// in [0..VF)
86 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000087};
88
89/// This is a helper struct for maintaining vectorization state. It's used for
90/// mapping values from the original loop to their corresponding values in
91/// the new loop. Two mappings are maintained: one for vectorized values and
92/// one for scalarized values. Vectorized values are represented with UF
93/// vector values in the new loop, and scalarized values are represented with
94/// UF x VF scalar values in the new loop. UF and VF are the unroll and
95/// vectorization factors, respectively.
96///
97/// Entries can be added to either map with setVectorValue and setScalarValue,
98/// which assert that an entry was not already added before. If an entry is to
99/// replace an existing one, call resetVectorValue and resetScalarValue. This is
100/// currently needed to modify the mapped values during "fix-up" operations that
101/// occur once the first phase of widening is complete. These operations include
102/// type truncation and the second phase of recurrence widening.
103///
104/// Entries from either map can be retrieved using the getVectorValue and
105/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000106struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000107 friend struct VPTransformState;
108
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000109private:
110 /// The unroll factor. Each entry in the vector map contains UF vector values.
111 unsigned UF;
112
113 /// The vectorization factor. Each entry in the scalar map contains UF x VF
114 /// scalar values.
115 unsigned VF;
116
117 /// The vector and scalar map storage. We use std::map and not DenseMap
118 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000119 using VectorParts = SmallVector<Value *, 2>;
120 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000121 std::map<Value *, VectorParts> VectorMapStorage;
122 std::map<Value *, ScalarParts> ScalarMapStorage;
123
124public:
125 /// Construct an empty map with the given unroll and vectorization factors.
126 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
127
128 /// \return True if the map has any vector entry for \p Key.
129 bool hasAnyVectorValue(Value *Key) const {
130 return VectorMapStorage.count(Key);
131 }
132
133 /// \return True if the map has a vector entry for \p Key and \p Part.
134 bool hasVectorValue(Value *Key, unsigned Part) const {
135 assert(Part < UF && "Queried Vector Part is too large.");
136 if (!hasAnyVectorValue(Key))
137 return false;
138 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
139 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
140 return Entry[Part] != nullptr;
141 }
142
143 /// \return True if the map has any scalar entry for \p Key.
144 bool hasAnyScalarValue(Value *Key) const {
145 return ScalarMapStorage.count(Key);
146 }
147
148 /// \return True if the map has a scalar entry for \p Key and \p Instance.
149 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
150 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
151 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
152 if (!hasAnyScalarValue(Key))
153 return false;
154 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
155 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
156 assert(Entry[Instance.Part].size() == VF &&
157 "ScalarParts has wrong dimensions.");
158 return Entry[Instance.Part][Instance.Lane] != nullptr;
159 }
160
161 /// Retrieve the existing vector value that corresponds to \p Key and
162 /// \p Part.
163 Value *getVectorValue(Value *Key, unsigned Part) {
164 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
165 return VectorMapStorage[Key][Part];
166 }
167
168 /// Retrieve the existing scalar value that corresponds to \p Key and
169 /// \p Instance.
170 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
171 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
172 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
173 }
174
175 /// Set a vector value associated with \p Key and \p Part. Assumes such a
176 /// value is not already set. If it is, use resetVectorValue() instead.
177 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
178 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
179 if (!VectorMapStorage.count(Key)) {
180 VectorParts Entry(UF);
181 VectorMapStorage[Key] = Entry;
182 }
183 VectorMapStorage[Key][Part] = Vector;
184 }
185
186 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
187 /// value is not already set.
188 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
189 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
190 if (!ScalarMapStorage.count(Key)) {
191 ScalarParts Entry(UF);
192 // TODO: Consider storing uniform values only per-part, as they occupy
193 // lane 0 only, keeping the other VF-1 redundant entries null.
194 for (unsigned Part = 0; Part < UF; ++Part)
195 Entry[Part].resize(VF, nullptr);
196 ScalarMapStorage[Key] = Entry;
197 }
198 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
199 }
200
201 /// Reset the vector value associated with \p Key for the given \p Part.
202 /// This function can be used to update values that have already been
203 /// vectorized. This is the case for "fix-up" operations including type
204 /// truncation and the second phase of recurrence vectorization.
205 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
206 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
207 VectorMapStorage[Key][Part] = Vector;
208 }
209
210 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
211 /// This function can be used to update values that have already been
212 /// scalarized. This is the case for "fix-up" operations including scalar phi
213 /// nodes for scalarized and predicated instructions.
214 void resetScalarValue(Value *Key, const VPIteration &Instance,
215 Value *Scalar) {
216 assert(hasScalarValue(Key, Instance) &&
217 "Scalar value not set for part and lane");
218 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
219 }
220};
221
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000222/// This class is used to enable the VPlan to invoke a method of ILV. This is
223/// needed until the method is refactored out of ILV and becomes reusable.
224struct VPCallback {
225 virtual ~VPCallback() {}
226 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
227};
228
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000229/// VPTransformState holds information passed down when "executing" a VPlan,
230/// needed for generating the output IR.
231struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000232 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
233 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000234 InnerLoopVectorizer *ILV, VPCallback &Callback)
235 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
236 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000237
238 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
239 unsigned VF;
240 unsigned UF;
241
242 /// Hold the indices to generate specific scalar instructions. Null indicates
243 /// that all instances are to be generated, using either scalar or vector
244 /// instructions.
245 Optional<VPIteration> Instance;
246
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000247 struct DataState {
248 /// A type for vectorized values in the new loop. Each value from the
249 /// original loop, when vectorized, is represented by UF vector values in
250 /// the new unrolled loop, where UF is the unroll factor.
251 typedef SmallVector<Value *, 2> PerPartValuesTy;
252
253 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
254 } Data;
255
256 /// Get the generated Value for a given VPValue and a given Part. Note that
257 /// as some Defs are still created by ILV and managed in its ValueMap, this
258 /// method will delegate the call to ILV in such cases in order to provide
259 /// callers a consistent API.
260 /// \see set.
261 Value *get(VPValue *Def, unsigned Part) {
262 // If Values have been set for this Def return the one relevant for \p Part.
263 if (Data.PerPartOutput.count(Def))
264 return Data.PerPartOutput[Def][Part];
265 // Def is managed by ILV: bring the Values from ValueMap.
266 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
267 }
268
269 /// Set the generated Value for a given VPValue and a given Part.
270 void set(VPValue *Def, Value *V, unsigned Part) {
271 if (!Data.PerPartOutput.count(Def)) {
272 DataState::PerPartValuesTy Entry(UF);
273 Data.PerPartOutput[Def] = Entry;
274 }
275 Data.PerPartOutput[Def][Part] = V;
276 }
277
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000278 /// Hold state information used when constructing the CFG of the output IR,
279 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
280 struct CFGState {
281 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000282 VPBasicBlock *PrevVPBB = nullptr;
283
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000284 /// The previous IR BasicBlock created or used. Initially set to the new
285 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000286 BasicBlock *PrevBB = nullptr;
287
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000288 /// The last IR BasicBlock in the output IR. Set to the new latch
289 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000290 BasicBlock *LastBB = nullptr;
291
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000292 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
293 /// of replication, maps the BasicBlock of the last replica created.
294 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
295
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000296 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000297 } CFG;
298
299 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000300 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000301
302 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000303 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000304
305 /// Hold a reference to the IRBuilder used to generate output IR code.
306 IRBuilder<> &Builder;
307
308 /// Hold a reference to the Value state information used when generating the
309 /// Values of the output IR.
310 VectorizerValueMap &ValueMap;
311
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000312 /// Hold a reference to a mapping between VPValues in VPlan and original
313 /// Values they correspond to.
314 VPValue2ValueTy VPValue2Value;
315
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000316 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000317 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000318
319 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000320};
321
322/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
323/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
324class VPBlockBase {
Diego Caballero168d04d2018-05-21 18:14:23 +0000325 friend class VPBlockUtils;
326
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000327private:
328 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
329
330 /// An optional name for the block.
331 std::string Name;
332
333 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
334 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000335 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000336
337 /// List of predecessor blocks.
338 SmallVector<VPBlockBase *, 1> Predecessors;
339
340 /// List of successor blocks.
341 SmallVector<VPBlockBase *, 1> Successors;
342
Diego Caballerod0953012018-07-09 15:57:09 +0000343 /// Successor selector, null for zero or single successor blocks.
344 VPValue *CondBit = nullptr;
345
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000346 /// Add \p Successor as the last successor to this block.
347 void appendSuccessor(VPBlockBase *Successor) {
348 assert(Successor && "Cannot add nullptr successor!");
349 Successors.push_back(Successor);
350 }
351
352 /// Add \p Predecessor as the last predecessor to this block.
353 void appendPredecessor(VPBlockBase *Predecessor) {
354 assert(Predecessor && "Cannot add nullptr predecessor!");
355 Predecessors.push_back(Predecessor);
356 }
357
358 /// Remove \p Predecessor from the predecessors of this block.
359 void removePredecessor(VPBlockBase *Predecessor) {
360 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
361 assert(Pos && "Predecessor does not exist");
362 Predecessors.erase(Pos);
363 }
364
365 /// Remove \p Successor from the successors of this block.
366 void removeSuccessor(VPBlockBase *Successor) {
367 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
368 assert(Pos && "Successor does not exist");
369 Successors.erase(Pos);
370 }
371
372protected:
373 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000374 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000375
376public:
377 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
378 /// that are actually instantiated. Values of this enumeration are kept in the
379 /// SubclassID field of the VPBlockBase objects. They are used for concrete
380 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000381 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000382
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000383 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000384
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000385 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000386
387 const std::string &getName() const { return Name; }
388
389 void setName(const Twine &newName) { Name = newName.str(); }
390
391 /// \return an ID for the concrete type of this object.
392 /// This is used to implement the classof checks. This should not be used
393 /// for any other purpose, as the values may change as LLVM evolves.
394 unsigned getVPBlockID() const { return SubclassID; }
395
Diego Caballero168d04d2018-05-21 18:14:23 +0000396 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000397 const VPRegionBlock *getParent() const { return Parent; }
398
399 void setParent(VPRegionBlock *P) { Parent = P; }
400
401 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
402 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
403 /// VPBlockBase is a VPBasicBlock, it is returned.
404 const VPBasicBlock *getEntryBasicBlock() const;
405 VPBasicBlock *getEntryBasicBlock();
406
407 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
408 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
409 /// VPBlockBase is a VPBasicBlock, it is returned.
410 const VPBasicBlock *getExitBasicBlock() const;
411 VPBasicBlock *getExitBasicBlock();
412
413 const VPBlocksTy &getSuccessors() const { return Successors; }
414 VPBlocksTy &getSuccessors() { return Successors; }
415
416 const VPBlocksTy &getPredecessors() const { return Predecessors; }
417 VPBlocksTy &getPredecessors() { return Predecessors; }
418
419 /// \return the successor of this VPBlockBase if it has a single successor.
420 /// Otherwise return a null pointer.
421 VPBlockBase *getSingleSuccessor() const {
422 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
423 }
424
425 /// \return the predecessor of this VPBlockBase if it has a single
426 /// predecessor. Otherwise return a null pointer.
427 VPBlockBase *getSinglePredecessor() const {
428 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
429 }
430
Diego Caballero168d04d2018-05-21 18:14:23 +0000431 size_t getNumSuccessors() const { return Successors.size(); }
432 size_t getNumPredecessors() const { return Predecessors.size(); }
433
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000434 /// An Enclosing Block of a block B is any block containing B, including B
435 /// itself. \return the closest enclosing block starting from "this", which
436 /// has successors. \return the root enclosing block if all enclosing blocks
437 /// have no successors.
438 VPBlockBase *getEnclosingBlockWithSuccessors();
439
440 /// \return the closest enclosing block starting from "this", which has
441 /// predecessors. \return the root enclosing block if all enclosing blocks
442 /// have no predecessors.
443 VPBlockBase *getEnclosingBlockWithPredecessors();
444
445 /// \return the successors either attached directly to this VPBlockBase or, if
446 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
447 /// successors of its own, search recursively for the first enclosing
448 /// VPRegionBlock that has successors and return them. If no such
449 /// VPRegionBlock exists, return the (empty) successors of the topmost
450 /// VPBlockBase reached.
451 const VPBlocksTy &getHierarchicalSuccessors() {
452 return getEnclosingBlockWithSuccessors()->getSuccessors();
453 }
454
455 /// \return the hierarchical successor of this VPBlockBase if it has a single
456 /// hierarchical successor. Otherwise return a null pointer.
457 VPBlockBase *getSingleHierarchicalSuccessor() {
458 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
459 }
460
461 /// \return the predecessors either attached directly to this VPBlockBase or,
462 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
463 /// predecessors of its own, search recursively for the first enclosing
464 /// VPRegionBlock that has predecessors and return them. If no such
465 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
466 /// VPBlockBase reached.
467 const VPBlocksTy &getHierarchicalPredecessors() {
468 return getEnclosingBlockWithPredecessors()->getPredecessors();
469 }
470
471 /// \return the hierarchical predecessor of this VPBlockBase if it has a
472 /// single hierarchical predecessor. Otherwise return a null pointer.
473 VPBlockBase *getSingleHierarchicalPredecessor() {
474 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
475 }
476
Diego Caballerod0953012018-07-09 15:57:09 +0000477 /// \return the condition bit selecting the successor.
478 VPValue *getCondBit() { return CondBit; }
479
480 const VPValue *getCondBit() const { return CondBit; }
481
482 void setCondBit(VPValue *CV) { CondBit = CV; }
483
Diego Caballero168d04d2018-05-21 18:14:23 +0000484 /// Set a given VPBlockBase \p Successor as the single successor of this
485 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
486 /// This VPBlockBase must have no successors.
487 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000488 assert(Successors.empty() && "Setting one successor when others exist.");
489 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000490 }
491
Diego Caballero168d04d2018-05-21 18:14:23 +0000492 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
Diego Caballerod0953012018-07-09 15:57:09 +0000493 /// successors of this VPBlockBase. \p Condition is set as the successor
494 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
495 /// IfFalse. This VPBlockBase must have no successors.
496 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
497 VPValue *Condition) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000498 assert(Successors.empty() && "Setting two successors when others exist.");
Diego Caballerod0953012018-07-09 15:57:09 +0000499 assert(Condition && "Setting two successors without condition!");
500 CondBit = Condition;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000501 appendSuccessor(IfTrue);
502 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000503 }
504
Diego Caballero168d04d2018-05-21 18:14:23 +0000505 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
506 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
507 /// as successor of any VPBasicBlock in \p NewPreds.
508 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
509 assert(Predecessors.empty() && "Block predecessors already set.");
510 for (auto *Pred : NewPreds)
511 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000512 }
513
514 /// The method which generates the output IR that correspond to this
515 /// VPBlockBase, thereby "executing" the VPlan.
516 virtual void execute(struct VPTransformState *State) = 0;
517
518 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
519 static void deleteCFG(VPBlockBase *Entry);
Diego Caballero2a34ac82018-07-30 21:33:31 +0000520
521 void printAsOperand(raw_ostream &OS, bool PrintType) const {
522 OS << getName();
523 }
524
525 void print(raw_ostream &OS) const {
526 // TODO: Only printing VPBB name for now since we only have dot printing
527 // support for VPInstructions/Recipes.
528 printAsOperand(OS, false);
529 }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000530};
531
532/// VPRecipeBase is a base class modeling a sequence of one or more output IR
533/// instructions.
534class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
535 friend VPBasicBlock;
536
537private:
538 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
539
540 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000541 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000542
543public:
544 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
545 /// that is actually instantiated. Values of this enumeration are kept in the
546 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
547 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000548 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000549 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000550 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000551 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000552 VPInterleaveSC,
553 VPPredInstPHISC,
554 VPReplicateSC,
555 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000556 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000557 VPWidenPHISC,
558 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000559 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000560
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000561 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
562 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000563
564 /// \return an ID for the concrete type of this object.
565 /// This is used to implement the classof checks. This should not be used
566 /// for any other purpose, as the values may change as LLVM evolves.
567 unsigned getVPRecipeID() const { return SubclassID; }
568
569 /// \return the VPBasicBlock which this VPRecipe belongs to.
570 VPBasicBlock *getParent() { return Parent; }
571 const VPBasicBlock *getParent() const { return Parent; }
572
573 /// The method which generates the output IR instructions that correspond to
574 /// this VPRecipe, thereby "executing" the VPlan.
575 virtual void execute(struct VPTransformState &State) = 0;
576
577 /// Each recipe prints itself.
578 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
Florian Hahn7591e4e2018-06-18 11:34:17 +0000579
580 /// Insert an unlinked recipe into a basic block immediately before
581 /// the specified recipe.
582 void insertBefore(VPRecipeBase *InsertPos);
Florian Hahn63cbcf92018-06-18 15:18:48 +0000583
584 /// This method unlinks 'this' from the containing basic block and deletes it.
585 ///
586 /// \returns an iterator pointing to the element after the erased one
587 iplist<VPRecipeBase>::iterator eraseFromParent();
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000588};
589
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000590/// This is a concrete Recipe that models a single VPlan-level instruction.
591/// While as any Recipe it may generate a sequence of IR instructions when
592/// executed, these instructions would always form a single-def expression as
593/// the VPInstruction is also a single def-use vertex.
594class VPInstruction : public VPUser, public VPRecipeBase {
Florian Hahn3385caa2018-06-18 18:28:49 +0000595 friend class VPlanHCFGTransforms;
596
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000597public:
598 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
599 enum { Not = Instruction::OtherOpsEnd + 1 };
600
601private:
602 typedef unsigned char OpcodeTy;
603 OpcodeTy Opcode;
604
605 /// Utility method serving execute(): generates a single instance of the
606 /// modeled instruction.
607 void generateInstruction(VPTransformState &State, unsigned Part);
608
609public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000610 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000611 : VPUser(VPValue::VPInstructionSC, Operands),
612 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
613
Diego Caballero168d04d2018-05-21 18:14:23 +0000614 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
615 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
616
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000617 /// Method to support type inquiry through isa, cast, and dyn_cast.
618 static inline bool classof(const VPValue *V) {
619 return V->getVPValueID() == VPValue::VPInstructionSC;
620 }
621
622 /// Method to support type inquiry through isa, cast, and dyn_cast.
623 static inline bool classof(const VPRecipeBase *R) {
624 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
625 }
626
627 unsigned getOpcode() const { return Opcode; }
628
629 /// Generate the instruction.
630 /// TODO: We currently execute only per-part unless a specific instance is
631 /// provided.
632 void execute(VPTransformState &State) override;
633
634 /// Print the Recipe.
635 void print(raw_ostream &O, const Twine &Indent) const override;
636
637 /// Print the VPInstruction.
638 void print(raw_ostream &O) const;
639};
640
Hal Finkel7333aa92017-12-16 01:12:50 +0000641/// VPWidenRecipe is a recipe for producing a copy of vector type for each
642/// Instruction in its ingredients independently, in order. This recipe covers
643/// most of the traditional vectorization cases where each ingredient transforms
644/// into a vectorized version of itself.
645class VPWidenRecipe : public VPRecipeBase {
646private:
647 /// Hold the ingredients by pointing to their original BasicBlock location.
648 BasicBlock::iterator Begin;
649 BasicBlock::iterator End;
650
651public:
652 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
653 End = I->getIterator();
654 Begin = End++;
655 }
656
657 ~VPWidenRecipe() override = default;
658
659 /// Method to support type inquiry through isa, cast, and dyn_cast.
660 static inline bool classof(const VPRecipeBase *V) {
661 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
662 }
663
664 /// Produce widened copies of all Ingredients.
665 void execute(VPTransformState &State) override;
666
667 /// Augment the recipe to include Instr, if it lies at its End.
668 bool appendInstruction(Instruction *Instr) {
669 if (End != Instr->getIterator())
670 return false;
671 End++;
672 return true;
673 }
674
675 /// Print the recipe.
676 void print(raw_ostream &O, const Twine &Indent) const override;
677};
678
679/// A recipe for handling phi nodes of integer and floating-point inductions,
680/// producing their vector and scalar values.
681class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
682private:
683 PHINode *IV;
684 TruncInst *Trunc;
685
686public:
687 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
688 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
689 ~VPWidenIntOrFpInductionRecipe() override = default;
690
691 /// Method to support type inquiry through isa, cast, and dyn_cast.
692 static inline bool classof(const VPRecipeBase *V) {
693 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
694 }
695
696 /// Generate the vectorized and scalarized versions of the phi node as
697 /// needed by their users.
698 void execute(VPTransformState &State) override;
699
700 /// Print the recipe.
701 void print(raw_ostream &O, const Twine &Indent) const override;
702};
703
704/// A recipe for handling all phi nodes except for integer and FP inductions.
705class VPWidenPHIRecipe : public VPRecipeBase {
706private:
707 PHINode *Phi;
708
709public:
710 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
711 ~VPWidenPHIRecipe() override = default;
712
713 /// Method to support type inquiry through isa, cast, and dyn_cast.
714 static inline bool classof(const VPRecipeBase *V) {
715 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
716 }
717
718 /// Generate the phi/select nodes.
719 void execute(VPTransformState &State) override;
720
721 /// Print the recipe.
722 void print(raw_ostream &O, const Twine &Indent) const override;
723};
724
725/// A recipe for vectorizing a phi-node as a sequence of mask-based select
726/// instructions.
727class VPBlendRecipe : public VPRecipeBase {
728private:
729 PHINode *Phi;
730
731 /// The blend operation is a User of a mask, if not null.
732 std::unique_ptr<VPUser> User;
733
734public:
735 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
736 : VPRecipeBase(VPBlendSC), Phi(Phi) {
737 assert((Phi->getNumIncomingValues() == 1 ||
738 Phi->getNumIncomingValues() == Masks.size()) &&
739 "Expected the same number of incoming values and masks");
740 if (!Masks.empty())
741 User.reset(new VPUser(Masks));
742 }
743
744 /// Method to support type inquiry through isa, cast, and dyn_cast.
745 static inline bool classof(const VPRecipeBase *V) {
746 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
747 }
748
749 /// Generate the phi/select nodes.
750 void execute(VPTransformState &State) override;
751
752 /// Print the recipe.
753 void print(raw_ostream &O, const Twine &Indent) const override;
754};
755
756/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
757/// or stores into one wide load/store and shuffles.
758class VPInterleaveRecipe : public VPRecipeBase {
759private:
760 const InterleaveGroup *IG;
761
762public:
763 VPInterleaveRecipe(const InterleaveGroup *IG)
764 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
765 ~VPInterleaveRecipe() override = default;
766
767 /// Method to support type inquiry through isa, cast, and dyn_cast.
768 static inline bool classof(const VPRecipeBase *V) {
769 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
770 }
771
772 /// Generate the wide load or store, and shuffles.
773 void execute(VPTransformState &State) override;
774
775 /// Print the recipe.
776 void print(raw_ostream &O, const Twine &Indent) const override;
777
778 const InterleaveGroup *getInterleaveGroup() { return IG; }
779};
780
781/// VPReplicateRecipe replicates a given instruction producing multiple scalar
782/// copies of the original scalar type, one per lane, instead of producing a
783/// single copy of widened type for all lanes. If the instruction is known to be
784/// uniform only one copy, per lane zero, will be generated.
785class VPReplicateRecipe : public VPRecipeBase {
786private:
787 /// The instruction being replicated.
788 Instruction *Ingredient;
789
790 /// Indicator if only a single replica per lane is needed.
791 bool IsUniform;
792
793 /// Indicator if the replicas are also predicated.
794 bool IsPredicated;
795
796 /// Indicator if the scalar values should also be packed into a vector.
797 bool AlsoPack;
798
799public:
800 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
801 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
802 IsPredicated(IsPredicated) {
803 // Retain the previous behavior of predicateInstructions(), where an
804 // insert-element of a predicated instruction got hoisted into the
805 // predicated basic block iff it was its only user. This is achieved by
806 // having predicated instructions also pack their values into a vector by
807 // default unless they have a replicated user which uses their scalar value.
808 AlsoPack = IsPredicated && !I->use_empty();
809 }
810
811 ~VPReplicateRecipe() override = default;
812
813 /// Method to support type inquiry through isa, cast, and dyn_cast.
814 static inline bool classof(const VPRecipeBase *V) {
815 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
816 }
817
818 /// Generate replicas of the desired Ingredient. Replicas will be generated
819 /// for all parts and lanes unless a specific part and lane are specified in
820 /// the \p State.
821 void execute(VPTransformState &State) override;
822
823 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
824
825 /// Print the recipe.
826 void print(raw_ostream &O, const Twine &Indent) const override;
827};
828
829/// A recipe for generating conditional branches on the bits of a mask.
830class VPBranchOnMaskRecipe : public VPRecipeBase {
831private:
832 std::unique_ptr<VPUser> User;
833
834public:
835 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
836 if (BlockInMask) // nullptr means all-one mask.
837 User.reset(new VPUser({BlockInMask}));
838 }
839
840 /// Method to support type inquiry through isa, cast, and dyn_cast.
841 static inline bool classof(const VPRecipeBase *V) {
842 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
843 }
844
845 /// Generate the extraction of the appropriate bit from the block mask and the
846 /// conditional branch.
847 void execute(VPTransformState &State) override;
848
849 /// Print the recipe.
850 void print(raw_ostream &O, const Twine &Indent) const override {
851 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
852 if (User)
853 O << *User->getOperand(0);
854 else
855 O << " All-One";
856 O << "\\l\"";
857 }
858};
859
860/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
861/// control converges back from a Branch-on-Mask. The phi nodes are needed in
862/// order to merge values that are set under such a branch and feed their uses.
863/// The phi nodes can be scalar or vector depending on the users of the value.
864/// This recipe works in concert with VPBranchOnMaskRecipe.
865class VPPredInstPHIRecipe : public VPRecipeBase {
866private:
867 Instruction *PredInst;
868
869public:
870 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
871 /// nodes after merging back from a Branch-on-Mask.
872 VPPredInstPHIRecipe(Instruction *PredInst)
873 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
874 ~VPPredInstPHIRecipe() override = default;
875
876 /// Method to support type inquiry through isa, cast, and dyn_cast.
877 static inline bool classof(const VPRecipeBase *V) {
878 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
879 }
880
881 /// Generates phi nodes for live-outs as needed to retain SSA form.
882 void execute(VPTransformState &State) override;
883
884 /// Print the recipe.
885 void print(raw_ostream &O, const Twine &Indent) const override;
886};
887
888/// A Recipe for widening load/store operations.
889/// TODO: We currently execute only per-part unless a specific instance is
890/// provided.
891class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
892private:
893 Instruction &Instr;
894 std::unique_ptr<VPUser> User;
895
896public:
897 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
898 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
899 if (Mask) // Create a VPInstruction to register as a user of the mask.
900 User.reset(new VPUser({Mask}));
901 }
902
903 /// Method to support type inquiry through isa, cast, and dyn_cast.
904 static inline bool classof(const VPRecipeBase *V) {
905 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
906 }
907
908 /// Generate the wide load/store.
909 void execute(VPTransformState &State) override;
910
911 /// Print the recipe.
912 void print(raw_ostream &O, const Twine &Indent) const override;
913};
914
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000915/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
916/// holds a sequence of zero or more VPRecipe's each representing a sequence of
917/// output IR instructions.
918class VPBasicBlock : public VPBlockBase {
919public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000920 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000921
922private:
923 /// The VPRecipes held in the order of output instructions to generate.
924 RecipeListTy Recipes;
925
926public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000927 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
928 : VPBlockBase(VPBasicBlockSC, Name.str()) {
929 if (Recipe)
930 appendRecipe(Recipe);
931 }
932
933 ~VPBasicBlock() override { Recipes.clear(); }
934
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000935 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000936 using iterator = RecipeListTy::iterator;
937 using const_iterator = RecipeListTy::const_iterator;
938 using reverse_iterator = RecipeListTy::reverse_iterator;
939 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000940
941 //===--------------------------------------------------------------------===//
942 /// Recipe iterator methods
943 ///
944 inline iterator begin() { return Recipes.begin(); }
945 inline const_iterator begin() const { return Recipes.begin(); }
946 inline iterator end() { return Recipes.end(); }
947 inline const_iterator end() const { return Recipes.end(); }
948
949 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
950 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
951 inline reverse_iterator rend() { return Recipes.rend(); }
952 inline const_reverse_iterator rend() const { return Recipes.rend(); }
953
954 inline size_t size() const { return Recipes.size(); }
955 inline bool empty() const { return Recipes.empty(); }
956 inline const VPRecipeBase &front() const { return Recipes.front(); }
957 inline VPRecipeBase &front() { return Recipes.front(); }
958 inline const VPRecipeBase &back() const { return Recipes.back(); }
959 inline VPRecipeBase &back() { return Recipes.back(); }
960
Florian Hahn7591e4e2018-06-18 11:34:17 +0000961 /// Returns a reference to the list of recipes.
962 RecipeListTy &getRecipeList() { return Recipes; }
963
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000964 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000965 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
966 return &VPBasicBlock::Recipes;
967 }
968
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000969 /// Method to support type inquiry through isa, cast, and dyn_cast.
970 static inline bool classof(const VPBlockBase *V) {
971 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
972 }
973
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000974 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000975 assert(Recipe && "No recipe to append.");
976 assert(!Recipe->Parent && "Recipe already in VPlan");
977 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000978 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000979 }
980
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000981 /// Augment the existing recipes of a VPBasicBlock with an additional
982 /// \p Recipe as the last recipe.
983 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
984
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000985 /// The method which generates the output IR instructions that correspond to
986 /// this VPBasicBlock, thereby "executing" the VPlan.
987 void execute(struct VPTransformState *State) override;
988
989private:
990 /// Create an IR BasicBlock to hold the output instructions generated by this
991 /// VPBasicBlock, and return it. Update the CFGState accordingly.
992 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
993};
994
995/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
996/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
997/// A VPRegionBlock may indicate that its contents are to be replicated several
998/// times. This is designed to support predicated scalarization, in which a
999/// scalar if-then code structure needs to be generated VF * UF times. Having
1000/// this replication indicator helps to keep a single model for multiple
1001/// candidate VF's. The actual replication takes place only once the desired VF
1002/// and UF have been determined.
1003class VPRegionBlock : public VPBlockBase {
1004private:
1005 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1006 VPBlockBase *Entry;
1007
1008 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1009 VPBlockBase *Exit;
1010
1011 /// An indicator whether this region is to generate multiple replicated
1012 /// instances of output IR corresponding to its VPBlockBases.
1013 bool IsReplicator;
1014
1015public:
1016 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1017 const std::string &Name = "", bool IsReplicator = false)
1018 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1019 IsReplicator(IsReplicator) {
1020 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1021 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1022 Entry->setParent(this);
1023 Exit->setParent(this);
1024 }
Diego Caballero168d04d2018-05-21 18:14:23 +00001025 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1026 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1027 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001028
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001029 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001030 if (Entry)
1031 deleteCFG(Entry);
1032 }
1033
1034 /// Method to support type inquiry through isa, cast, and dyn_cast.
1035 static inline bool classof(const VPBlockBase *V) {
1036 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1037 }
1038
1039 const VPBlockBase *getEntry() const { return Entry; }
1040 VPBlockBase *getEntry() { return Entry; }
1041
Diego Caballero168d04d2018-05-21 18:14:23 +00001042 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1043 /// EntryBlock must have no predecessors.
1044 void setEntry(VPBlockBase *EntryBlock) {
1045 assert(EntryBlock->getPredecessors().empty() &&
1046 "Entry block cannot have predecessors.");
1047 Entry = EntryBlock;
1048 EntryBlock->setParent(this);
1049 }
1050
Diego Caballero2a34ac82018-07-30 21:33:31 +00001051 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1052 // specific interface of llvm::Function, instead of using
1053 // GraphTraints::getEntryNode. We should add a new template parameter to
1054 // DominatorTreeBase representing the Graph type.
1055 VPBlockBase &front() const { return *Entry; }
1056
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001057 const VPBlockBase *getExit() const { return Exit; }
1058 VPBlockBase *getExit() { return Exit; }
1059
Diego Caballero168d04d2018-05-21 18:14:23 +00001060 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1061 /// ExitBlock must have no successors.
1062 void setExit(VPBlockBase *ExitBlock) {
1063 assert(ExitBlock->getSuccessors().empty() &&
1064 "Exit block cannot have successors.");
1065 Exit = ExitBlock;
1066 ExitBlock->setParent(this);
1067 }
1068
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001069 /// An indicator whether this region is to generate multiple replicated
1070 /// instances of output IR corresponding to its VPBlockBases.
1071 bool isReplicator() const { return IsReplicator; }
1072
1073 /// The method which generates the output IR instructions that correspond to
1074 /// this VPRegionBlock, thereby "executing" the VPlan.
1075 void execute(struct VPTransformState *State) override;
1076};
1077
1078/// VPlan models a candidate for vectorization, encoding various decisions take
1079/// to produce efficient output IR, including which branches, basic-blocks and
1080/// output IR instructions to generate, and their cost. VPlan holds a
1081/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1082/// VPBlock.
1083class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001084 friend class VPlanPrinter;
1085
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001086private:
1087 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1088 VPBlockBase *Entry;
1089
1090 /// Holds the VFs applicable to this VPlan.
1091 SmallSet<unsigned, 2> VFs;
1092
1093 /// Holds the name of the VPlan, for printing.
1094 std::string Name;
1095
Diego Caballero168d04d2018-05-21 18:14:23 +00001096 /// Holds all the external definitions created for this VPlan.
1097 // TODO: Introduce a specific representation for external definitions in
1098 // VPlan. External definitions must be immutable and hold a pointer to its
1099 // underlying IR that will be used to implement its structural comparison
1100 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001101 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001102
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001103 /// Holds a mapping between Values and their corresponding VPValue inside
1104 /// VPlan.
1105 Value2VPValueTy Value2VPValue;
1106
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001107public:
1108 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1109
1110 ~VPlan() {
1111 if (Entry)
1112 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001113 for (auto &MapEntry : Value2VPValue)
1114 delete MapEntry.second;
Diego Caballero168d04d2018-05-21 18:14:23 +00001115 for (VPValue *Def : VPExternalDefs)
1116 delete Def;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001117 }
1118
1119 /// Generate the IR code for this VPlan.
1120 void execute(struct VPTransformState *State);
1121
1122 VPBlockBase *getEntry() { return Entry; }
1123 const VPBlockBase *getEntry() const { return Entry; }
1124
1125 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1126
1127 void addVF(unsigned VF) { VFs.insert(VF); }
1128
1129 bool hasVF(unsigned VF) { return VFs.count(VF); }
1130
1131 const std::string &getName() const { return Name; }
1132
1133 void setName(const Twine &newName) { Name = newName.str(); }
1134
Diego Caballero168d04d2018-05-21 18:14:23 +00001135 /// Add \p VPVal to the pool of external definitions if it's not already
1136 /// in the pool.
1137 void addExternalDef(VPValue *VPVal) {
1138 VPExternalDefs.insert(VPVal);
1139 }
1140
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001141 void addVPValue(Value *V) {
1142 assert(V && "Trying to add a null Value to VPlan");
1143 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1144 Value2VPValue[V] = new VPValue();
1145 }
1146
1147 VPValue *getVPValue(Value *V) {
1148 assert(V && "Trying to get the VPValue of a null Value");
1149 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1150 return Value2VPValue[V];
1151 }
1152
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001153private:
1154 /// Add to the given dominator tree the header block and every new basic block
1155 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001156 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001157 BasicBlock *LoopPreHeaderBB,
1158 BasicBlock *LoopLatchBB);
1159};
1160
1161/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1162/// indented and follows the dot format.
1163class VPlanPrinter {
1164 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1165 friend inline raw_ostream &operator<<(raw_ostream &OS,
1166 const struct VPlanIngredient &I);
1167
1168private:
1169 raw_ostream &OS;
1170 VPlan &Plan;
1171 unsigned Depth;
1172 unsigned TabWidth = 2;
1173 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001174 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001175 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1176
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001177 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1178
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001179 /// Handle indentation.
1180 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1181
1182 /// Print a given \p Block of the Plan.
1183 void dumpBlock(const VPBlockBase *Block);
1184
1185 /// Print the information related to the CFG edges going out of a given
1186 /// \p Block, followed by printing the successor blocks themselves.
1187 void dumpEdges(const VPBlockBase *Block);
1188
1189 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1190 /// its successor blocks.
1191 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1192
1193 /// Print a given \p Region of the Plan.
1194 void dumpRegion(const VPRegionBlock *Region);
1195
1196 unsigned getOrCreateBID(const VPBlockBase *Block) {
1197 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1198 }
1199
1200 const Twine getOrCreateName(const VPBlockBase *Block);
1201
1202 const Twine getUID(const VPBlockBase *Block);
1203
1204 /// Print the information related to a CFG edge between two VPBlockBases.
1205 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1206 const Twine &Label);
1207
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001208 void dump();
1209
1210 static void printAsIngredient(raw_ostream &O, Value *V);
1211};
1212
1213struct VPlanIngredient {
1214 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001215
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001216 VPlanIngredient(Value *V) : V(V) {}
1217};
1218
1219inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1220 VPlanPrinter::printAsIngredient(OS, I.V);
1221 return OS;
1222}
1223
1224inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1225 VPlanPrinter Printer(OS, Plan);
1226 Printer.dump();
1227 return OS;
1228}
1229
Diego Caballero2a34ac82018-07-30 21:33:31 +00001230//===----------------------------------------------------------------------===//
1231// GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs //
1232//===----------------------------------------------------------------------===//
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001233
Diego Caballero2a34ac82018-07-30 21:33:31 +00001234// The following set of template specializations implement GraphTraits to treat
1235// any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1236// that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1237// VPBlockBase is a VPRegionBlock, this specialization provides access to its
1238// successors/predecessors but not to the blocks inside the region.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001239
1240template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001241 using NodeRef = VPBlockBase *;
1242 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001243
1244 static NodeRef getEntryNode(NodeRef N) { return N; }
1245
1246 static inline ChildIteratorType child_begin(NodeRef N) {
1247 return N->getSuccessors().begin();
1248 }
1249
1250 static inline ChildIteratorType child_end(NodeRef N) {
1251 return N->getSuccessors().end();
1252 }
1253};
1254
1255template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001256 using NodeRef = const VPBlockBase *;
1257 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001258
1259 static NodeRef getEntryNode(NodeRef N) { return N; }
1260
1261 static inline ChildIteratorType child_begin(NodeRef N) {
1262 return N->getSuccessors().begin();
1263 }
1264
1265 static inline ChildIteratorType child_end(NodeRef N) {
1266 return N->getSuccessors().end();
1267 }
1268};
1269
Diego Caballero2a34ac82018-07-30 21:33:31 +00001270// Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1271// of successors for the inverse traversal.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001272template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001273 using NodeRef = VPBlockBase *;
1274 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001275
Diego Caballero2a34ac82018-07-30 21:33:31 +00001276 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001277
1278 static inline ChildIteratorType child_begin(NodeRef N) {
1279 return N->getPredecessors().begin();
1280 }
1281
1282 static inline ChildIteratorType child_end(NodeRef N) {
1283 return N->getPredecessors().end();
1284 }
1285};
1286
Diego Caballero2a34ac82018-07-30 21:33:31 +00001287// The following set of template specializations implement GraphTraits to
1288// treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1289// to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1290// (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1291// there won't be automatic recursion into other VPBlockBases that turn to be
1292// VPRegionBlocks.
1293
1294template <>
1295struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1296 using GraphRef = VPRegionBlock *;
1297 using nodes_iterator = df_iterator<NodeRef>;
1298
1299 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1300
1301 static nodes_iterator nodes_begin(GraphRef N) {
1302 return nodes_iterator::begin(N->getEntry());
1303 }
1304
1305 static nodes_iterator nodes_end(GraphRef N) {
1306 // df_iterator::end() returns an empty iterator so the node used doesn't
1307 // matter.
1308 return nodes_iterator::end(N);
1309 }
1310};
1311
1312template <>
1313struct GraphTraits<const VPRegionBlock *>
1314 : public GraphTraits<const VPBlockBase *> {
1315 using GraphRef = const VPRegionBlock *;
1316 using nodes_iterator = df_iterator<NodeRef>;
1317
1318 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1319
1320 static nodes_iterator nodes_begin(GraphRef N) {
1321 return nodes_iterator::begin(N->getEntry());
1322 }
1323
1324 static nodes_iterator nodes_end(GraphRef N) {
1325 // df_iterator::end() returns an empty iterator so the node used doesn't
1326 // matter.
1327 return nodes_iterator::end(N);
1328 }
1329};
1330
1331template <>
1332struct GraphTraits<Inverse<VPRegionBlock *>>
1333 : public GraphTraits<Inverse<VPBlockBase *>> {
1334 using GraphRef = VPRegionBlock *;
1335 using nodes_iterator = df_iterator<NodeRef>;
1336
1337 static NodeRef getEntryNode(Inverse<GraphRef> N) {
1338 return N.Graph->getExit();
1339 }
1340
1341 static nodes_iterator nodes_begin(GraphRef N) {
1342 return nodes_iterator::begin(N->getExit());
1343 }
1344
1345 static nodes_iterator nodes_end(GraphRef N) {
1346 // df_iterator::end() returns an empty iterator so the node used doesn't
1347 // matter.
1348 return nodes_iterator::end(N);
1349 }
1350};
1351
Diego Caballero168d04d2018-05-21 18:14:23 +00001352//===----------------------------------------------------------------------===//
1353// VPlan Utilities
1354//===----------------------------------------------------------------------===//
1355
1356/// Class that provides utilities for VPBlockBases in VPlan.
1357class VPBlockUtils {
1358public:
1359 VPBlockUtils() = delete;
1360
1361 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
Diego Caballerod0953012018-07-09 15:57:09 +00001362 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1363 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1364 /// has more than one successor, its conditional bit is propagated to \p
1365 /// NewBlock. \p NewBlock must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001366 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1367 assert(NewBlock->getSuccessors().empty() &&
1368 "Can't insert new block with successors.");
1369 // TODO: move successors from BlockPtr to NewBlock when this functionality
1370 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1371 // already has successors.
1372 BlockPtr->setOneSuccessor(NewBlock);
1373 NewBlock->setPredecessors({BlockPtr});
1374 NewBlock->setParent(BlockPtr->getParent());
1375 }
1376
1377 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1378 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1379 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
Diego Caballerod0953012018-07-09 15:57:09 +00001380 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1381 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1382 /// must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001383 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
Diego Caballerod0953012018-07-09 15:57:09 +00001384 VPValue *Condition, VPBlockBase *BlockPtr) {
Diego Caballero168d04d2018-05-21 18:14:23 +00001385 assert(IfTrue->getSuccessors().empty() &&
1386 "Can't insert IfTrue with successors.");
1387 assert(IfFalse->getSuccessors().empty() &&
1388 "Can't insert IfFalse with successors.");
Diego Caballerod0953012018-07-09 15:57:09 +00001389 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
Diego Caballero168d04d2018-05-21 18:14:23 +00001390 IfTrue->setPredecessors({BlockPtr});
1391 IfFalse->setPredecessors({BlockPtr});
1392 IfTrue->setParent(BlockPtr->getParent());
1393 IfFalse->setParent(BlockPtr->getParent());
1394 }
1395
1396 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1397 /// the successors of \p From and \p From to the predecessors of \p To. Both
1398 /// VPBlockBases must have the same parent, which can be null. Both
1399 /// VPBlockBases can be already connected to other VPBlockBases.
1400 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1401 assert((From->getParent() == To->getParent()) &&
1402 "Can't connect two block with different parents");
1403 assert(From->getNumSuccessors() < 2 &&
1404 "Blocks can't have more than two successors.");
1405 From->appendSuccessor(To);
1406 To->appendPredecessor(From);
1407 }
1408
1409 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1410 /// from the successors of \p From and \p From from the predecessors of \p To.
1411 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1412 assert(To && "Successor to disconnect is null.");
1413 From->removeSuccessor(To);
1414 To->removePredecessor(From);
1415 }
1416};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001417
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001418} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001419
1420#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H