blob: 2804f16ec9cdb17691209a9e4f44c54af6bd665c [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ayal Zaks1f58dda2017-08-27 12:55:46 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko6cadde72017-10-17 21:27:42 +00008//
Ayal Zaks1f58dda2017-08-27 12:55:46 +00009/// \file
10/// This file contains the declarations of the Vectorization Plan base classes:
11/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
12/// VPBlockBase, together implementing a Hierarchical CFG;
13/// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
14/// treated as proper graphs for generic algorithms;
15/// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
16/// within VPBasicBlocks;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000017/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
18/// instruction;
19/// 5. The VPlan class holding a candidate for vectorization;
20/// 6. The VPlanPrinter class providing a way to print a plan in dot format;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000021/// These are documented in docs/VectorizationPlan.rst.
Eugene Zelenko6cadde72017-10-17 21:27:42 +000022//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000023//===----------------------------------------------------------------------===//
24
25#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27
Diego Caballero35871502018-07-31 01:57:29 +000028#include "VPlanLoopInfo.h"
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"
Florian Hahna4dc7fe2018-11-13 15:58:18 +000040#include "llvm/Analysis/VectorUtils.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000041#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000042#include <algorithm>
43#include <cassert>
44#include <cstddef>
45#include <map>
46#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000047
48namespace llvm {
49
Hal Finkel0f1314c2018-01-07 16:02:58 +000050class LoopVectorizationLegality;
51class LoopVectorizationCostModel;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000052class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000053class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000054class InnerLoopVectorizer;
Florian Hahna4dc7fe2018-11-13 15:58:18 +000055template <class T> class InterleaveGroup;
56class LoopInfo;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000057class raw_ostream;
58class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000059class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000060class VPRegionBlock;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000061class VPlan;
Florian Hahn09e516c2018-11-14 13:11:49 +000062class VPlanSlp;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000063
64/// A range of powers-of-2 vectorization factors with fixed start and
65/// adjustable end. The range includes start and excludes end, e.g.,:
66/// [1, 9) = {1, 2, 4, 8}
67struct VFRange {
68 // A power of 2.
69 const unsigned Start;
70
71 // Need not be a power of 2. If End <= Start range is empty.
72 unsigned End;
73};
74
75using VPlanPtr = std::unique_ptr<VPlan>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000076
77/// In what follows, the term "input IR" refers to code that is fed into the
78/// vectorizer whereas the term "output IR" refers to code that is generated by
79/// the vectorizer.
80
81/// VPIteration represents a single point in the iteration space of the output
82/// (vectorized and/or unrolled) IR loop.
83struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000084 /// in [0..UF)
85 unsigned Part;
86
87 /// in [0..VF)
88 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000089};
90
91/// This is a helper struct for maintaining vectorization state. It's used for
92/// mapping values from the original loop to their corresponding values in
93/// the new loop. Two mappings are maintained: one for vectorized values and
94/// one for scalarized values. Vectorized values are represented with UF
95/// vector values in the new loop, and scalarized values are represented with
96/// UF x VF scalar values in the new loop. UF and VF are the unroll and
97/// vectorization factors, respectively.
98///
99/// Entries can be added to either map with setVectorValue and setScalarValue,
100/// which assert that an entry was not already added before. If an entry is to
101/// replace an existing one, call resetVectorValue and resetScalarValue. This is
102/// currently needed to modify the mapped values during "fix-up" operations that
103/// occur once the first phase of widening is complete. These operations include
104/// type truncation and the second phase of recurrence widening.
105///
106/// Entries from either map can be retrieved using the getVectorValue and
107/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000108struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000109 friend struct VPTransformState;
110
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000111private:
112 /// The unroll factor. Each entry in the vector map contains UF vector values.
113 unsigned UF;
114
115 /// The vectorization factor. Each entry in the scalar map contains UF x VF
116 /// scalar values.
117 unsigned VF;
118
119 /// The vector and scalar map storage. We use std::map and not DenseMap
120 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000121 using VectorParts = SmallVector<Value *, 2>;
122 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000123 std::map<Value *, VectorParts> VectorMapStorage;
124 std::map<Value *, ScalarParts> ScalarMapStorage;
125
126public:
127 /// Construct an empty map with the given unroll and vectorization factors.
128 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
129
130 /// \return True if the map has any vector entry for \p Key.
131 bool hasAnyVectorValue(Value *Key) const {
132 return VectorMapStorage.count(Key);
133 }
134
135 /// \return True if the map has a vector entry for \p Key and \p Part.
136 bool hasVectorValue(Value *Key, unsigned Part) const {
137 assert(Part < UF && "Queried Vector Part is too large.");
138 if (!hasAnyVectorValue(Key))
139 return false;
140 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
141 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
142 return Entry[Part] != nullptr;
143 }
144
145 /// \return True if the map has any scalar entry for \p Key.
146 bool hasAnyScalarValue(Value *Key) const {
147 return ScalarMapStorage.count(Key);
148 }
149
150 /// \return True if the map has a scalar entry for \p Key and \p Instance.
151 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
152 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
153 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
154 if (!hasAnyScalarValue(Key))
155 return false;
156 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
157 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
158 assert(Entry[Instance.Part].size() == VF &&
159 "ScalarParts has wrong dimensions.");
160 return Entry[Instance.Part][Instance.Lane] != nullptr;
161 }
162
163 /// Retrieve the existing vector value that corresponds to \p Key and
164 /// \p Part.
165 Value *getVectorValue(Value *Key, unsigned Part) {
166 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
167 return VectorMapStorage[Key][Part];
168 }
169
170 /// Retrieve the existing scalar value that corresponds to \p Key and
171 /// \p Instance.
172 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
173 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
174 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
175 }
176
177 /// Set a vector value associated with \p Key and \p Part. Assumes such a
178 /// value is not already set. If it is, use resetVectorValue() instead.
179 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
180 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
181 if (!VectorMapStorage.count(Key)) {
182 VectorParts Entry(UF);
183 VectorMapStorage[Key] = Entry;
184 }
185 VectorMapStorage[Key][Part] = Vector;
186 }
187
188 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
189 /// value is not already set.
190 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
191 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
192 if (!ScalarMapStorage.count(Key)) {
193 ScalarParts Entry(UF);
194 // TODO: Consider storing uniform values only per-part, as they occupy
195 // lane 0 only, keeping the other VF-1 redundant entries null.
196 for (unsigned Part = 0; Part < UF; ++Part)
197 Entry[Part].resize(VF, nullptr);
198 ScalarMapStorage[Key] = Entry;
199 }
200 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
201 }
202
203 /// Reset the vector value associated with \p Key for the given \p Part.
204 /// This function can be used to update values that have already been
205 /// vectorized. This is the case for "fix-up" operations including type
206 /// truncation and the second phase of recurrence vectorization.
207 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
208 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
209 VectorMapStorage[Key][Part] = Vector;
210 }
211
212 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
213 /// This function can be used to update values that have already been
214 /// scalarized. This is the case for "fix-up" operations including scalar phi
215 /// nodes for scalarized and predicated instructions.
216 void resetScalarValue(Value *Key, const VPIteration &Instance,
217 Value *Scalar) {
218 assert(hasScalarValue(Key, Instance) &&
219 "Scalar value not set for part and lane");
220 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
221 }
222};
223
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000224/// This class is used to enable the VPlan to invoke a method of ILV. This is
225/// needed until the method is refactored out of ILV and becomes reusable.
226struct VPCallback {
227 virtual ~VPCallback() {}
228 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
229};
230
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000231/// VPTransformState holds information passed down when "executing" a VPlan,
232/// needed for generating the output IR.
233struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000234 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
235 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000236 InnerLoopVectorizer *ILV, VPCallback &Callback)
237 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
238 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000239
240 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
241 unsigned VF;
242 unsigned UF;
243
244 /// Hold the indices to generate specific scalar instructions. Null indicates
245 /// that all instances are to be generated, using either scalar or vector
246 /// instructions.
247 Optional<VPIteration> Instance;
248
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000249 struct DataState {
250 /// A type for vectorized values in the new loop. Each value from the
251 /// original loop, when vectorized, is represented by UF vector values in
252 /// the new unrolled loop, where UF is the unroll factor.
253 typedef SmallVector<Value *, 2> PerPartValuesTy;
254
255 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
256 } Data;
257
258 /// Get the generated Value for a given VPValue and a given Part. Note that
259 /// as some Defs are still created by ILV and managed in its ValueMap, this
260 /// method will delegate the call to ILV in such cases in order to provide
261 /// callers a consistent API.
262 /// \see set.
263 Value *get(VPValue *Def, unsigned Part) {
264 // If Values have been set for this Def return the one relevant for \p Part.
265 if (Data.PerPartOutput.count(Def))
266 return Data.PerPartOutput[Def][Part];
267 // Def is managed by ILV: bring the Values from ValueMap.
268 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
269 }
270
271 /// Set the generated Value for a given VPValue and a given Part.
272 void set(VPValue *Def, Value *V, unsigned Part) {
273 if (!Data.PerPartOutput.count(Def)) {
274 DataState::PerPartValuesTy Entry(UF);
275 Data.PerPartOutput[Def] = Entry;
276 }
277 Data.PerPartOutput[Def][Part] = V;
278 }
279
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000280 /// Hold state information used when constructing the CFG of the output IR,
281 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
282 struct CFGState {
283 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000284 VPBasicBlock *PrevVPBB = nullptr;
285
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000286 /// The previous IR BasicBlock created or used. Initially set to the new
287 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000288 BasicBlock *PrevBB = nullptr;
289
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000290 /// The last IR BasicBlock in the output IR. Set to the new latch
291 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000292 BasicBlock *LastBB = nullptr;
293
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000294 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
295 /// of replication, maps the BasicBlock of the last replica created.
296 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
297
Hideki Saitoea7f3032018-09-14 00:36:00 +0000298 /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
299 /// up at the end of vector code generation.
300 SmallVector<VPBasicBlock *, 8> VPBBsToFix;
301
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000302 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000303 } CFG;
304
305 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000306 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000307
308 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000309 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000310
311 /// Hold a reference to the IRBuilder used to generate output IR code.
312 IRBuilder<> &Builder;
313
314 /// Hold a reference to the Value state information used when generating the
315 /// Values of the output IR.
316 VectorizerValueMap &ValueMap;
317
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000318 /// Hold a reference to a mapping between VPValues in VPlan and original
319 /// Values they correspond to.
320 VPValue2ValueTy VPValue2Value;
321
Ayal Zaksb0b53122018-10-18 15:03:15 +0000322 /// Hold the trip count of the scalar loop.
323 Value *TripCount = nullptr;
324
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000325 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000326 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000327
328 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000329};
330
331/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
332/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
333class VPBlockBase {
Diego Caballero168d04d2018-05-21 18:14:23 +0000334 friend class VPBlockUtils;
335
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000336private:
337 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
338
339 /// An optional name for the block.
340 std::string Name;
341
342 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
343 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000344 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000345
346 /// List of predecessor blocks.
347 SmallVector<VPBlockBase *, 1> Predecessors;
348
349 /// List of successor blocks.
350 SmallVector<VPBlockBase *, 1> Successors;
351
Diego Caballerod0953012018-07-09 15:57:09 +0000352 /// Successor selector, null for zero or single successor blocks.
353 VPValue *CondBit = nullptr;
354
Hideki Saito4e4ecae2019-01-23 22:43:12 +0000355 /// Current block predicate - null if the block does not need a predicate.
356 VPValue *Predicate = nullptr;
357
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000358 /// Add \p Successor as the last successor to this block.
359 void appendSuccessor(VPBlockBase *Successor) {
360 assert(Successor && "Cannot add nullptr successor!");
361 Successors.push_back(Successor);
362 }
363
364 /// Add \p Predecessor as the last predecessor to this block.
365 void appendPredecessor(VPBlockBase *Predecessor) {
366 assert(Predecessor && "Cannot add nullptr predecessor!");
367 Predecessors.push_back(Predecessor);
368 }
369
370 /// Remove \p Predecessor from the predecessors of this block.
371 void removePredecessor(VPBlockBase *Predecessor) {
372 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
373 assert(Pos && "Predecessor does not exist");
374 Predecessors.erase(Pos);
375 }
376
377 /// Remove \p Successor from the successors of this block.
378 void removeSuccessor(VPBlockBase *Successor) {
379 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
380 assert(Pos && "Successor does not exist");
381 Successors.erase(Pos);
382 }
383
384protected:
385 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000386 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000387
388public:
389 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
390 /// that are actually instantiated. Values of this enumeration are kept in the
391 /// SubclassID field of the VPBlockBase objects. They are used for concrete
392 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000393 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000394
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000395 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000396
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000397 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000398
399 const std::string &getName() const { return Name; }
400
401 void setName(const Twine &newName) { Name = newName.str(); }
402
403 /// \return an ID for the concrete type of this object.
404 /// This is used to implement the classof checks. This should not be used
405 /// for any other purpose, as the values may change as LLVM evolves.
406 unsigned getVPBlockID() const { return SubclassID; }
407
Diego Caballero168d04d2018-05-21 18:14:23 +0000408 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000409 const VPRegionBlock *getParent() const { return Parent; }
410
411 void setParent(VPRegionBlock *P) { Parent = P; }
412
413 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
414 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
415 /// VPBlockBase is a VPBasicBlock, it is returned.
416 const VPBasicBlock *getEntryBasicBlock() const;
417 VPBasicBlock *getEntryBasicBlock();
418
419 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
420 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
421 /// VPBlockBase is a VPBasicBlock, it is returned.
422 const VPBasicBlock *getExitBasicBlock() const;
423 VPBasicBlock *getExitBasicBlock();
424
425 const VPBlocksTy &getSuccessors() const { return Successors; }
426 VPBlocksTy &getSuccessors() { return Successors; }
427
428 const VPBlocksTy &getPredecessors() const { return Predecessors; }
429 VPBlocksTy &getPredecessors() { return Predecessors; }
430
431 /// \return the successor of this VPBlockBase if it has a single successor.
432 /// Otherwise return a null pointer.
433 VPBlockBase *getSingleSuccessor() const {
434 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
435 }
436
437 /// \return the predecessor of this VPBlockBase if it has a single
438 /// predecessor. Otherwise return a null pointer.
439 VPBlockBase *getSinglePredecessor() const {
440 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
441 }
442
Diego Caballero168d04d2018-05-21 18:14:23 +0000443 size_t getNumSuccessors() const { return Successors.size(); }
444 size_t getNumPredecessors() const { return Predecessors.size(); }
445
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000446 /// An Enclosing Block of a block B is any block containing B, including B
447 /// itself. \return the closest enclosing block starting from "this", which
448 /// has successors. \return the root enclosing block if all enclosing blocks
449 /// have no successors.
450 VPBlockBase *getEnclosingBlockWithSuccessors();
451
452 /// \return the closest enclosing block starting from "this", which has
453 /// predecessors. \return the root enclosing block if all enclosing blocks
454 /// have no predecessors.
455 VPBlockBase *getEnclosingBlockWithPredecessors();
456
457 /// \return the successors either attached directly to this VPBlockBase or, if
458 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
459 /// successors of its own, search recursively for the first enclosing
460 /// VPRegionBlock that has successors and return them. If no such
461 /// VPRegionBlock exists, return the (empty) successors of the topmost
462 /// VPBlockBase reached.
463 const VPBlocksTy &getHierarchicalSuccessors() {
464 return getEnclosingBlockWithSuccessors()->getSuccessors();
465 }
466
467 /// \return the hierarchical successor of this VPBlockBase if it has a single
468 /// hierarchical successor. Otherwise return a null pointer.
469 VPBlockBase *getSingleHierarchicalSuccessor() {
470 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
471 }
472
473 /// \return the predecessors either attached directly to this VPBlockBase or,
474 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
475 /// predecessors of its own, search recursively for the first enclosing
476 /// VPRegionBlock that has predecessors and return them. If no such
477 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
478 /// VPBlockBase reached.
479 const VPBlocksTy &getHierarchicalPredecessors() {
480 return getEnclosingBlockWithPredecessors()->getPredecessors();
481 }
482
483 /// \return the hierarchical predecessor of this VPBlockBase if it has a
484 /// single hierarchical predecessor. Otherwise return a null pointer.
485 VPBlockBase *getSingleHierarchicalPredecessor() {
486 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
487 }
488
Diego Caballerod0953012018-07-09 15:57:09 +0000489 /// \return the condition bit selecting the successor.
490 VPValue *getCondBit() { return CondBit; }
491
492 const VPValue *getCondBit() const { return CondBit; }
493
494 void setCondBit(VPValue *CV) { CondBit = CV; }
495
Hideki Saito4e4ecae2019-01-23 22:43:12 +0000496 VPValue *getPredicate() { return Predicate; }
497
498 const VPValue *getPredicate() const { return Predicate; }
499
500 void setPredicate(VPValue *Pred) { Predicate = Pred; }
501
Diego Caballero168d04d2018-05-21 18:14:23 +0000502 /// Set a given VPBlockBase \p Successor as the single successor of this
503 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
504 /// This VPBlockBase must have no successors.
505 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000506 assert(Successors.empty() && "Setting one successor when others exist.");
507 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000508 }
509
Diego Caballero168d04d2018-05-21 18:14:23 +0000510 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
Diego Caballerod0953012018-07-09 15:57:09 +0000511 /// successors of this VPBlockBase. \p Condition is set as the successor
512 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
513 /// IfFalse. This VPBlockBase must have no successors.
514 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
515 VPValue *Condition) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000516 assert(Successors.empty() && "Setting two successors when others exist.");
Diego Caballerod0953012018-07-09 15:57:09 +0000517 assert(Condition && "Setting two successors without condition!");
518 CondBit = Condition;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000519 appendSuccessor(IfTrue);
520 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000521 }
522
Diego Caballero168d04d2018-05-21 18:14:23 +0000523 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
524 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
525 /// as successor of any VPBasicBlock in \p NewPreds.
526 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
527 assert(Predecessors.empty() && "Block predecessors already set.");
528 for (auto *Pred : NewPreds)
529 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000530 }
531
Hideki Saito4e4ecae2019-01-23 22:43:12 +0000532 /// Remove all the predecessor of this block.
533 void clearPredecessors() { Predecessors.clear(); }
534
535 /// Remove all the successors of this block and set to null its condition bit
536 void clearSuccessors() {
537 Successors.clear();
538 CondBit = nullptr;
539 }
540
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000541 /// The method which generates the output IR that correspond to this
542 /// VPBlockBase, thereby "executing" the VPlan.
543 virtual void execute(struct VPTransformState *State) = 0;
544
545 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
546 static void deleteCFG(VPBlockBase *Entry);
Diego Caballero2a34ac82018-07-30 21:33:31 +0000547
548 void printAsOperand(raw_ostream &OS, bool PrintType) const {
549 OS << getName();
550 }
551
552 void print(raw_ostream &OS) const {
553 // TODO: Only printing VPBB name for now since we only have dot printing
554 // support for VPInstructions/Recipes.
555 printAsOperand(OS, false);
556 }
Diego Caballero35871502018-07-31 01:57:29 +0000557
558 /// Return true if it is legal to hoist instructions into this block.
559 bool isLegalToHoistInto() {
560 // There are currently no constraints that prevent an instruction to be
561 // hoisted into a VPBlockBase.
562 return true;
563 }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000564};
565
566/// VPRecipeBase is a base class modeling a sequence of one or more output IR
567/// instructions.
568class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
569 friend VPBasicBlock;
Gil Rapaport7f152542019-10-07 17:24:33 +0300570 friend class VPBlockUtils;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000571
572private:
573 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
574
575 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000576 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000577
578public:
579 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
580 /// that is actually instantiated. Values of this enumeration are kept in the
581 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
582 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000583 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000584 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000585 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000586 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000587 VPInterleaveSC,
588 VPPredInstPHISC,
589 VPReplicateSC,
590 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000591 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000592 VPWidenPHISC,
593 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000594 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000595
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000596 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
597 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000598
599 /// \return an ID for the concrete type of this object.
600 /// This is used to implement the classof checks. This should not be used
601 /// for any other purpose, as the values may change as LLVM evolves.
602 unsigned getVPRecipeID() const { return SubclassID; }
603
604 /// \return the VPBasicBlock which this VPRecipe belongs to.
605 VPBasicBlock *getParent() { return Parent; }
606 const VPBasicBlock *getParent() const { return Parent; }
607
608 /// The method which generates the output IR instructions that correspond to
609 /// this VPRecipe, thereby "executing" the VPlan.
610 virtual void execute(struct VPTransformState &State) = 0;
611
612 /// Each recipe prints itself.
613 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
Florian Hahn7591e4e2018-06-18 11:34:17 +0000614
615 /// Insert an unlinked recipe into a basic block immediately before
616 /// the specified recipe.
617 void insertBefore(VPRecipeBase *InsertPos);
Florian Hahn63cbcf92018-06-18 15:18:48 +0000618
Gil Rapaport7f152542019-10-07 17:24:33 +0300619 /// Insert an unlinked Recipe into a basic block immediately after
620 /// the specified Recipe.
621 void insertAfter(VPRecipeBase *InsertPos);
622
Florian Hahn39d4c9f2019-10-11 15:36:55 +0000623 /// Unlink this recipe from its current VPBasicBlock and insert it into
624 /// the VPBasicBlock that MovePos lives in, right after MovePos.
625 void moveAfter(VPRecipeBase *MovePos);
626
Gil Rapaport7f152542019-10-07 17:24:33 +0300627 /// This method unlinks 'this' from the containing basic block, but does not
628 /// delete it.
629 void removeFromParent();
630
Florian Hahn63cbcf92018-06-18 15:18:48 +0000631 /// This method unlinks 'this' from the containing basic block and deletes it.
632 ///
633 /// \returns an iterator pointing to the element after the erased one
634 iplist<VPRecipeBase>::iterator eraseFromParent();
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000635};
636
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000637/// This is a concrete Recipe that models a single VPlan-level instruction.
638/// While as any Recipe it may generate a sequence of IR instructions when
639/// executed, these instructions would always form a single-def expression as
640/// the VPInstruction is also a single def-use vertex.
641class VPInstruction : public VPUser, public VPRecipeBase {
Florian Hahn3385caa2018-06-18 18:28:49 +0000642 friend class VPlanHCFGTransforms;
Florian Hahn09e516c2018-11-14 13:11:49 +0000643 friend class VPlanSlp;
Florian Hahn3385caa2018-06-18 18:28:49 +0000644
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000645public:
646 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
Florian Hahn09e516c2018-11-14 13:11:49 +0000647 enum {
648 Not = Instruction::OtherOpsEnd + 1,
649 ICmpULE,
650 SLPLoad,
651 SLPStore,
652 };
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000653
654private:
655 typedef unsigned char OpcodeTy;
656 OpcodeTy Opcode;
657
658 /// Utility method serving execute(): generates a single instance of the
659 /// modeled instruction.
660 void generateInstruction(VPTransformState &State, unsigned Part);
661
Florian Hahn09e516c2018-11-14 13:11:49 +0000662protected:
663 Instruction *getUnderlyingInstr() {
664 return cast_or_null<Instruction>(getUnderlyingValue());
665 }
666
667 void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
668
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000669public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000670 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000671 : VPUser(VPValue::VPInstructionSC, Operands),
672 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
673
Diego Caballero168d04d2018-05-21 18:14:23 +0000674 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
675 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
676
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000677 /// Method to support type inquiry through isa, cast, and dyn_cast.
678 static inline bool classof(const VPValue *V) {
679 return V->getVPValueID() == VPValue::VPInstructionSC;
680 }
681
Florian Hahn09e516c2018-11-14 13:11:49 +0000682 VPInstruction *clone() const {
683 SmallVector<VPValue *, 2> Operands(operands());
684 return new VPInstruction(Opcode, Operands);
685 }
686
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000687 /// Method to support type inquiry through isa, cast, and dyn_cast.
688 static inline bool classof(const VPRecipeBase *R) {
689 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
690 }
691
692 unsigned getOpcode() const { return Opcode; }
693
694 /// Generate the instruction.
695 /// TODO: We currently execute only per-part unless a specific instance is
696 /// provided.
697 void execute(VPTransformState &State) override;
698
699 /// Print the Recipe.
700 void print(raw_ostream &O, const Twine &Indent) const override;
701
702 /// Print the VPInstruction.
703 void print(raw_ostream &O) const;
Florian Hahn09e516c2018-11-14 13:11:49 +0000704
705 /// Return true if this instruction may modify memory.
706 bool mayWriteToMemory() const {
707 // TODO: we can use attributes of the called function to rule out memory
708 // modifications.
709 return Opcode == Instruction::Store || Opcode == Instruction::Call ||
710 Opcode == Instruction::Invoke || Opcode == SLPStore;
711 }
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000712};
713
Hal Finkel7333aa92017-12-16 01:12:50 +0000714/// VPWidenRecipe is a recipe for producing a copy of vector type for each
715/// Instruction in its ingredients independently, in order. This recipe covers
716/// most of the traditional vectorization cases where each ingredient transforms
717/// into a vectorized version of itself.
718class VPWidenRecipe : public VPRecipeBase {
719private:
720 /// Hold the ingredients by pointing to their original BasicBlock location.
721 BasicBlock::iterator Begin;
722 BasicBlock::iterator End;
723
724public:
725 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
726 End = I->getIterator();
727 Begin = End++;
728 }
729
730 ~VPWidenRecipe() override = default;
731
732 /// Method to support type inquiry through isa, cast, and dyn_cast.
733 static inline bool classof(const VPRecipeBase *V) {
734 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
735 }
736
737 /// Produce widened copies of all Ingredients.
738 void execute(VPTransformState &State) override;
739
740 /// Augment the recipe to include Instr, if it lies at its End.
741 bool appendInstruction(Instruction *Instr) {
742 if (End != Instr->getIterator())
743 return false;
744 End++;
745 return true;
746 }
747
748 /// Print the recipe.
749 void print(raw_ostream &O, const Twine &Indent) const override;
750};
751
752/// A recipe for handling phi nodes of integer and floating-point inductions,
753/// producing their vector and scalar values.
754class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
755private:
756 PHINode *IV;
757 TruncInst *Trunc;
758
759public:
760 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
761 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
762 ~VPWidenIntOrFpInductionRecipe() override = default;
763
764 /// Method to support type inquiry through isa, cast, and dyn_cast.
765 static inline bool classof(const VPRecipeBase *V) {
766 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
767 }
768
769 /// Generate the vectorized and scalarized versions of the phi node as
770 /// needed by their users.
771 void execute(VPTransformState &State) override;
772
773 /// Print the recipe.
774 void print(raw_ostream &O, const Twine &Indent) const override;
775};
776
777/// A recipe for handling all phi nodes except for integer and FP inductions.
778class VPWidenPHIRecipe : public VPRecipeBase {
779private:
780 PHINode *Phi;
781
782public:
783 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
784 ~VPWidenPHIRecipe() override = default;
785
786 /// Method to support type inquiry through isa, cast, and dyn_cast.
787 static inline bool classof(const VPRecipeBase *V) {
788 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
789 }
790
791 /// Generate the phi/select nodes.
792 void execute(VPTransformState &State) override;
793
794 /// Print the recipe.
795 void print(raw_ostream &O, const Twine &Indent) const override;
796};
797
798/// A recipe for vectorizing a phi-node as a sequence of mask-based select
799/// instructions.
800class VPBlendRecipe : public VPRecipeBase {
801private:
802 PHINode *Phi;
803
804 /// The blend operation is a User of a mask, if not null.
805 std::unique_ptr<VPUser> User;
806
807public:
808 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
809 : VPRecipeBase(VPBlendSC), Phi(Phi) {
810 assert((Phi->getNumIncomingValues() == 1 ||
811 Phi->getNumIncomingValues() == Masks.size()) &&
812 "Expected the same number of incoming values and masks");
813 if (!Masks.empty())
814 User.reset(new VPUser(Masks));
815 }
816
817 /// Method to support type inquiry through isa, cast, and dyn_cast.
818 static inline bool classof(const VPRecipeBase *V) {
819 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
820 }
821
822 /// Generate the phi/select nodes.
823 void execute(VPTransformState &State) override;
824
825 /// Print the recipe.
826 void print(raw_ostream &O, const Twine &Indent) const override;
827};
828
829/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
830/// or stores into one wide load/store and shuffles.
831class VPInterleaveRecipe : public VPRecipeBase {
832private:
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000833 const InterleaveGroup<Instruction> *IG;
Dorit Nuzman38bbf812018-10-14 08:50:06 +0000834 std::unique_ptr<VPUser> User;
Hal Finkel7333aa92017-12-16 01:12:50 +0000835
836public:
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000837 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Mask)
Dorit Nuzman38bbf812018-10-14 08:50:06 +0000838 : VPRecipeBase(VPInterleaveSC), IG(IG) {
839 if (Mask) // Create a VPInstruction to register as a user of the mask.
840 User.reset(new VPUser({Mask}));
841 }
Hal Finkel7333aa92017-12-16 01:12:50 +0000842 ~VPInterleaveRecipe() override = default;
843
844 /// Method to support type inquiry through isa, cast, and dyn_cast.
845 static inline bool classof(const VPRecipeBase *V) {
846 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
847 }
848
849 /// Generate the wide load or store, and shuffles.
850 void execute(VPTransformState &State) override;
851
852 /// Print the recipe.
853 void print(raw_ostream &O, const Twine &Indent) const override;
854
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000855 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
Hal Finkel7333aa92017-12-16 01:12:50 +0000856};
857
858/// VPReplicateRecipe replicates a given instruction producing multiple scalar
859/// copies of the original scalar type, one per lane, instead of producing a
860/// single copy of widened type for all lanes. If the instruction is known to be
861/// uniform only one copy, per lane zero, will be generated.
862class VPReplicateRecipe : public VPRecipeBase {
863private:
864 /// The instruction being replicated.
865 Instruction *Ingredient;
866
867 /// Indicator if only a single replica per lane is needed.
868 bool IsUniform;
869
870 /// Indicator if the replicas are also predicated.
871 bool IsPredicated;
872
873 /// Indicator if the scalar values should also be packed into a vector.
874 bool AlsoPack;
875
876public:
877 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
878 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
879 IsPredicated(IsPredicated) {
880 // Retain the previous behavior of predicateInstructions(), where an
881 // insert-element of a predicated instruction got hoisted into the
882 // predicated basic block iff it was its only user. This is achieved by
883 // having predicated instructions also pack their values into a vector by
884 // default unless they have a replicated user which uses their scalar value.
885 AlsoPack = IsPredicated && !I->use_empty();
886 }
887
888 ~VPReplicateRecipe() override = default;
889
890 /// Method to support type inquiry through isa, cast, and dyn_cast.
891 static inline bool classof(const VPRecipeBase *V) {
892 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
893 }
894
895 /// Generate replicas of the desired Ingredient. Replicas will be generated
896 /// for all parts and lanes unless a specific part and lane are specified in
897 /// the \p State.
898 void execute(VPTransformState &State) override;
899
900 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
901
902 /// Print the recipe.
903 void print(raw_ostream &O, const Twine &Indent) const override;
904};
905
906/// A recipe for generating conditional branches on the bits of a mask.
907class VPBranchOnMaskRecipe : public VPRecipeBase {
908private:
909 std::unique_ptr<VPUser> User;
910
911public:
912 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
913 if (BlockInMask) // nullptr means all-one mask.
914 User.reset(new VPUser({BlockInMask}));
915 }
916
917 /// Method to support type inquiry through isa, cast, and dyn_cast.
918 static inline bool classof(const VPRecipeBase *V) {
919 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
920 }
921
922 /// Generate the extraction of the appropriate bit from the block mask and the
923 /// conditional branch.
924 void execute(VPTransformState &State) override;
925
926 /// Print the recipe.
927 void print(raw_ostream &O, const Twine &Indent) const override {
928 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
929 if (User)
930 O << *User->getOperand(0);
931 else
932 O << " All-One";
933 O << "\\l\"";
934 }
935};
936
937/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
938/// control converges back from a Branch-on-Mask. The phi nodes are needed in
939/// order to merge values that are set under such a branch and feed their uses.
940/// The phi nodes can be scalar or vector depending on the users of the value.
941/// This recipe works in concert with VPBranchOnMaskRecipe.
942class VPPredInstPHIRecipe : public VPRecipeBase {
943private:
944 Instruction *PredInst;
945
946public:
947 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
948 /// nodes after merging back from a Branch-on-Mask.
949 VPPredInstPHIRecipe(Instruction *PredInst)
950 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
951 ~VPPredInstPHIRecipe() override = default;
952
953 /// Method to support type inquiry through isa, cast, and dyn_cast.
954 static inline bool classof(const VPRecipeBase *V) {
955 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
956 }
957
958 /// Generates phi nodes for live-outs as needed to retain SSA form.
959 void execute(VPTransformState &State) override;
960
961 /// Print the recipe.
962 void print(raw_ostream &O, const Twine &Indent) const override;
963};
964
965/// A Recipe for widening load/store operations.
966/// TODO: We currently execute only per-part unless a specific instance is
967/// provided.
968class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
969private:
970 Instruction &Instr;
971 std::unique_ptr<VPUser> User;
972
973public:
974 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
975 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
976 if (Mask) // Create a VPInstruction to register as a user of the mask.
977 User.reset(new VPUser({Mask}));
978 }
979
980 /// Method to support type inquiry through isa, cast, and dyn_cast.
981 static inline bool classof(const VPRecipeBase *V) {
982 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
983 }
984
Gil Rapaport7f152542019-10-07 17:24:33 +0300985 /// Return the mask used by this recipe. Note that a full mask is represented
986 /// by a nullptr.
987 VPValue *getMask() {
988 // Mask is the last operand.
989 return User ? User->getOperand(User->getNumOperands() - 1) : nullptr;
990 }
991
Hal Finkel7333aa92017-12-16 01:12:50 +0000992 /// Generate the wide load/store.
993 void execute(VPTransformState &State) override;
994
995 /// Print the recipe.
996 void print(raw_ostream &O, const Twine &Indent) const override;
997};
998
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000999/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1000/// holds a sequence of zero or more VPRecipe's each representing a sequence of
1001/// output IR instructions.
1002class VPBasicBlock : public VPBlockBase {
1003public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001004 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001005
1006private:
1007 /// The VPRecipes held in the order of output instructions to generate.
1008 RecipeListTy Recipes;
1009
1010public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001011 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1012 : VPBlockBase(VPBasicBlockSC, Name.str()) {
1013 if (Recipe)
1014 appendRecipe(Recipe);
1015 }
1016
1017 ~VPBasicBlock() override { Recipes.clear(); }
1018
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001019 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001020 using iterator = RecipeListTy::iterator;
1021 using const_iterator = RecipeListTy::const_iterator;
1022 using reverse_iterator = RecipeListTy::reverse_iterator;
1023 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001024
1025 //===--------------------------------------------------------------------===//
1026 /// Recipe iterator methods
1027 ///
1028 inline iterator begin() { return Recipes.begin(); }
1029 inline const_iterator begin() const { return Recipes.begin(); }
1030 inline iterator end() { return Recipes.end(); }
1031 inline const_iterator end() const { return Recipes.end(); }
1032
1033 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1034 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1035 inline reverse_iterator rend() { return Recipes.rend(); }
1036 inline const_reverse_iterator rend() const { return Recipes.rend(); }
1037
1038 inline size_t size() const { return Recipes.size(); }
1039 inline bool empty() const { return Recipes.empty(); }
1040 inline const VPRecipeBase &front() const { return Recipes.front(); }
1041 inline VPRecipeBase &front() { return Recipes.front(); }
1042 inline const VPRecipeBase &back() const { return Recipes.back(); }
1043 inline VPRecipeBase &back() { return Recipes.back(); }
1044
Florian Hahn7591e4e2018-06-18 11:34:17 +00001045 /// Returns a reference to the list of recipes.
1046 RecipeListTy &getRecipeList() { return Recipes; }
1047
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001048 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001049 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1050 return &VPBasicBlock::Recipes;
1051 }
1052
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001053 /// Method to support type inquiry through isa, cast, and dyn_cast.
1054 static inline bool classof(const VPBlockBase *V) {
1055 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
1056 }
1057
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001058 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001059 assert(Recipe && "No recipe to append.");
1060 assert(!Recipe->Parent && "Recipe already in VPlan");
1061 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001062 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001063 }
1064
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001065 /// Augment the existing recipes of a VPBasicBlock with an additional
1066 /// \p Recipe as the last recipe.
1067 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1068
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001069 /// The method which generates the output IR instructions that correspond to
1070 /// this VPBasicBlock, thereby "executing" the VPlan.
1071 void execute(struct VPTransformState *State) override;
1072
1073private:
1074 /// Create an IR BasicBlock to hold the output instructions generated by this
1075 /// VPBasicBlock, and return it. Update the CFGState accordingly.
1076 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1077};
1078
1079/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1080/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1081/// A VPRegionBlock may indicate that its contents are to be replicated several
1082/// times. This is designed to support predicated scalarization, in which a
1083/// scalar if-then code structure needs to be generated VF * UF times. Having
1084/// this replication indicator helps to keep a single model for multiple
1085/// candidate VF's. The actual replication takes place only once the desired VF
1086/// and UF have been determined.
1087class VPRegionBlock : public VPBlockBase {
1088private:
1089 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1090 VPBlockBase *Entry;
1091
1092 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1093 VPBlockBase *Exit;
1094
1095 /// An indicator whether this region is to generate multiple replicated
1096 /// instances of output IR corresponding to its VPBlockBases.
1097 bool IsReplicator;
1098
1099public:
1100 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1101 const std::string &Name = "", bool IsReplicator = false)
1102 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1103 IsReplicator(IsReplicator) {
1104 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1105 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1106 Entry->setParent(this);
1107 Exit->setParent(this);
1108 }
Diego Caballero168d04d2018-05-21 18:14:23 +00001109 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1110 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1111 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001112
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001113 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001114 if (Entry)
1115 deleteCFG(Entry);
1116 }
1117
1118 /// Method to support type inquiry through isa, cast, and dyn_cast.
1119 static inline bool classof(const VPBlockBase *V) {
1120 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1121 }
1122
1123 const VPBlockBase *getEntry() const { return Entry; }
1124 VPBlockBase *getEntry() { return Entry; }
1125
Diego Caballero168d04d2018-05-21 18:14:23 +00001126 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1127 /// EntryBlock must have no predecessors.
1128 void setEntry(VPBlockBase *EntryBlock) {
1129 assert(EntryBlock->getPredecessors().empty() &&
1130 "Entry block cannot have predecessors.");
1131 Entry = EntryBlock;
1132 EntryBlock->setParent(this);
1133 }
1134
Diego Caballero2a34ac82018-07-30 21:33:31 +00001135 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1136 // specific interface of llvm::Function, instead of using
1137 // GraphTraints::getEntryNode. We should add a new template parameter to
1138 // DominatorTreeBase representing the Graph type.
1139 VPBlockBase &front() const { return *Entry; }
1140
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001141 const VPBlockBase *getExit() const { return Exit; }
1142 VPBlockBase *getExit() { return Exit; }
1143
Diego Caballero168d04d2018-05-21 18:14:23 +00001144 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1145 /// ExitBlock must have no successors.
1146 void setExit(VPBlockBase *ExitBlock) {
1147 assert(ExitBlock->getSuccessors().empty() &&
1148 "Exit block cannot have successors.");
1149 Exit = ExitBlock;
1150 ExitBlock->setParent(this);
1151 }
1152
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001153 /// An indicator whether this region is to generate multiple replicated
1154 /// instances of output IR corresponding to its VPBlockBases.
1155 bool isReplicator() const { return IsReplicator; }
1156
1157 /// The method which generates the output IR instructions that correspond to
1158 /// this VPRegionBlock, thereby "executing" the VPlan.
1159 void execute(struct VPTransformState *State) override;
1160};
1161
Florian Hahnfe459ce2019-12-02 18:21:07 +00001162//===----------------------------------------------------------------------===//
1163// GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs //
1164//===----------------------------------------------------------------------===//
1165
1166// The following set of template specializations implement GraphTraits to treat
1167// any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1168// that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1169// VPBlockBase is a VPRegionBlock, this specialization provides access to its
1170// successors/predecessors but not to the blocks inside the region.
1171
1172template <> struct GraphTraits<VPBlockBase *> {
1173 using NodeRef = VPBlockBase *;
1174 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1175
1176 static NodeRef getEntryNode(NodeRef N) { return N; }
1177
1178 static inline ChildIteratorType child_begin(NodeRef N) {
1179 return N->getSuccessors().begin();
1180 }
1181
1182 static inline ChildIteratorType child_end(NodeRef N) {
1183 return N->getSuccessors().end();
1184 }
1185};
1186
1187template <> struct GraphTraits<const VPBlockBase *> {
1188 using NodeRef = const VPBlockBase *;
1189 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1190
1191 static NodeRef getEntryNode(NodeRef N) { return N; }
1192
1193 static inline ChildIteratorType child_begin(NodeRef N) {
1194 return N->getSuccessors().begin();
1195 }
1196
1197 static inline ChildIteratorType child_end(NodeRef N) {
1198 return N->getSuccessors().end();
1199 }
1200};
1201
1202// Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1203// of successors for the inverse traversal.
1204template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1205 using NodeRef = VPBlockBase *;
1206 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1207
1208 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1209
1210 static inline ChildIteratorType child_begin(NodeRef N) {
1211 return N->getPredecessors().begin();
1212 }
1213
1214 static inline ChildIteratorType child_end(NodeRef N) {
1215 return N->getPredecessors().end();
1216 }
1217};
1218
1219// The following set of template specializations implement GraphTraits to
1220// treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1221// to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1222// (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1223// there won't be automatic recursion into other VPBlockBases that turn to be
1224// VPRegionBlocks.
1225
1226template <>
1227struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1228 using GraphRef = VPRegionBlock *;
1229 using nodes_iterator = df_iterator<NodeRef>;
1230
1231 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1232
1233 static nodes_iterator nodes_begin(GraphRef N) {
1234 return nodes_iterator::begin(N->getEntry());
1235 }
1236
1237 static nodes_iterator nodes_end(GraphRef N) {
1238 // df_iterator::end() returns an empty iterator so the node used doesn't
1239 // matter.
1240 return nodes_iterator::end(N);
1241 }
1242};
1243
1244template <>
1245struct GraphTraits<const VPRegionBlock *>
1246 : public GraphTraits<const VPBlockBase *> {
1247 using GraphRef = const VPRegionBlock *;
1248 using nodes_iterator = df_iterator<NodeRef>;
1249
1250 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1251
1252 static nodes_iterator nodes_begin(GraphRef N) {
1253 return nodes_iterator::begin(N->getEntry());
1254 }
1255
1256 static nodes_iterator nodes_end(GraphRef N) {
1257 // df_iterator::end() returns an empty iterator so the node used doesn't
1258 // matter.
1259 return nodes_iterator::end(N);
1260 }
1261};
1262
1263template <>
1264struct GraphTraits<Inverse<VPRegionBlock *>>
1265 : public GraphTraits<Inverse<VPBlockBase *>> {
1266 using GraphRef = VPRegionBlock *;
1267 using nodes_iterator = df_iterator<NodeRef>;
1268
1269 static NodeRef getEntryNode(Inverse<GraphRef> N) {
1270 return N.Graph->getExit();
1271 }
1272
1273 static nodes_iterator nodes_begin(GraphRef N) {
1274 return nodes_iterator::begin(N->getExit());
1275 }
1276
1277 static nodes_iterator nodes_end(GraphRef N) {
1278 // df_iterator::end() returns an empty iterator so the node used doesn't
1279 // matter.
1280 return nodes_iterator::end(N);
1281 }
1282};
1283
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001284/// VPlan models a candidate for vectorization, encoding various decisions take
1285/// to produce efficient output IR, including which branches, basic-blocks and
1286/// output IR instructions to generate, and their cost. VPlan holds a
1287/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1288/// VPBlock.
1289class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001290 friend class VPlanPrinter;
1291
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001292private:
1293 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1294 VPBlockBase *Entry;
1295
1296 /// Holds the VFs applicable to this VPlan.
1297 SmallSet<unsigned, 2> VFs;
1298
1299 /// Holds the name of the VPlan, for printing.
1300 std::string Name;
1301
Diego Caballero168d04d2018-05-21 18:14:23 +00001302 /// Holds all the external definitions created for this VPlan.
1303 // TODO: Introduce a specific representation for external definitions in
1304 // VPlan. External definitions must be immutable and hold a pointer to its
1305 // underlying IR that will be used to implement its structural comparison
1306 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001307 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001308
Ayal Zaksb0b53122018-10-18 15:03:15 +00001309 /// Represents the backedge taken count of the original loop, for folding
1310 /// the tail.
1311 VPValue *BackedgeTakenCount = nullptr;
1312
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001313 /// Holds a mapping between Values and their corresponding VPValue inside
1314 /// VPlan.
1315 Value2VPValueTy Value2VPValue;
1316
Diego Caballero35871502018-07-31 01:57:29 +00001317 /// Holds the VPLoopInfo analysis for this VPlan.
1318 VPLoopInfo VPLInfo;
1319
Hideki Saitod19851a2018-09-14 02:02:57 +00001320 /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1321 SmallVector<VPValue *, 4> VPCBVs;
1322
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001323public:
1324 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1325
1326 ~VPlan() {
1327 if (Entry)
1328 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001329 for (auto &MapEntry : Value2VPValue)
Ayal Zaksb0b53122018-10-18 15:03:15 +00001330 if (MapEntry.second != BackedgeTakenCount)
1331 delete MapEntry.second;
1332 if (BackedgeTakenCount)
1333 delete BackedgeTakenCount; // Delete once, if in Value2VPValue or not.
Diego Caballero168d04d2018-05-21 18:14:23 +00001334 for (VPValue *Def : VPExternalDefs)
1335 delete Def;
Hideki Saitod19851a2018-09-14 02:02:57 +00001336 for (VPValue *CBV : VPCBVs)
1337 delete CBV;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001338 }
1339
1340 /// Generate the IR code for this VPlan.
1341 void execute(struct VPTransformState *State);
1342
1343 VPBlockBase *getEntry() { return Entry; }
1344 const VPBlockBase *getEntry() const { return Entry; }
1345
1346 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1347
Ayal Zaksb0b53122018-10-18 15:03:15 +00001348 /// The backedge taken count of the original loop.
1349 VPValue *getOrCreateBackedgeTakenCount() {
1350 if (!BackedgeTakenCount)
1351 BackedgeTakenCount = new VPValue();
1352 return BackedgeTakenCount;
1353 }
1354
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001355 void addVF(unsigned VF) { VFs.insert(VF); }
1356
1357 bool hasVF(unsigned VF) { return VFs.count(VF); }
1358
1359 const std::string &getName() const { return Name; }
1360
1361 void setName(const Twine &newName) { Name = newName.str(); }
1362
Diego Caballero168d04d2018-05-21 18:14:23 +00001363 /// Add \p VPVal to the pool of external definitions if it's not already
1364 /// in the pool.
1365 void addExternalDef(VPValue *VPVal) {
1366 VPExternalDefs.insert(VPVal);
1367 }
1368
Hideki Saitod19851a2018-09-14 02:02:57 +00001369 /// Add \p CBV to the vector of condition bit values.
1370 void addCBV(VPValue *CBV) {
1371 VPCBVs.push_back(CBV);
1372 }
1373
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001374 void addVPValue(Value *V) {
1375 assert(V && "Trying to add a null Value to VPlan");
1376 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1377 Value2VPValue[V] = new VPValue();
1378 }
1379
1380 VPValue *getVPValue(Value *V) {
1381 assert(V && "Trying to get the VPValue of a null Value");
1382 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1383 return Value2VPValue[V];
1384 }
1385
Diego Caballero35871502018-07-31 01:57:29 +00001386 /// Return the VPLoopInfo analysis for this VPlan.
1387 VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1388 const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1389
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001390private:
1391 /// Add to the given dominator tree the header block and every new basic block
1392 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001393 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001394 BasicBlock *LoopPreHeaderBB,
1395 BasicBlock *LoopLatchBB);
1396};
1397
1398/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1399/// indented and follows the dot format.
1400class VPlanPrinter {
1401 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1402 friend inline raw_ostream &operator<<(raw_ostream &OS,
1403 const struct VPlanIngredient &I);
1404
1405private:
1406 raw_ostream &OS;
1407 VPlan &Plan;
Simon Pilgrim81ba6112019-11-03 11:17:05 +00001408 unsigned Depth = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001409 unsigned TabWidth = 2;
1410 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001411 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001412 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1413
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001414 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1415
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001416 /// Handle indentation.
1417 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1418
1419 /// Print a given \p Block of the Plan.
1420 void dumpBlock(const VPBlockBase *Block);
1421
1422 /// Print the information related to the CFG edges going out of a given
1423 /// \p Block, followed by printing the successor blocks themselves.
1424 void dumpEdges(const VPBlockBase *Block);
1425
1426 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1427 /// its successor blocks.
1428 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1429
1430 /// Print a given \p Region of the Plan.
1431 void dumpRegion(const VPRegionBlock *Region);
1432
1433 unsigned getOrCreateBID(const VPBlockBase *Block) {
1434 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1435 }
1436
1437 const Twine getOrCreateName(const VPBlockBase *Block);
1438
1439 const Twine getUID(const VPBlockBase *Block);
1440
1441 /// Print the information related to a CFG edge between two VPBlockBases.
1442 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1443 const Twine &Label);
1444
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001445 void dump();
1446
1447 static void printAsIngredient(raw_ostream &O, Value *V);
1448};
1449
1450struct VPlanIngredient {
1451 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001452
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001453 VPlanIngredient(Value *V) : V(V) {}
1454};
1455
1456inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1457 VPlanPrinter::printAsIngredient(OS, I.V);
1458 return OS;
1459}
1460
1461inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1462 VPlanPrinter Printer(OS, Plan);
1463 Printer.dump();
1464 return OS;
1465}
1466
Diego Caballero2a34ac82018-07-30 21:33:31 +00001467
Diego Caballero168d04d2018-05-21 18:14:23 +00001468//===----------------------------------------------------------------------===//
1469// VPlan Utilities
1470//===----------------------------------------------------------------------===//
1471
1472/// Class that provides utilities for VPBlockBases in VPlan.
1473class VPBlockUtils {
1474public:
1475 VPBlockUtils() = delete;
1476
1477 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
Diego Caballerod0953012018-07-09 15:57:09 +00001478 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1479 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1480 /// has more than one successor, its conditional bit is propagated to \p
1481 /// NewBlock. \p NewBlock must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001482 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1483 assert(NewBlock->getSuccessors().empty() &&
1484 "Can't insert new block with successors.");
1485 // TODO: move successors from BlockPtr to NewBlock when this functionality
1486 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1487 // already has successors.
1488 BlockPtr->setOneSuccessor(NewBlock);
1489 NewBlock->setPredecessors({BlockPtr});
1490 NewBlock->setParent(BlockPtr->getParent());
1491 }
1492
1493 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1494 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1495 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
Diego Caballerod0953012018-07-09 15:57:09 +00001496 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1497 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1498 /// must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001499 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
Diego Caballerod0953012018-07-09 15:57:09 +00001500 VPValue *Condition, VPBlockBase *BlockPtr) {
Diego Caballero168d04d2018-05-21 18:14:23 +00001501 assert(IfTrue->getSuccessors().empty() &&
1502 "Can't insert IfTrue with successors.");
1503 assert(IfFalse->getSuccessors().empty() &&
1504 "Can't insert IfFalse with successors.");
Diego Caballerod0953012018-07-09 15:57:09 +00001505 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
Diego Caballero168d04d2018-05-21 18:14:23 +00001506 IfTrue->setPredecessors({BlockPtr});
1507 IfFalse->setPredecessors({BlockPtr});
1508 IfTrue->setParent(BlockPtr->getParent());
1509 IfFalse->setParent(BlockPtr->getParent());
1510 }
1511
1512 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1513 /// the successors of \p From and \p From to the predecessors of \p To. Both
1514 /// VPBlockBases must have the same parent, which can be null. Both
1515 /// VPBlockBases can be already connected to other VPBlockBases.
1516 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1517 assert((From->getParent() == To->getParent()) &&
1518 "Can't connect two block with different parents");
1519 assert(From->getNumSuccessors() < 2 &&
1520 "Blocks can't have more than two successors.");
1521 From->appendSuccessor(To);
1522 To->appendPredecessor(From);
1523 }
1524
1525 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1526 /// from the successors of \p From and \p From from the predecessors of \p To.
1527 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1528 assert(To && "Successor to disconnect is null.");
1529 From->removeSuccessor(To);
1530 To->removePredecessor(From);
1531 }
Hideki Saito4e4ecae2019-01-23 22:43:12 +00001532
1533 /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
1534 static bool isBackEdge(const VPBlockBase *FromBlock,
1535 const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
1536 assert(FromBlock->getParent() == ToBlock->getParent() &&
1537 FromBlock->getParent() && "Must be in same region");
1538 const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
1539 const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
1540 if (!FromLoop || !ToLoop || FromLoop != ToLoop)
1541 return false;
1542
1543 // A back-edge is a branch from the loop latch to its header.
1544 return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
1545 }
1546
1547 /// Returns true if \p Block is a loop latch
1548 static bool blockIsLoopLatch(const VPBlockBase *Block,
1549 const VPLoopInfo *VPLInfo) {
1550 if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
1551 return ParentVPL->isLoopLatch(Block);
1552
1553 return false;
1554 }
1555
1556 /// Count and return the number of succesors of \p PredBlock excluding any
1557 /// backedges.
1558 static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
1559 VPLoopInfo *VPLI) {
1560 unsigned Count = 0;
1561 for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
1562 if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
1563 Count++;
1564 }
1565 return Count;
1566 }
Diego Caballero168d04d2018-05-21 18:14:23 +00001567};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001568
Florian Hahna4dc7fe2018-11-13 15:58:18 +00001569class VPInterleavedAccessInfo {
1570private:
1571 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
1572 InterleaveGroupMap;
1573
1574 /// Type for mapping of instruction based interleave groups to VPInstruction
1575 /// interleave groups
1576 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
1577 InterleaveGroup<VPInstruction> *>;
1578
1579 /// Recursively \p Region and populate VPlan based interleave groups based on
1580 /// \p IAI.
1581 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
1582 InterleavedAccessInfo &IAI);
1583 /// Recursively traverse \p Block and populate VPlan based interleave groups
1584 /// based on \p IAI.
1585 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1586 InterleavedAccessInfo &IAI);
1587
1588public:
1589 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
1590
1591 ~VPInterleavedAccessInfo() {
1592 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
1593 // Avoid releasing a pointer twice.
1594 for (auto &I : InterleaveGroupMap)
1595 DelSet.insert(I.second);
1596 for (auto *Ptr : DelSet)
1597 delete Ptr;
1598 }
1599
1600 /// Get the interleave group that \p Instr belongs to.
1601 ///
1602 /// \returns nullptr if doesn't have such group.
1603 InterleaveGroup<VPInstruction> *
1604 getInterleaveGroup(VPInstruction *Instr) const {
1605 if (InterleaveGroupMap.count(Instr))
1606 return InterleaveGroupMap.find(Instr)->second;
1607 return nullptr;
1608 }
1609};
1610
Florian Hahn09e516c2018-11-14 13:11:49 +00001611/// Class that maps (parts of) an existing VPlan to trees of combined
1612/// VPInstructions.
1613class VPlanSlp {
1614private:
1615 enum class OpMode { Failed, Load, Opcode };
1616
1617 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
1618 /// DenseMap keys.
1619 struct BundleDenseMapInfo {
1620 static SmallVector<VPValue *, 4> getEmptyKey() {
1621 return {reinterpret_cast<VPValue *>(-1)};
1622 }
1623
1624 static SmallVector<VPValue *, 4> getTombstoneKey() {
1625 return {reinterpret_cast<VPValue *>(-2)};
1626 }
1627
1628 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
1629 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1630 }
1631
1632 static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
1633 const SmallVector<VPValue *, 4> &RHS) {
1634 return LHS == RHS;
1635 }
1636 };
1637
1638 /// Mapping of values in the original VPlan to a combined VPInstruction.
1639 DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
1640 BundleToCombined;
1641
1642 VPInterleavedAccessInfo &IAI;
1643
1644 /// Basic block to operate on. For now, only instructions in a single BB are
1645 /// considered.
1646 const VPBasicBlock &BB;
1647
1648 /// Indicates whether we managed to combine all visited instructions or not.
1649 bool CompletelySLP = true;
1650
1651 /// Width of the widest combined bundle in bits.
1652 unsigned WidestBundleBits = 0;
1653
1654 using MultiNodeOpTy =
1655 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
1656
1657 // Input operand bundles for the current multi node. Each multi node operand
1658 // bundle contains values not matching the multi node's opcode. They will
1659 // be reordered in reorderMultiNodeOps, once we completed building a
1660 // multi node.
1661 SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
1662
1663 /// Indicates whether we are building a multi node currently.
1664 bool MultiNodeActive = false;
1665
1666 /// Check if we can vectorize Operands together.
1667 bool areVectorizable(ArrayRef<VPValue *> Operands) const;
1668
1669 /// Add combined instruction \p New for the bundle \p Operands.
1670 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
1671
1672 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
1673 VPInstruction *markFailed();
1674
1675 /// Reorder operands in the multi node to maximize sequential memory access
1676 /// and commutative operations.
1677 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
1678
1679 /// Choose the best candidate to use for the lane after \p Last. The set of
1680 /// candidates to choose from are values with an opcode matching \p Last's
1681 /// or loads consecutive to \p Last.
1682 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
Florian Hahn6df11862018-11-14 15:58:40 +00001683 SmallPtrSetImpl<VPValue *> &Candidates,
Florian Hahn09e516c2018-11-14 13:11:49 +00001684 VPInterleavedAccessInfo &IAI);
1685
1686 /// Print bundle \p Values to dbgs().
1687 void dumpBundle(ArrayRef<VPValue *> Values);
1688
1689public:
1690 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
1691
1692 ~VPlanSlp() {
1693 for (auto &KV : BundleToCombined)
1694 delete KV.second;
1695 }
1696
1697 /// Tries to build an SLP tree rooted at \p Operands and returns a
1698 /// VPInstruction combining \p Operands, if they can be combined.
1699 VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
1700
1701 /// Return the width of the widest combined bundle in bits.
1702 unsigned getWidestBundleBits() const { return WidestBundleBits; }
1703
1704 /// Return true if all visited instruction can be combined.
1705 bool isCompletelySLP() const { return CompletelySLP; }
1706};
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001707} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001708
1709#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H