File: | build/source/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp |
Warning: | line 9966, column 30 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// | |||
2 | // | |||
3 | // 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 | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This pass implements the Bottom Up SLP vectorizer. It detects consecutive | |||
10 | // stores that can be put together into vector-stores. Next, it attempts to | |||
11 | // construct vectorizable tree using the use-def chains. If a profitable tree | |||
12 | // was found, the SLP vectorizer performs vectorization on the tree. | |||
13 | // | |||
14 | // The pass is inspired by the work described in the paper: | |||
15 | // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks. | |||
16 | // | |||
17 | //===----------------------------------------------------------------------===// | |||
18 | ||||
19 | #include "llvm/Transforms/Vectorize/SLPVectorizer.h" | |||
20 | #include "llvm/ADT/DenseMap.h" | |||
21 | #include "llvm/ADT/DenseSet.h" | |||
22 | #include "llvm/ADT/Optional.h" | |||
23 | #include "llvm/ADT/PostOrderIterator.h" | |||
24 | #include "llvm/ADT/PriorityQueue.h" | |||
25 | #include "llvm/ADT/STLExtras.h" | |||
26 | #include "llvm/ADT/SetOperations.h" | |||
27 | #include "llvm/ADT/SetVector.h" | |||
28 | #include "llvm/ADT/SmallBitVector.h" | |||
29 | #include "llvm/ADT/SmallPtrSet.h" | |||
30 | #include "llvm/ADT/SmallSet.h" | |||
31 | #include "llvm/ADT/SmallString.h" | |||
32 | #include "llvm/ADT/Statistic.h" | |||
33 | #include "llvm/ADT/iterator.h" | |||
34 | #include "llvm/ADT/iterator_range.h" | |||
35 | #include "llvm/Analysis/AliasAnalysis.h" | |||
36 | #include "llvm/Analysis/AssumptionCache.h" | |||
37 | #include "llvm/Analysis/CodeMetrics.h" | |||
38 | #include "llvm/Analysis/DemandedBits.h" | |||
39 | #include "llvm/Analysis/GlobalsModRef.h" | |||
40 | #include "llvm/Analysis/IVDescriptors.h" | |||
41 | #include "llvm/Analysis/LoopAccessAnalysis.h" | |||
42 | #include "llvm/Analysis/LoopInfo.h" | |||
43 | #include "llvm/Analysis/MemoryLocation.h" | |||
44 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" | |||
45 | #include "llvm/Analysis/ScalarEvolution.h" | |||
46 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" | |||
47 | #include "llvm/Analysis/TargetLibraryInfo.h" | |||
48 | #include "llvm/Analysis/TargetTransformInfo.h" | |||
49 | #include "llvm/Analysis/ValueTracking.h" | |||
50 | #include "llvm/Analysis/VectorUtils.h" | |||
51 | #include "llvm/IR/Attributes.h" | |||
52 | #include "llvm/IR/BasicBlock.h" | |||
53 | #include "llvm/IR/Constant.h" | |||
54 | #include "llvm/IR/Constants.h" | |||
55 | #include "llvm/IR/DataLayout.h" | |||
56 | #include "llvm/IR/DerivedTypes.h" | |||
57 | #include "llvm/IR/Dominators.h" | |||
58 | #include "llvm/IR/Function.h" | |||
59 | #include "llvm/IR/IRBuilder.h" | |||
60 | #include "llvm/IR/InstrTypes.h" | |||
61 | #include "llvm/IR/Instruction.h" | |||
62 | #include "llvm/IR/Instructions.h" | |||
63 | #include "llvm/IR/IntrinsicInst.h" | |||
64 | #include "llvm/IR/Intrinsics.h" | |||
65 | #include "llvm/IR/Module.h" | |||
66 | #include "llvm/IR/Operator.h" | |||
67 | #include "llvm/IR/PatternMatch.h" | |||
68 | #include "llvm/IR/Type.h" | |||
69 | #include "llvm/IR/Use.h" | |||
70 | #include "llvm/IR/User.h" | |||
71 | #include "llvm/IR/Value.h" | |||
72 | #include "llvm/IR/ValueHandle.h" | |||
73 | #ifdef EXPENSIVE_CHECKS | |||
74 | #include "llvm/IR/Verifier.h" | |||
75 | #endif | |||
76 | #include "llvm/Pass.h" | |||
77 | #include "llvm/Support/Casting.h" | |||
78 | #include "llvm/Support/CommandLine.h" | |||
79 | #include "llvm/Support/Compiler.h" | |||
80 | #include "llvm/Support/DOTGraphTraits.h" | |||
81 | #include "llvm/Support/Debug.h" | |||
82 | #include "llvm/Support/ErrorHandling.h" | |||
83 | #include "llvm/Support/GraphWriter.h" | |||
84 | #include "llvm/Support/InstructionCost.h" | |||
85 | #include "llvm/Support/KnownBits.h" | |||
86 | #include "llvm/Support/MathExtras.h" | |||
87 | #include "llvm/Support/raw_ostream.h" | |||
88 | #include "llvm/Transforms/Utils/InjectTLIMappings.h" | |||
89 | #include "llvm/Transforms/Utils/Local.h" | |||
90 | #include "llvm/Transforms/Utils/LoopUtils.h" | |||
91 | #include "llvm/Transforms/Vectorize.h" | |||
92 | #include <algorithm> | |||
93 | #include <cassert> | |||
94 | #include <cstdint> | |||
95 | #include <iterator> | |||
96 | #include <memory> | |||
97 | #include <set> | |||
98 | #include <string> | |||
99 | #include <tuple> | |||
100 | #include <utility> | |||
101 | #include <vector> | |||
102 | ||||
103 | using namespace llvm; | |||
104 | using namespace llvm::PatternMatch; | |||
105 | using namespace slpvectorizer; | |||
106 | ||||
107 | #define SV_NAME"slp-vectorizer" "slp-vectorizer" | |||
108 | #define DEBUG_TYPE"SLP" "SLP" | |||
109 | ||||
110 | STATISTIC(NumVectorInstructions, "Number of vector instructions generated")static llvm::Statistic NumVectorInstructions = {"SLP", "NumVectorInstructions" , "Number of vector instructions generated"}; | |||
111 | ||||
112 | cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden, | |||
113 | cl::desc("Run the SLP vectorization passes")); | |||
114 | ||||
115 | static cl::opt<int> | |||
116 | SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, | |||
117 | cl::desc("Only vectorize if you gain more than this " | |||
118 | "number ")); | |||
119 | ||||
120 | static cl::opt<bool> | |||
121 | ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, | |||
122 | cl::desc("Attempt to vectorize horizontal reductions")); | |||
123 | ||||
124 | static cl::opt<bool> ShouldStartVectorizeHorAtStore( | |||
125 | "slp-vectorize-hor-store", cl::init(false), cl::Hidden, | |||
126 | cl::desc( | |||
127 | "Attempt to vectorize horizontal reductions feeding into a store")); | |||
128 | ||||
129 | static cl::opt<int> | |||
130 | MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, | |||
131 | cl::desc("Attempt to vectorize for this register size in bits")); | |||
132 | ||||
133 | static cl::opt<unsigned> | |||
134 | MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden, | |||
135 | cl::desc("Maximum SLP vectorization factor (0=unlimited)")); | |||
136 | ||||
137 | static cl::opt<int> | |||
138 | MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, | |||
139 | cl::desc("Maximum depth of the lookup for consecutive stores.")); | |||
140 | ||||
141 | /// Limits the size of scheduling regions in a block. | |||
142 | /// It avoid long compile times for _very_ large blocks where vector | |||
143 | /// instructions are spread over a wide range. | |||
144 | /// This limit is way higher than needed by real-world functions. | |||
145 | static cl::opt<int> | |||
146 | ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, | |||
147 | cl::desc("Limit the size of the SLP scheduling region per block")); | |||
148 | ||||
149 | static cl::opt<int> MinVectorRegSizeOption( | |||
150 | "slp-min-reg-size", cl::init(128), cl::Hidden, | |||
151 | cl::desc("Attempt to vectorize for this register size in bits")); | |||
152 | ||||
153 | static cl::opt<unsigned> RecursionMaxDepth( | |||
154 | "slp-recursion-max-depth", cl::init(12), cl::Hidden, | |||
155 | cl::desc("Limit the recursion depth when building a vectorizable tree")); | |||
156 | ||||
157 | static cl::opt<unsigned> MinTreeSize( | |||
158 | "slp-min-tree-size", cl::init(3), cl::Hidden, | |||
159 | cl::desc("Only vectorize small trees if they are fully vectorizable")); | |||
160 | ||||
161 | // The maximum depth that the look-ahead score heuristic will explore. | |||
162 | // The higher this value, the higher the compilation time overhead. | |||
163 | static cl::opt<int> LookAheadMaxDepth( | |||
164 | "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, | |||
165 | cl::desc("The maximum look-ahead depth for operand reordering scores")); | |||
166 | ||||
167 | // The maximum depth that the look-ahead score heuristic will explore | |||
168 | // when it probing among candidates for vectorization tree roots. | |||
169 | // The higher this value, the higher the compilation time overhead but unlike | |||
170 | // similar limit for operands ordering this is less frequently used, hence | |||
171 | // impact of higher value is less noticeable. | |||
172 | static cl::opt<int> RootLookAheadMaxDepth( | |||
173 | "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden, | |||
174 | cl::desc("The maximum look-ahead depth for searching best rooting option")); | |||
175 | ||||
176 | static cl::opt<bool> | |||
177 | ViewSLPTree("view-slp-tree", cl::Hidden, | |||
178 | cl::desc("Display the SLP trees with Graphviz")); | |||
179 | ||||
180 | // Limit the number of alias checks. The limit is chosen so that | |||
181 | // it has no negative effect on the llvm benchmarks. | |||
182 | static const unsigned AliasedCheckLimit = 10; | |||
183 | ||||
184 | // Another limit for the alias checks: The maximum distance between load/store | |||
185 | // instructions where alias checks are done. | |||
186 | // This limit is useful for very large basic blocks. | |||
187 | static const unsigned MaxMemDepDistance = 160; | |||
188 | ||||
189 | /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling | |||
190 | /// regions to be handled. | |||
191 | static const int MinScheduleRegionSize = 16; | |||
192 | ||||
193 | /// Predicate for the element types that the SLP vectorizer supports. | |||
194 | /// | |||
195 | /// The most important thing to filter here are types which are invalid in LLVM | |||
196 | /// vectors. We also filter target specific types which have absolutely no | |||
197 | /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just | |||
198 | /// avoids spending time checking the cost model and realizing that they will | |||
199 | /// be inevitably scalarized. | |||
200 | static bool isValidElementType(Type *Ty) { | |||
201 | return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && | |||
202 | !Ty->isPPC_FP128Ty(); | |||
203 | } | |||
204 | ||||
205 | /// \returns True if the value is a constant (but not globals/constant | |||
206 | /// expressions). | |||
207 | static bool isConstant(Value *V) { | |||
208 | return isa<Constant>(V) && !isa<ConstantExpr, GlobalValue>(V); | |||
209 | } | |||
210 | ||||
211 | /// Checks if \p V is one of vector-like instructions, i.e. undef, | |||
212 | /// insertelement/extractelement with constant indices for fixed vector type or | |||
213 | /// extractvalue instruction. | |||
214 | static bool isVectorLikeInstWithConstOps(Value *V) { | |||
215 | if (!isa<InsertElementInst, ExtractElementInst>(V) && | |||
216 | !isa<ExtractValueInst, UndefValue>(V)) | |||
217 | return false; | |||
218 | auto *I = dyn_cast<Instruction>(V); | |||
219 | if (!I || isa<ExtractValueInst>(I)) | |||
220 | return true; | |||
221 | if (!isa<FixedVectorType>(I->getOperand(0)->getType())) | |||
222 | return false; | |||
223 | if (isa<ExtractElementInst>(I)) | |||
224 | return isConstant(I->getOperand(1)); | |||
225 | assert(isa<InsertElementInst>(V) && "Expected only insertelement.")(static_cast <bool> (isa<InsertElementInst>(V) && "Expected only insertelement.") ? void (0) : __assert_fail ( "isa<InsertElementInst>(V) && \"Expected only insertelement.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 225, __extension__ __PRETTY_FUNCTION__)); | |||
226 | return isConstant(I->getOperand(2)); | |||
227 | } | |||
228 | ||||
229 | /// \returns true if all of the instructions in \p VL are in the same block or | |||
230 | /// false otherwise. | |||
231 | static bool allSameBlock(ArrayRef<Value *> VL) { | |||
232 | Instruction *I0 = dyn_cast<Instruction>(VL[0]); | |||
233 | if (!I0) | |||
234 | return false; | |||
235 | if (all_of(VL, isVectorLikeInstWithConstOps)) | |||
236 | return true; | |||
237 | ||||
238 | BasicBlock *BB = I0->getParent(); | |||
239 | for (int I = 1, E = VL.size(); I < E; I++) { | |||
240 | auto *II = dyn_cast<Instruction>(VL[I]); | |||
241 | if (!II) | |||
242 | return false; | |||
243 | ||||
244 | if (BB != II->getParent()) | |||
245 | return false; | |||
246 | } | |||
247 | return true; | |||
248 | } | |||
249 | ||||
250 | /// \returns True if all of the values in \p VL are constants (but not | |||
251 | /// globals/constant expressions). | |||
252 | static bool allConstant(ArrayRef<Value *> VL) { | |||
253 | // Constant expressions and globals can't be vectorized like normal integer/FP | |||
254 | // constants. | |||
255 | return all_of(VL, isConstant); | |||
256 | } | |||
257 | ||||
258 | /// \returns True if all of the values in \p VL are identical or some of them | |||
259 | /// are UndefValue. | |||
260 | static bool isSplat(ArrayRef<Value *> VL) { | |||
261 | Value *FirstNonUndef = nullptr; | |||
262 | for (Value *V : VL) { | |||
263 | if (isa<UndefValue>(V)) | |||
264 | continue; | |||
265 | if (!FirstNonUndef) { | |||
266 | FirstNonUndef = V; | |||
267 | continue; | |||
268 | } | |||
269 | if (V != FirstNonUndef) | |||
270 | return false; | |||
271 | } | |||
272 | return FirstNonUndef != nullptr; | |||
273 | } | |||
274 | ||||
275 | /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. | |||
276 | static bool isCommutative(Instruction *I) { | |||
277 | if (auto *Cmp = dyn_cast<CmpInst>(I)) | |||
278 | return Cmp->isCommutative(); | |||
279 | if (auto *BO = dyn_cast<BinaryOperator>(I)) | |||
280 | return BO->isCommutative(); | |||
281 | // TODO: This should check for generic Instruction::isCommutative(), but | |||
282 | // we need to confirm that the caller code correctly handles Intrinsics | |||
283 | // for example (does not have 2 operands). | |||
284 | return false; | |||
285 | } | |||
286 | ||||
287 | /// \returns inserting index of InsertElement or InsertValue instruction, | |||
288 | /// using Offset as base offset for index. | |||
289 | static Optional<unsigned> getInsertIndex(const Value *InsertInst, | |||
290 | unsigned Offset = 0) { | |||
291 | int Index = Offset; | |||
292 | if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { | |||
293 | const auto *VT = dyn_cast<FixedVectorType>(IE->getType()); | |||
294 | if (!VT) | |||
295 | return None; | |||
296 | const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2)); | |||
297 | if (!CI) | |||
298 | return None; | |||
299 | if (CI->getValue().uge(VT->getNumElements())) | |||
300 | return None; | |||
301 | Index *= VT->getNumElements(); | |||
302 | Index += CI->getZExtValue(); | |||
303 | return Index; | |||
304 | } | |||
305 | ||||
306 | const auto *IV = cast<InsertValueInst>(InsertInst); | |||
307 | Type *CurrentType = IV->getType(); | |||
308 | for (unsigned I : IV->indices()) { | |||
309 | if (const auto *ST = dyn_cast<StructType>(CurrentType)) { | |||
310 | Index *= ST->getNumElements(); | |||
311 | CurrentType = ST->getElementType(I); | |||
312 | } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) { | |||
313 | Index *= AT->getNumElements(); | |||
314 | CurrentType = AT->getElementType(); | |||
315 | } else { | |||
316 | return None; | |||
317 | } | |||
318 | Index += I; | |||
319 | } | |||
320 | return Index; | |||
321 | } | |||
322 | ||||
323 | /// Checks if the given value is actually an undefined constant vector. | |||
324 | /// Also, if the\p ShuffleMask is not empty, tries to check if the non-masked | |||
325 | /// elements actually mask the insertelement buildvector, if any. | |||
326 | template <bool IsPoisonOnly = false> | |||
327 | static SmallBitVector isUndefVector(const Value *V, | |||
328 | ArrayRef<int> ShuffleMask = None) { | |||
329 | SmallBitVector Res(ShuffleMask.empty() ? 1 : ShuffleMask.size(), true); | |||
330 | using T = std::conditional_t<IsPoisonOnly, PoisonValue, UndefValue>; | |||
331 | if (isa<T>(V)) | |||
332 | return Res; | |||
333 | auto *VecTy = dyn_cast<FixedVectorType>(V->getType()); | |||
334 | if (!VecTy) | |||
335 | return Res.reset(); | |||
336 | auto *C = dyn_cast<Constant>(V); | |||
337 | if (!C) { | |||
338 | if (!ShuffleMask.empty()) { | |||
339 | const Value *Base = V; | |||
340 | while (auto *II = dyn_cast<InsertElementInst>(Base)) { | |||
341 | if (isa<T>(II->getOperand(1))) | |||
342 | continue; | |||
343 | Base = II->getOperand(0); | |||
344 | Optional<unsigned> Idx = getInsertIndex(II); | |||
345 | if (!Idx) | |||
346 | continue; | |||
347 | if (*Idx < ShuffleMask.size() && ShuffleMask[*Idx] == UndefMaskElem) | |||
348 | Res.reset(*Idx); | |||
349 | } | |||
350 | // TODO: Add analysis for shuffles here too. | |||
351 | if (V == Base) { | |||
352 | Res.reset(); | |||
353 | } else { | |||
354 | SmallVector<int> SubMask(ShuffleMask.size(), UndefMaskElem); | |||
355 | Res &= isUndefVector<IsPoisonOnly>(Base, SubMask); | |||
356 | } | |||
357 | } else { | |||
358 | Res.reset(); | |||
359 | } | |||
360 | return Res; | |||
361 | } | |||
362 | for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { | |||
363 | if (Constant *Elem = C->getAggregateElement(I)) | |||
364 | if (!isa<T>(Elem) && | |||
365 | (ShuffleMask.empty() || | |||
366 | (I < ShuffleMask.size() && ShuffleMask[I] == UndefMaskElem))) | |||
367 | Res.reset(I); | |||
368 | } | |||
369 | return Res; | |||
370 | } | |||
371 | ||||
372 | /// Checks if the vector of instructions can be represented as a shuffle, like: | |||
373 | /// %x0 = extractelement <4 x i8> %x, i32 0 | |||
374 | /// %x3 = extractelement <4 x i8> %x, i32 3 | |||
375 | /// %y1 = extractelement <4 x i8> %y, i32 1 | |||
376 | /// %y2 = extractelement <4 x i8> %y, i32 2 | |||
377 | /// %x0x0 = mul i8 %x0, %x0 | |||
378 | /// %x3x3 = mul i8 %x3, %x3 | |||
379 | /// %y1y1 = mul i8 %y1, %y1 | |||
380 | /// %y2y2 = mul i8 %y2, %y2 | |||
381 | /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 | |||
382 | /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 | |||
383 | /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 | |||
384 | /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 | |||
385 | /// ret <4 x i8> %ins4 | |||
386 | /// can be transformed into: | |||
387 | /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, | |||
388 | /// i32 6> | |||
389 | /// %2 = mul <4 x i8> %1, %1 | |||
390 | /// ret <4 x i8> %2 | |||
391 | /// We convert this initially to something like: | |||
392 | /// %x0 = extractelement <4 x i8> %x, i32 0 | |||
393 | /// %x3 = extractelement <4 x i8> %x, i32 3 | |||
394 | /// %y1 = extractelement <4 x i8> %y, i32 1 | |||
395 | /// %y2 = extractelement <4 x i8> %y, i32 2 | |||
396 | /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 | |||
397 | /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 | |||
398 | /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 | |||
399 | /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 | |||
400 | /// %5 = mul <4 x i8> %4, %4 | |||
401 | /// %6 = extractelement <4 x i8> %5, i32 0 | |||
402 | /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 | |||
403 | /// %7 = extractelement <4 x i8> %5, i32 1 | |||
404 | /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 | |||
405 | /// %8 = extractelement <4 x i8> %5, i32 2 | |||
406 | /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 | |||
407 | /// %9 = extractelement <4 x i8> %5, i32 3 | |||
408 | /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 | |||
409 | /// ret <4 x i8> %ins4 | |||
410 | /// InstCombiner transforms this into a shuffle and vector mul | |||
411 | /// Mask will return the Shuffle Mask equivalent to the extracted elements. | |||
412 | /// TODO: Can we split off and reuse the shuffle mask detection from | |||
413 | /// ShuffleVectorInst/getShuffleCost? | |||
414 | static Optional<TargetTransformInfo::ShuffleKind> | |||
415 | isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { | |||
416 | const auto *It = | |||
417 | find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); }); | |||
418 | if (It == VL.end()) | |||
419 | return None; | |||
420 | auto *EI0 = cast<ExtractElementInst>(*It); | |||
421 | if (isa<ScalableVectorType>(EI0->getVectorOperandType())) | |||
422 | return None; | |||
423 | unsigned Size = | |||
424 | cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); | |||
425 | Value *Vec1 = nullptr; | |||
426 | Value *Vec2 = nullptr; | |||
427 | enum ShuffleMode { Unknown, Select, Permute }; | |||
428 | ShuffleMode CommonShuffleMode = Unknown; | |||
429 | Mask.assign(VL.size(), UndefMaskElem); | |||
430 | for (unsigned I = 0, E = VL.size(); I < E; ++I) { | |||
431 | // Undef can be represented as an undef element in a vector. | |||
432 | if (isa<UndefValue>(VL[I])) | |||
433 | continue; | |||
434 | auto *EI = cast<ExtractElementInst>(VL[I]); | |||
435 | if (isa<ScalableVectorType>(EI->getVectorOperandType())) | |||
436 | return None; | |||
437 | auto *Vec = EI->getVectorOperand(); | |||
438 | // We can extractelement from undef or poison vector. | |||
439 | if (isUndefVector(Vec).all()) | |||
440 | continue; | |||
441 | // All vector operands must have the same number of vector elements. | |||
442 | if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) | |||
443 | return None; | |||
444 | if (isa<UndefValue>(EI->getIndexOperand())) | |||
445 | continue; | |||
446 | auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); | |||
447 | if (!Idx) | |||
448 | return None; | |||
449 | // Undefined behavior if Idx is negative or >= Size. | |||
450 | if (Idx->getValue().uge(Size)) | |||
451 | continue; | |||
452 | unsigned IntIdx = Idx->getValue().getZExtValue(); | |||
453 | Mask[I] = IntIdx; | |||
454 | // For correct shuffling we have to have at most 2 different vector operands | |||
455 | // in all extractelement instructions. | |||
456 | if (!Vec1 || Vec1 == Vec) { | |||
457 | Vec1 = Vec; | |||
458 | } else if (!Vec2 || Vec2 == Vec) { | |||
459 | Vec2 = Vec; | |||
460 | Mask[I] += Size; | |||
461 | } else { | |||
462 | return None; | |||
463 | } | |||
464 | if (CommonShuffleMode == Permute) | |||
465 | continue; | |||
466 | // If the extract index is not the same as the operation number, it is a | |||
467 | // permutation. | |||
468 | if (IntIdx != I) { | |||
469 | CommonShuffleMode = Permute; | |||
470 | continue; | |||
471 | } | |||
472 | CommonShuffleMode = Select; | |||
473 | } | |||
474 | // If we're not crossing lanes in different vectors, consider it as blending. | |||
475 | if (CommonShuffleMode == Select && Vec2) | |||
476 | return TargetTransformInfo::SK_Select; | |||
477 | // If Vec2 was never used, we have a permutation of a single vector, otherwise | |||
478 | // we have permutation of 2 vectors. | |||
479 | return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc | |||
480 | : TargetTransformInfo::SK_PermuteSingleSrc; | |||
481 | } | |||
482 | ||||
483 | namespace { | |||
484 | ||||
485 | /// Main data required for vectorization of instructions. | |||
486 | struct InstructionsState { | |||
487 | /// The very first instruction in the list with the main opcode. | |||
488 | Value *OpValue = nullptr; | |||
489 | ||||
490 | /// The main/alternate instruction. | |||
491 | Instruction *MainOp = nullptr; | |||
492 | Instruction *AltOp = nullptr; | |||
493 | ||||
494 | /// The main/alternate opcodes for the list of instructions. | |||
495 | unsigned getOpcode() const { | |||
496 | return MainOp ? MainOp->getOpcode() : 0; | |||
497 | } | |||
498 | ||||
499 | unsigned getAltOpcode() const { | |||
500 | return AltOp ? AltOp->getOpcode() : 0; | |||
501 | } | |||
502 | ||||
503 | /// Some of the instructions in the list have alternate opcodes. | |||
504 | bool isAltShuffle() const { return AltOp != MainOp; } | |||
505 | ||||
506 | bool isOpcodeOrAlt(Instruction *I) const { | |||
507 | unsigned CheckedOpcode = I->getOpcode(); | |||
508 | return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; | |||
509 | } | |||
510 | ||||
511 | InstructionsState() = delete; | |||
512 | InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) | |||
513 | : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} | |||
514 | }; | |||
515 | ||||
516 | } // end anonymous namespace | |||
517 | ||||
518 | /// Chooses the correct key for scheduling data. If \p Op has the same (or | |||
519 | /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p | |||
520 | /// OpValue. | |||
521 | static Value *isOneOf(const InstructionsState &S, Value *Op) { | |||
522 | auto *I = dyn_cast<Instruction>(Op); | |||
523 | if (I && S.isOpcodeOrAlt(I)) | |||
524 | return Op; | |||
525 | return S.OpValue; | |||
526 | } | |||
527 | ||||
528 | /// \returns true if \p Opcode is allowed as part of of the main/alternate | |||
529 | /// instruction for SLP vectorization. | |||
530 | /// | |||
531 | /// Example of unsupported opcode is SDIV that can potentially cause UB if the | |||
532 | /// "shuffled out" lane would result in division by zero. | |||
533 | static bool isValidForAlternation(unsigned Opcode) { | |||
534 | if (Instruction::isIntDivRem(Opcode)) | |||
535 | return false; | |||
536 | ||||
537 | return true; | |||
538 | } | |||
539 | ||||
540 | static InstructionsState getSameOpcode(ArrayRef<Value *> VL, | |||
541 | const TargetLibraryInfo &TLI, | |||
542 | unsigned BaseIndex = 0); | |||
543 | ||||
544 | /// Checks if the provided operands of 2 cmp instructions are compatible, i.e. | |||
545 | /// compatible instructions or constants, or just some other regular values. | |||
546 | static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0, | |||
547 | Value *Op1, const TargetLibraryInfo &TLI) { | |||
548 | return (isConstant(BaseOp0) && isConstant(Op0)) || | |||
549 | (isConstant(BaseOp1) && isConstant(Op1)) || | |||
550 | (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) && | |||
551 | !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) || | |||
552 | BaseOp0 == Op0 || BaseOp1 == Op1 || | |||
553 | getSameOpcode({BaseOp0, Op0}, TLI).getOpcode() || | |||
554 | getSameOpcode({BaseOp1, Op1}, TLI).getOpcode(); | |||
555 | } | |||
556 | ||||
557 | /// \returns true if a compare instruction \p CI has similar "look" and | |||
558 | /// same predicate as \p BaseCI, "as is" or with its operands and predicate | |||
559 | /// swapped, false otherwise. | |||
560 | static bool isCmpSameOrSwapped(const CmpInst *BaseCI, const CmpInst *CI, | |||
561 | const TargetLibraryInfo &TLI) { | |||
562 | assert(BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() &&(static_cast <bool> (BaseCI->getOperand(0)->getType () == CI->getOperand(0)->getType() && "Assessing comparisons of different types?" ) ? void (0) : __assert_fail ("BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() && \"Assessing comparisons of different types?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 563, __extension__ __PRETTY_FUNCTION__)) | |||
563 | "Assessing comparisons of different types?")(static_cast <bool> (BaseCI->getOperand(0)->getType () == CI->getOperand(0)->getType() && "Assessing comparisons of different types?" ) ? void (0) : __assert_fail ("BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() && \"Assessing comparisons of different types?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 563, __extension__ __PRETTY_FUNCTION__)); | |||
564 | CmpInst::Predicate BasePred = BaseCI->getPredicate(); | |||
565 | CmpInst::Predicate Pred = CI->getPredicate(); | |||
566 | CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(Pred); | |||
567 | ||||
568 | Value *BaseOp0 = BaseCI->getOperand(0); | |||
569 | Value *BaseOp1 = BaseCI->getOperand(1); | |||
570 | Value *Op0 = CI->getOperand(0); | |||
571 | Value *Op1 = CI->getOperand(1); | |||
572 | ||||
573 | return (BasePred == Pred && | |||
574 | areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1, TLI)) || | |||
575 | (BasePred == SwappedPred && | |||
576 | areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0, TLI)); | |||
577 | } | |||
578 | ||||
579 | /// \returns analysis of the Instructions in \p VL described in | |||
580 | /// InstructionsState, the Opcode that we suppose the whole list | |||
581 | /// could be vectorized even if its structure is diverse. | |||
582 | static InstructionsState getSameOpcode(ArrayRef<Value *> VL, | |||
583 | const TargetLibraryInfo &TLI, | |||
584 | unsigned BaseIndex) { | |||
585 | // Make sure these are all Instructions. | |||
586 | if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) | |||
587 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
588 | ||||
589 | bool IsCastOp = isa<CastInst>(VL[BaseIndex]); | |||
590 | bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); | |||
591 | bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]); | |||
592 | CmpInst::Predicate BasePred = | |||
593 | IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate() | |||
594 | : CmpInst::BAD_ICMP_PREDICATE; | |||
595 | unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); | |||
596 | unsigned AltOpcode = Opcode; | |||
597 | unsigned AltIndex = BaseIndex; | |||
598 | ||||
599 | // Check for one alternate opcode from another BinaryOperator. | |||
600 | // TODO - generalize to support all operators (types, calls etc.). | |||
601 | auto *IBase = cast<Instruction>(VL[BaseIndex]); | |||
602 | Intrinsic::ID BaseID = 0; | |||
603 | SmallVector<VFInfo> BaseMappings; | |||
604 | if (auto *CallBase = dyn_cast<CallInst>(IBase)) { | |||
605 | BaseID = getVectorIntrinsicIDForCall(CallBase, &TLI); | |||
606 | BaseMappings = VFDatabase(*CallBase).getMappings(*CallBase); | |||
607 | if (!isTriviallyVectorizable(BaseID) && BaseMappings.empty()) | |||
608 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
609 | } | |||
610 | for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { | |||
611 | auto *I = cast<Instruction>(VL[Cnt]); | |||
612 | unsigned InstOpcode = I->getOpcode(); | |||
613 | if (IsBinOp && isa<BinaryOperator>(I)) { | |||
614 | if (InstOpcode == Opcode || InstOpcode == AltOpcode) | |||
615 | continue; | |||
616 | if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && | |||
617 | isValidForAlternation(Opcode)) { | |||
618 | AltOpcode = InstOpcode; | |||
619 | AltIndex = Cnt; | |||
620 | continue; | |||
621 | } | |||
622 | } else if (IsCastOp && isa<CastInst>(I)) { | |||
623 | Value *Op0 = IBase->getOperand(0); | |||
624 | Type *Ty0 = Op0->getType(); | |||
625 | Value *Op1 = I->getOperand(0); | |||
626 | Type *Ty1 = Op1->getType(); | |||
627 | if (Ty0 == Ty1) { | |||
628 | if (InstOpcode == Opcode || InstOpcode == AltOpcode) | |||
629 | continue; | |||
630 | if (Opcode == AltOpcode) { | |||
631 | assert(isValidForAlternation(Opcode) &&(static_cast <bool> (isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && "Cast isn't safe for alternation, logic needs to be updated!" ) ? void (0) : __assert_fail ("isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && \"Cast isn't safe for alternation, logic needs to be updated!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 633, __extension__ __PRETTY_FUNCTION__)) | |||
632 | isValidForAlternation(InstOpcode) &&(static_cast <bool> (isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && "Cast isn't safe for alternation, logic needs to be updated!" ) ? void (0) : __assert_fail ("isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && \"Cast isn't safe for alternation, logic needs to be updated!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 633, __extension__ __PRETTY_FUNCTION__)) | |||
633 | "Cast isn't safe for alternation, logic needs to be updated!")(static_cast <bool> (isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && "Cast isn't safe for alternation, logic needs to be updated!" ) ? void (0) : __assert_fail ("isValidForAlternation(Opcode) && isValidForAlternation(InstOpcode) && \"Cast isn't safe for alternation, logic needs to be updated!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 633, __extension__ __PRETTY_FUNCTION__)); | |||
634 | AltOpcode = InstOpcode; | |||
635 | AltIndex = Cnt; | |||
636 | continue; | |||
637 | } | |||
638 | } | |||
639 | } else if (auto *Inst = dyn_cast<CmpInst>(VL[Cnt]); Inst && IsCmpOp) { | |||
640 | auto *BaseInst = cast<CmpInst>(VL[BaseIndex]); | |||
641 | Type *Ty0 = BaseInst->getOperand(0)->getType(); | |||
642 | Type *Ty1 = Inst->getOperand(0)->getType(); | |||
643 | if (Ty0 == Ty1) { | |||
644 | assert(InstOpcode == Opcode && "Expected same CmpInst opcode.")(static_cast <bool> (InstOpcode == Opcode && "Expected same CmpInst opcode." ) ? void (0) : __assert_fail ("InstOpcode == Opcode && \"Expected same CmpInst opcode.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 644, __extension__ __PRETTY_FUNCTION__)); | |||
645 | // Check for compatible operands. If the corresponding operands are not | |||
646 | // compatible - need to perform alternate vectorization. | |||
647 | CmpInst::Predicate CurrentPred = Inst->getPredicate(); | |||
648 | CmpInst::Predicate SwappedCurrentPred = | |||
649 | CmpInst::getSwappedPredicate(CurrentPred); | |||
650 | ||||
651 | if (E == 2 && | |||
652 | (BasePred == CurrentPred || BasePred == SwappedCurrentPred)) | |||
653 | continue; | |||
654 | ||||
655 | if (isCmpSameOrSwapped(BaseInst, Inst, TLI)) | |||
656 | continue; | |||
657 | auto *AltInst = cast<CmpInst>(VL[AltIndex]); | |||
658 | if (AltIndex != BaseIndex) { | |||
659 | if (isCmpSameOrSwapped(AltInst, Inst, TLI)) | |||
660 | continue; | |||
661 | } else if (BasePred != CurrentPred) { | |||
662 | assert((static_cast <bool> (isValidForAlternation(InstOpcode) && "CmpInst isn't safe for alternation, logic needs to be updated!" ) ? void (0) : __assert_fail ("isValidForAlternation(InstOpcode) && \"CmpInst isn't safe for alternation, logic needs to be updated!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 664, __extension__ __PRETTY_FUNCTION__)) | |||
663 | isValidForAlternation(InstOpcode) &&(static_cast <bool> (isValidForAlternation(InstOpcode) && "CmpInst isn't safe for alternation, logic needs to be updated!" ) ? void (0) : __assert_fail ("isValidForAlternation(InstOpcode) && \"CmpInst isn't safe for alternation, logic needs to be updated!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 664, __extension__ __PRETTY_FUNCTION__)) | |||
664 | "CmpInst isn't safe for alternation, logic needs to be updated!")(static_cast <bool> (isValidForAlternation(InstOpcode) && "CmpInst isn't safe for alternation, logic needs to be updated!" ) ? void (0) : __assert_fail ("isValidForAlternation(InstOpcode) && \"CmpInst isn't safe for alternation, logic needs to be updated!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 664, __extension__ __PRETTY_FUNCTION__)); | |||
665 | AltIndex = Cnt; | |||
666 | continue; | |||
667 | } | |||
668 | CmpInst::Predicate AltPred = AltInst->getPredicate(); | |||
669 | if (BasePred == CurrentPred || BasePred == SwappedCurrentPred || | |||
670 | AltPred == CurrentPred || AltPred == SwappedCurrentPred) | |||
671 | continue; | |||
672 | } | |||
673 | } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) { | |||
674 | if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) { | |||
675 | if (Gep->getNumOperands() != 2 || | |||
676 | Gep->getOperand(0)->getType() != IBase->getOperand(0)->getType()) | |||
677 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
678 | } else if (auto *EI = dyn_cast<ExtractElementInst>(I)) { | |||
679 | if (!isVectorLikeInstWithConstOps(EI)) | |||
680 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
681 | } else if (auto *LI = dyn_cast<LoadInst>(I)) { | |||
682 | auto *BaseLI = cast<LoadInst>(IBase); | |||
683 | if (!LI->isSimple() || !BaseLI->isSimple()) | |||
684 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
685 | } else if (auto *Call = dyn_cast<CallInst>(I)) { | |||
686 | auto *CallBase = cast<CallInst>(IBase); | |||
687 | if (Call->getCalledFunction() != CallBase->getCalledFunction()) | |||
688 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
689 | if (Call->hasOperandBundles() && | |||
690 | !std::equal(Call->op_begin() + Call->getBundleOperandsStartIndex(), | |||
691 | Call->op_begin() + Call->getBundleOperandsEndIndex(), | |||
692 | CallBase->op_begin() + | |||
693 | CallBase->getBundleOperandsStartIndex())) | |||
694 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
695 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, &TLI); | |||
696 | if (ID != BaseID) | |||
697 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
698 | if (!ID) { | |||
699 | SmallVector<VFInfo> Mappings = VFDatabase(*Call).getMappings(*Call); | |||
700 | if (Mappings.size() != BaseMappings.size() || | |||
701 | Mappings.front().ISA != BaseMappings.front().ISA || | |||
702 | Mappings.front().ScalarName != BaseMappings.front().ScalarName || | |||
703 | Mappings.front().VectorName != BaseMappings.front().VectorName || | |||
704 | Mappings.front().Shape.VF != BaseMappings.front().Shape.VF || | |||
705 | Mappings.front().Shape.Parameters != | |||
706 | BaseMappings.front().Shape.Parameters) | |||
707 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
708 | } | |||
709 | } | |||
710 | continue; | |||
711 | } | |||
712 | return InstructionsState(VL[BaseIndex], nullptr, nullptr); | |||
713 | } | |||
714 | ||||
715 | return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), | |||
716 | cast<Instruction>(VL[AltIndex])); | |||
717 | } | |||
718 | ||||
719 | /// \returns true if all of the values in \p VL have the same type or false | |||
720 | /// otherwise. | |||
721 | static bool allSameType(ArrayRef<Value *> VL) { | |||
722 | Type *Ty = VL[0]->getType(); | |||
723 | for (int i = 1, e = VL.size(); i < e; i++) | |||
724 | if (VL[i]->getType() != Ty) | |||
725 | return false; | |||
726 | ||||
727 | return true; | |||
728 | } | |||
729 | ||||
730 | /// \returns True if Extract{Value,Element} instruction extracts element Idx. | |||
731 | static Optional<unsigned> getExtractIndex(Instruction *E) { | |||
732 | unsigned Opcode = E->getOpcode(); | |||
733 | assert((Opcode == Instruction::ExtractElement ||(static_cast <bool> ((Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && "Expected extractelement or extractvalue instruction." ) ? void (0) : __assert_fail ("(Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && \"Expected extractelement or extractvalue instruction.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 735, __extension__ __PRETTY_FUNCTION__)) | |||
734 | Opcode == Instruction::ExtractValue) &&(static_cast <bool> ((Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && "Expected extractelement or extractvalue instruction." ) ? void (0) : __assert_fail ("(Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && \"Expected extractelement or extractvalue instruction.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 735, __extension__ __PRETTY_FUNCTION__)) | |||
735 | "Expected extractelement or extractvalue instruction.")(static_cast <bool> ((Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && "Expected extractelement or extractvalue instruction." ) ? void (0) : __assert_fail ("(Opcode == Instruction::ExtractElement || Opcode == Instruction::ExtractValue) && \"Expected extractelement or extractvalue instruction.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 735, __extension__ __PRETTY_FUNCTION__)); | |||
736 | if (Opcode == Instruction::ExtractElement) { | |||
737 | auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); | |||
738 | if (!CI) | |||
739 | return None; | |||
740 | return CI->getZExtValue(); | |||
741 | } | |||
742 | ExtractValueInst *EI = cast<ExtractValueInst>(E); | |||
743 | if (EI->getNumIndices() != 1) | |||
744 | return None; | |||
745 | return *EI->idx_begin(); | |||
746 | } | |||
747 | ||||
748 | /// \returns True if in-tree use also needs extract. This refers to | |||
749 | /// possible scalar operand in vectorized instruction. | |||
750 | static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, | |||
751 | TargetLibraryInfo *TLI) { | |||
752 | unsigned Opcode = UserInst->getOpcode(); | |||
753 | switch (Opcode) { | |||
754 | case Instruction::Load: { | |||
755 | LoadInst *LI = cast<LoadInst>(UserInst); | |||
756 | return (LI->getPointerOperand() == Scalar); | |||
757 | } | |||
758 | case Instruction::Store: { | |||
759 | StoreInst *SI = cast<StoreInst>(UserInst); | |||
760 | return (SI->getPointerOperand() == Scalar); | |||
761 | } | |||
762 | case Instruction::Call: { | |||
763 | CallInst *CI = cast<CallInst>(UserInst); | |||
764 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
765 | for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { | |||
766 | if (isVectorIntrinsicWithScalarOpAtArg(ID, i)) | |||
767 | return (CI->getArgOperand(i) == Scalar); | |||
768 | } | |||
769 | [[fallthrough]]; | |||
770 | } | |||
771 | default: | |||
772 | return false; | |||
773 | } | |||
774 | } | |||
775 | ||||
776 | /// \returns the AA location that is being access by the instruction. | |||
777 | static MemoryLocation getLocation(Instruction *I) { | |||
778 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) | |||
779 | return MemoryLocation::get(SI); | |||
780 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) | |||
781 | return MemoryLocation::get(LI); | |||
782 | return MemoryLocation(); | |||
783 | } | |||
784 | ||||
785 | /// \returns True if the instruction is not a volatile or atomic load/store. | |||
786 | static bool isSimple(Instruction *I) { | |||
787 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) | |||
788 | return LI->isSimple(); | |||
789 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) | |||
790 | return SI->isSimple(); | |||
791 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) | |||
792 | return !MI->isVolatile(); | |||
793 | return true; | |||
794 | } | |||
795 | ||||
796 | /// Shuffles \p Mask in accordance with the given \p SubMask. | |||
797 | static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { | |||
798 | if (SubMask.empty()) | |||
799 | return; | |||
800 | if (Mask.empty()) { | |||
801 | Mask.append(SubMask.begin(), SubMask.end()); | |||
802 | return; | |||
803 | } | |||
804 | SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); | |||
805 | int TermValue = std::min(Mask.size(), SubMask.size()); | |||
806 | for (int I = 0, E = SubMask.size(); I < E; ++I) { | |||
807 | if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || | |||
808 | Mask[SubMask[I]] >= TermValue) | |||
809 | continue; | |||
810 | NewMask[I] = Mask[SubMask[I]]; | |||
811 | } | |||
812 | Mask.swap(NewMask); | |||
813 | } | |||
814 | ||||
815 | /// Order may have elements assigned special value (size) which is out of | |||
816 | /// bounds. Such indices only appear on places which correspond to undef values | |||
817 | /// (see canReuseExtract for details) and used in order to avoid undef values | |||
818 | /// have effect on operands ordering. | |||
819 | /// The first loop below simply finds all unused indices and then the next loop | |||
820 | /// nest assigns these indices for undef values positions. | |||
821 | /// As an example below Order has two undef positions and they have assigned | |||
822 | /// values 3 and 7 respectively: | |||
823 | /// before: 6 9 5 4 9 2 1 0 | |||
824 | /// after: 6 3 5 4 7 2 1 0 | |||
825 | static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { | |||
826 | const unsigned Sz = Order.size(); | |||
827 | SmallBitVector UnusedIndices(Sz, /*t=*/true); | |||
828 | SmallBitVector MaskedIndices(Sz); | |||
829 | for (unsigned I = 0; I < Sz; ++I) { | |||
830 | if (Order[I] < Sz) | |||
831 | UnusedIndices.reset(Order[I]); | |||
832 | else | |||
833 | MaskedIndices.set(I); | |||
834 | } | |||
835 | if (MaskedIndices.none()) | |||
836 | return; | |||
837 | assert(UnusedIndices.count() == MaskedIndices.count() &&(static_cast <bool> (UnusedIndices.count() == MaskedIndices .count() && "Non-synced masked/available indices.") ? void (0) : __assert_fail ("UnusedIndices.count() == MaskedIndices.count() && \"Non-synced masked/available indices.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 838, __extension__ __PRETTY_FUNCTION__)) | |||
838 | "Non-synced masked/available indices.")(static_cast <bool> (UnusedIndices.count() == MaskedIndices .count() && "Non-synced masked/available indices.") ? void (0) : __assert_fail ("UnusedIndices.count() == MaskedIndices.count() && \"Non-synced masked/available indices.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 838, __extension__ __PRETTY_FUNCTION__)); | |||
839 | int Idx = UnusedIndices.find_first(); | |||
840 | int MIdx = MaskedIndices.find_first(); | |||
841 | while (MIdx >= 0) { | |||
842 | assert(Idx >= 0 && "Indices must be synced.")(static_cast <bool> (Idx >= 0 && "Indices must be synced." ) ? void (0) : __assert_fail ("Idx >= 0 && \"Indices must be synced.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 842, __extension__ __PRETTY_FUNCTION__)); | |||
843 | Order[MIdx] = Idx; | |||
844 | Idx = UnusedIndices.find_next(Idx); | |||
845 | MIdx = MaskedIndices.find_next(MIdx); | |||
846 | } | |||
847 | } | |||
848 | ||||
849 | namespace llvm { | |||
850 | ||||
851 | static void inversePermutation(ArrayRef<unsigned> Indices, | |||
852 | SmallVectorImpl<int> &Mask) { | |||
853 | Mask.clear(); | |||
854 | const unsigned E = Indices.size(); | |||
855 | Mask.resize(E, UndefMaskElem); | |||
856 | for (unsigned I = 0; I < E; ++I) | |||
857 | Mask[Indices[I]] = I; | |||
858 | } | |||
859 | ||||
860 | /// Reorders the list of scalars in accordance with the given \p Mask. | |||
861 | static void reorderScalars(SmallVectorImpl<Value *> &Scalars, | |||
862 | ArrayRef<int> Mask) { | |||
863 | assert(!Mask.empty() && "Expected non-empty mask.")(static_cast <bool> (!Mask.empty() && "Expected non-empty mask." ) ? void (0) : __assert_fail ("!Mask.empty() && \"Expected non-empty mask.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 863, __extension__ __PRETTY_FUNCTION__)); | |||
864 | SmallVector<Value *> Prev(Scalars.size(), | |||
865 | UndefValue::get(Scalars.front()->getType())); | |||
866 | Prev.swap(Scalars); | |||
867 | for (unsigned I = 0, E = Prev.size(); I < E; ++I) | |||
868 | if (Mask[I] != UndefMaskElem) | |||
869 | Scalars[Mask[I]] = Prev[I]; | |||
870 | } | |||
871 | ||||
872 | /// Checks if the provided value does not require scheduling. It does not | |||
873 | /// require scheduling if this is not an instruction or it is an instruction | |||
874 | /// that does not read/write memory and all operands are either not instructions | |||
875 | /// or phi nodes or instructions from different blocks. | |||
876 | static bool areAllOperandsNonInsts(Value *V) { | |||
877 | auto *I = dyn_cast<Instruction>(V); | |||
878 | if (!I) | |||
879 | return true; | |||
880 | return !mayHaveNonDefUseDependency(*I) && | |||
881 | all_of(I->operands(), [I](Value *V) { | |||
882 | auto *IO = dyn_cast<Instruction>(V); | |||
883 | if (!IO) | |||
884 | return true; | |||
885 | return isa<PHINode>(IO) || IO->getParent() != I->getParent(); | |||
886 | }); | |||
887 | } | |||
888 | ||||
889 | /// Checks if the provided value does not require scheduling. It does not | |||
890 | /// require scheduling if this is not an instruction or it is an instruction | |||
891 | /// that does not read/write memory and all users are phi nodes or instructions | |||
892 | /// from the different blocks. | |||
893 | static bool isUsedOutsideBlock(Value *V) { | |||
894 | auto *I = dyn_cast<Instruction>(V); | |||
895 | if (!I) | |||
896 | return true; | |||
897 | // Limits the number of uses to save compile time. | |||
898 | constexpr int UsesLimit = 8; | |||
899 | return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) && | |||
900 | all_of(I->users(), [I](User *U) { | |||
901 | auto *IU = dyn_cast<Instruction>(U); | |||
902 | if (!IU) | |||
903 | return true; | |||
904 | return IU->getParent() != I->getParent() || isa<PHINode>(IU); | |||
905 | }); | |||
906 | } | |||
907 | ||||
908 | /// Checks if the specified value does not require scheduling. It does not | |||
909 | /// require scheduling if all operands and all users do not need to be scheduled | |||
910 | /// in the current basic block. | |||
911 | static bool doesNotNeedToBeScheduled(Value *V) { | |||
912 | return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V); | |||
913 | } | |||
914 | ||||
915 | /// Checks if the specified array of instructions does not require scheduling. | |||
916 | /// It is so if all either instructions have operands that do not require | |||
917 | /// scheduling or their users do not require scheduling since they are phis or | |||
918 | /// in other basic blocks. | |||
919 | static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) { | |||
920 | return !VL.empty() && | |||
921 | (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts)); | |||
922 | } | |||
923 | ||||
924 | namespace slpvectorizer { | |||
925 | ||||
926 | /// Bottom Up SLP Vectorizer. | |||
927 | class BoUpSLP { | |||
928 | struct TreeEntry; | |||
929 | struct ScheduleData; | |||
930 | ||||
931 | public: | |||
932 | using ValueList = SmallVector<Value *, 8>; | |||
933 | using InstrList = SmallVector<Instruction *, 16>; | |||
934 | using ValueSet = SmallPtrSet<Value *, 16>; | |||
935 | using StoreList = SmallVector<StoreInst *, 8>; | |||
936 | using ExtraValueToDebugLocsMap = | |||
937 | MapVector<Value *, SmallVector<Instruction *, 2>>; | |||
938 | using OrdersType = SmallVector<unsigned, 4>; | |||
939 | ||||
940 | BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, | |||
941 | TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, | |||
942 | DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, | |||
943 | const DataLayout *DL, OptimizationRemarkEmitter *ORE) | |||
944 | : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li), | |||
945 | DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { | |||
946 | CodeMetrics::collectEphemeralValues(F, AC, EphValues); | |||
947 | // Use the vector register size specified by the target unless overridden | |||
948 | // by a command-line option. | |||
949 | // TODO: It would be better to limit the vectorization factor based on | |||
950 | // data type rather than just register size. For example, x86 AVX has | |||
951 | // 256-bit registers, but it does not support integer operations | |||
952 | // at that width (that requires AVX2). | |||
953 | if (MaxVectorRegSizeOption.getNumOccurrences()) | |||
954 | MaxVecRegSize = MaxVectorRegSizeOption; | |||
955 | else | |||
956 | MaxVecRegSize = | |||
957 | TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) | |||
958 | .getFixedSize(); | |||
959 | ||||
960 | if (MinVectorRegSizeOption.getNumOccurrences()) | |||
961 | MinVecRegSize = MinVectorRegSizeOption; | |||
962 | else | |||
963 | MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); | |||
964 | } | |||
965 | ||||
966 | /// Vectorize the tree that starts with the elements in \p VL. | |||
967 | /// Returns the vectorized root. | |||
968 | Value *vectorizeTree(); | |||
969 | ||||
970 | /// Vectorize the tree but with the list of externally used values \p | |||
971 | /// ExternallyUsedValues. Values in this MapVector can be replaced but the | |||
972 | /// generated extractvalue instructions. | |||
973 | Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); | |||
974 | ||||
975 | /// \returns the cost incurred by unwanted spills and fills, caused by | |||
976 | /// holding live values over call sites. | |||
977 | InstructionCost getSpillCost() const; | |||
978 | ||||
979 | /// \returns the vectorization cost of the subtree that starts at \p VL. | |||
980 | /// A negative number means that this is profitable. | |||
981 | InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); | |||
982 | ||||
983 | /// Construct a vectorizable tree that starts at \p Roots, ignoring users for | |||
984 | /// the purpose of scheduling and extraction in the \p UserIgnoreLst. | |||
985 | void buildTree(ArrayRef<Value *> Roots, | |||
986 | const SmallDenseSet<Value *> &UserIgnoreLst); | |||
987 | ||||
988 | /// Construct a vectorizable tree that starts at \p Roots. | |||
989 | void buildTree(ArrayRef<Value *> Roots); | |||
990 | ||||
991 | /// Checks if the very first tree node is going to be vectorized. | |||
992 | bool isVectorizedFirstNode() const { | |||
993 | return !VectorizableTree.empty() && | |||
994 | VectorizableTree.front()->State == TreeEntry::Vectorize; | |||
995 | } | |||
996 | ||||
997 | /// Returns the main instruction for the very first node. | |||
998 | Instruction *getFirstNodeMainOp() const { | |||
999 | assert(!VectorizableTree.empty() && "No tree to get the first node from")(static_cast <bool> (!VectorizableTree.empty() && "No tree to get the first node from") ? void (0) : __assert_fail ("!VectorizableTree.empty() && \"No tree to get the first node from\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 999, __extension__ __PRETTY_FUNCTION__)); | |||
1000 | return VectorizableTree.front()->getMainOp(); | |||
1001 | } | |||
1002 | ||||
1003 | /// Builds external uses of the vectorized scalars, i.e. the list of | |||
1004 | /// vectorized scalars to be extracted, their lanes and their scalar users. \p | |||
1005 | /// ExternallyUsedValues contains additional list of external uses to handle | |||
1006 | /// vectorization of reductions. | |||
1007 | void | |||
1008 | buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); | |||
1009 | ||||
1010 | /// Clear the internal data structures that are created by 'buildTree'. | |||
1011 | void deleteTree() { | |||
1012 | VectorizableTree.clear(); | |||
1013 | ScalarToTreeEntry.clear(); | |||
1014 | MustGather.clear(); | |||
1015 | ExternalUses.clear(); | |||
1016 | for (auto &Iter : BlocksSchedules) { | |||
1017 | BlockScheduling *BS = Iter.second.get(); | |||
1018 | BS->clear(); | |||
1019 | } | |||
1020 | MinBWs.clear(); | |||
1021 | InstrElementSize.clear(); | |||
1022 | UserIgnoreList = nullptr; | |||
1023 | } | |||
1024 | ||||
1025 | unsigned getTreeSize() const { return VectorizableTree.size(); } | |||
1026 | ||||
1027 | /// Perform LICM and CSE on the newly generated gather sequences. | |||
1028 | void optimizeGatherSequence(); | |||
1029 | ||||
1030 | /// Checks if the specified gather tree entry \p TE can be represented as a | |||
1031 | /// shuffled vector entry + (possibly) permutation with other gathers. It | |||
1032 | /// implements the checks only for possibly ordered scalars (Loads, | |||
1033 | /// ExtractElement, ExtractValue), which can be part of the graph. | |||
1034 | Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); | |||
1035 | ||||
1036 | /// Sort loads into increasing pointers offsets to allow greater clustering. | |||
1037 | Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE); | |||
1038 | ||||
1039 | /// Gets reordering data for the given tree entry. If the entry is vectorized | |||
1040 | /// - just return ReorderIndices, otherwise check if the scalars can be | |||
1041 | /// reordered and return the most optimal order. | |||
1042 | /// \param TopToBottom If true, include the order of vectorized stores and | |||
1043 | /// insertelement nodes, otherwise skip them. | |||
1044 | Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom); | |||
1045 | ||||
1046 | /// Reorders the current graph to the most profitable order starting from the | |||
1047 | /// root node to the leaf nodes. The best order is chosen only from the nodes | |||
1048 | /// of the same size (vectorization factor). Smaller nodes are considered | |||
1049 | /// parts of subgraph with smaller VF and they are reordered independently. We | |||
1050 | /// can make it because we still need to extend smaller nodes to the wider VF | |||
1051 | /// and we can merge reordering shuffles with the widening shuffles. | |||
1052 | void reorderTopToBottom(); | |||
1053 | ||||
1054 | /// Reorders the current graph to the most profitable order starting from | |||
1055 | /// leaves to the root. It allows to rotate small subgraphs and reduce the | |||
1056 | /// number of reshuffles if the leaf nodes use the same order. In this case we | |||
1057 | /// can merge the orders and just shuffle user node instead of shuffling its | |||
1058 | /// operands. Plus, even the leaf nodes have different orders, it allows to | |||
1059 | /// sink reordering in the graph closer to the root node and merge it later | |||
1060 | /// during analysis. | |||
1061 | void reorderBottomToTop(bool IgnoreReorder = false); | |||
1062 | ||||
1063 | /// \return The vector element size in bits to use when vectorizing the | |||
1064 | /// expression tree ending at \p V. If V is a store, the size is the width of | |||
1065 | /// the stored value. Otherwise, the size is the width of the largest loaded | |||
1066 | /// value reaching V. This method is used by the vectorizer to calculate | |||
1067 | /// vectorization factors. | |||
1068 | unsigned getVectorElementSize(Value *V); | |||
1069 | ||||
1070 | /// Compute the minimum type sizes required to represent the entries in a | |||
1071 | /// vectorizable tree. | |||
1072 | void computeMinimumValueSizes(); | |||
1073 | ||||
1074 | // \returns maximum vector register size as set by TTI or overridden by cl::opt. | |||
1075 | unsigned getMaxVecRegSize() const { | |||
1076 | return MaxVecRegSize; | |||
1077 | } | |||
1078 | ||||
1079 | // \returns minimum vector register size as set by cl::opt. | |||
1080 | unsigned getMinVecRegSize() const { | |||
1081 | return MinVecRegSize; | |||
1082 | } | |||
1083 | ||||
1084 | unsigned getMinVF(unsigned Sz) const { | |||
1085 | return std::max(2U, getMinVecRegSize() / Sz); | |||
1086 | } | |||
1087 | ||||
1088 | unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { | |||
1089 | unsigned MaxVF = MaxVFOption.getNumOccurrences() ? | |||
1090 | MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); | |||
1091 | return MaxVF ? MaxVF : UINT_MAX(2147483647 *2U +1U); | |||
1092 | } | |||
1093 | ||||
1094 | /// Check if homogeneous aggregate is isomorphic to some VectorType. | |||
1095 | /// Accepts homogeneous multidimensional aggregate of scalars/vectors like | |||
1096 | /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, | |||
1097 | /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. | |||
1098 | /// | |||
1099 | /// \returns number of elements in vector if isomorphism exists, 0 otherwise. | |||
1100 | unsigned canMapToVector(Type *T, const DataLayout &DL) const; | |||
1101 | ||||
1102 | /// \returns True if the VectorizableTree is both tiny and not fully | |||
1103 | /// vectorizable. We do not vectorize such trees. | |||
1104 | bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; | |||
1105 | ||||
1106 | /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values | |||
1107 | /// can be load combined in the backend. Load combining may not be allowed in | |||
1108 | /// the IR optimizer, so we do not want to alter the pattern. For example, | |||
1109 | /// partially transforming a scalar bswap() pattern into vector code is | |||
1110 | /// effectively impossible for the backend to undo. | |||
1111 | /// TODO: If load combining is allowed in the IR optimizer, this analysis | |||
1112 | /// may not be necessary. | |||
1113 | bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; | |||
1114 | ||||
1115 | /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values | |||
1116 | /// can be load combined in the backend. Load combining may not be allowed in | |||
1117 | /// the IR optimizer, so we do not want to alter the pattern. For example, | |||
1118 | /// partially transforming a scalar bswap() pattern into vector code is | |||
1119 | /// effectively impossible for the backend to undo. | |||
1120 | /// TODO: If load combining is allowed in the IR optimizer, this analysis | |||
1121 | /// may not be necessary. | |||
1122 | bool isLoadCombineCandidate() const; | |||
1123 | ||||
1124 | OptimizationRemarkEmitter *getORE() { return ORE; } | |||
1125 | ||||
1126 | /// This structure holds any data we need about the edges being traversed | |||
1127 | /// during buildTree_rec(). We keep track of: | |||
1128 | /// (i) the user TreeEntry index, and | |||
1129 | /// (ii) the index of the edge. | |||
1130 | struct EdgeInfo { | |||
1131 | EdgeInfo() = default; | |||
1132 | EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) | |||
1133 | : UserTE(UserTE), EdgeIdx(EdgeIdx) {} | |||
1134 | /// The user TreeEntry. | |||
1135 | TreeEntry *UserTE = nullptr; | |||
1136 | /// The operand index of the use. | |||
1137 | unsigned EdgeIdx = UINT_MAX(2147483647 *2U +1U); | |||
1138 | #ifndef NDEBUG | |||
1139 | friend inline raw_ostream &operator<<(raw_ostream &OS, | |||
1140 | const BoUpSLP::EdgeInfo &EI) { | |||
1141 | EI.dump(OS); | |||
1142 | return OS; | |||
1143 | } | |||
1144 | /// Debug print. | |||
1145 | void dump(raw_ostream &OS) const { | |||
1146 | OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") | |||
1147 | << " EdgeIdx:" << EdgeIdx << "}"; | |||
1148 | } | |||
1149 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { dump(dbgs()); } | |||
1150 | #endif | |||
1151 | }; | |||
1152 | ||||
1153 | /// A helper class used for scoring candidates for two consecutive lanes. | |||
1154 | class LookAheadHeuristics { | |||
1155 | const TargetLibraryInfo &TLI; | |||
1156 | const DataLayout &DL; | |||
1157 | ScalarEvolution &SE; | |||
1158 | const BoUpSLP &R; | |||
1159 | int NumLanes; // Total number of lanes (aka vectorization factor). | |||
1160 | int MaxLevel; // The maximum recursion depth for accumulating score. | |||
1161 | ||||
1162 | public: | |||
1163 | LookAheadHeuristics(const TargetLibraryInfo &TLI, const DataLayout &DL, | |||
1164 | ScalarEvolution &SE, const BoUpSLP &R, int NumLanes, | |||
1165 | int MaxLevel) | |||
1166 | : TLI(TLI), DL(DL), SE(SE), R(R), NumLanes(NumLanes), | |||
1167 | MaxLevel(MaxLevel) {} | |||
1168 | ||||
1169 | // The hard-coded scores listed here are not very important, though it shall | |||
1170 | // be higher for better matches to improve the resulting cost. When | |||
1171 | // computing the scores of matching one sub-tree with another, we are | |||
1172 | // basically counting the number of values that are matching. So even if all | |||
1173 | // scores are set to 1, we would still get a decent matching result. | |||
1174 | // However, sometimes we have to break ties. For example we may have to | |||
1175 | // choose between matching loads vs matching opcodes. This is what these | |||
1176 | // scores are helping us with: they provide the order of preference. Also, | |||
1177 | // this is important if the scalar is externally used or used in another | |||
1178 | // tree entry node in the different lane. | |||
1179 | ||||
1180 | /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). | |||
1181 | static const int ScoreConsecutiveLoads = 4; | |||
1182 | /// The same load multiple times. This should have a better score than | |||
1183 | /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it | |||
1184 | /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for | |||
1185 | /// a vector load and 1.0 for a broadcast. | |||
1186 | static const int ScoreSplatLoads = 3; | |||
1187 | /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]). | |||
1188 | static const int ScoreReversedLoads = 3; | |||
1189 | /// A load candidate for masked gather. | |||
1190 | static const int ScoreMaskedGatherCandidate = 1; | |||
1191 | /// ExtractElementInst from same vector and consecutive indexes. | |||
1192 | static const int ScoreConsecutiveExtracts = 4; | |||
1193 | /// ExtractElementInst from same vector and reversed indices. | |||
1194 | static const int ScoreReversedExtracts = 3; | |||
1195 | /// Constants. | |||
1196 | static const int ScoreConstants = 2; | |||
1197 | /// Instructions with the same opcode. | |||
1198 | static const int ScoreSameOpcode = 2; | |||
1199 | /// Instructions with alt opcodes (e.g, add + sub). | |||
1200 | static const int ScoreAltOpcodes = 1; | |||
1201 | /// Identical instructions (a.k.a. splat or broadcast). | |||
1202 | static const int ScoreSplat = 1; | |||
1203 | /// Matching with an undef is preferable to failing. | |||
1204 | static const int ScoreUndef = 1; | |||
1205 | /// Score for failing to find a decent match. | |||
1206 | static const int ScoreFail = 0; | |||
1207 | /// Score if all users are vectorized. | |||
1208 | static const int ScoreAllUserVectorized = 1; | |||
1209 | ||||
1210 | /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. | |||
1211 | /// \p U1 and \p U2 are the users of \p V1 and \p V2. | |||
1212 | /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p | |||
1213 | /// MainAltOps. | |||
1214 | int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2, | |||
1215 | ArrayRef<Value *> MainAltOps) const { | |||
1216 | if (!isValidElementType(V1->getType()) || | |||
1217 | !isValidElementType(V2->getType())) | |||
1218 | return LookAheadHeuristics::ScoreFail; | |||
1219 | ||||
1220 | if (V1 == V2) { | |||
1221 | if (isa<LoadInst>(V1)) { | |||
1222 | // Retruns true if the users of V1 and V2 won't need to be extracted. | |||
1223 | auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) { | |||
1224 | // Bail out if we have too many uses to save compilation time. | |||
1225 | static constexpr unsigned Limit = 8; | |||
1226 | if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit)) | |||
1227 | return false; | |||
1228 | ||||
1229 | auto AllUsersVectorized = [U1, U2, this](Value *V) { | |||
1230 | return llvm::all_of(V->users(), [U1, U2, this](Value *U) { | |||
1231 | return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr; | |||
1232 | }); | |||
1233 | }; | |||
1234 | return AllUsersVectorized(V1) && AllUsersVectorized(V2); | |||
1235 | }; | |||
1236 | // A broadcast of a load can be cheaper on some targets. | |||
1237 | if (R.TTI->isLegalBroadcastLoad(V1->getType(), | |||
1238 | ElementCount::getFixed(NumLanes)) && | |||
1239 | ((int)V1->getNumUses() == NumLanes || | |||
1240 | AllUsersAreInternal(V1, V2))) | |||
1241 | return LookAheadHeuristics::ScoreSplatLoads; | |||
1242 | } | |||
1243 | return LookAheadHeuristics::ScoreSplat; | |||
1244 | } | |||
1245 | ||||
1246 | auto *LI1 = dyn_cast<LoadInst>(V1); | |||
1247 | auto *LI2 = dyn_cast<LoadInst>(V2); | |||
1248 | if (LI1 && LI2) { | |||
1249 | if (LI1->getParent() != LI2->getParent() || !LI1->isSimple() || | |||
1250 | !LI2->isSimple()) | |||
1251 | return LookAheadHeuristics::ScoreFail; | |||
1252 | ||||
1253 | Optional<int> Dist = getPointersDiff( | |||
1254 | LI1->getType(), LI1->getPointerOperand(), LI2->getType(), | |||
1255 | LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); | |||
1256 | if (!Dist || *Dist == 0) { | |||
1257 | if (getUnderlyingObject(LI1->getPointerOperand()) == | |||
1258 | getUnderlyingObject(LI2->getPointerOperand()) && | |||
1259 | R.TTI->isLegalMaskedGather( | |||
1260 | FixedVectorType::get(LI1->getType(), NumLanes), | |||
1261 | LI1->getAlign())) | |||
1262 | return LookAheadHeuristics::ScoreMaskedGatherCandidate; | |||
1263 | return LookAheadHeuristics::ScoreFail; | |||
1264 | } | |||
1265 | // The distance is too large - still may be profitable to use masked | |||
1266 | // loads/gathers. | |||
1267 | if (std::abs(*Dist) > NumLanes / 2) | |||
1268 | return LookAheadHeuristics::ScoreMaskedGatherCandidate; | |||
1269 | // This still will detect consecutive loads, but we might have "holes" | |||
1270 | // in some cases. It is ok for non-power-2 vectorization and may produce | |||
1271 | // better results. It should not affect current vectorization. | |||
1272 | return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads | |||
1273 | : LookAheadHeuristics::ScoreReversedLoads; | |||
1274 | } | |||
1275 | ||||
1276 | auto *C1 = dyn_cast<Constant>(V1); | |||
1277 | auto *C2 = dyn_cast<Constant>(V2); | |||
1278 | if (C1 && C2) | |||
1279 | return LookAheadHeuristics::ScoreConstants; | |||
1280 | ||||
1281 | // Extracts from consecutive indexes of the same vector better score as | |||
1282 | // the extracts could be optimized away. | |||
1283 | Value *EV1; | |||
1284 | ConstantInt *Ex1Idx; | |||
1285 | if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) { | |||
1286 | // Undefs are always profitable for extractelements. | |||
1287 | if (isa<UndefValue>(V2)) | |||
1288 | return LookAheadHeuristics::ScoreConsecutiveExtracts; | |||
1289 | Value *EV2 = nullptr; | |||
1290 | ConstantInt *Ex2Idx = nullptr; | |||
1291 | if (match(V2, | |||
1292 | m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx), | |||
1293 | m_Undef())))) { | |||
1294 | // Undefs are always profitable for extractelements. | |||
1295 | if (!Ex2Idx) | |||
1296 | return LookAheadHeuristics::ScoreConsecutiveExtracts; | |||
1297 | if (isUndefVector(EV2).all() && EV2->getType() == EV1->getType()) | |||
1298 | return LookAheadHeuristics::ScoreConsecutiveExtracts; | |||
1299 | if (EV2 == EV1) { | |||
1300 | int Idx1 = Ex1Idx->getZExtValue(); | |||
1301 | int Idx2 = Ex2Idx->getZExtValue(); | |||
1302 | int Dist = Idx2 - Idx1; | |||
1303 | // The distance is too large - still may be profitable to use | |||
1304 | // shuffles. | |||
1305 | if (std::abs(Dist) == 0) | |||
1306 | return LookAheadHeuristics::ScoreSplat; | |||
1307 | if (std::abs(Dist) > NumLanes / 2) | |||
1308 | return LookAheadHeuristics::ScoreSameOpcode; | |||
1309 | return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts | |||
1310 | : LookAheadHeuristics::ScoreReversedExtracts; | |||
1311 | } | |||
1312 | return LookAheadHeuristics::ScoreAltOpcodes; | |||
1313 | } | |||
1314 | return LookAheadHeuristics::ScoreFail; | |||
1315 | } | |||
1316 | ||||
1317 | auto *I1 = dyn_cast<Instruction>(V1); | |||
1318 | auto *I2 = dyn_cast<Instruction>(V2); | |||
1319 | if (I1 && I2) { | |||
1320 | if (I1->getParent() != I2->getParent()) | |||
1321 | return LookAheadHeuristics::ScoreFail; | |||
1322 | SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end()); | |||
1323 | Ops.push_back(I1); | |||
1324 | Ops.push_back(I2); | |||
1325 | InstructionsState S = getSameOpcode(Ops, TLI); | |||
1326 | // Note: Only consider instructions with <= 2 operands to avoid | |||
1327 | // complexity explosion. | |||
1328 | if (S.getOpcode() && | |||
1329 | (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() || | |||
1330 | !S.isAltShuffle()) && | |||
1331 | all_of(Ops, [&S](Value *V) { | |||
1332 | return cast<Instruction>(V)->getNumOperands() == | |||
1333 | S.MainOp->getNumOperands(); | |||
1334 | })) | |||
1335 | return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes | |||
1336 | : LookAheadHeuristics::ScoreSameOpcode; | |||
1337 | } | |||
1338 | ||||
1339 | if (isa<UndefValue>(V2)) | |||
1340 | return LookAheadHeuristics::ScoreUndef; | |||
1341 | ||||
1342 | return LookAheadHeuristics::ScoreFail; | |||
1343 | } | |||
1344 | ||||
1345 | /// Go through the operands of \p LHS and \p RHS recursively until | |||
1346 | /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are | |||
1347 | /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands | |||
1348 | /// of \p U1 and \p U2), except at the beginning of the recursion where | |||
1349 | /// these are set to nullptr. | |||
1350 | /// | |||
1351 | /// For example: | |||
1352 | /// \verbatim | |||
1353 | /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] | |||
1354 | /// \ / \ / \ / \ / | |||
1355 | /// + + + + | |||
1356 | /// G1 G2 G3 G4 | |||
1357 | /// \endverbatim | |||
1358 | /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at | |||
1359 | /// each level recursively, accumulating the score. It starts from matching | |||
1360 | /// the additions at level 0, then moves on to the loads (level 1). The | |||
1361 | /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and | |||
1362 | /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while | |||
1363 | /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail. | |||
1364 | /// Please note that the order of the operands does not matter, as we | |||
1365 | /// evaluate the score of all profitable combinations of operands. In | |||
1366 | /// other words the score of G1 and G4 is the same as G1 and G2. This | |||
1367 | /// heuristic is based on ideas described in: | |||
1368 | /// Look-ahead SLP: Auto-vectorization in the presence of commutative | |||
1369 | /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, | |||
1370 | /// Luís F. W. Góes | |||
1371 | int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1, | |||
1372 | Instruction *U2, int CurrLevel, | |||
1373 | ArrayRef<Value *> MainAltOps) const { | |||
1374 | ||||
1375 | // Get the shallow score of V1 and V2. | |||
1376 | int ShallowScoreAtThisLevel = | |||
1377 | getShallowScore(LHS, RHS, U1, U2, MainAltOps); | |||
1378 | ||||
1379 | // If reached MaxLevel, | |||
1380 | // or if V1 and V2 are not instructions, | |||
1381 | // or if they are SPLAT, | |||
1382 | // or if they are not consecutive, | |||
1383 | // or if profitable to vectorize loads or extractelements, early return | |||
1384 | // the current cost. | |||
1385 | auto *I1 = dyn_cast<Instruction>(LHS); | |||
1386 | auto *I2 = dyn_cast<Instruction>(RHS); | |||
1387 | if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || | |||
1388 | ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail || | |||
1389 | (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) || | |||
1390 | (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) || | |||
1391 | (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) && | |||
1392 | ShallowScoreAtThisLevel)) | |||
1393 | return ShallowScoreAtThisLevel; | |||
1394 | assert(I1 && I2 && "Should have early exited.")(static_cast <bool> (I1 && I2 && "Should have early exited." ) ? void (0) : __assert_fail ("I1 && I2 && \"Should have early exited.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1394, __extension__ __PRETTY_FUNCTION__)); | |||
1395 | ||||
1396 | // Contains the I2 operand indexes that got matched with I1 operands. | |||
1397 | SmallSet<unsigned, 4> Op2Used; | |||
1398 | ||||
1399 | // Recursion towards the operands of I1 and I2. We are trying all possible | |||
1400 | // operand pairs, and keeping track of the best score. | |||
1401 | for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); | |||
1402 | OpIdx1 != NumOperands1; ++OpIdx1) { | |||
1403 | // Try to pair op1I with the best operand of I2. | |||
1404 | int MaxTmpScore = 0; | |||
1405 | unsigned MaxOpIdx2 = 0; | |||
1406 | bool FoundBest = false; | |||
1407 | // If I2 is commutative try all combinations. | |||
1408 | unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; | |||
1409 | unsigned ToIdx = isCommutative(I2) | |||
1410 | ? I2->getNumOperands() | |||
1411 | : std::min(I2->getNumOperands(), OpIdx1 + 1); | |||
1412 | assert(FromIdx <= ToIdx && "Bad index")(static_cast <bool> (FromIdx <= ToIdx && "Bad index" ) ? void (0) : __assert_fail ("FromIdx <= ToIdx && \"Bad index\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1412, __extension__ __PRETTY_FUNCTION__)); | |||
1413 | for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { | |||
1414 | // Skip operands already paired with OpIdx1. | |||
1415 | if (Op2Used.count(OpIdx2)) | |||
1416 | continue; | |||
1417 | // Recursively calculate the cost at each level | |||
1418 | int TmpScore = | |||
1419 | getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2), | |||
1420 | I1, I2, CurrLevel + 1, None); | |||
1421 | // Look for the best score. | |||
1422 | if (TmpScore > LookAheadHeuristics::ScoreFail && | |||
1423 | TmpScore > MaxTmpScore) { | |||
1424 | MaxTmpScore = TmpScore; | |||
1425 | MaxOpIdx2 = OpIdx2; | |||
1426 | FoundBest = true; | |||
1427 | } | |||
1428 | } | |||
1429 | if (FoundBest) { | |||
1430 | // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. | |||
1431 | Op2Used.insert(MaxOpIdx2); | |||
1432 | ShallowScoreAtThisLevel += MaxTmpScore; | |||
1433 | } | |||
1434 | } | |||
1435 | return ShallowScoreAtThisLevel; | |||
1436 | } | |||
1437 | }; | |||
1438 | /// A helper data structure to hold the operands of a vector of instructions. | |||
1439 | /// This supports a fixed vector length for all operand vectors. | |||
1440 | class VLOperands { | |||
1441 | /// For each operand we need (i) the value, and (ii) the opcode that it | |||
1442 | /// would be attached to if the expression was in a left-linearized form. | |||
1443 | /// This is required to avoid illegal operand reordering. | |||
1444 | /// For example: | |||
1445 | /// \verbatim | |||
1446 | /// 0 Op1 | |||
1447 | /// |/ | |||
1448 | /// Op1 Op2 Linearized + Op2 | |||
1449 | /// \ / ----------> |/ | |||
1450 | /// - - | |||
1451 | /// | |||
1452 | /// Op1 - Op2 (0 + Op1) - Op2 | |||
1453 | /// \endverbatim | |||
1454 | /// | |||
1455 | /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. | |||
1456 | /// | |||
1457 | /// Another way to think of this is to track all the operations across the | |||
1458 | /// path from the operand all the way to the root of the tree and to | |||
1459 | /// calculate the operation that corresponds to this path. For example, the | |||
1460 | /// path from Op2 to the root crosses the RHS of the '-', therefore the | |||
1461 | /// corresponding operation is a '-' (which matches the one in the | |||
1462 | /// linearized tree, as shown above). | |||
1463 | /// | |||
1464 | /// For lack of a better term, we refer to this operation as Accumulated | |||
1465 | /// Path Operation (APO). | |||
1466 | struct OperandData { | |||
1467 | OperandData() = default; | |||
1468 | OperandData(Value *V, bool APO, bool IsUsed) | |||
1469 | : V(V), APO(APO), IsUsed(IsUsed) {} | |||
1470 | /// The operand value. | |||
1471 | Value *V = nullptr; | |||
1472 | /// TreeEntries only allow a single opcode, or an alternate sequence of | |||
1473 | /// them (e.g, +, -). Therefore, we can safely use a boolean value for the | |||
1474 | /// APO. It is set to 'true' if 'V' is attached to an inverse operation | |||
1475 | /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise | |||
1476 | /// (e.g., Add/Mul) | |||
1477 | bool APO = false; | |||
1478 | /// Helper data for the reordering function. | |||
1479 | bool IsUsed = false; | |||
1480 | }; | |||
1481 | ||||
1482 | /// During operand reordering, we are trying to select the operand at lane | |||
1483 | /// that matches best with the operand at the neighboring lane. Our | |||
1484 | /// selection is based on the type of value we are looking for. For example, | |||
1485 | /// if the neighboring lane has a load, we need to look for a load that is | |||
1486 | /// accessing a consecutive address. These strategies are summarized in the | |||
1487 | /// 'ReorderingMode' enumerator. | |||
1488 | enum class ReorderingMode { | |||
1489 | Load, ///< Matching loads to consecutive memory addresses | |||
1490 | Opcode, ///< Matching instructions based on opcode (same or alternate) | |||
1491 | Constant, ///< Matching constants | |||
1492 | Splat, ///< Matching the same instruction multiple times (broadcast) | |||
1493 | Failed, ///< We failed to create a vectorizable group | |||
1494 | }; | |||
1495 | ||||
1496 | using OperandDataVec = SmallVector<OperandData, 2>; | |||
1497 | ||||
1498 | /// A vector of operand vectors. | |||
1499 | SmallVector<OperandDataVec, 4> OpsVec; | |||
1500 | ||||
1501 | const TargetLibraryInfo &TLI; | |||
1502 | const DataLayout &DL; | |||
1503 | ScalarEvolution &SE; | |||
1504 | const BoUpSLP &R; | |||
1505 | ||||
1506 | /// \returns the operand data at \p OpIdx and \p Lane. | |||
1507 | OperandData &getData(unsigned OpIdx, unsigned Lane) { | |||
1508 | return OpsVec[OpIdx][Lane]; | |||
1509 | } | |||
1510 | ||||
1511 | /// \returns the operand data at \p OpIdx and \p Lane. Const version. | |||
1512 | const OperandData &getData(unsigned OpIdx, unsigned Lane) const { | |||
1513 | return OpsVec[OpIdx][Lane]; | |||
1514 | } | |||
1515 | ||||
1516 | /// Clears the used flag for all entries. | |||
1517 | void clearUsed() { | |||
1518 | for (unsigned OpIdx = 0, NumOperands = getNumOperands(); | |||
1519 | OpIdx != NumOperands; ++OpIdx) | |||
1520 | for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; | |||
1521 | ++Lane) | |||
1522 | OpsVec[OpIdx][Lane].IsUsed = false; | |||
1523 | } | |||
1524 | ||||
1525 | /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. | |||
1526 | void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { | |||
1527 | std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); | |||
1528 | } | |||
1529 | ||||
1530 | /// \param Lane lane of the operands under analysis. | |||
1531 | /// \param OpIdx operand index in \p Lane lane we're looking the best | |||
1532 | /// candidate for. | |||
1533 | /// \param Idx operand index of the current candidate value. | |||
1534 | /// \returns The additional score due to possible broadcasting of the | |||
1535 | /// elements in the lane. It is more profitable to have power-of-2 unique | |||
1536 | /// elements in the lane, it will be vectorized with higher probability | |||
1537 | /// after removing duplicates. Currently the SLP vectorizer supports only | |||
1538 | /// vectorization of the power-of-2 number of unique scalars. | |||
1539 | int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { | |||
1540 | Value *IdxLaneV = getData(Idx, Lane).V; | |||
1541 | if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V) | |||
1542 | return 0; | |||
1543 | SmallPtrSet<Value *, 4> Uniques; | |||
1544 | for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) { | |||
1545 | if (Ln == Lane) | |||
1546 | continue; | |||
1547 | Value *OpIdxLnV = getData(OpIdx, Ln).V; | |||
1548 | if (!isa<Instruction>(OpIdxLnV)) | |||
1549 | return 0; | |||
1550 | Uniques.insert(OpIdxLnV); | |||
1551 | } | |||
1552 | int UniquesCount = Uniques.size(); | |||
1553 | int UniquesCntWithIdxLaneV = | |||
1554 | Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1; | |||
1555 | Value *OpIdxLaneV = getData(OpIdx, Lane).V; | |||
1556 | int UniquesCntWithOpIdxLaneV = | |||
1557 | Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1; | |||
1558 | if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV) | |||
1559 | return 0; | |||
1560 | return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) - | |||
1561 | UniquesCntWithOpIdxLaneV) - | |||
1562 | (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV); | |||
1563 | } | |||
1564 | ||||
1565 | /// \param Lane lane of the operands under analysis. | |||
1566 | /// \param OpIdx operand index in \p Lane lane we're looking the best | |||
1567 | /// candidate for. | |||
1568 | /// \param Idx operand index of the current candidate value. | |||
1569 | /// \returns The additional score for the scalar which users are all | |||
1570 | /// vectorized. | |||
1571 | int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { | |||
1572 | Value *IdxLaneV = getData(Idx, Lane).V; | |||
1573 | Value *OpIdxLaneV = getData(OpIdx, Lane).V; | |||
1574 | // Do not care about number of uses for vector-like instructions | |||
1575 | // (extractelement/extractvalue with constant indices), they are extracts | |||
1576 | // themselves and already externally used. Vectorization of such | |||
1577 | // instructions does not add extra extractelement instruction, just may | |||
1578 | // remove it. | |||
1579 | if (isVectorLikeInstWithConstOps(IdxLaneV) && | |||
1580 | isVectorLikeInstWithConstOps(OpIdxLaneV)) | |||
1581 | return LookAheadHeuristics::ScoreAllUserVectorized; | |||
1582 | auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV); | |||
1583 | if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV)) | |||
1584 | return 0; | |||
1585 | return R.areAllUsersVectorized(IdxLaneI, None) | |||
1586 | ? LookAheadHeuristics::ScoreAllUserVectorized | |||
1587 | : 0; | |||
1588 | } | |||
1589 | ||||
1590 | /// Score scaling factor for fully compatible instructions but with | |||
1591 | /// different number of external uses. Allows better selection of the | |||
1592 | /// instructions with less external uses. | |||
1593 | static const int ScoreScaleFactor = 10; | |||
1594 | ||||
1595 | /// \Returns the look-ahead score, which tells us how much the sub-trees | |||
1596 | /// rooted at \p LHS and \p RHS match, the more they match the higher the | |||
1597 | /// score. This helps break ties in an informed way when we cannot decide on | |||
1598 | /// the order of the operands by just considering the immediate | |||
1599 | /// predecessors. | |||
1600 | int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps, | |||
1601 | int Lane, unsigned OpIdx, unsigned Idx, | |||
1602 | bool &IsUsed) { | |||
1603 | LookAheadHeuristics LookAhead(TLI, DL, SE, R, getNumLanes(), | |||
1604 | LookAheadMaxDepth); | |||
1605 | // Keep track of the instruction stack as we recurse into the operands | |||
1606 | // during the look-ahead score exploration. | |||
1607 | int Score = | |||
1608 | LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr, | |||
1609 | /*CurrLevel=*/1, MainAltOps); | |||
1610 | if (Score) { | |||
1611 | int SplatScore = getSplatScore(Lane, OpIdx, Idx); | |||
1612 | if (Score <= -SplatScore) { | |||
1613 | // Set the minimum score for splat-like sequence to avoid setting | |||
1614 | // failed state. | |||
1615 | Score = 1; | |||
1616 | } else { | |||
1617 | Score += SplatScore; | |||
1618 | // Scale score to see the difference between different operands | |||
1619 | // and similar operands but all vectorized/not all vectorized | |||
1620 | // uses. It does not affect actual selection of the best | |||
1621 | // compatible operand in general, just allows to select the | |||
1622 | // operand with all vectorized uses. | |||
1623 | Score *= ScoreScaleFactor; | |||
1624 | Score += getExternalUseScore(Lane, OpIdx, Idx); | |||
1625 | IsUsed = true; | |||
1626 | } | |||
1627 | } | |||
1628 | return Score; | |||
1629 | } | |||
1630 | ||||
1631 | /// Best defined scores per lanes between the passes. Used to choose the | |||
1632 | /// best operand (with the highest score) between the passes. | |||
1633 | /// The key - {Operand Index, Lane}. | |||
1634 | /// The value - the best score between the passes for the lane and the | |||
1635 | /// operand. | |||
1636 | SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8> | |||
1637 | BestScoresPerLanes; | |||
1638 | ||||
1639 | // Search all operands in Ops[*][Lane] for the one that matches best | |||
1640 | // Ops[OpIdx][LastLane] and return its opreand index. | |||
1641 | // If no good match can be found, return None. | |||
1642 | Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane, | |||
1643 | ArrayRef<ReorderingMode> ReorderingModes, | |||
1644 | ArrayRef<Value *> MainAltOps) { | |||
1645 | unsigned NumOperands = getNumOperands(); | |||
1646 | ||||
1647 | // The operand of the previous lane at OpIdx. | |||
1648 | Value *OpLastLane = getData(OpIdx, LastLane).V; | |||
1649 | ||||
1650 | // Our strategy mode for OpIdx. | |||
1651 | ReorderingMode RMode = ReorderingModes[OpIdx]; | |||
1652 | if (RMode == ReorderingMode::Failed) | |||
1653 | return None; | |||
1654 | ||||
1655 | // The linearized opcode of the operand at OpIdx, Lane. | |||
1656 | bool OpIdxAPO = getData(OpIdx, Lane).APO; | |||
1657 | ||||
1658 | // The best operand index and its score. | |||
1659 | // Sometimes we have more than one option (e.g., Opcode and Undefs), so we | |||
1660 | // are using the score to differentiate between the two. | |||
1661 | struct BestOpData { | |||
1662 | Optional<unsigned> Idx = None; | |||
1663 | unsigned Score = 0; | |||
1664 | } BestOp; | |||
1665 | BestOp.Score = | |||
1666 | BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0) | |||
1667 | .first->second; | |||
1668 | ||||
1669 | // Track if the operand must be marked as used. If the operand is set to | |||
1670 | // Score 1 explicitly (because of non power-of-2 unique scalars, we may | |||
1671 | // want to reestimate the operands again on the following iterations). | |||
1672 | bool IsUsed = | |||
1673 | RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant; | |||
1674 | // Iterate through all unused operands and look for the best. | |||
1675 | for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { | |||
1676 | // Get the operand at Idx and Lane. | |||
1677 | OperandData &OpData = getData(Idx, Lane); | |||
1678 | Value *Op = OpData.V; | |||
1679 | bool OpAPO = OpData.APO; | |||
1680 | ||||
1681 | // Skip already selected operands. | |||
1682 | if (OpData.IsUsed) | |||
1683 | continue; | |||
1684 | ||||
1685 | // Skip if we are trying to move the operand to a position with a | |||
1686 | // different opcode in the linearized tree form. This would break the | |||
1687 | // semantics. | |||
1688 | if (OpAPO != OpIdxAPO) | |||
1689 | continue; | |||
1690 | ||||
1691 | // Look for an operand that matches the current mode. | |||
1692 | switch (RMode) { | |||
1693 | case ReorderingMode::Load: | |||
1694 | case ReorderingMode::Constant: | |||
1695 | case ReorderingMode::Opcode: { | |||
1696 | bool LeftToRight = Lane > LastLane; | |||
1697 | Value *OpLeft = (LeftToRight) ? OpLastLane : Op; | |||
1698 | Value *OpRight = (LeftToRight) ? Op : OpLastLane; | |||
1699 | int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane, | |||
1700 | OpIdx, Idx, IsUsed); | |||
1701 | if (Score > static_cast<int>(BestOp.Score)) { | |||
1702 | BestOp.Idx = Idx; | |||
1703 | BestOp.Score = Score; | |||
1704 | BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score; | |||
1705 | } | |||
1706 | break; | |||
1707 | } | |||
1708 | case ReorderingMode::Splat: | |||
1709 | if (Op == OpLastLane) | |||
1710 | BestOp.Idx = Idx; | |||
1711 | break; | |||
1712 | case ReorderingMode::Failed: | |||
1713 | llvm_unreachable("Not expected Failed reordering mode.")::llvm::llvm_unreachable_internal("Not expected Failed reordering mode." , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1713); | |||
1714 | } | |||
1715 | } | |||
1716 | ||||
1717 | if (BestOp.Idx) { | |||
1718 | getData(*BestOp.Idx, Lane).IsUsed = IsUsed; | |||
1719 | return BestOp.Idx; | |||
1720 | } | |||
1721 | // If we could not find a good match return None. | |||
1722 | return None; | |||
1723 | } | |||
1724 | ||||
1725 | /// Helper for reorderOperandVecs. | |||
1726 | /// \returns the lane that we should start reordering from. This is the one | |||
1727 | /// which has the least number of operands that can freely move about or | |||
1728 | /// less profitable because it already has the most optimal set of operands. | |||
1729 | unsigned getBestLaneToStartReordering() const { | |||
1730 | unsigned Min = UINT_MAX(2147483647 *2U +1U); | |||
1731 | unsigned SameOpNumber = 0; | |||
1732 | // std::pair<unsigned, unsigned> is used to implement a simple voting | |||
1733 | // algorithm and choose the lane with the least number of operands that | |||
1734 | // can freely move about or less profitable because it already has the | |||
1735 | // most optimal set of operands. The first unsigned is a counter for | |||
1736 | // voting, the second unsigned is the counter of lanes with instructions | |||
1737 | // with same/alternate opcodes and same parent basic block. | |||
1738 | MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap; | |||
1739 | // Try to be closer to the original results, if we have multiple lanes | |||
1740 | // with same cost. If 2 lanes have the same cost, use the one with the | |||
1741 | // lowest index. | |||
1742 | for (int I = getNumLanes(); I > 0; --I) { | |||
1743 | unsigned Lane = I - 1; | |||
1744 | OperandsOrderData NumFreeOpsHash = | |||
1745 | getMaxNumOperandsThatCanBeReordered(Lane); | |||
1746 | // Compare the number of operands that can move and choose the one with | |||
1747 | // the least number. | |||
1748 | if (NumFreeOpsHash.NumOfAPOs < Min) { | |||
1749 | Min = NumFreeOpsHash.NumOfAPOs; | |||
1750 | SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; | |||
1751 | HashMap.clear(); | |||
1752 | HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); | |||
1753 | } else if (NumFreeOpsHash.NumOfAPOs == Min && | |||
1754 | NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) { | |||
1755 | // Select the most optimal lane in terms of number of operands that | |||
1756 | // should be moved around. | |||
1757 | SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; | |||
1758 | HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); | |||
1759 | } else if (NumFreeOpsHash.NumOfAPOs == Min && | |||
1760 | NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) { | |||
1761 | auto It = HashMap.find(NumFreeOpsHash.Hash); | |||
1762 | if (It == HashMap.end()) | |||
1763 | HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); | |||
1764 | else | |||
1765 | ++It->second.first; | |||
1766 | } | |||
1767 | } | |||
1768 | // Select the lane with the minimum counter. | |||
1769 | unsigned BestLane = 0; | |||
1770 | unsigned CntMin = UINT_MAX(2147483647 *2U +1U); | |||
1771 | for (const auto &Data : reverse(HashMap)) { | |||
1772 | if (Data.second.first < CntMin) { | |||
1773 | CntMin = Data.second.first; | |||
1774 | BestLane = Data.second.second; | |||
1775 | } | |||
1776 | } | |||
1777 | return BestLane; | |||
1778 | } | |||
1779 | ||||
1780 | /// Data structure that helps to reorder operands. | |||
1781 | struct OperandsOrderData { | |||
1782 | /// The best number of operands with the same APOs, which can be | |||
1783 | /// reordered. | |||
1784 | unsigned NumOfAPOs = UINT_MAX(2147483647 *2U +1U); | |||
1785 | /// Number of operands with the same/alternate instruction opcode and | |||
1786 | /// parent. | |||
1787 | unsigned NumOpsWithSameOpcodeParent = 0; | |||
1788 | /// Hash for the actual operands ordering. | |||
1789 | /// Used to count operands, actually their position id and opcode | |||
1790 | /// value. It is used in the voting mechanism to find the lane with the | |||
1791 | /// least number of operands that can freely move about or less profitable | |||
1792 | /// because it already has the most optimal set of operands. Can be | |||
1793 | /// replaced with SmallVector<unsigned> instead but hash code is faster | |||
1794 | /// and requires less memory. | |||
1795 | unsigned Hash = 0; | |||
1796 | }; | |||
1797 | /// \returns the maximum number of operands that are allowed to be reordered | |||
1798 | /// for \p Lane and the number of compatible instructions(with the same | |||
1799 | /// parent/opcode). This is used as a heuristic for selecting the first lane | |||
1800 | /// to start operand reordering. | |||
1801 | OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { | |||
1802 | unsigned CntTrue = 0; | |||
1803 | unsigned NumOperands = getNumOperands(); | |||
1804 | // Operands with the same APO can be reordered. We therefore need to count | |||
1805 | // how many of them we have for each APO, like this: Cnt[APO] = x. | |||
1806 | // Since we only have two APOs, namely true and false, we can avoid using | |||
1807 | // a map. Instead we can simply count the number of operands that | |||
1808 | // correspond to one of them (in this case the 'true' APO), and calculate | |||
1809 | // the other by subtracting it from the total number of operands. | |||
1810 | // Operands with the same instruction opcode and parent are more | |||
1811 | // profitable since we don't need to move them in many cases, with a high | |||
1812 | // probability such lane already can be vectorized effectively. | |||
1813 | bool AllUndefs = true; | |||
1814 | unsigned NumOpsWithSameOpcodeParent = 0; | |||
1815 | Instruction *OpcodeI = nullptr; | |||
1816 | BasicBlock *Parent = nullptr; | |||
1817 | unsigned Hash = 0; | |||
1818 | for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { | |||
1819 | const OperandData &OpData = getData(OpIdx, Lane); | |||
1820 | if (OpData.APO) | |||
1821 | ++CntTrue; | |||
1822 | // Use Boyer-Moore majority voting for finding the majority opcode and | |||
1823 | // the number of times it occurs. | |||
1824 | if (auto *I = dyn_cast<Instruction>(OpData.V)) { | |||
1825 | if (!OpcodeI || !getSameOpcode({OpcodeI, I}, TLI).getOpcode() || | |||
1826 | I->getParent() != Parent) { | |||
1827 | if (NumOpsWithSameOpcodeParent == 0) { | |||
1828 | NumOpsWithSameOpcodeParent = 1; | |||
1829 | OpcodeI = I; | |||
1830 | Parent = I->getParent(); | |||
1831 | } else { | |||
1832 | --NumOpsWithSameOpcodeParent; | |||
1833 | } | |||
1834 | } else { | |||
1835 | ++NumOpsWithSameOpcodeParent; | |||
1836 | } | |||
1837 | } | |||
1838 | Hash = hash_combine( | |||
1839 | Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1))); | |||
1840 | AllUndefs = AllUndefs && isa<UndefValue>(OpData.V); | |||
1841 | } | |||
1842 | if (AllUndefs) | |||
1843 | return {}; | |||
1844 | OperandsOrderData Data; | |||
1845 | Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue); | |||
1846 | Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent; | |||
1847 | Data.Hash = Hash; | |||
1848 | return Data; | |||
1849 | } | |||
1850 | ||||
1851 | /// Go through the instructions in VL and append their operands. | |||
1852 | void appendOperandsOfVL(ArrayRef<Value *> VL) { | |||
1853 | assert(!VL.empty() && "Bad VL")(static_cast <bool> (!VL.empty() && "Bad VL") ? void (0) : __assert_fail ("!VL.empty() && \"Bad VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1853, __extension__ __PRETTY_FUNCTION__)); | |||
1854 | assert((empty() || VL.size() == getNumLanes()) &&(static_cast <bool> ((empty() || VL.size() == getNumLanes ()) && "Expected same number of lanes") ? void (0) : __assert_fail ("(empty() || VL.size() == getNumLanes()) && \"Expected same number of lanes\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1855, __extension__ __PRETTY_FUNCTION__)) | |||
1855 | "Expected same number of lanes")(static_cast <bool> ((empty() || VL.size() == getNumLanes ()) && "Expected same number of lanes") ? void (0) : __assert_fail ("(empty() || VL.size() == getNumLanes()) && \"Expected same number of lanes\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1855, __extension__ __PRETTY_FUNCTION__)); | |||
1856 | assert(isa<Instruction>(VL[0]) && "Expected instruction")(static_cast <bool> (isa<Instruction>(VL[0]) && "Expected instruction") ? void (0) : __assert_fail ("isa<Instruction>(VL[0]) && \"Expected instruction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1856, __extension__ __PRETTY_FUNCTION__)); | |||
1857 | unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); | |||
1858 | OpsVec.resize(NumOperands); | |||
1859 | unsigned NumLanes = VL.size(); | |||
1860 | for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { | |||
1861 | OpsVec[OpIdx].resize(NumLanes); | |||
1862 | for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { | |||
1863 | assert(isa<Instruction>(VL[Lane]) && "Expected instruction")(static_cast <bool> (isa<Instruction>(VL[Lane]) && "Expected instruction") ? void (0) : __assert_fail ("isa<Instruction>(VL[Lane]) && \"Expected instruction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1863, __extension__ __PRETTY_FUNCTION__)); | |||
1864 | // Our tree has just 3 nodes: the root and two operands. | |||
1865 | // It is therefore trivial to get the APO. We only need to check the | |||
1866 | // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or | |||
1867 | // RHS operand. The LHS operand of both add and sub is never attached | |||
1868 | // to an inversese operation in the linearized form, therefore its APO | |||
1869 | // is false. The RHS is true only if VL[Lane] is an inverse operation. | |||
1870 | ||||
1871 | // Since operand reordering is performed on groups of commutative | |||
1872 | // operations or alternating sequences (e.g., +, -), we can safely | |||
1873 | // tell the inverse operations by checking commutativity. | |||
1874 | bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); | |||
1875 | bool APO = (OpIdx == 0) ? false : IsInverseOperation; | |||
1876 | OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), | |||
1877 | APO, false}; | |||
1878 | } | |||
1879 | } | |||
1880 | } | |||
1881 | ||||
1882 | /// \returns the number of operands. | |||
1883 | unsigned getNumOperands() const { return OpsVec.size(); } | |||
1884 | ||||
1885 | /// \returns the number of lanes. | |||
1886 | unsigned getNumLanes() const { return OpsVec[0].size(); } | |||
1887 | ||||
1888 | /// \returns the operand value at \p OpIdx and \p Lane. | |||
1889 | Value *getValue(unsigned OpIdx, unsigned Lane) const { | |||
1890 | return getData(OpIdx, Lane).V; | |||
1891 | } | |||
1892 | ||||
1893 | /// \returns true if the data structure is empty. | |||
1894 | bool empty() const { return OpsVec.empty(); } | |||
1895 | ||||
1896 | /// Clears the data. | |||
1897 | void clear() { OpsVec.clear(); } | |||
1898 | ||||
1899 | /// \Returns true if there are enough operands identical to \p Op to fill | |||
1900 | /// the whole vector. | |||
1901 | /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. | |||
1902 | bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { | |||
1903 | bool OpAPO = getData(OpIdx, Lane).APO; | |||
1904 | for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { | |||
1905 | if (Ln == Lane) | |||
1906 | continue; | |||
1907 | // This is set to true if we found a candidate for broadcast at Lane. | |||
1908 | bool FoundCandidate = false; | |||
1909 | for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { | |||
1910 | OperandData &Data = getData(OpI, Ln); | |||
1911 | if (Data.APO != OpAPO || Data.IsUsed) | |||
1912 | continue; | |||
1913 | if (Data.V == Op) { | |||
1914 | FoundCandidate = true; | |||
1915 | Data.IsUsed = true; | |||
1916 | break; | |||
1917 | } | |||
1918 | } | |||
1919 | if (!FoundCandidate) | |||
1920 | return false; | |||
1921 | } | |||
1922 | return true; | |||
1923 | } | |||
1924 | ||||
1925 | public: | |||
1926 | /// Initialize with all the operands of the instruction vector \p RootVL. | |||
1927 | VLOperands(ArrayRef<Value *> RootVL, const TargetLibraryInfo &TLI, | |||
1928 | const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R) | |||
1929 | : TLI(TLI), DL(DL), SE(SE), R(R) { | |||
1930 | // Append all the operands of RootVL. | |||
1931 | appendOperandsOfVL(RootVL); | |||
1932 | } | |||
1933 | ||||
1934 | /// \Returns a value vector with the operands across all lanes for the | |||
1935 | /// opearnd at \p OpIdx. | |||
1936 | ValueList getVL(unsigned OpIdx) const { | |||
1937 | ValueList OpVL(OpsVec[OpIdx].size()); | |||
1938 | assert(OpsVec[OpIdx].size() == getNumLanes() &&(static_cast <bool> (OpsVec[OpIdx].size() == getNumLanes () && "Expected same num of lanes across all operands" ) ? void (0) : __assert_fail ("OpsVec[OpIdx].size() == getNumLanes() && \"Expected same num of lanes across all operands\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1939, __extension__ __PRETTY_FUNCTION__)) | |||
1939 | "Expected same num of lanes across all operands")(static_cast <bool> (OpsVec[OpIdx].size() == getNumLanes () && "Expected same num of lanes across all operands" ) ? void (0) : __assert_fail ("OpsVec[OpIdx].size() == getNumLanes() && \"Expected same num of lanes across all operands\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 1939, __extension__ __PRETTY_FUNCTION__)); | |||
1940 | for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) | |||
1941 | OpVL[Lane] = OpsVec[OpIdx][Lane].V; | |||
1942 | return OpVL; | |||
1943 | } | |||
1944 | ||||
1945 | // Performs operand reordering for 2 or more operands. | |||
1946 | // The original operands are in OrigOps[OpIdx][Lane]. | |||
1947 | // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. | |||
1948 | void reorder() { | |||
1949 | unsigned NumOperands = getNumOperands(); | |||
1950 | unsigned NumLanes = getNumLanes(); | |||
1951 | // Each operand has its own mode. We are using this mode to help us select | |||
1952 | // the instructions for each lane, so that they match best with the ones | |||
1953 | // we have selected so far. | |||
1954 | SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); | |||
1955 | ||||
1956 | // This is a greedy single-pass algorithm. We are going over each lane | |||
1957 | // once and deciding on the best order right away with no back-tracking. | |||
1958 | // However, in order to increase its effectiveness, we start with the lane | |||
1959 | // that has operands that can move the least. For example, given the | |||
1960 | // following lanes: | |||
1961 | // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd | |||
1962 | // Lane 1 : A[1] = C[1] - B[1] // Visited 1st | |||
1963 | // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd | |||
1964 | // Lane 3 : A[3] = C[3] - B[3] // Visited 4th | |||
1965 | // we will start at Lane 1, since the operands of the subtraction cannot | |||
1966 | // be reordered. Then we will visit the rest of the lanes in a circular | |||
1967 | // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. | |||
1968 | ||||
1969 | // Find the first lane that we will start our search from. | |||
1970 | unsigned FirstLane = getBestLaneToStartReordering(); | |||
1971 | ||||
1972 | // Initialize the modes. | |||
1973 | for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { | |||
1974 | Value *OpLane0 = getValue(OpIdx, FirstLane); | |||
1975 | // Keep track if we have instructions with all the same opcode on one | |||
1976 | // side. | |||
1977 | if (isa<LoadInst>(OpLane0)) | |||
1978 | ReorderingModes[OpIdx] = ReorderingMode::Load; | |||
1979 | else if (isa<Instruction>(OpLane0)) { | |||
1980 | // Check if OpLane0 should be broadcast. | |||
1981 | if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) | |||
1982 | ReorderingModes[OpIdx] = ReorderingMode::Splat; | |||
1983 | else | |||
1984 | ReorderingModes[OpIdx] = ReorderingMode::Opcode; | |||
1985 | } | |||
1986 | else if (isa<Constant>(OpLane0)) | |||
1987 | ReorderingModes[OpIdx] = ReorderingMode::Constant; | |||
1988 | else if (isa<Argument>(OpLane0)) | |||
1989 | // Our best hope is a Splat. It may save some cost in some cases. | |||
1990 | ReorderingModes[OpIdx] = ReorderingMode::Splat; | |||
1991 | else | |||
1992 | // NOTE: This should be unreachable. | |||
1993 | ReorderingModes[OpIdx] = ReorderingMode::Failed; | |||
1994 | } | |||
1995 | ||||
1996 | // Check that we don't have same operands. No need to reorder if operands | |||
1997 | // are just perfect diamond or shuffled diamond match. Do not do it only | |||
1998 | // for possible broadcasts or non-power of 2 number of scalars (just for | |||
1999 | // now). | |||
2000 | auto &&SkipReordering = [this]() { | |||
2001 | SmallPtrSet<Value *, 4> UniqueValues; | |||
2002 | ArrayRef<OperandData> Op0 = OpsVec.front(); | |||
2003 | for (const OperandData &Data : Op0) | |||
2004 | UniqueValues.insert(Data.V); | |||
2005 | for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) { | |||
2006 | if (any_of(Op, [&UniqueValues](const OperandData &Data) { | |||
2007 | return !UniqueValues.contains(Data.V); | |||
2008 | })) | |||
2009 | return false; | |||
2010 | } | |||
2011 | // TODO: Check if we can remove a check for non-power-2 number of | |||
2012 | // scalars after full support of non-power-2 vectorization. | |||
2013 | return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size()); | |||
2014 | }; | |||
2015 | ||||
2016 | // If the initial strategy fails for any of the operand indexes, then we | |||
2017 | // perform reordering again in a second pass. This helps avoid assigning | |||
2018 | // high priority to the failed strategy, and should improve reordering for | |||
2019 | // the non-failed operand indexes. | |||
2020 | for (int Pass = 0; Pass != 2; ++Pass) { | |||
2021 | // Check if no need to reorder operands since they're are perfect or | |||
2022 | // shuffled diamond match. | |||
2023 | // Need to to do it to avoid extra external use cost counting for | |||
2024 | // shuffled matches, which may cause regressions. | |||
2025 | if (SkipReordering()) | |||
2026 | break; | |||
2027 | // Skip the second pass if the first pass did not fail. | |||
2028 | bool StrategyFailed = false; | |||
2029 | // Mark all operand data as free to use. | |||
2030 | clearUsed(); | |||
2031 | // We keep the original operand order for the FirstLane, so reorder the | |||
2032 | // rest of the lanes. We are visiting the nodes in a circular fashion, | |||
2033 | // using FirstLane as the center point and increasing the radius | |||
2034 | // distance. | |||
2035 | SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands); | |||
2036 | for (unsigned I = 0; I < NumOperands; ++I) | |||
2037 | MainAltOps[I].push_back(getData(I, FirstLane).V); | |||
2038 | ||||
2039 | for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { | |||
2040 | // Visit the lane on the right and then the lane on the left. | |||
2041 | for (int Direction : {+1, -1}) { | |||
2042 | int Lane = FirstLane + Direction * Distance; | |||
2043 | if (Lane < 0 || Lane >= (int)NumLanes) | |||
2044 | continue; | |||
2045 | int LastLane = Lane - Direction; | |||
2046 | assert(LastLane >= 0 && LastLane < (int)NumLanes &&(static_cast <bool> (LastLane >= 0 && LastLane < (int)NumLanes && "Out of bounds") ? void (0) : __assert_fail ("LastLane >= 0 && LastLane < (int)NumLanes && \"Out of bounds\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2047, __extension__ __PRETTY_FUNCTION__)) | |||
2047 | "Out of bounds")(static_cast <bool> (LastLane >= 0 && LastLane < (int)NumLanes && "Out of bounds") ? void (0) : __assert_fail ("LastLane >= 0 && LastLane < (int)NumLanes && \"Out of bounds\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2047, __extension__ __PRETTY_FUNCTION__)); | |||
2048 | // Look for a good match for each operand. | |||
2049 | for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { | |||
2050 | // Search for the operand that matches SortedOps[OpIdx][Lane-1]. | |||
2051 | Optional<unsigned> BestIdx = getBestOperand( | |||
2052 | OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]); | |||
2053 | // By not selecting a value, we allow the operands that follow to | |||
2054 | // select a better matching value. We will get a non-null value in | |||
2055 | // the next run of getBestOperand(). | |||
2056 | if (BestIdx) { | |||
2057 | // Swap the current operand with the one returned by | |||
2058 | // getBestOperand(). | |||
2059 | swap(OpIdx, *BestIdx, Lane); | |||
2060 | } else { | |||
2061 | // We failed to find a best operand, set mode to 'Failed'. | |||
2062 | ReorderingModes[OpIdx] = ReorderingMode::Failed; | |||
2063 | // Enable the second pass. | |||
2064 | StrategyFailed = true; | |||
2065 | } | |||
2066 | // Try to get the alternate opcode and follow it during analysis. | |||
2067 | if (MainAltOps[OpIdx].size() != 2) { | |||
2068 | OperandData &AltOp = getData(OpIdx, Lane); | |||
2069 | InstructionsState OpS = | |||
2070 | getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}, TLI); | |||
2071 | if (OpS.getOpcode() && OpS.isAltShuffle()) | |||
2072 | MainAltOps[OpIdx].push_back(AltOp.V); | |||
2073 | } | |||
2074 | } | |||
2075 | } | |||
2076 | } | |||
2077 | // Skip second pass if the strategy did not fail. | |||
2078 | if (!StrategyFailed) | |||
2079 | break; | |||
2080 | } | |||
2081 | } | |||
2082 | ||||
2083 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | |||
2084 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static StringRef getModeStr(ReorderingMode RMode) { | |||
2085 | switch (RMode) { | |||
2086 | case ReorderingMode::Load: | |||
2087 | return "Load"; | |||
2088 | case ReorderingMode::Opcode: | |||
2089 | return "Opcode"; | |||
2090 | case ReorderingMode::Constant: | |||
2091 | return "Constant"; | |||
2092 | case ReorderingMode::Splat: | |||
2093 | return "Splat"; | |||
2094 | case ReorderingMode::Failed: | |||
2095 | return "Failed"; | |||
2096 | } | |||
2097 | llvm_unreachable("Unimplemented Reordering Type")::llvm::llvm_unreachable_internal("Unimplemented Reordering Type" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2097); | |||
2098 | } | |||
2099 | ||||
2100 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static raw_ostream &printMode(ReorderingMode RMode, | |||
2101 | raw_ostream &OS) { | |||
2102 | return OS << getModeStr(RMode); | |||
2103 | } | |||
2104 | ||||
2105 | /// Debug print. | |||
2106 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static void dumpMode(ReorderingMode RMode) { | |||
2107 | printMode(RMode, dbgs()); | |||
2108 | } | |||
2109 | ||||
2110 | friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { | |||
2111 | return printMode(RMode, OS); | |||
2112 | } | |||
2113 | ||||
2114 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) raw_ostream &print(raw_ostream &OS) const { | |||
2115 | const unsigned Indent = 2; | |||
2116 | unsigned Cnt = 0; | |||
2117 | for (const OperandDataVec &OpDataVec : OpsVec) { | |||
2118 | OS << "Operand " << Cnt++ << "\n"; | |||
2119 | for (const OperandData &OpData : OpDataVec) { | |||
2120 | OS.indent(Indent) << "{"; | |||
2121 | if (Value *V = OpData.V) | |||
2122 | OS << *V; | |||
2123 | else | |||
2124 | OS << "null"; | |||
2125 | OS << ", APO:" << OpData.APO << "}\n"; | |||
2126 | } | |||
2127 | OS << "\n"; | |||
2128 | } | |||
2129 | return OS; | |||
2130 | } | |||
2131 | ||||
2132 | /// Debug print. | |||
2133 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { print(dbgs()); } | |||
2134 | #endif | |||
2135 | }; | |||
2136 | ||||
2137 | /// Evaluate each pair in \p Candidates and return index into \p Candidates | |||
2138 | /// for a pair which have highest score deemed to have best chance to form | |||
2139 | /// root of profitable tree to vectorize. Return None if no candidate scored | |||
2140 | /// above the LookAheadHeuristics::ScoreFail. | |||
2141 | /// \param Limit Lower limit of the cost, considered to be good enough score. | |||
2142 | Optional<int> | |||
2143 | findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates, | |||
2144 | int Limit = LookAheadHeuristics::ScoreFail) { | |||
2145 | LookAheadHeuristics LookAhead(*TLI, *DL, *SE, *this, /*NumLanes=*/2, | |||
2146 | RootLookAheadMaxDepth); | |||
2147 | int BestScore = Limit; | |||
2148 | Optional<int> Index; | |||
2149 | for (int I : seq<int>(0, Candidates.size())) { | |||
2150 | int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first, | |||
2151 | Candidates[I].second, | |||
2152 | /*U1=*/nullptr, /*U2=*/nullptr, | |||
2153 | /*Level=*/1, None); | |||
2154 | if (Score > BestScore) { | |||
2155 | BestScore = Score; | |||
2156 | Index = I; | |||
2157 | } | |||
2158 | } | |||
2159 | return Index; | |||
2160 | } | |||
2161 | ||||
2162 | /// Checks if the instruction is marked for deletion. | |||
2163 | bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } | |||
2164 | ||||
2165 | /// Removes an instruction from its block and eventually deletes it. | |||
2166 | /// It's like Instruction::eraseFromParent() except that the actual deletion | |||
2167 | /// is delayed until BoUpSLP is destructed. | |||
2168 | void eraseInstruction(Instruction *I) { | |||
2169 | DeletedInstructions.insert(I); | |||
2170 | } | |||
2171 | ||||
2172 | /// Checks if the instruction was already analyzed for being possible | |||
2173 | /// reduction root. | |||
2174 | bool isAnalyzedReductionRoot(Instruction *I) const { | |||
2175 | return AnalyzedReductionsRoots.count(I); | |||
2176 | } | |||
2177 | /// Register given instruction as already analyzed for being possible | |||
2178 | /// reduction root. | |||
2179 | void analyzedReductionRoot(Instruction *I) { | |||
2180 | AnalyzedReductionsRoots.insert(I); | |||
2181 | } | |||
2182 | /// Checks if the provided list of reduced values was checked already for | |||
2183 | /// vectorization. | |||
2184 | bool areAnalyzedReductionVals(ArrayRef<Value *> VL) const { | |||
2185 | return AnalyzedReductionVals.contains(hash_value(VL)); | |||
2186 | } | |||
2187 | /// Adds the list of reduced values to list of already checked values for the | |||
2188 | /// vectorization. | |||
2189 | void analyzedReductionVals(ArrayRef<Value *> VL) { | |||
2190 | AnalyzedReductionVals.insert(hash_value(VL)); | |||
2191 | } | |||
2192 | /// Clear the list of the analyzed reduction root instructions. | |||
2193 | void clearReductionData() { | |||
2194 | AnalyzedReductionsRoots.clear(); | |||
2195 | AnalyzedReductionVals.clear(); | |||
2196 | } | |||
2197 | /// Checks if the given value is gathered in one of the nodes. | |||
2198 | bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const { | |||
2199 | return any_of(MustGather, [&](Value *V) { return Vals.contains(V); }); | |||
2200 | } | |||
2201 | ||||
2202 | ~BoUpSLP(); | |||
2203 | ||||
2204 | private: | |||
2205 | /// Check if the operands on the edges \p Edges of the \p UserTE allows | |||
2206 | /// reordering (i.e. the operands can be reordered because they have only one | |||
2207 | /// user and reordarable). | |||
2208 | /// \param ReorderableGathers List of all gather nodes that require reordering | |||
2209 | /// (e.g., gather of extractlements or partially vectorizable loads). | |||
2210 | /// \param GatherOps List of gather operand nodes for \p UserTE that require | |||
2211 | /// reordering, subset of \p NonVectorized. | |||
2212 | bool | |||
2213 | canReorderOperands(TreeEntry *UserTE, | |||
2214 | SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, | |||
2215 | ArrayRef<TreeEntry *> ReorderableGathers, | |||
2216 | SmallVectorImpl<TreeEntry *> &GatherOps); | |||
2217 | ||||
2218 | /// Checks if the given \p TE is a gather node with clustered reused scalars | |||
2219 | /// and reorders it per given \p Mask. | |||
2220 | void reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const; | |||
2221 | ||||
2222 | /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, | |||
2223 | /// if any. If it is not vectorized (gather node), returns nullptr. | |||
2224 | TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) { | |||
2225 | ArrayRef<Value *> VL = UserTE->getOperand(OpIdx); | |||
2226 | TreeEntry *TE = nullptr; | |||
2227 | const auto *It = find_if(VL, [this, &TE](Value *V) { | |||
2228 | TE = getTreeEntry(V); | |||
2229 | return TE; | |||
2230 | }); | |||
2231 | if (It != VL.end() && TE->isSame(VL)) | |||
2232 | return TE; | |||
2233 | return nullptr; | |||
2234 | } | |||
2235 | ||||
2236 | /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, | |||
2237 | /// if any. If it is not vectorized (gather node), returns nullptr. | |||
2238 | const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE, | |||
2239 | unsigned OpIdx) const { | |||
2240 | return const_cast<BoUpSLP *>(this)->getVectorizedOperand( | |||
2241 | const_cast<TreeEntry *>(UserTE), OpIdx); | |||
2242 | } | |||
2243 | ||||
2244 | /// Checks if all users of \p I are the part of the vectorization tree. | |||
2245 | bool areAllUsersVectorized(Instruction *I, | |||
2246 | ArrayRef<Value *> VectorizedVals) const; | |||
2247 | ||||
2248 | /// Return information about the vector formed for the specified index | |||
2249 | /// of a vector of (the same) instruction. | |||
2250 | TargetTransformInfo::OperandValueInfo getOperandInfo(ArrayRef<Value *> VL, | |||
2251 | unsigned OpIdx); | |||
2252 | ||||
2253 | /// \returns the cost of the vectorizable entry. | |||
2254 | InstructionCost getEntryCost(const TreeEntry *E, | |||
2255 | ArrayRef<Value *> VectorizedVals); | |||
2256 | ||||
2257 | /// This is the recursive part of buildTree. | |||
2258 | void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, | |||
2259 | const EdgeInfo &EI); | |||
2260 | ||||
2261 | /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can | |||
2262 | /// be vectorized to use the original vector (or aggregate "bitcast" to a | |||
2263 | /// vector) and sets \p CurrentOrder to the identity permutation; otherwise | |||
2264 | /// returns false, setting \p CurrentOrder to either an empty vector or a | |||
2265 | /// non-identity permutation that allows to reuse extract instructions. | |||
2266 | bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, | |||
2267 | SmallVectorImpl<unsigned> &CurrentOrder) const; | |||
2268 | ||||
2269 | /// Vectorize a single entry in the tree. | |||
2270 | Value *vectorizeTree(TreeEntry *E); | |||
2271 | ||||
2272 | /// Vectorize a single entry in the tree, starting in \p VL. | |||
2273 | Value *vectorizeTree(ArrayRef<Value *> VL); | |||
2274 | ||||
2275 | /// Create a new vector from a list of scalar values. Produces a sequence | |||
2276 | /// which exploits values reused across lanes, and arranges the inserts | |||
2277 | /// for ease of later optimization. | |||
2278 | Value *createBuildVector(ArrayRef<Value *> VL); | |||
2279 | ||||
2280 | /// \returns the scalarization cost for this type. Scalarization in this | |||
2281 | /// context means the creation of vectors from a group of scalars. If \p | |||
2282 | /// NeedToShuffle is true, need to add a cost of reshuffling some of the | |||
2283 | /// vector elements. | |||
2284 | InstructionCost getGatherCost(FixedVectorType *Ty, | |||
2285 | const APInt &ShuffledIndices, | |||
2286 | bool NeedToShuffle) const; | |||
2287 | ||||
2288 | /// Returns the instruction in the bundle, which can be used as a base point | |||
2289 | /// for scheduling. Usually it is the last instruction in the bundle, except | |||
2290 | /// for the case when all operands are external (in this case, it is the first | |||
2291 | /// instruction in the list). | |||
2292 | Instruction &getLastInstructionInBundle(const TreeEntry *E); | |||
2293 | ||||
2294 | /// Checks if the gathered \p VL can be represented as shuffle(s) of previous | |||
2295 | /// tree entries. | |||
2296 | /// \returns ShuffleKind, if gathered values can be represented as shuffles of | |||
2297 | /// previous tree entries. \p Mask is filled with the shuffle mask. | |||
2298 | Optional<TargetTransformInfo::ShuffleKind> | |||
2299 | isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, | |||
2300 | SmallVectorImpl<const TreeEntry *> &Entries); | |||
2301 | ||||
2302 | /// \returns the scalarization cost for this list of values. Assuming that | |||
2303 | /// this subtree gets vectorized, we may need to extract the values from the | |||
2304 | /// roots. This method calculates the cost of extracting the values. | |||
2305 | InstructionCost getGatherCost(ArrayRef<Value *> VL) const; | |||
2306 | ||||
2307 | /// Set the Builder insert point to one after the last instruction in | |||
2308 | /// the bundle | |||
2309 | void setInsertPointAfterBundle(const TreeEntry *E); | |||
2310 | ||||
2311 | /// \returns a vector from a collection of scalars in \p VL. | |||
2312 | Value *gather(ArrayRef<Value *> VL); | |||
2313 | ||||
2314 | /// \returns whether the VectorizableTree is fully vectorizable and will | |||
2315 | /// be beneficial even the tree height is tiny. | |||
2316 | bool isFullyVectorizableTinyTree(bool ForReduction) const; | |||
2317 | ||||
2318 | /// Reorder commutative or alt operands to get better probability of | |||
2319 | /// generating vectorized code. | |||
2320 | static void reorderInputsAccordingToOpcode( | |||
2321 | ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left, | |||
2322 | SmallVectorImpl<Value *> &Right, const TargetLibraryInfo &TLI, | |||
2323 | const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R); | |||
2324 | ||||
2325 | /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the | |||
2326 | /// users of \p TE and collects the stores. It returns the map from the store | |||
2327 | /// pointers to the collected stores. | |||
2328 | DenseMap<Value *, SmallVector<StoreInst *, 4>> | |||
2329 | collectUserStores(const BoUpSLP::TreeEntry *TE) const; | |||
2330 | ||||
2331 | /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the | |||
2332 | /// stores in \p StoresVec can form a vector instruction. If so it returns true | |||
2333 | /// and populates \p ReorderIndices with the shuffle indices of the the stores | |||
2334 | /// when compared to the sorted vector. | |||
2335 | bool canFormVector(const SmallVector<StoreInst *, 4> &StoresVec, | |||
2336 | OrdersType &ReorderIndices) const; | |||
2337 | ||||
2338 | /// Iterates through the users of \p TE, looking for scalar stores that can be | |||
2339 | /// potentially vectorized in a future SLP-tree. If found, it keeps track of | |||
2340 | /// their order and builds an order index vector for each store bundle. It | |||
2341 | /// returns all these order vectors found. | |||
2342 | /// We run this after the tree has formed, otherwise we may come across user | |||
2343 | /// instructions that are not yet in the tree. | |||
2344 | SmallVector<OrdersType, 1> | |||
2345 | findExternalStoreUsersReorderIndices(TreeEntry *TE) const; | |||
2346 | ||||
2347 | struct TreeEntry { | |||
2348 | using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; | |||
2349 | TreeEntry(VecTreeTy &Container) : Container(Container) {} | |||
2350 | ||||
2351 | /// \returns true if the scalars in VL are equal to this entry. | |||
2352 | bool isSame(ArrayRef<Value *> VL) const { | |||
2353 | auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { | |||
2354 | if (Mask.size() != VL.size() && VL.size() == Scalars.size()) | |||
2355 | return std::equal(VL.begin(), VL.end(), Scalars.begin()); | |||
2356 | return VL.size() == Mask.size() && | |||
2357 | std::equal(VL.begin(), VL.end(), Mask.begin(), | |||
2358 | [Scalars](Value *V, int Idx) { | |||
2359 | return (isa<UndefValue>(V) && | |||
2360 | Idx == UndefMaskElem) || | |||
2361 | (Idx != UndefMaskElem && V == Scalars[Idx]); | |||
2362 | }); | |||
2363 | }; | |||
2364 | if (!ReorderIndices.empty()) { | |||
2365 | // TODO: implement matching if the nodes are just reordered, still can | |||
2366 | // treat the vector as the same if the list of scalars matches VL | |||
2367 | // directly, without reordering. | |||
2368 | SmallVector<int> Mask; | |||
2369 | inversePermutation(ReorderIndices, Mask); | |||
2370 | if (VL.size() == Scalars.size()) | |||
2371 | return IsSame(Scalars, Mask); | |||
2372 | if (VL.size() == ReuseShuffleIndices.size()) { | |||
2373 | ::addMask(Mask, ReuseShuffleIndices); | |||
2374 | return IsSame(Scalars, Mask); | |||
2375 | } | |||
2376 | return false; | |||
2377 | } | |||
2378 | return IsSame(Scalars, ReuseShuffleIndices); | |||
2379 | } | |||
2380 | ||||
2381 | /// \returns true if current entry has same operands as \p TE. | |||
2382 | bool hasEqualOperands(const TreeEntry &TE) const { | |||
2383 | if (TE.getNumOperands() != getNumOperands()) | |||
2384 | return false; | |||
2385 | SmallBitVector Used(getNumOperands()); | |||
2386 | for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { | |||
2387 | unsigned PrevCount = Used.count(); | |||
2388 | for (unsigned K = 0; K < E; ++K) { | |||
2389 | if (Used.test(K)) | |||
2390 | continue; | |||
2391 | if (getOperand(K) == TE.getOperand(I)) { | |||
2392 | Used.set(K); | |||
2393 | break; | |||
2394 | } | |||
2395 | } | |||
2396 | // Check if we actually found the matching operand. | |||
2397 | if (PrevCount == Used.count()) | |||
2398 | return false; | |||
2399 | } | |||
2400 | return true; | |||
2401 | } | |||
2402 | ||||
2403 | /// \return Final vectorization factor for the node. Defined by the total | |||
2404 | /// number of vectorized scalars, including those, used several times in the | |||
2405 | /// entry and counted in the \a ReuseShuffleIndices, if any. | |||
2406 | unsigned getVectorFactor() const { | |||
2407 | if (!ReuseShuffleIndices.empty()) | |||
2408 | return ReuseShuffleIndices.size(); | |||
2409 | return Scalars.size(); | |||
2410 | }; | |||
2411 | ||||
2412 | /// A vector of scalars. | |||
2413 | ValueList Scalars; | |||
2414 | ||||
2415 | /// The Scalars are vectorized into this value. It is initialized to Null. | |||
2416 | Value *VectorizedValue = nullptr; | |||
2417 | ||||
2418 | /// Do we need to gather this sequence or vectorize it | |||
2419 | /// (either with vector instruction or with scatter/gather | |||
2420 | /// intrinsics for store/load)? | |||
2421 | enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; | |||
2422 | EntryState State; | |||
2423 | ||||
2424 | /// Does this sequence require some shuffling? | |||
2425 | SmallVector<int, 4> ReuseShuffleIndices; | |||
2426 | ||||
2427 | /// Does this entry require reordering? | |||
2428 | SmallVector<unsigned, 4> ReorderIndices; | |||
2429 | ||||
2430 | /// Points back to the VectorizableTree. | |||
2431 | /// | |||
2432 | /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has | |||
2433 | /// to be a pointer and needs to be able to initialize the child iterator. | |||
2434 | /// Thus we need a reference back to the container to translate the indices | |||
2435 | /// to entries. | |||
2436 | VecTreeTy &Container; | |||
2437 | ||||
2438 | /// The TreeEntry index containing the user of this entry. We can actually | |||
2439 | /// have multiple users so the data structure is not truly a tree. | |||
2440 | SmallVector<EdgeInfo, 1> UserTreeIndices; | |||
2441 | ||||
2442 | /// The index of this treeEntry in VectorizableTree. | |||
2443 | int Idx = -1; | |||
2444 | ||||
2445 | private: | |||
2446 | /// The operands of each instruction in each lane Operands[op_index][lane]. | |||
2447 | /// Note: This helps avoid the replication of the code that performs the | |||
2448 | /// reordering of operands during buildTree_rec() and vectorizeTree(). | |||
2449 | SmallVector<ValueList, 2> Operands; | |||
2450 | ||||
2451 | /// The main/alternate instruction. | |||
2452 | Instruction *MainOp = nullptr; | |||
2453 | Instruction *AltOp = nullptr; | |||
2454 | ||||
2455 | public: | |||
2456 | /// Set this bundle's \p OpIdx'th operand to \p OpVL. | |||
2457 | void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { | |||
2458 | if (Operands.size() < OpIdx + 1) | |||
2459 | Operands.resize(OpIdx + 1); | |||
2460 | assert(Operands[OpIdx].empty() && "Already resized?")(static_cast <bool> (Operands[OpIdx].empty() && "Already resized?") ? void (0) : __assert_fail ("Operands[OpIdx].empty() && \"Already resized?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2460, __extension__ __PRETTY_FUNCTION__)); | |||
2461 | assert(OpVL.size() <= Scalars.size() &&(static_cast <bool> (OpVL.size() <= Scalars.size() && "Number of operands is greater than the number of scalars.") ? void (0) : __assert_fail ("OpVL.size() <= Scalars.size() && \"Number of operands is greater than the number of scalars.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2462, __extension__ __PRETTY_FUNCTION__)) | |||
2462 | "Number of operands is greater than the number of scalars.")(static_cast <bool> (OpVL.size() <= Scalars.size() && "Number of operands is greater than the number of scalars.") ? void (0) : __assert_fail ("OpVL.size() <= Scalars.size() && \"Number of operands is greater than the number of scalars.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2462, __extension__ __PRETTY_FUNCTION__)); | |||
2463 | Operands[OpIdx].resize(OpVL.size()); | |||
2464 | copy(OpVL, Operands[OpIdx].begin()); | |||
2465 | } | |||
2466 | ||||
2467 | /// Set the operands of this bundle in their original order. | |||
2468 | void setOperandsInOrder() { | |||
2469 | assert(Operands.empty() && "Already initialized?")(static_cast <bool> (Operands.empty() && "Already initialized?" ) ? void (0) : __assert_fail ("Operands.empty() && \"Already initialized?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2469, __extension__ __PRETTY_FUNCTION__)); | |||
2470 | auto *I0 = cast<Instruction>(Scalars[0]); | |||
2471 | Operands.resize(I0->getNumOperands()); | |||
2472 | unsigned NumLanes = Scalars.size(); | |||
2473 | for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); | |||
2474 | OpIdx != NumOperands; ++OpIdx) { | |||
2475 | Operands[OpIdx].resize(NumLanes); | |||
2476 | for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { | |||
2477 | auto *I = cast<Instruction>(Scalars[Lane]); | |||
2478 | assert(I->getNumOperands() == NumOperands &&(static_cast <bool> (I->getNumOperands() == NumOperands && "Expected same number of operands") ? void (0) : __assert_fail ("I->getNumOperands() == NumOperands && \"Expected same number of operands\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2479, __extension__ __PRETTY_FUNCTION__)) | |||
2479 | "Expected same number of operands")(static_cast <bool> (I->getNumOperands() == NumOperands && "Expected same number of operands") ? void (0) : __assert_fail ("I->getNumOperands() == NumOperands && \"Expected same number of operands\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2479, __extension__ __PRETTY_FUNCTION__)); | |||
2480 | Operands[OpIdx][Lane] = I->getOperand(OpIdx); | |||
2481 | } | |||
2482 | } | |||
2483 | } | |||
2484 | ||||
2485 | /// Reorders operands of the node to the given mask \p Mask. | |||
2486 | void reorderOperands(ArrayRef<int> Mask) { | |||
2487 | for (ValueList &Operand : Operands) | |||
2488 | reorderScalars(Operand, Mask); | |||
2489 | } | |||
2490 | ||||
2491 | /// \returns the \p OpIdx operand of this TreeEntry. | |||
2492 | ValueList &getOperand(unsigned OpIdx) { | |||
2493 | assert(OpIdx < Operands.size() && "Off bounds")(static_cast <bool> (OpIdx < Operands.size() && "Off bounds") ? void (0) : __assert_fail ("OpIdx < Operands.size() && \"Off bounds\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2493, __extension__ __PRETTY_FUNCTION__)); | |||
2494 | return Operands[OpIdx]; | |||
2495 | } | |||
2496 | ||||
2497 | /// \returns the \p OpIdx operand of this TreeEntry. | |||
2498 | ArrayRef<Value *> getOperand(unsigned OpIdx) const { | |||
2499 | assert(OpIdx < Operands.size() && "Off bounds")(static_cast <bool> (OpIdx < Operands.size() && "Off bounds") ? void (0) : __assert_fail ("OpIdx < Operands.size() && \"Off bounds\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2499, __extension__ __PRETTY_FUNCTION__)); | |||
2500 | return Operands[OpIdx]; | |||
2501 | } | |||
2502 | ||||
2503 | /// \returns the number of operands. | |||
2504 | unsigned getNumOperands() const { return Operands.size(); } | |||
2505 | ||||
2506 | /// \return the single \p OpIdx operand. | |||
2507 | Value *getSingleOperand(unsigned OpIdx) const { | |||
2508 | assert(OpIdx < Operands.size() && "Off bounds")(static_cast <bool> (OpIdx < Operands.size() && "Off bounds") ? void (0) : __assert_fail ("OpIdx < Operands.size() && \"Off bounds\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2508, __extension__ __PRETTY_FUNCTION__)); | |||
2509 | assert(!Operands[OpIdx].empty() && "No operand available")(static_cast <bool> (!Operands[OpIdx].empty() && "No operand available") ? void (0) : __assert_fail ("!Operands[OpIdx].empty() && \"No operand available\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2509, __extension__ __PRETTY_FUNCTION__)); | |||
2510 | return Operands[OpIdx][0]; | |||
2511 | } | |||
2512 | ||||
2513 | /// Some of the instructions in the list have alternate opcodes. | |||
2514 | bool isAltShuffle() const { return MainOp != AltOp; } | |||
2515 | ||||
2516 | bool isOpcodeOrAlt(Instruction *I) const { | |||
2517 | unsigned CheckedOpcode = I->getOpcode(); | |||
2518 | return (getOpcode() == CheckedOpcode || | |||
2519 | getAltOpcode() == CheckedOpcode); | |||
2520 | } | |||
2521 | ||||
2522 | /// Chooses the correct key for scheduling data. If \p Op has the same (or | |||
2523 | /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is | |||
2524 | /// \p OpValue. | |||
2525 | Value *isOneOf(Value *Op) const { | |||
2526 | auto *I = dyn_cast<Instruction>(Op); | |||
2527 | if (I && isOpcodeOrAlt(I)) | |||
2528 | return Op; | |||
2529 | return MainOp; | |||
2530 | } | |||
2531 | ||||
2532 | void setOperations(const InstructionsState &S) { | |||
2533 | MainOp = S.MainOp; | |||
2534 | AltOp = S.AltOp; | |||
2535 | } | |||
2536 | ||||
2537 | Instruction *getMainOp() const { | |||
2538 | return MainOp; | |||
2539 | } | |||
2540 | ||||
2541 | Instruction *getAltOp() const { | |||
2542 | return AltOp; | |||
2543 | } | |||
2544 | ||||
2545 | /// The main/alternate opcodes for the list of instructions. | |||
2546 | unsigned getOpcode() const { | |||
2547 | return MainOp ? MainOp->getOpcode() : 0; | |||
2548 | } | |||
2549 | ||||
2550 | unsigned getAltOpcode() const { | |||
2551 | return AltOp ? AltOp->getOpcode() : 0; | |||
2552 | } | |||
2553 | ||||
2554 | /// When ReuseReorderShuffleIndices is empty it just returns position of \p | |||
2555 | /// V within vector of Scalars. Otherwise, try to remap on its reuse index. | |||
2556 | int findLaneForValue(Value *V) const { | |||
2557 | unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); | |||
2558 | assert(FoundLane < Scalars.size() && "Couldn't find extract lane")(static_cast <bool> (FoundLane < Scalars.size() && "Couldn't find extract lane") ? void (0) : __assert_fail ("FoundLane < Scalars.size() && \"Couldn't find extract lane\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2558, __extension__ __PRETTY_FUNCTION__)); | |||
2559 | if (!ReorderIndices.empty()) | |||
2560 | FoundLane = ReorderIndices[FoundLane]; | |||
2561 | assert(FoundLane < Scalars.size() && "Couldn't find extract lane")(static_cast <bool> (FoundLane < Scalars.size() && "Couldn't find extract lane") ? void (0) : __assert_fail ("FoundLane < Scalars.size() && \"Couldn't find extract lane\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2561, __extension__ __PRETTY_FUNCTION__)); | |||
2562 | if (!ReuseShuffleIndices.empty()) { | |||
2563 | FoundLane = std::distance(ReuseShuffleIndices.begin(), | |||
2564 | find(ReuseShuffleIndices, FoundLane)); | |||
2565 | } | |||
2566 | return FoundLane; | |||
2567 | } | |||
2568 | ||||
2569 | #ifndef NDEBUG | |||
2570 | /// Debug printer. | |||
2571 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const { | |||
2572 | dbgs() << Idx << ".\n"; | |||
2573 | for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { | |||
2574 | dbgs() << "Operand " << OpI << ":\n"; | |||
2575 | for (const Value *V : Operands[OpI]) | |||
2576 | dbgs().indent(2) << *V << "\n"; | |||
2577 | } | |||
2578 | dbgs() << "Scalars: \n"; | |||
2579 | for (Value *V : Scalars) | |||
2580 | dbgs().indent(2) << *V << "\n"; | |||
2581 | dbgs() << "State: "; | |||
2582 | switch (State) { | |||
2583 | case Vectorize: | |||
2584 | dbgs() << "Vectorize\n"; | |||
2585 | break; | |||
2586 | case ScatterVectorize: | |||
2587 | dbgs() << "ScatterVectorize\n"; | |||
2588 | break; | |||
2589 | case NeedToGather: | |||
2590 | dbgs() << "NeedToGather\n"; | |||
2591 | break; | |||
2592 | } | |||
2593 | dbgs() << "MainOp: "; | |||
2594 | if (MainOp) | |||
2595 | dbgs() << *MainOp << "\n"; | |||
2596 | else | |||
2597 | dbgs() << "NULL\n"; | |||
2598 | dbgs() << "AltOp: "; | |||
2599 | if (AltOp) | |||
2600 | dbgs() << *AltOp << "\n"; | |||
2601 | else | |||
2602 | dbgs() << "NULL\n"; | |||
2603 | dbgs() << "VectorizedValue: "; | |||
2604 | if (VectorizedValue) | |||
2605 | dbgs() << *VectorizedValue << "\n"; | |||
2606 | else | |||
2607 | dbgs() << "NULL\n"; | |||
2608 | dbgs() << "ReuseShuffleIndices: "; | |||
2609 | if (ReuseShuffleIndices.empty()) | |||
2610 | dbgs() << "Empty"; | |||
2611 | else | |||
2612 | for (int ReuseIdx : ReuseShuffleIndices) | |||
2613 | dbgs() << ReuseIdx << ", "; | |||
2614 | dbgs() << "\n"; | |||
2615 | dbgs() << "ReorderIndices: "; | |||
2616 | for (unsigned ReorderIdx : ReorderIndices) | |||
2617 | dbgs() << ReorderIdx << ", "; | |||
2618 | dbgs() << "\n"; | |||
2619 | dbgs() << "UserTreeIndices: "; | |||
2620 | for (const auto &EInfo : UserTreeIndices) | |||
2621 | dbgs() << EInfo << ", "; | |||
2622 | dbgs() << "\n"; | |||
2623 | } | |||
2624 | #endif | |||
2625 | }; | |||
2626 | ||||
2627 | #ifndef NDEBUG | |||
2628 | void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, | |||
2629 | InstructionCost VecCost, | |||
2630 | InstructionCost ScalarCost) const { | |||
2631 | dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); | |||
2632 | dbgs() << "SLP: Costs:\n"; | |||
2633 | dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; | |||
2634 | dbgs() << "SLP: VectorCost = " << VecCost << "\n"; | |||
2635 | dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; | |||
2636 | dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << | |||
2637 | ReuseShuffleCost + VecCost - ScalarCost << "\n"; | |||
2638 | } | |||
2639 | #endif | |||
2640 | ||||
2641 | /// Create a new VectorizableTree entry. | |||
2642 | TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, | |||
2643 | const InstructionsState &S, | |||
2644 | const EdgeInfo &UserTreeIdx, | |||
2645 | ArrayRef<int> ReuseShuffleIndices = None, | |||
2646 | ArrayRef<unsigned> ReorderIndices = None) { | |||
2647 | TreeEntry::EntryState EntryState = | |||
2648 | Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; | |||
2649 | return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, | |||
2650 | ReuseShuffleIndices, ReorderIndices); | |||
2651 | } | |||
2652 | ||||
2653 | TreeEntry *newTreeEntry(ArrayRef<Value *> VL, | |||
2654 | TreeEntry::EntryState EntryState, | |||
2655 | Optional<ScheduleData *> Bundle, | |||
2656 | const InstructionsState &S, | |||
2657 | const EdgeInfo &UserTreeIdx, | |||
2658 | ArrayRef<int> ReuseShuffleIndices = None, | |||
2659 | ArrayRef<unsigned> ReorderIndices = None) { | |||
2660 | assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||(static_cast <bool> (((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && "Need to vectorize gather entry?" ) ? void (0) : __assert_fail ("((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && \"Need to vectorize gather entry?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2662, __extension__ __PRETTY_FUNCTION__)) | |||
2661 | (Bundle && EntryState != TreeEntry::NeedToGather)) &&(static_cast <bool> (((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && "Need to vectorize gather entry?" ) ? void (0) : __assert_fail ("((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && \"Need to vectorize gather entry?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2662, __extension__ __PRETTY_FUNCTION__)) | |||
2662 | "Need to vectorize gather entry?")(static_cast <bool> (((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && "Need to vectorize gather entry?" ) ? void (0) : __assert_fail ("((!Bundle && EntryState == TreeEntry::NeedToGather) || (Bundle && EntryState != TreeEntry::NeedToGather)) && \"Need to vectorize gather entry?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2662, __extension__ __PRETTY_FUNCTION__)); | |||
2663 | VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); | |||
2664 | TreeEntry *Last = VectorizableTree.back().get(); | |||
2665 | Last->Idx = VectorizableTree.size() - 1; | |||
2666 | Last->State = EntryState; | |||
2667 | Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), | |||
2668 | ReuseShuffleIndices.end()); | |||
2669 | if (ReorderIndices.empty()) { | |||
2670 | Last->Scalars.assign(VL.begin(), VL.end()); | |||
2671 | Last->setOperations(S); | |||
2672 | } else { | |||
2673 | // Reorder scalars and build final mask. | |||
2674 | Last->Scalars.assign(VL.size(), nullptr); | |||
2675 | transform(ReorderIndices, Last->Scalars.begin(), | |||
2676 | [VL](unsigned Idx) -> Value * { | |||
2677 | if (Idx >= VL.size()) | |||
2678 | return UndefValue::get(VL.front()->getType()); | |||
2679 | return VL[Idx]; | |||
2680 | }); | |||
2681 | InstructionsState S = getSameOpcode(Last->Scalars, *TLI); | |||
2682 | Last->setOperations(S); | |||
2683 | Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); | |||
2684 | } | |||
2685 | if (Last->State != TreeEntry::NeedToGather) { | |||
2686 | for (Value *V : VL) { | |||
2687 | assert(!getTreeEntry(V) && "Scalar already in tree!")(static_cast <bool> (!getTreeEntry(V) && "Scalar already in tree!" ) ? void (0) : __assert_fail ("!getTreeEntry(V) && \"Scalar already in tree!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2687, __extension__ __PRETTY_FUNCTION__)); | |||
2688 | ScalarToTreeEntry[V] = Last; | |||
2689 | } | |||
2690 | // Update the scheduler bundle to point to this TreeEntry. | |||
2691 | ScheduleData *BundleMember = *Bundle; | |||
2692 | assert((BundleMember || isa<PHINode>(S.MainOp) ||(static_cast <bool> ((BundleMember || isa<PHINode> (S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule (VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail ("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2695, __extension__ __PRETTY_FUNCTION__)) | |||
2693 | isVectorLikeInstWithConstOps(S.MainOp) ||(static_cast <bool> ((BundleMember || isa<PHINode> (S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule (VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail ("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2695, __extension__ __PRETTY_FUNCTION__)) | |||
2694 | doesNotNeedToSchedule(VL)) &&(static_cast <bool> ((BundleMember || isa<PHINode> (S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule (VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail ("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2695, __extension__ __PRETTY_FUNCTION__)) | |||
2695 | "Bundle and VL out of sync")(static_cast <bool> ((BundleMember || isa<PHINode> (S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule (VL)) && "Bundle and VL out of sync") ? void (0) : __assert_fail ("(BundleMember || isa<PHINode>(S.MainOp) || isVectorLikeInstWithConstOps(S.MainOp) || doesNotNeedToSchedule(VL)) && \"Bundle and VL out of sync\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2695, __extension__ __PRETTY_FUNCTION__)); | |||
2696 | if (BundleMember) { | |||
2697 | for (Value *V : VL) { | |||
2698 | if (doesNotNeedToBeScheduled(V)) | |||
2699 | continue; | |||
2700 | assert(BundleMember && "Unexpected end of bundle.")(static_cast <bool> (BundleMember && "Unexpected end of bundle." ) ? void (0) : __assert_fail ("BundleMember && \"Unexpected end of bundle.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2700, __extension__ __PRETTY_FUNCTION__)); | |||
2701 | BundleMember->TE = Last; | |||
2702 | BundleMember = BundleMember->NextInBundle; | |||
2703 | } | |||
2704 | } | |||
2705 | assert(!BundleMember && "Bundle and VL out of sync")(static_cast <bool> (!BundleMember && "Bundle and VL out of sync" ) ? void (0) : __assert_fail ("!BundleMember && \"Bundle and VL out of sync\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2705, __extension__ __PRETTY_FUNCTION__)); | |||
2706 | } else { | |||
2707 | MustGather.insert(VL.begin(), VL.end()); | |||
2708 | } | |||
2709 | ||||
2710 | if (UserTreeIdx.UserTE) | |||
2711 | Last->UserTreeIndices.push_back(UserTreeIdx); | |||
2712 | ||||
2713 | return Last; | |||
2714 | } | |||
2715 | ||||
2716 | /// -- Vectorization State -- | |||
2717 | /// Holds all of the tree entries. | |||
2718 | TreeEntry::VecTreeTy VectorizableTree; | |||
2719 | ||||
2720 | #ifndef NDEBUG | |||
2721 | /// Debug printer. | |||
2722 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dumpVectorizableTree() const { | |||
2723 | for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { | |||
2724 | VectorizableTree[Id]->dump(); | |||
2725 | dbgs() << "\n"; | |||
2726 | } | |||
2727 | } | |||
2728 | #endif | |||
2729 | ||||
2730 | TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } | |||
2731 | ||||
2732 | const TreeEntry *getTreeEntry(Value *V) const { | |||
2733 | return ScalarToTreeEntry.lookup(V); | |||
2734 | } | |||
2735 | ||||
2736 | /// Maps a specific scalar to its tree entry. | |||
2737 | SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; | |||
2738 | ||||
2739 | /// Maps a value to the proposed vectorizable size. | |||
2740 | SmallDenseMap<Value *, unsigned> InstrElementSize; | |||
2741 | ||||
2742 | /// A list of scalars that we found that we need to keep as scalars. | |||
2743 | ValueSet MustGather; | |||
2744 | ||||
2745 | /// This POD struct describes one external user in the vectorized tree. | |||
2746 | struct ExternalUser { | |||
2747 | ExternalUser(Value *S, llvm::User *U, int L) | |||
2748 | : Scalar(S), User(U), Lane(L) {} | |||
2749 | ||||
2750 | // Which scalar in our function. | |||
2751 | Value *Scalar; | |||
2752 | ||||
2753 | // Which user that uses the scalar. | |||
2754 | llvm::User *User; | |||
2755 | ||||
2756 | // Which lane does the scalar belong to. | |||
2757 | int Lane; | |||
2758 | }; | |||
2759 | using UserList = SmallVector<ExternalUser, 16>; | |||
2760 | ||||
2761 | /// Checks if two instructions may access the same memory. | |||
2762 | /// | |||
2763 | /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it | |||
2764 | /// is invariant in the calling loop. | |||
2765 | bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, | |||
2766 | Instruction *Inst2) { | |||
2767 | // First check if the result is already in the cache. | |||
2768 | AliasCacheKey key = std::make_pair(Inst1, Inst2); | |||
2769 | Optional<bool> &result = AliasCache[key]; | |||
2770 | if (result) { | |||
2771 | return result.value(); | |||
2772 | } | |||
2773 | bool aliased = true; | |||
2774 | if (Loc1.Ptr && isSimple(Inst1)) | |||
2775 | aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1)); | |||
2776 | // Store the result in the cache. | |||
2777 | result = aliased; | |||
2778 | return aliased; | |||
2779 | } | |||
2780 | ||||
2781 | using AliasCacheKey = std::pair<Instruction *, Instruction *>; | |||
2782 | ||||
2783 | /// Cache for alias results. | |||
2784 | /// TODO: consider moving this to the AliasAnalysis itself. | |||
2785 | DenseMap<AliasCacheKey, Optional<bool>> AliasCache; | |||
2786 | ||||
2787 | // Cache for pointerMayBeCaptured calls inside AA. This is preserved | |||
2788 | // globally through SLP because we don't perform any action which | |||
2789 | // invalidates capture results. | |||
2790 | BatchAAResults BatchAA; | |||
2791 | ||||
2792 | /// Temporary store for deleted instructions. Instructions will be deleted | |||
2793 | /// eventually when the BoUpSLP is destructed. The deferral is required to | |||
2794 | /// ensure that there are no incorrect collisions in the AliasCache, which | |||
2795 | /// can happen if a new instruction is allocated at the same address as a | |||
2796 | /// previously deleted instruction. | |||
2797 | DenseSet<Instruction *> DeletedInstructions; | |||
2798 | ||||
2799 | /// Set of the instruction, being analyzed already for reductions. | |||
2800 | SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots; | |||
2801 | ||||
2802 | /// Set of hashes for the list of reduction values already being analyzed. | |||
2803 | DenseSet<size_t> AnalyzedReductionVals; | |||
2804 | ||||
2805 | /// A list of values that need to extracted out of the tree. | |||
2806 | /// This list holds pairs of (Internal Scalar : External User). External User | |||
2807 | /// can be nullptr, it means that this Internal Scalar will be used later, | |||
2808 | /// after vectorization. | |||
2809 | UserList ExternalUses; | |||
2810 | ||||
2811 | /// Values used only by @llvm.assume calls. | |||
2812 | SmallPtrSet<const Value *, 32> EphValues; | |||
2813 | ||||
2814 | /// Holds all of the instructions that we gathered, shuffle instructions and | |||
2815 | /// extractelements. | |||
2816 | SetVector<Instruction *> GatherShuffleExtractSeq; | |||
2817 | ||||
2818 | /// A list of blocks that we are going to CSE. | |||
2819 | SetVector<BasicBlock *> CSEBlocks; | |||
2820 | ||||
2821 | /// Contains all scheduling relevant data for an instruction. | |||
2822 | /// A ScheduleData either represents a single instruction or a member of an | |||
2823 | /// instruction bundle (= a group of instructions which is combined into a | |||
2824 | /// vector instruction). | |||
2825 | struct ScheduleData { | |||
2826 | // The initial value for the dependency counters. It means that the | |||
2827 | // dependencies are not calculated yet. | |||
2828 | enum { InvalidDeps = -1 }; | |||
2829 | ||||
2830 | ScheduleData() = default; | |||
2831 | ||||
2832 | void init(int BlockSchedulingRegionID, Value *OpVal) { | |||
2833 | FirstInBundle = this; | |||
2834 | NextInBundle = nullptr; | |||
2835 | NextLoadStore = nullptr; | |||
2836 | IsScheduled = false; | |||
2837 | SchedulingRegionID = BlockSchedulingRegionID; | |||
2838 | clearDependencies(); | |||
2839 | OpValue = OpVal; | |||
2840 | TE = nullptr; | |||
2841 | } | |||
2842 | ||||
2843 | /// Verify basic self consistency properties | |||
2844 | void verify() { | |||
2845 | if (hasValidDependencies()) { | |||
2846 | assert(UnscheduledDeps <= Dependencies && "invariant")(static_cast <bool> (UnscheduledDeps <= Dependencies && "invariant") ? void (0) : __assert_fail ("UnscheduledDeps <= Dependencies && \"invariant\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2846, __extension__ __PRETTY_FUNCTION__)); | |||
2847 | } else { | |||
2848 | assert(UnscheduledDeps == Dependencies && "invariant")(static_cast <bool> (UnscheduledDeps == Dependencies && "invariant") ? void (0) : __assert_fail ("UnscheduledDeps == Dependencies && \"invariant\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2848, __extension__ __PRETTY_FUNCTION__)); | |||
2849 | } | |||
2850 | ||||
2851 | if (IsScheduled) { | |||
2852 | assert(isSchedulingEntity() &&(static_cast <bool> (isSchedulingEntity() && "unexpected scheduled state" ) ? void (0) : __assert_fail ("isSchedulingEntity() && \"unexpected scheduled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2853, __extension__ __PRETTY_FUNCTION__)) | |||
2853 | "unexpected scheduled state")(static_cast <bool> (isSchedulingEntity() && "unexpected scheduled state" ) ? void (0) : __assert_fail ("isSchedulingEntity() && \"unexpected scheduled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2853, __extension__ __PRETTY_FUNCTION__)); | |||
2854 | for (const ScheduleData *BundleMember = this; BundleMember; | |||
2855 | BundleMember = BundleMember->NextInBundle) { | |||
2856 | assert(BundleMember->hasValidDependencies() &&(static_cast <bool> (BundleMember->hasValidDependencies () && BundleMember->UnscheduledDeps == 0 && "unexpected scheduled state") ? void (0) : __assert_fail ("BundleMember->hasValidDependencies() && BundleMember->UnscheduledDeps == 0 && \"unexpected scheduled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2858, __extension__ __PRETTY_FUNCTION__)) | |||
2857 | BundleMember->UnscheduledDeps == 0 &&(static_cast <bool> (BundleMember->hasValidDependencies () && BundleMember->UnscheduledDeps == 0 && "unexpected scheduled state") ? void (0) : __assert_fail ("BundleMember->hasValidDependencies() && BundleMember->UnscheduledDeps == 0 && \"unexpected scheduled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2858, __extension__ __PRETTY_FUNCTION__)) | |||
2858 | "unexpected scheduled state")(static_cast <bool> (BundleMember->hasValidDependencies () && BundleMember->UnscheduledDeps == 0 && "unexpected scheduled state") ? void (0) : __assert_fail ("BundleMember->hasValidDependencies() && BundleMember->UnscheduledDeps == 0 && \"unexpected scheduled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2858, __extension__ __PRETTY_FUNCTION__)); | |||
2859 | assert((BundleMember == this || !BundleMember->IsScheduled) &&(static_cast <bool> ((BundleMember == this || !BundleMember ->IsScheduled) && "only bundle is marked scheduled" ) ? void (0) : __assert_fail ("(BundleMember == this || !BundleMember->IsScheduled) && \"only bundle is marked scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2860, __extension__ __PRETTY_FUNCTION__)) | |||
2860 | "only bundle is marked scheduled")(static_cast <bool> ((BundleMember == this || !BundleMember ->IsScheduled) && "only bundle is marked scheduled" ) ? void (0) : __assert_fail ("(BundleMember == this || !BundleMember->IsScheduled) && \"only bundle is marked scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2860, __extension__ __PRETTY_FUNCTION__)); | |||
2861 | } | |||
2862 | } | |||
2863 | ||||
2864 | assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&(static_cast <bool> (Inst->getParent() == FirstInBundle ->Inst->getParent() && "all bundle members must be in same basic block" ) ? void (0) : __assert_fail ("Inst->getParent() == FirstInBundle->Inst->getParent() && \"all bundle members must be in same basic block\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2865, __extension__ __PRETTY_FUNCTION__)) | |||
2865 | "all bundle members must be in same basic block")(static_cast <bool> (Inst->getParent() == FirstInBundle ->Inst->getParent() && "all bundle members must be in same basic block" ) ? void (0) : __assert_fail ("Inst->getParent() == FirstInBundle->Inst->getParent() && \"all bundle members must be in same basic block\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2865, __extension__ __PRETTY_FUNCTION__)); | |||
2866 | } | |||
2867 | ||||
2868 | /// Returns true if the dependency information has been calculated. | |||
2869 | /// Note that depenendency validity can vary between instructions within | |||
2870 | /// a single bundle. | |||
2871 | bool hasValidDependencies() const { return Dependencies != InvalidDeps; } | |||
2872 | ||||
2873 | /// Returns true for single instructions and for bundle representatives | |||
2874 | /// (= the head of a bundle). | |||
2875 | bool isSchedulingEntity() const { return FirstInBundle == this; } | |||
2876 | ||||
2877 | /// Returns true if it represents an instruction bundle and not only a | |||
2878 | /// single instruction. | |||
2879 | bool isPartOfBundle() const { | |||
2880 | return NextInBundle != nullptr || FirstInBundle != this || TE; | |||
2881 | } | |||
2882 | ||||
2883 | /// Returns true if it is ready for scheduling, i.e. it has no more | |||
2884 | /// unscheduled depending instructions/bundles. | |||
2885 | bool isReady() const { | |||
2886 | assert(isSchedulingEntity() &&(static_cast <bool> (isSchedulingEntity() && "can't consider non-scheduling entity for ready list" ) ? void (0) : __assert_fail ("isSchedulingEntity() && \"can't consider non-scheduling entity for ready list\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2887, __extension__ __PRETTY_FUNCTION__)) | |||
2887 | "can't consider non-scheduling entity for ready list")(static_cast <bool> (isSchedulingEntity() && "can't consider non-scheduling entity for ready list" ) ? void (0) : __assert_fail ("isSchedulingEntity() && \"can't consider non-scheduling entity for ready list\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2887, __extension__ __PRETTY_FUNCTION__)); | |||
2888 | return unscheduledDepsInBundle() == 0 && !IsScheduled; | |||
2889 | } | |||
2890 | ||||
2891 | /// Modifies the number of unscheduled dependencies for this instruction, | |||
2892 | /// and returns the number of remaining dependencies for the containing | |||
2893 | /// bundle. | |||
2894 | int incrementUnscheduledDeps(int Incr) { | |||
2895 | assert(hasValidDependencies() &&(static_cast <bool> (hasValidDependencies() && "increment of unscheduled deps would be meaningless" ) ? void (0) : __assert_fail ("hasValidDependencies() && \"increment of unscheduled deps would be meaningless\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2896, __extension__ __PRETTY_FUNCTION__)) | |||
2896 | "increment of unscheduled deps would be meaningless")(static_cast <bool> (hasValidDependencies() && "increment of unscheduled deps would be meaningless" ) ? void (0) : __assert_fail ("hasValidDependencies() && \"increment of unscheduled deps would be meaningless\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2896, __extension__ __PRETTY_FUNCTION__)); | |||
2897 | UnscheduledDeps += Incr; | |||
2898 | return FirstInBundle->unscheduledDepsInBundle(); | |||
2899 | } | |||
2900 | ||||
2901 | /// Sets the number of unscheduled dependencies to the number of | |||
2902 | /// dependencies. | |||
2903 | void resetUnscheduledDeps() { | |||
2904 | UnscheduledDeps = Dependencies; | |||
2905 | } | |||
2906 | ||||
2907 | /// Clears all dependency information. | |||
2908 | void clearDependencies() { | |||
2909 | Dependencies = InvalidDeps; | |||
2910 | resetUnscheduledDeps(); | |||
2911 | MemoryDependencies.clear(); | |||
2912 | ControlDependencies.clear(); | |||
2913 | } | |||
2914 | ||||
2915 | int unscheduledDepsInBundle() const { | |||
2916 | assert(isSchedulingEntity() && "only meaningful on the bundle")(static_cast <bool> (isSchedulingEntity() && "only meaningful on the bundle" ) ? void (0) : __assert_fail ("isSchedulingEntity() && \"only meaningful on the bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 2916, __extension__ __PRETTY_FUNCTION__)); | |||
2917 | int Sum = 0; | |||
2918 | for (const ScheduleData *BundleMember = this; BundleMember; | |||
2919 | BundleMember = BundleMember->NextInBundle) { | |||
2920 | if (BundleMember->UnscheduledDeps == InvalidDeps) | |||
2921 | return InvalidDeps; | |||
2922 | Sum += BundleMember->UnscheduledDeps; | |||
2923 | } | |||
2924 | return Sum; | |||
2925 | } | |||
2926 | ||||
2927 | void dump(raw_ostream &os) const { | |||
2928 | if (!isSchedulingEntity()) { | |||
2929 | os << "/ " << *Inst; | |||
2930 | } else if (NextInBundle) { | |||
2931 | os << '[' << *Inst; | |||
2932 | ScheduleData *SD = NextInBundle; | |||
2933 | while (SD) { | |||
2934 | os << ';' << *SD->Inst; | |||
2935 | SD = SD->NextInBundle; | |||
2936 | } | |||
2937 | os << ']'; | |||
2938 | } else { | |||
2939 | os << *Inst; | |||
2940 | } | |||
2941 | } | |||
2942 | ||||
2943 | Instruction *Inst = nullptr; | |||
2944 | ||||
2945 | /// Opcode of the current instruction in the schedule data. | |||
2946 | Value *OpValue = nullptr; | |||
2947 | ||||
2948 | /// The TreeEntry that this instruction corresponds to. | |||
2949 | TreeEntry *TE = nullptr; | |||
2950 | ||||
2951 | /// Points to the head in an instruction bundle (and always to this for | |||
2952 | /// single instructions). | |||
2953 | ScheduleData *FirstInBundle = nullptr; | |||
2954 | ||||
2955 | /// Single linked list of all instructions in a bundle. Null if it is a | |||
2956 | /// single instruction. | |||
2957 | ScheduleData *NextInBundle = nullptr; | |||
2958 | ||||
2959 | /// Single linked list of all memory instructions (e.g. load, store, call) | |||
2960 | /// in the block - until the end of the scheduling region. | |||
2961 | ScheduleData *NextLoadStore = nullptr; | |||
2962 | ||||
2963 | /// The dependent memory instructions. | |||
2964 | /// This list is derived on demand in calculateDependencies(). | |||
2965 | SmallVector<ScheduleData *, 4> MemoryDependencies; | |||
2966 | ||||
2967 | /// List of instructions which this instruction could be control dependent | |||
2968 | /// on. Allowing such nodes to be scheduled below this one could introduce | |||
2969 | /// a runtime fault which didn't exist in the original program. | |||
2970 | /// ex: this is a load or udiv following a readonly call which inf loops | |||
2971 | SmallVector<ScheduleData *, 4> ControlDependencies; | |||
2972 | ||||
2973 | /// This ScheduleData is in the current scheduling region if this matches | |||
2974 | /// the current SchedulingRegionID of BlockScheduling. | |||
2975 | int SchedulingRegionID = 0; | |||
2976 | ||||
2977 | /// Used for getting a "good" final ordering of instructions. | |||
2978 | int SchedulingPriority = 0; | |||
2979 | ||||
2980 | /// The number of dependencies. Constitutes of the number of users of the | |||
2981 | /// instruction plus the number of dependent memory instructions (if any). | |||
2982 | /// This value is calculated on demand. | |||
2983 | /// If InvalidDeps, the number of dependencies is not calculated yet. | |||
2984 | int Dependencies = InvalidDeps; | |||
2985 | ||||
2986 | /// The number of dependencies minus the number of dependencies of scheduled | |||
2987 | /// instructions. As soon as this is zero, the instruction/bundle gets ready | |||
2988 | /// for scheduling. | |||
2989 | /// Note that this is negative as long as Dependencies is not calculated. | |||
2990 | int UnscheduledDeps = InvalidDeps; | |||
2991 | ||||
2992 | /// True if this instruction is scheduled (or considered as scheduled in the | |||
2993 | /// dry-run). | |||
2994 | bool IsScheduled = false; | |||
2995 | }; | |||
2996 | ||||
2997 | #ifndef NDEBUG | |||
2998 | friend inline raw_ostream &operator<<(raw_ostream &os, | |||
2999 | const BoUpSLP::ScheduleData &SD) { | |||
3000 | SD.dump(os); | |||
3001 | return os; | |||
3002 | } | |||
3003 | #endif | |||
3004 | ||||
3005 | friend struct GraphTraits<BoUpSLP *>; | |||
3006 | friend struct DOTGraphTraits<BoUpSLP *>; | |||
3007 | ||||
3008 | /// Contains all scheduling data for a basic block. | |||
3009 | /// It does not schedules instructions, which are not memory read/write | |||
3010 | /// instructions and their operands are either constants, or arguments, or | |||
3011 | /// phis, or instructions from others blocks, or their users are phis or from | |||
3012 | /// the other blocks. The resulting vector instructions can be placed at the | |||
3013 | /// beginning of the basic block without scheduling (if operands does not need | |||
3014 | /// to be scheduled) or at the end of the block (if users are outside of the | |||
3015 | /// block). It allows to save some compile time and memory used by the | |||
3016 | /// compiler. | |||
3017 | /// ScheduleData is assigned for each instruction in between the boundaries of | |||
3018 | /// the tree entry, even for those, which are not part of the graph. It is | |||
3019 | /// required to correctly follow the dependencies between the instructions and | |||
3020 | /// their correct scheduling. The ScheduleData is not allocated for the | |||
3021 | /// instructions, which do not require scheduling, like phis, nodes with | |||
3022 | /// extractelements/insertelements only or nodes with instructions, with | |||
3023 | /// uses/operands outside of the block. | |||
3024 | struct BlockScheduling { | |||
3025 | BlockScheduling(BasicBlock *BB) | |||
3026 | : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} | |||
3027 | ||||
3028 | void clear() { | |||
3029 | ReadyInsts.clear(); | |||
3030 | ScheduleStart = nullptr; | |||
3031 | ScheduleEnd = nullptr; | |||
3032 | FirstLoadStoreInRegion = nullptr; | |||
3033 | LastLoadStoreInRegion = nullptr; | |||
3034 | RegionHasStackSave = false; | |||
3035 | ||||
3036 | // Reduce the maximum schedule region size by the size of the | |||
3037 | // previous scheduling run. | |||
3038 | ScheduleRegionSizeLimit -= ScheduleRegionSize; | |||
3039 | if (ScheduleRegionSizeLimit < MinScheduleRegionSize) | |||
3040 | ScheduleRegionSizeLimit = MinScheduleRegionSize; | |||
3041 | ScheduleRegionSize = 0; | |||
3042 | ||||
3043 | // Make a new scheduling region, i.e. all existing ScheduleData is not | |||
3044 | // in the new region yet. | |||
3045 | ++SchedulingRegionID; | |||
3046 | } | |||
3047 | ||||
3048 | ScheduleData *getScheduleData(Instruction *I) { | |||
3049 | if (BB != I->getParent()) | |||
3050 | // Avoid lookup if can't possibly be in map. | |||
3051 | return nullptr; | |||
3052 | ScheduleData *SD = ScheduleDataMap.lookup(I); | |||
3053 | if (SD && isInSchedulingRegion(SD)) | |||
3054 | return SD; | |||
3055 | return nullptr; | |||
3056 | } | |||
3057 | ||||
3058 | ScheduleData *getScheduleData(Value *V) { | |||
3059 | if (auto *I = dyn_cast<Instruction>(V)) | |||
3060 | return getScheduleData(I); | |||
3061 | return nullptr; | |||
3062 | } | |||
3063 | ||||
3064 | ScheduleData *getScheduleData(Value *V, Value *Key) { | |||
3065 | if (V == Key) | |||
3066 | return getScheduleData(V); | |||
3067 | auto I = ExtraScheduleDataMap.find(V); | |||
3068 | if (I != ExtraScheduleDataMap.end()) { | |||
3069 | ScheduleData *SD = I->second.lookup(Key); | |||
3070 | if (SD && isInSchedulingRegion(SD)) | |||
3071 | return SD; | |||
3072 | } | |||
3073 | return nullptr; | |||
3074 | } | |||
3075 | ||||
3076 | bool isInSchedulingRegion(ScheduleData *SD) const { | |||
3077 | return SD->SchedulingRegionID == SchedulingRegionID; | |||
3078 | } | |||
3079 | ||||
3080 | /// Marks an instruction as scheduled and puts all dependent ready | |||
3081 | /// instructions into the ready-list. | |||
3082 | template <typename ReadyListType> | |||
3083 | void schedule(ScheduleData *SD, ReadyListType &ReadyList) { | |||
3084 | SD->IsScheduled = true; | |||
3085 | LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: schedule " << *SD << "\n"; } } while (false); | |||
3086 | ||||
3087 | for (ScheduleData *BundleMember = SD; BundleMember; | |||
3088 | BundleMember = BundleMember->NextInBundle) { | |||
3089 | if (BundleMember->Inst != BundleMember->OpValue) | |||
3090 | continue; | |||
3091 | ||||
3092 | // Handle the def-use chain dependencies. | |||
3093 | ||||
3094 | // Decrement the unscheduled counter and insert to ready list if ready. | |||
3095 | auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { | |||
3096 | doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { | |||
3097 | if (OpDef && OpDef->hasValidDependencies() && | |||
3098 | OpDef->incrementUnscheduledDeps(-1) == 0) { | |||
3099 | // There are no more unscheduled dependencies after | |||
3100 | // decrementing, so we can put the dependent instruction | |||
3101 | // into the ready list. | |||
3102 | ScheduleData *DepBundle = OpDef->FirstInBundle; | |||
3103 | assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled && "already scheduled bundle gets ready") ? void (0) : __assert_fail ("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3104, __extension__ __PRETTY_FUNCTION__)) | |||
3104 | "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled && "already scheduled bundle gets ready") ? void (0) : __assert_fail ("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3104, __extension__ __PRETTY_FUNCTION__)); | |||
3105 | ReadyList.insert(DepBundle); | |||
3106 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n"; } } while (false) | |||
3107 | << "SLP: gets ready (def): " << *DepBundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready (def): " << *DepBundle << "\n"; } } while (false); | |||
3108 | } | |||
3109 | }); | |||
3110 | }; | |||
3111 | ||||
3112 | // If BundleMember is a vector bundle, its operands may have been | |||
3113 | // reordered during buildTree(). We therefore need to get its operands | |||
3114 | // through the TreeEntry. | |||
3115 | if (TreeEntry *TE = BundleMember->TE) { | |||
3116 | // Need to search for the lane since the tree entry can be reordered. | |||
3117 | int Lane = std::distance(TE->Scalars.begin(), | |||
3118 | find(TE->Scalars, BundleMember->Inst)); | |||
3119 | assert(Lane >= 0 && "Lane not set")(static_cast <bool> (Lane >= 0 && "Lane not set" ) ? void (0) : __assert_fail ("Lane >= 0 && \"Lane not set\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3119, __extension__ __PRETTY_FUNCTION__)); | |||
3120 | ||||
3121 | // Since vectorization tree is being built recursively this assertion | |||
3122 | // ensures that the tree entry has all operands set before reaching | |||
3123 | // this code. Couple of exceptions known at the moment are extracts | |||
3124 | // where their second (immediate) operand is not added. Since | |||
3125 | // immediates do not affect scheduler behavior this is considered | |||
3126 | // okay. | |||
3127 | auto *In = BundleMember->Inst; | |||
3128 | assert(In &&(static_cast <bool> (In && (isa<ExtractValueInst , ExtractElementInst>(In) || In->getNumOperands() == TE ->getNumOperands()) && "Missed TreeEntry operands?" ) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3131, __extension__ __PRETTY_FUNCTION__)) | |||
3129 | (isa<ExtractValueInst, ExtractElementInst>(In) ||(static_cast <bool> (In && (isa<ExtractValueInst , ExtractElementInst>(In) || In->getNumOperands() == TE ->getNumOperands()) && "Missed TreeEntry operands?" ) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3131, __extension__ __PRETTY_FUNCTION__)) | |||
3130 | In->getNumOperands() == TE->getNumOperands()) &&(static_cast <bool> (In && (isa<ExtractValueInst , ExtractElementInst>(In) || In->getNumOperands() == TE ->getNumOperands()) && "Missed TreeEntry operands?" ) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3131, __extension__ __PRETTY_FUNCTION__)) | |||
3131 | "Missed TreeEntry operands?")(static_cast <bool> (In && (isa<ExtractValueInst , ExtractElementInst>(In) || In->getNumOperands() == TE ->getNumOperands()) && "Missed TreeEntry operands?" ) ? void (0) : __assert_fail ("In && (isa<ExtractValueInst, ExtractElementInst>(In) || In->getNumOperands() == TE->getNumOperands()) && \"Missed TreeEntry operands?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3131, __extension__ __PRETTY_FUNCTION__)); | |||
3132 | (void)In; // fake use to avoid build failure when assertions disabled | |||
3133 | ||||
3134 | for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); | |||
3135 | OpIdx != NumOperands; ++OpIdx) | |||
3136 | if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) | |||
3137 | DecrUnsched(I); | |||
3138 | } else { | |||
3139 | // If BundleMember is a stand-alone instruction, no operand reordering | |||
3140 | // has taken place, so we directly access its operands. | |||
3141 | for (Use &U : BundleMember->Inst->operands()) | |||
3142 | if (auto *I = dyn_cast<Instruction>(U.get())) | |||
3143 | DecrUnsched(I); | |||
3144 | } | |||
3145 | // Handle the memory dependencies. | |||
3146 | for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { | |||
3147 | if (MemoryDepSD->hasValidDependencies() && | |||
3148 | MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { | |||
3149 | // There are no more unscheduled dependencies after decrementing, | |||
3150 | // so we can put the dependent instruction into the ready list. | |||
3151 | ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; | |||
3152 | assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled && "already scheduled bundle gets ready") ? void (0) : __assert_fail ("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3153, __extension__ __PRETTY_FUNCTION__)) | |||
3153 | "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled && "already scheduled bundle gets ready") ? void (0) : __assert_fail ("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3153, __extension__ __PRETTY_FUNCTION__)); | |||
3154 | ReadyList.insert(DepBundle); | |||
3155 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n"; } } while (false) | |||
3156 | << "SLP: gets ready (mem): " << *DepBundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready (mem): " << *DepBundle << "\n"; } } while (false); | |||
3157 | } | |||
3158 | } | |||
3159 | // Handle the control dependencies. | |||
3160 | for (ScheduleData *DepSD : BundleMember->ControlDependencies) { | |||
3161 | if (DepSD->incrementUnscheduledDeps(-1) == 0) { | |||
3162 | // There are no more unscheduled dependencies after decrementing, | |||
3163 | // so we can put the dependent instruction into the ready list. | |||
3164 | ScheduleData *DepBundle = DepSD->FirstInBundle; | |||
3165 | assert(!DepBundle->IsScheduled &&(static_cast <bool> (!DepBundle->IsScheduled && "already scheduled bundle gets ready") ? void (0) : __assert_fail ("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3166, __extension__ __PRETTY_FUNCTION__)) | |||
3166 | "already scheduled bundle gets ready")(static_cast <bool> (!DepBundle->IsScheduled && "already scheduled bundle gets ready") ? void (0) : __assert_fail ("!DepBundle->IsScheduled && \"already scheduled bundle gets ready\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3166, __extension__ __PRETTY_FUNCTION__)); | |||
3167 | ReadyList.insert(DepBundle); | |||
3168 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready (ctl): " << *DepBundle << "\n"; } } while (false) | |||
3169 | << "SLP: gets ready (ctl): " << *DepBundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready (ctl): " << *DepBundle << "\n"; } } while (false); | |||
3170 | } | |||
3171 | } | |||
3172 | ||||
3173 | } | |||
3174 | } | |||
3175 | ||||
3176 | /// Verify basic self consistency properties of the data structure. | |||
3177 | void verify() { | |||
3178 | if (!ScheduleStart) | |||
3179 | return; | |||
3180 | ||||
3181 | assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&(static_cast <bool> (ScheduleStart->getParent() == ScheduleEnd ->getParent() && ScheduleStart->comesBefore(ScheduleEnd ) && "Not a valid scheduling region?") ? void (0) : __assert_fail ("ScheduleStart->getParent() == ScheduleEnd->getParent() && ScheduleStart->comesBefore(ScheduleEnd) && \"Not a valid scheduling region?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3183, __extension__ __PRETTY_FUNCTION__)) | |||
3182 | ScheduleStart->comesBefore(ScheduleEnd) &&(static_cast <bool> (ScheduleStart->getParent() == ScheduleEnd ->getParent() && ScheduleStart->comesBefore(ScheduleEnd ) && "Not a valid scheduling region?") ? void (0) : __assert_fail ("ScheduleStart->getParent() == ScheduleEnd->getParent() && ScheduleStart->comesBefore(ScheduleEnd) && \"Not a valid scheduling region?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3183, __extension__ __PRETTY_FUNCTION__)) | |||
3183 | "Not a valid scheduling region?")(static_cast <bool> (ScheduleStart->getParent() == ScheduleEnd ->getParent() && ScheduleStart->comesBefore(ScheduleEnd ) && "Not a valid scheduling region?") ? void (0) : __assert_fail ("ScheduleStart->getParent() == ScheduleEnd->getParent() && ScheduleStart->comesBefore(ScheduleEnd) && \"Not a valid scheduling region?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3183, __extension__ __PRETTY_FUNCTION__)); | |||
3184 | ||||
3185 | for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { | |||
3186 | auto *SD = getScheduleData(I); | |||
3187 | if (!SD) | |||
3188 | continue; | |||
3189 | assert(isInSchedulingRegion(SD) &&(static_cast <bool> (isInSchedulingRegion(SD) && "primary schedule data not in window?") ? void (0) : __assert_fail ("isInSchedulingRegion(SD) && \"primary schedule data not in window?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3190, __extension__ __PRETTY_FUNCTION__)) | |||
3190 | "primary schedule data not in window?")(static_cast <bool> (isInSchedulingRegion(SD) && "primary schedule data not in window?") ? void (0) : __assert_fail ("isInSchedulingRegion(SD) && \"primary schedule data not in window?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3190, __extension__ __PRETTY_FUNCTION__)); | |||
3191 | assert(isInSchedulingRegion(SD->FirstInBundle) &&(static_cast <bool> (isInSchedulingRegion(SD->FirstInBundle ) && "entire bundle in window!") ? void (0) : __assert_fail ("isInSchedulingRegion(SD->FirstInBundle) && \"entire bundle in window!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3192, __extension__ __PRETTY_FUNCTION__)) | |||
3192 | "entire bundle in window!")(static_cast <bool> (isInSchedulingRegion(SD->FirstInBundle ) && "entire bundle in window!") ? void (0) : __assert_fail ("isInSchedulingRegion(SD->FirstInBundle) && \"entire bundle in window!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3192, __extension__ __PRETTY_FUNCTION__)); | |||
3193 | (void)SD; | |||
3194 | doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); | |||
3195 | } | |||
3196 | ||||
3197 | for (auto *SD : ReadyInsts) { | |||
3198 | assert(SD->isSchedulingEntity() && SD->isReady() &&(static_cast <bool> (SD->isSchedulingEntity() && SD->isReady() && "item in ready list not ready?") ? void (0) : __assert_fail ("SD->isSchedulingEntity() && SD->isReady() && \"item in ready list not ready?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3199, __extension__ __PRETTY_FUNCTION__)) | |||
3199 | "item in ready list not ready?")(static_cast <bool> (SD->isSchedulingEntity() && SD->isReady() && "item in ready list not ready?") ? void (0) : __assert_fail ("SD->isSchedulingEntity() && SD->isReady() && \"item in ready list not ready?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3199, __extension__ __PRETTY_FUNCTION__)); | |||
3200 | (void)SD; | |||
3201 | } | |||
3202 | } | |||
3203 | ||||
3204 | void doForAllOpcodes(Value *V, | |||
3205 | function_ref<void(ScheduleData *SD)> Action) { | |||
3206 | if (ScheduleData *SD = getScheduleData(V)) | |||
3207 | Action(SD); | |||
3208 | auto I = ExtraScheduleDataMap.find(V); | |||
3209 | if (I != ExtraScheduleDataMap.end()) | |||
3210 | for (auto &P : I->second) | |||
3211 | if (isInSchedulingRegion(P.second)) | |||
3212 | Action(P.second); | |||
3213 | } | |||
3214 | ||||
3215 | /// Put all instructions into the ReadyList which are ready for scheduling. | |||
3216 | template <typename ReadyListType> | |||
3217 | void initialFillReadyList(ReadyListType &ReadyList) { | |||
3218 | for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { | |||
3219 | doForAllOpcodes(I, [&](ScheduleData *SD) { | |||
3220 | if (SD->isSchedulingEntity() && SD->hasValidDependencies() && | |||
3221 | SD->isReady()) { | |||
3222 | ReadyList.insert(SD); | |||
3223 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: initially in ready list: " << *SD << "\n"; } } while (false) | |||
3224 | << "SLP: initially in ready list: " << *SD << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: initially in ready list: " << *SD << "\n"; } } while (false); | |||
3225 | } | |||
3226 | }); | |||
3227 | } | |||
3228 | } | |||
3229 | ||||
3230 | /// Build a bundle from the ScheduleData nodes corresponding to the | |||
3231 | /// scalar instruction for each lane. | |||
3232 | ScheduleData *buildBundle(ArrayRef<Value *> VL); | |||
3233 | ||||
3234 | /// Checks if a bundle of instructions can be scheduled, i.e. has no | |||
3235 | /// cyclic dependencies. This is only a dry-run, no instructions are | |||
3236 | /// actually moved at this stage. | |||
3237 | /// \returns the scheduling bundle. The returned Optional value is non-None | |||
3238 | /// if \p VL is allowed to be scheduled. | |||
3239 | Optional<ScheduleData *> | |||
3240 | tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, | |||
3241 | const InstructionsState &S); | |||
3242 | ||||
3243 | /// Un-bundles a group of instructions. | |||
3244 | void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); | |||
3245 | ||||
3246 | /// Allocates schedule data chunk. | |||
3247 | ScheduleData *allocateScheduleDataChunks(); | |||
3248 | ||||
3249 | /// Extends the scheduling region so that V is inside the region. | |||
3250 | /// \returns true if the region size is within the limit. | |||
3251 | bool extendSchedulingRegion(Value *V, const InstructionsState &S); | |||
3252 | ||||
3253 | /// Initialize the ScheduleData structures for new instructions in the | |||
3254 | /// scheduling region. | |||
3255 | void initScheduleData(Instruction *FromI, Instruction *ToI, | |||
3256 | ScheduleData *PrevLoadStore, | |||
3257 | ScheduleData *NextLoadStore); | |||
3258 | ||||
3259 | /// Updates the dependency information of a bundle and of all instructions/ | |||
3260 | /// bundles which depend on the original bundle. | |||
3261 | void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, | |||
3262 | BoUpSLP *SLP); | |||
3263 | ||||
3264 | /// Sets all instruction in the scheduling region to un-scheduled. | |||
3265 | void resetSchedule(); | |||
3266 | ||||
3267 | BasicBlock *BB; | |||
3268 | ||||
3269 | /// Simple memory allocation for ScheduleData. | |||
3270 | std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; | |||
3271 | ||||
3272 | /// The size of a ScheduleData array in ScheduleDataChunks. | |||
3273 | int ChunkSize; | |||
3274 | ||||
3275 | /// The allocator position in the current chunk, which is the last entry | |||
3276 | /// of ScheduleDataChunks. | |||
3277 | int ChunkPos; | |||
3278 | ||||
3279 | /// Attaches ScheduleData to Instruction. | |||
3280 | /// Note that the mapping survives during all vectorization iterations, i.e. | |||
3281 | /// ScheduleData structures are recycled. | |||
3282 | DenseMap<Instruction *, ScheduleData *> ScheduleDataMap; | |||
3283 | ||||
3284 | /// Attaches ScheduleData to Instruction with the leading key. | |||
3285 | DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> | |||
3286 | ExtraScheduleDataMap; | |||
3287 | ||||
3288 | /// The ready-list for scheduling (only used for the dry-run). | |||
3289 | SetVector<ScheduleData *> ReadyInsts; | |||
3290 | ||||
3291 | /// The first instruction of the scheduling region. | |||
3292 | Instruction *ScheduleStart = nullptr; | |||
3293 | ||||
3294 | /// The first instruction _after_ the scheduling region. | |||
3295 | Instruction *ScheduleEnd = nullptr; | |||
3296 | ||||
3297 | /// The first memory accessing instruction in the scheduling region | |||
3298 | /// (can be null). | |||
3299 | ScheduleData *FirstLoadStoreInRegion = nullptr; | |||
3300 | ||||
3301 | /// The last memory accessing instruction in the scheduling region | |||
3302 | /// (can be null). | |||
3303 | ScheduleData *LastLoadStoreInRegion = nullptr; | |||
3304 | ||||
3305 | /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling | |||
3306 | /// region? Used to optimize the dependence calculation for the | |||
3307 | /// common case where there isn't. | |||
3308 | bool RegionHasStackSave = false; | |||
3309 | ||||
3310 | /// The current size of the scheduling region. | |||
3311 | int ScheduleRegionSize = 0; | |||
3312 | ||||
3313 | /// The maximum size allowed for the scheduling region. | |||
3314 | int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; | |||
3315 | ||||
3316 | /// The ID of the scheduling region. For a new vectorization iteration this | |||
3317 | /// is incremented which "removes" all ScheduleData from the region. | |||
3318 | /// Make sure that the initial SchedulingRegionID is greater than the | |||
3319 | /// initial SchedulingRegionID in ScheduleData (which is 0). | |||
3320 | int SchedulingRegionID = 1; | |||
3321 | }; | |||
3322 | ||||
3323 | /// Attaches the BlockScheduling structures to basic blocks. | |||
3324 | MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; | |||
3325 | ||||
3326 | /// Performs the "real" scheduling. Done before vectorization is actually | |||
3327 | /// performed in a basic block. | |||
3328 | void scheduleBlock(BlockScheduling *BS); | |||
3329 | ||||
3330 | /// List of users to ignore during scheduling and that don't need extracting. | |||
3331 | const SmallDenseSet<Value *> *UserIgnoreList = nullptr; | |||
3332 | ||||
3333 | /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of | |||
3334 | /// sorted SmallVectors of unsigned. | |||
3335 | struct OrdersTypeDenseMapInfo { | |||
3336 | static OrdersType getEmptyKey() { | |||
3337 | OrdersType V; | |||
3338 | V.push_back(~1U); | |||
3339 | return V; | |||
3340 | } | |||
3341 | ||||
3342 | static OrdersType getTombstoneKey() { | |||
3343 | OrdersType V; | |||
3344 | V.push_back(~2U); | |||
3345 | return V; | |||
3346 | } | |||
3347 | ||||
3348 | static unsigned getHashValue(const OrdersType &V) { | |||
3349 | return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); | |||
3350 | } | |||
3351 | ||||
3352 | static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { | |||
3353 | return LHS == RHS; | |||
3354 | } | |||
3355 | }; | |||
3356 | ||||
3357 | // Analysis and block reference. | |||
3358 | Function *F; | |||
3359 | ScalarEvolution *SE; | |||
3360 | TargetTransformInfo *TTI; | |||
3361 | TargetLibraryInfo *TLI; | |||
3362 | LoopInfo *LI; | |||
3363 | DominatorTree *DT; | |||
3364 | AssumptionCache *AC; | |||
3365 | DemandedBits *DB; | |||
3366 | const DataLayout *DL; | |||
3367 | OptimizationRemarkEmitter *ORE; | |||
3368 | ||||
3369 | unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. | |||
3370 | unsigned MinVecRegSize; // Set by cl::opt (default: 128). | |||
3371 | ||||
3372 | /// Instruction builder to construct the vectorized tree. | |||
3373 | IRBuilder<> Builder; | |||
3374 | ||||
3375 | /// A map of scalar integer values to the smallest bit width with which they | |||
3376 | /// can legally be represented. The values map to (width, signed) pairs, | |||
3377 | /// where "width" indicates the minimum bit width and "signed" is True if the | |||
3378 | /// value must be signed-extended, rather than zero-extended, back to its | |||
3379 | /// original width. | |||
3380 | MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; | |||
3381 | }; | |||
3382 | ||||
3383 | } // end namespace slpvectorizer | |||
3384 | ||||
3385 | template <> struct GraphTraits<BoUpSLP *> { | |||
3386 | using TreeEntry = BoUpSLP::TreeEntry; | |||
3387 | ||||
3388 | /// NodeRef has to be a pointer per the GraphWriter. | |||
3389 | using NodeRef = TreeEntry *; | |||
3390 | ||||
3391 | using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; | |||
3392 | ||||
3393 | /// Add the VectorizableTree to the index iterator to be able to return | |||
3394 | /// TreeEntry pointers. | |||
3395 | struct ChildIteratorType | |||
3396 | : public iterator_adaptor_base< | |||
3397 | ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { | |||
3398 | ContainerTy &VectorizableTree; | |||
3399 | ||||
3400 | ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, | |||
3401 | ContainerTy &VT) | |||
3402 | : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} | |||
3403 | ||||
3404 | NodeRef operator*() { return I->UserTE; } | |||
3405 | }; | |||
3406 | ||||
3407 | static NodeRef getEntryNode(BoUpSLP &R) { | |||
3408 | return R.VectorizableTree[0].get(); | |||
3409 | } | |||
3410 | ||||
3411 | static ChildIteratorType child_begin(NodeRef N) { | |||
3412 | return {N->UserTreeIndices.begin(), N->Container}; | |||
3413 | } | |||
3414 | ||||
3415 | static ChildIteratorType child_end(NodeRef N) { | |||
3416 | return {N->UserTreeIndices.end(), N->Container}; | |||
3417 | } | |||
3418 | ||||
3419 | /// For the node iterator we just need to turn the TreeEntry iterator into a | |||
3420 | /// TreeEntry* iterator so that it dereferences to NodeRef. | |||
3421 | class nodes_iterator { | |||
3422 | using ItTy = ContainerTy::iterator; | |||
3423 | ItTy It; | |||
3424 | ||||
3425 | public: | |||
3426 | nodes_iterator(const ItTy &It2) : It(It2) {} | |||
3427 | NodeRef operator*() { return It->get(); } | |||
3428 | nodes_iterator operator++() { | |||
3429 | ++It; | |||
3430 | return *this; | |||
3431 | } | |||
3432 | bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } | |||
3433 | }; | |||
3434 | ||||
3435 | static nodes_iterator nodes_begin(BoUpSLP *R) { | |||
3436 | return nodes_iterator(R->VectorizableTree.begin()); | |||
3437 | } | |||
3438 | ||||
3439 | static nodes_iterator nodes_end(BoUpSLP *R) { | |||
3440 | return nodes_iterator(R->VectorizableTree.end()); | |||
3441 | } | |||
3442 | ||||
3443 | static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } | |||
3444 | }; | |||
3445 | ||||
3446 | template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { | |||
3447 | using TreeEntry = BoUpSLP::TreeEntry; | |||
3448 | ||||
3449 | DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} | |||
3450 | ||||
3451 | std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { | |||
3452 | std::string Str; | |||
3453 | raw_string_ostream OS(Str); | |||
3454 | if (isSplat(Entry->Scalars)) | |||
3455 | OS << "<splat> "; | |||
3456 | for (auto *V : Entry->Scalars) { | |||
3457 | OS << *V; | |||
3458 | if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { | |||
3459 | return EU.Scalar == V; | |||
3460 | })) | |||
3461 | OS << " <extract>"; | |||
3462 | OS << "\n"; | |||
3463 | } | |||
3464 | return Str; | |||
3465 | } | |||
3466 | ||||
3467 | static std::string getNodeAttributes(const TreeEntry *Entry, | |||
3468 | const BoUpSLP *) { | |||
3469 | if (Entry->State == TreeEntry::NeedToGather) | |||
3470 | return "color=red"; | |||
3471 | return ""; | |||
3472 | } | |||
3473 | }; | |||
3474 | ||||
3475 | } // end namespace llvm | |||
3476 | ||||
3477 | BoUpSLP::~BoUpSLP() { | |||
3478 | SmallVector<WeakTrackingVH> DeadInsts; | |||
3479 | for (auto *I : DeletedInstructions) { | |||
3480 | for (Use &U : I->operands()) { | |||
3481 | auto *Op = dyn_cast<Instruction>(U.get()); | |||
3482 | if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() && | |||
3483 | wouldInstructionBeTriviallyDead(Op, TLI)) | |||
3484 | DeadInsts.emplace_back(Op); | |||
3485 | } | |||
3486 | I->dropAllReferences(); | |||
3487 | } | |||
3488 | for (auto *I : DeletedInstructions) { | |||
3489 | assert(I->use_empty() &&(static_cast <bool> (I->use_empty() && "trying to erase instruction with users." ) ? void (0) : __assert_fail ("I->use_empty() && \"trying to erase instruction with users.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3490, __extension__ __PRETTY_FUNCTION__)) | |||
3490 | "trying to erase instruction with users.")(static_cast <bool> (I->use_empty() && "trying to erase instruction with users." ) ? void (0) : __assert_fail ("I->use_empty() && \"trying to erase instruction with users.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3490, __extension__ __PRETTY_FUNCTION__)); | |||
3491 | I->eraseFromParent(); | |||
3492 | } | |||
3493 | ||||
3494 | // Cleanup any dead scalar code feeding the vectorized instructions | |||
3495 | RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI); | |||
3496 | ||||
3497 | #ifdef EXPENSIVE_CHECKS | |||
3498 | // If we could guarantee that this call is not extremely slow, we could | |||
3499 | // remove the ifdef limitation (see PR47712). | |||
3500 | assert(!verifyFunction(*F, &dbgs()))(static_cast <bool> (!verifyFunction(*F, &dbgs())) ? void (0) : __assert_fail ("!verifyFunction(*F, &dbgs())" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3500, __extension__ __PRETTY_FUNCTION__)); | |||
3501 | #endif | |||
3502 | } | |||
3503 | ||||
3504 | /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses | |||
3505 | /// contains original mask for the scalars reused in the node. Procedure | |||
3506 | /// transform this mask in accordance with the given \p Mask. | |||
3507 | static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { | |||
3508 | assert(!Mask.empty() && Reuses.size() == Mask.size() &&(static_cast <bool> (!Mask.empty() && Reuses.size () == Mask.size() && "Expected non-empty mask.") ? void (0) : __assert_fail ("!Mask.empty() && Reuses.size() == Mask.size() && \"Expected non-empty mask.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3509, __extension__ __PRETTY_FUNCTION__)) | |||
3509 | "Expected non-empty mask.")(static_cast <bool> (!Mask.empty() && Reuses.size () == Mask.size() && "Expected non-empty mask.") ? void (0) : __assert_fail ("!Mask.empty() && Reuses.size() == Mask.size() && \"Expected non-empty mask.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3509, __extension__ __PRETTY_FUNCTION__)); | |||
3510 | SmallVector<int> Prev(Reuses.begin(), Reuses.end()); | |||
3511 | Prev.swap(Reuses); | |||
3512 | for (unsigned I = 0, E = Prev.size(); I < E; ++I) | |||
3513 | if (Mask[I] != UndefMaskElem) | |||
3514 | Reuses[Mask[I]] = Prev[I]; | |||
3515 | } | |||
3516 | ||||
3517 | /// Reorders the given \p Order according to the given \p Mask. \p Order - is | |||
3518 | /// the original order of the scalars. Procedure transforms the provided order | |||
3519 | /// in accordance with the given \p Mask. If the resulting \p Order is just an | |||
3520 | /// identity order, \p Order is cleared. | |||
3521 | static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { | |||
3522 | assert(!Mask.empty() && "Expected non-empty mask.")(static_cast <bool> (!Mask.empty() && "Expected non-empty mask." ) ? void (0) : __assert_fail ("!Mask.empty() && \"Expected non-empty mask.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3522, __extension__ __PRETTY_FUNCTION__)); | |||
3523 | SmallVector<int> MaskOrder; | |||
3524 | if (Order.empty()) { | |||
3525 | MaskOrder.resize(Mask.size()); | |||
3526 | std::iota(MaskOrder.begin(), MaskOrder.end(), 0); | |||
3527 | } else { | |||
3528 | inversePermutation(Order, MaskOrder); | |||
3529 | } | |||
3530 | reorderReuses(MaskOrder, Mask); | |||
3531 | if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { | |||
3532 | Order.clear(); | |||
3533 | return; | |||
3534 | } | |||
3535 | Order.assign(Mask.size(), Mask.size()); | |||
3536 | for (unsigned I = 0, E = Mask.size(); I < E; ++I) | |||
3537 | if (MaskOrder[I] != UndefMaskElem) | |||
3538 | Order[MaskOrder[I]] = I; | |||
3539 | fixupOrderingIndices(Order); | |||
3540 | } | |||
3541 | ||||
3542 | Optional<BoUpSLP::OrdersType> | |||
3543 | BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { | |||
3544 | assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.")(static_cast <bool> (TE.State == TreeEntry::NeedToGather && "Expected gather node only.") ? void (0) : __assert_fail ("TE.State == TreeEntry::NeedToGather && \"Expected gather node only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3544, __extension__ __PRETTY_FUNCTION__)); | |||
3545 | unsigned NumScalars = TE.Scalars.size(); | |||
3546 | OrdersType CurrentOrder(NumScalars, NumScalars); | |||
3547 | SmallVector<int> Positions; | |||
3548 | SmallBitVector UsedPositions(NumScalars); | |||
3549 | const TreeEntry *STE = nullptr; | |||
3550 | // Try to find all gathered scalars that are gets vectorized in other | |||
3551 | // vectorize node. Here we can have only one single tree vector node to | |||
3552 | // correctly identify order of the gathered scalars. | |||
3553 | for (unsigned I = 0; I < NumScalars; ++I) { | |||
3554 | Value *V = TE.Scalars[I]; | |||
3555 | if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) | |||
3556 | continue; | |||
3557 | if (const auto *LocalSTE = getTreeEntry(V)) { | |||
3558 | if (!STE) | |||
3559 | STE = LocalSTE; | |||
3560 | else if (STE != LocalSTE) | |||
3561 | // Take the order only from the single vector node. | |||
3562 | return None; | |||
3563 | unsigned Lane = | |||
3564 | std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); | |||
3565 | if (Lane >= NumScalars) | |||
3566 | return None; | |||
3567 | if (CurrentOrder[Lane] != NumScalars) { | |||
3568 | if (Lane != I) | |||
3569 | continue; | |||
3570 | UsedPositions.reset(CurrentOrder[Lane]); | |||
3571 | } | |||
3572 | // The partial identity (where only some elements of the gather node are | |||
3573 | // in the identity order) is good. | |||
3574 | CurrentOrder[Lane] = I; | |||
3575 | UsedPositions.set(I); | |||
3576 | } | |||
3577 | } | |||
3578 | // Need to keep the order if we have a vector entry and at least 2 scalars or | |||
3579 | // the vectorized entry has just 2 scalars. | |||
3580 | if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { | |||
3581 | auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { | |||
3582 | for (unsigned I = 0; I < NumScalars; ++I) | |||
3583 | if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) | |||
3584 | return false; | |||
3585 | return true; | |||
3586 | }; | |||
3587 | if (IsIdentityOrder(CurrentOrder)) { | |||
3588 | CurrentOrder.clear(); | |||
3589 | return CurrentOrder; | |||
3590 | } | |||
3591 | auto *It = CurrentOrder.begin(); | |||
3592 | for (unsigned I = 0; I < NumScalars;) { | |||
3593 | if (UsedPositions.test(I)) { | |||
3594 | ++I; | |||
3595 | continue; | |||
3596 | } | |||
3597 | if (*It == NumScalars) { | |||
3598 | *It = I; | |||
3599 | ++I; | |||
3600 | } | |||
3601 | ++It; | |||
3602 | } | |||
3603 | return CurrentOrder; | |||
3604 | } | |||
3605 | return None; | |||
3606 | } | |||
3607 | ||||
3608 | namespace { | |||
3609 | /// Tracks the state we can represent the loads in the given sequence. | |||
3610 | enum class LoadsState { Gather, Vectorize, ScatterVectorize }; | |||
3611 | } // anonymous namespace | |||
3612 | ||||
3613 | static bool arePointersCompatible(Value *Ptr1, Value *Ptr2, | |||
3614 | const TargetLibraryInfo &TLI, | |||
3615 | bool CompareOpcodes = true) { | |||
3616 | if (getUnderlyingObject(Ptr1) != getUnderlyingObject(Ptr2)) | |||
3617 | return false; | |||
3618 | auto *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1); | |||
3619 | if (!GEP1) | |||
3620 | return false; | |||
3621 | auto *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2); | |||
3622 | if (!GEP2) | |||
3623 | return false; | |||
3624 | return GEP1->getNumOperands() == 2 && GEP2->getNumOperands() == 2 && | |||
3625 | ((isConstant(GEP1->getOperand(1)) && | |||
3626 | isConstant(GEP2->getOperand(1))) || | |||
3627 | !CompareOpcodes || | |||
3628 | getSameOpcode({GEP1->getOperand(1), GEP2->getOperand(1)}, TLI) | |||
3629 | .getOpcode()); | |||
3630 | } | |||
3631 | ||||
3632 | /// Checks if the given array of loads can be represented as a vectorized, | |||
3633 | /// scatter or just simple gather. | |||
3634 | static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, | |||
3635 | const TargetTransformInfo &TTI, | |||
3636 | const DataLayout &DL, ScalarEvolution &SE, | |||
3637 | LoopInfo &LI, const TargetLibraryInfo &TLI, | |||
3638 | SmallVectorImpl<unsigned> &Order, | |||
3639 | SmallVectorImpl<Value *> &PointerOps) { | |||
3640 | // Check that a vectorized load would load the same memory as a scalar | |||
3641 | // load. For example, we don't want to vectorize loads that are smaller | |||
3642 | // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM | |||
3643 | // treats loading/storing it as an i8 struct. If we vectorize loads/stores | |||
3644 | // from such a struct, we read/write packed bits disagreeing with the | |||
3645 | // unvectorized version. | |||
3646 | Type *ScalarTy = VL0->getType(); | |||
3647 | ||||
3648 | if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) | |||
3649 | return LoadsState::Gather; | |||
3650 | ||||
3651 | // Make sure all loads in the bundle are simple - we can't vectorize | |||
3652 | // atomic or volatile loads. | |||
3653 | PointerOps.clear(); | |||
3654 | PointerOps.resize(VL.size()); | |||
3655 | auto *POIter = PointerOps.begin(); | |||
3656 | for (Value *V : VL) { | |||
3657 | auto *L = cast<LoadInst>(V); | |||
3658 | if (!L->isSimple()) | |||
3659 | return LoadsState::Gather; | |||
3660 | *POIter = L->getPointerOperand(); | |||
3661 | ++POIter; | |||
3662 | } | |||
3663 | ||||
3664 | Order.clear(); | |||
3665 | // Check the order of pointer operands or that all pointers are the same. | |||
3666 | bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order); | |||
3667 | if (IsSorted || all_of(PointerOps, [&](Value *P) { | |||
3668 | return arePointersCompatible(P, PointerOps.front(), TLI); | |||
3669 | })) { | |||
3670 | if (IsSorted) { | |||
3671 | Value *Ptr0; | |||
3672 | Value *PtrN; | |||
3673 | if (Order.empty()) { | |||
3674 | Ptr0 = PointerOps.front(); | |||
3675 | PtrN = PointerOps.back(); | |||
3676 | } else { | |||
3677 | Ptr0 = PointerOps[Order.front()]; | |||
3678 | PtrN = PointerOps[Order.back()]; | |||
3679 | } | |||
3680 | Optional<int> Diff = | |||
3681 | getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); | |||
3682 | // Check that the sorted loads are consecutive. | |||
3683 | if (static_cast<unsigned>(*Diff) == VL.size() - 1) | |||
3684 | return LoadsState::Vectorize; | |||
3685 | } | |||
3686 | // TODO: need to improve analysis of the pointers, if not all of them are | |||
3687 | // GEPs or have > 2 operands, we end up with a gather node, which just | |||
3688 | // increases the cost. | |||
3689 | Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent()); | |||
3690 | bool ProfitableGatherPointers = | |||
3691 | static_cast<unsigned>(count_if(PointerOps, [L](Value *V) { | |||
3692 | return L && L->isLoopInvariant(V); | |||
3693 | })) <= VL.size() / 2 && VL.size() > 2; | |||
3694 | if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) { | |||
3695 | auto *GEP = dyn_cast<GetElementPtrInst>(P); | |||
3696 | return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) || | |||
3697 | (GEP && GEP->getNumOperands() == 2); | |||
3698 | })) { | |||
3699 | Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); | |||
3700 | for (Value *V : VL) | |||
3701 | CommonAlignment = | |||
3702 | std::min(CommonAlignment, cast<LoadInst>(V)->getAlign()); | |||
3703 | auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); | |||
3704 | if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) && | |||
3705 | !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment)) | |||
3706 | return LoadsState::ScatterVectorize; | |||
3707 | } | |||
3708 | } | |||
3709 | ||||
3710 | return LoadsState::Gather; | |||
3711 | } | |||
3712 | ||||
3713 | bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, | |||
3714 | const DataLayout &DL, ScalarEvolution &SE, | |||
3715 | SmallVectorImpl<unsigned> &SortedIndices) { | |||
3716 | assert(llvm::all_of((static_cast <bool> (llvm::all_of( VL, [](const Value * V) { return V->getType()->isPointerTy(); }) && "Expected list of pointer operands." ) ? void (0) : __assert_fail ("llvm::all_of( VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && \"Expected list of pointer operands.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3718, __extension__ __PRETTY_FUNCTION__)) | |||
3717 | VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&(static_cast <bool> (llvm::all_of( VL, [](const Value * V) { return V->getType()->isPointerTy(); }) && "Expected list of pointer operands." ) ? void (0) : __assert_fail ("llvm::all_of( VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && \"Expected list of pointer operands.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3718, __extension__ __PRETTY_FUNCTION__)) | |||
3718 | "Expected list of pointer operands.")(static_cast <bool> (llvm::all_of( VL, [](const Value * V) { return V->getType()->isPointerTy(); }) && "Expected list of pointer operands." ) ? void (0) : __assert_fail ("llvm::all_of( VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && \"Expected list of pointer operands.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3718, __extension__ __PRETTY_FUNCTION__)); | |||
3719 | // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each | |||
3720 | // Ptr into, sort and return the sorted indices with values next to one | |||
3721 | // another. | |||
3722 | MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases; | |||
3723 | Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U)); | |||
3724 | ||||
3725 | unsigned Cnt = 1; | |||
3726 | for (Value *Ptr : VL.drop_front()) { | |||
3727 | bool Found = any_of(Bases, [&](auto &Base) { | |||
3728 | Optional<int> Diff = | |||
3729 | getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE, | |||
3730 | /*StrictCheck=*/true); | |||
3731 | if (!Diff) | |||
3732 | return false; | |||
3733 | ||||
3734 | Base.second.emplace_back(Ptr, *Diff, Cnt++); | |||
3735 | return true; | |||
3736 | }); | |||
3737 | ||||
3738 | if (!Found) { | |||
3739 | // If we haven't found enough to usefully cluster, return early. | |||
3740 | if (Bases.size() > VL.size() / 2 - 1) | |||
3741 | return false; | |||
3742 | ||||
3743 | // Not found already - add a new Base | |||
3744 | Bases[Ptr].emplace_back(Ptr, 0, Cnt++); | |||
3745 | } | |||
3746 | } | |||
3747 | ||||
3748 | // For each of the bases sort the pointers by Offset and check if any of the | |||
3749 | // base become consecutively allocated. | |||
3750 | bool AnyConsecutive = false; | |||
3751 | for (auto &Base : Bases) { | |||
3752 | auto &Vec = Base.second; | |||
3753 | if (Vec.size() > 1) { | |||
3754 | llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X, | |||
3755 | const std::tuple<Value *, int, unsigned> &Y) { | |||
3756 | return std::get<1>(X) < std::get<1>(Y); | |||
3757 | }); | |||
3758 | int InitialOffset = std::get<1>(Vec[0]); | |||
3759 | AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) { | |||
3760 | return std::get<1>(P.value()) == int(P.index()) + InitialOffset; | |||
3761 | }); | |||
3762 | } | |||
3763 | } | |||
3764 | ||||
3765 | // Fill SortedIndices array only if it looks worth-while to sort the ptrs. | |||
3766 | SortedIndices.clear(); | |||
3767 | if (!AnyConsecutive) | |||
3768 | return false; | |||
3769 | ||||
3770 | for (auto &Base : Bases) { | |||
3771 | for (auto &T : Base.second) | |||
3772 | SortedIndices.push_back(std::get<2>(T)); | |||
3773 | } | |||
3774 | ||||
3775 | assert(SortedIndices.size() == VL.size() &&(static_cast <bool> (SortedIndices.size() == VL.size() && "Expected SortedIndices to be the size of VL") ? void (0) : __assert_fail ("SortedIndices.size() == VL.size() && \"Expected SortedIndices to be the size of VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3776, __extension__ __PRETTY_FUNCTION__)) | |||
3776 | "Expected SortedIndices to be the size of VL")(static_cast <bool> (SortedIndices.size() == VL.size() && "Expected SortedIndices to be the size of VL") ? void (0) : __assert_fail ("SortedIndices.size() == VL.size() && \"Expected SortedIndices to be the size of VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3776, __extension__ __PRETTY_FUNCTION__)); | |||
3777 | return true; | |||
3778 | } | |||
3779 | ||||
3780 | Optional<BoUpSLP::OrdersType> | |||
3781 | BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) { | |||
3782 | assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.")(static_cast <bool> (TE.State == TreeEntry::NeedToGather && "Expected gather node only.") ? void (0) : __assert_fail ("TE.State == TreeEntry::NeedToGather && \"Expected gather node only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 3782, __extension__ __PRETTY_FUNCTION__)); | |||
3783 | Type *ScalarTy = TE.Scalars[0]->getType(); | |||
3784 | ||||
3785 | SmallVector<Value *> Ptrs; | |||
3786 | Ptrs.reserve(TE.Scalars.size()); | |||
3787 | for (Value *V : TE.Scalars) { | |||
3788 | auto *L = dyn_cast<LoadInst>(V); | |||
3789 | if (!L || !L->isSimple()) | |||
3790 | return None; | |||
3791 | Ptrs.push_back(L->getPointerOperand()); | |||
3792 | } | |||
3793 | ||||
3794 | BoUpSLP::OrdersType Order; | |||
3795 | if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order)) | |||
3796 | return Order; | |||
3797 | return None; | |||
3798 | } | |||
3799 | ||||
3800 | /// Check if two insertelement instructions are from the same buildvector. | |||
3801 | static bool areTwoInsertFromSameBuildVector( | |||
3802 | InsertElementInst *VU, InsertElementInst *V, | |||
3803 | function_ref<Value *(InsertElementInst *)> GetBaseOperand) { | |||
3804 | // Instructions must be from the same basic blocks. | |||
3805 | if (VU->getParent() != V->getParent()) | |||
3806 | return false; | |||
3807 | // Checks if 2 insertelements are from the same buildvector. | |||
3808 | if (VU->getType() != V->getType()) | |||
3809 | return false; | |||
3810 | // Multiple used inserts are separate nodes. | |||
3811 | if (!VU->hasOneUse() && !V->hasOneUse()) | |||
3812 | return false; | |||
3813 | auto *IE1 = VU; | |||
3814 | auto *IE2 = V; | |||
3815 | Optional<unsigned> Idx1 = getInsertIndex(IE1); | |||
3816 | Optional<unsigned> Idx2 = getInsertIndex(IE2); | |||
3817 | if (Idx1 == None || Idx2 == None) | |||
3818 | return false; | |||
3819 | // Go through the vector operand of insertelement instructions trying to find | |||
3820 | // either VU as the original vector for IE2 or V as the original vector for | |||
3821 | // IE1. | |||
3822 | do { | |||
3823 | if (IE2 == VU) | |||
3824 | return VU->hasOneUse(); | |||
3825 | if (IE1 == V) | |||
3826 | return V->hasOneUse(); | |||
3827 | if (IE1) { | |||
3828 | if ((IE1 != VU && !IE1->hasOneUse()) || | |||
3829 | getInsertIndex(IE1).value_or(*Idx2) == *Idx2) | |||
3830 | IE1 = nullptr; | |||
3831 | else | |||
3832 | IE1 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE1)); | |||
3833 | } | |||
3834 | if (IE2) { | |||
3835 | if ((IE2 != V && !IE2->hasOneUse()) || | |||
3836 | getInsertIndex(IE2).value_or(*Idx1) == *Idx1) | |||
3837 | IE2 = nullptr; | |||
3838 | else | |||
3839 | IE2 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE2)); | |||
3840 | } | |||
3841 | } while (IE1 || IE2); | |||
3842 | return false; | |||
3843 | } | |||
3844 | ||||
3845 | Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, | |||
3846 | bool TopToBottom) { | |||
3847 | // No need to reorder if need to shuffle reuses, still need to shuffle the | |||
3848 | // node. | |||
3849 | if (!TE.ReuseShuffleIndices.empty()) { | |||
3850 | // Check if reuse shuffle indices can be improved by reordering. | |||
3851 | // For this, check that reuse mask is "clustered", i.e. each scalar values | |||
3852 | // is used once in each submask of size <number_of_scalars>. | |||
3853 | // Example: 4 scalar values. | |||
3854 | // ReuseShuffleIndices mask: 0, 1, 2, 3, 3, 2, 0, 1 - clustered. | |||
3855 | // 0, 1, 2, 3, 3, 3, 1, 0 - not clustered, because | |||
3856 | // element 3 is used twice in the second submask. | |||
3857 | unsigned Sz = TE.Scalars.size(); | |||
3858 | if (!ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices, | |||
3859 | Sz)) | |||
3860 | return None; | |||
3861 | unsigned VF = TE.getVectorFactor(); | |||
3862 | // Try build correct order for extractelement instructions. | |||
3863 | SmallVector<int> ReusedMask(TE.ReuseShuffleIndices.begin(), | |||
3864 | TE.ReuseShuffleIndices.end()); | |||
3865 | if (TE.getOpcode() == Instruction::ExtractElement && !TE.isAltShuffle() && | |||
3866 | all_of(TE.Scalars, [Sz](Value *V) { | |||
3867 | Optional<unsigned> Idx = getExtractIndex(cast<Instruction>(V)); | |||
3868 | return Idx && *Idx < Sz; | |||
3869 | })) { | |||
3870 | SmallVector<int> ReorderMask(Sz, UndefMaskElem); | |||
3871 | if (TE.ReorderIndices.empty()) | |||
3872 | std::iota(ReorderMask.begin(), ReorderMask.end(), 0); | |||
3873 | else | |||
3874 | inversePermutation(TE.ReorderIndices, ReorderMask); | |||
3875 | for (unsigned I = 0; I < VF; ++I) { | |||
3876 | int &Idx = ReusedMask[I]; | |||
3877 | if (Idx == UndefMaskElem) | |||
3878 | continue; | |||
3879 | Value *V = TE.Scalars[ReorderMask[Idx]]; | |||
3880 | Optional<unsigned> EI = getExtractIndex(cast<Instruction>(V)); | |||
3881 | Idx = std::distance(ReorderMask.begin(), find(ReorderMask, *EI)); | |||
3882 | } | |||
3883 | } | |||
3884 | // Build the order of the VF size, need to reorder reuses shuffles, they are | |||
3885 | // always of VF size. | |||
3886 | OrdersType ResOrder(VF); | |||
3887 | std::iota(ResOrder.begin(), ResOrder.end(), 0); | |||
3888 | auto *It = ResOrder.begin(); | |||
3889 | for (unsigned K = 0; K < VF; K += Sz) { | |||
3890 | OrdersType CurrentOrder(TE.ReorderIndices); | |||
3891 | SmallVector<int> SubMask(makeArrayRef(ReusedMask).slice(K, Sz)); | |||
3892 | if (SubMask.front() == UndefMaskElem) | |||
3893 | std::iota(SubMask.begin(), SubMask.end(), 0); | |||
3894 | reorderOrder(CurrentOrder, SubMask); | |||
3895 | transform(CurrentOrder, It, [K](unsigned Pos) { return Pos + K; }); | |||
3896 | std::advance(It, Sz); | |||
3897 | } | |||
3898 | if (all_of(enumerate(ResOrder), | |||
3899 | [](const auto &Data) { return Data.index() == Data.value(); })) | |||
3900 | return {}; // Use identity order. | |||
3901 | return ResOrder; | |||
3902 | } | |||
3903 | if (TE.State == TreeEntry::Vectorize && | |||
3904 | (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || | |||
3905 | (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && | |||
3906 | !TE.isAltShuffle()) | |||
3907 | return TE.ReorderIndices; | |||
3908 | if (TE.State == TreeEntry::Vectorize && TE.getOpcode() == Instruction::PHI) { | |||
3909 | auto PHICompare = [](llvm::Value *V1, llvm::Value *V2) { | |||
3910 | if (!V1->hasOneUse() || !V2->hasOneUse()) | |||
3911 | return false; | |||
3912 | auto *FirstUserOfPhi1 = cast<Instruction>(*V1->user_begin()); | |||
3913 | auto *FirstUserOfPhi2 = cast<Instruction>(*V2->user_begin()); | |||
3914 | if (auto *IE1 = dyn_cast<InsertElementInst>(FirstUserOfPhi1)) | |||
3915 | if (auto *IE2 = dyn_cast<InsertElementInst>(FirstUserOfPhi2)) { | |||
3916 | if (!areTwoInsertFromSameBuildVector( | |||
3917 | IE1, IE2, | |||
3918 | [](InsertElementInst *II) { return II->getOperand(0); })) | |||
3919 | return false; | |||
3920 | Optional<unsigned> Idx1 = getInsertIndex(IE1); | |||
3921 | Optional<unsigned> Idx2 = getInsertIndex(IE2); | |||
3922 | if (Idx1 == None || Idx2 == None) | |||
3923 | return false; | |||
3924 | return *Idx1 < *Idx2; | |||
3925 | } | |||
3926 | if (auto *EE1 = dyn_cast<ExtractElementInst>(FirstUserOfPhi1)) | |||
3927 | if (auto *EE2 = dyn_cast<ExtractElementInst>(FirstUserOfPhi2)) { | |||
3928 | if (EE1->getOperand(0) != EE2->getOperand(0)) | |||
3929 | return false; | |||
3930 | Optional<unsigned> Idx1 = getExtractIndex(EE1); | |||
3931 | Optional<unsigned> Idx2 = getExtractIndex(EE2); | |||
3932 | if (Idx1 == None || Idx2 == None) | |||
3933 | return false; | |||
3934 | return *Idx1 < *Idx2; | |||
3935 | } | |||
3936 | return false; | |||
3937 | }; | |||
3938 | auto IsIdentityOrder = [](const OrdersType &Order) { | |||
3939 | for (unsigned Idx : seq<unsigned>(0, Order.size())) | |||
3940 | if (Idx != Order[Idx]) | |||
3941 | return false; | |||
3942 | return true; | |||
3943 | }; | |||
3944 | if (!TE.ReorderIndices.empty()) | |||
3945 | return TE.ReorderIndices; | |||
3946 | DenseMap<Value *, unsigned> PhiToId; | |||
3947 | SmallVector<Value *, 4> Phis; | |||
3948 | OrdersType ResOrder(TE.Scalars.size()); | |||
3949 | for (unsigned Id = 0, Sz = TE.Scalars.size(); Id < Sz; ++Id) { | |||
3950 | PhiToId[TE.Scalars[Id]] = Id; | |||
3951 | Phis.push_back(TE.Scalars[Id]); | |||
3952 | } | |||
3953 | llvm::stable_sort(Phis, PHICompare); | |||
3954 | for (unsigned Id = 0, Sz = Phis.size(); Id < Sz; ++Id) | |||
3955 | ResOrder[Id] = PhiToId[Phis[Id]]; | |||
3956 | if (IsIdentityOrder(ResOrder)) | |||
3957 | return {}; | |||
3958 | return ResOrder; | |||
3959 | } | |||
3960 | if (TE.State == TreeEntry::NeedToGather) { | |||
3961 | // TODO: add analysis of other gather nodes with extractelement | |||
3962 | // instructions and other values/instructions, not only undefs. | |||
3963 | if (((TE.getOpcode() == Instruction::ExtractElement && | |||
3964 | !TE.isAltShuffle()) || | |||
3965 | (all_of(TE.Scalars, | |||
3966 | [](Value *V) { | |||
3967 | return isa<UndefValue, ExtractElementInst>(V); | |||
3968 | }) && | |||
3969 | any_of(TE.Scalars, | |||
3970 | [](Value *V) { return isa<ExtractElementInst>(V); }))) && | |||
3971 | all_of(TE.Scalars, | |||
3972 | [](Value *V) { | |||
3973 | auto *EE = dyn_cast<ExtractElementInst>(V); | |||
3974 | return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); | |||
3975 | }) && | |||
3976 | allSameType(TE.Scalars)) { | |||
3977 | // Check that gather of extractelements can be represented as | |||
3978 | // just a shuffle of a single vector. | |||
3979 | OrdersType CurrentOrder; | |||
3980 | bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); | |||
3981 | if (Reuse || !CurrentOrder.empty()) { | |||
3982 | if (!CurrentOrder.empty()) | |||
3983 | fixupOrderingIndices(CurrentOrder); | |||
3984 | return CurrentOrder; | |||
3985 | } | |||
3986 | } | |||
3987 | if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) | |||
3988 | return CurrentOrder; | |||
3989 | if (TE.Scalars.size() >= 4) | |||
3990 | if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE)) | |||
3991 | return Order; | |||
3992 | } | |||
3993 | return None; | |||
3994 | } | |||
3995 | ||||
3996 | /// Checks if the given mask is a "clustered" mask with the same clusters of | |||
3997 | /// size \p Sz, which are not identity submasks. | |||
3998 | static bool isRepeatedNonIdentityClusteredMask(ArrayRef<int> Mask, | |||
3999 | unsigned Sz) { | |||
4000 | ArrayRef<int> FirstCluster = Mask.slice(0, Sz); | |||
4001 | if (ShuffleVectorInst::isIdentityMask(FirstCluster)) | |||
4002 | return false; | |||
4003 | for (unsigned I = Sz, E = Mask.size(); I < E; I += Sz) { | |||
4004 | ArrayRef<int> Cluster = Mask.slice(I, Sz); | |||
4005 | if (Cluster != FirstCluster) | |||
4006 | return false; | |||
4007 | } | |||
4008 | return true; | |||
4009 | } | |||
4010 | ||||
4011 | void BoUpSLP::reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const { | |||
4012 | // For vectorized and non-clustered reused - just reorder reuses mask. | |||
4013 | const unsigned Sz = TE.Scalars.size(); | |||
4014 | if (TE.State != TreeEntry::NeedToGather || !TE.ReorderIndices.empty() || | |||
4015 | !ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices, | |||
4016 | Sz) || | |||
4017 | !isRepeatedNonIdentityClusteredMask(TE.ReuseShuffleIndices, Sz)) { | |||
4018 | reorderReuses(TE.ReuseShuffleIndices, Mask); | |||
4019 | return; | |||
4020 | } | |||
4021 | // Try to improve gathered nodes with clustered reuses, if possible. | |||
4022 | reorderScalars(TE.Scalars, makeArrayRef(TE.ReuseShuffleIndices).slice(0, Sz)); | |||
4023 | // Fill the reuses mask with the identity submasks. | |||
4024 | for (auto *It = TE.ReuseShuffleIndices.begin(), | |||
4025 | *End = TE.ReuseShuffleIndices.end(); | |||
4026 | It != End; std::advance(It, Sz)) | |||
4027 | std::iota(It, std::next(It, Sz), 0); | |||
4028 | } | |||
4029 | ||||
4030 | void BoUpSLP::reorderTopToBottom() { | |||
4031 | // Maps VF to the graph nodes. | |||
4032 | DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; | |||
4033 | // ExtractElement gather nodes which can be vectorized and need to handle | |||
4034 | // their ordering. | |||
4035 | DenseMap<const TreeEntry *, OrdersType> GathersToOrders; | |||
4036 | ||||
4037 | // Phi nodes can have preferred ordering based on their result users | |||
4038 | DenseMap<const TreeEntry *, OrdersType> PhisToOrders; | |||
4039 | ||||
4040 | // AltShuffles can also have a preferred ordering that leads to fewer | |||
4041 | // instructions, e.g., the addsub instruction in x86. | |||
4042 | DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders; | |||
4043 | ||||
4044 | // Maps a TreeEntry to the reorder indices of external users. | |||
4045 | DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>> | |||
4046 | ExternalUserReorderMap; | |||
4047 | // FIXME: Workaround for syntax error reported by MSVC buildbots. | |||
4048 | TargetTransformInfo &TTIRef = *TTI; | |||
4049 | // Find all reorderable nodes with the given VF. | |||
4050 | // Currently the are vectorized stores,loads,extracts + some gathering of | |||
4051 | // extracts. | |||
4052 | for_each(VectorizableTree, [this, &TTIRef, &VFToOrderedEntries, | |||
4053 | &GathersToOrders, &ExternalUserReorderMap, | |||
4054 | &AltShufflesToOrders, &PhisToOrders]( | |||
4055 | const std::unique_ptr<TreeEntry> &TE) { | |||
4056 | // Look for external users that will probably be vectorized. | |||
4057 | SmallVector<OrdersType, 1> ExternalUserReorderIndices = | |||
4058 | findExternalStoreUsersReorderIndices(TE.get()); | |||
4059 | if (!ExternalUserReorderIndices.empty()) { | |||
4060 | VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); | |||
4061 | ExternalUserReorderMap.try_emplace(TE.get(), | |||
4062 | std::move(ExternalUserReorderIndices)); | |||
4063 | } | |||
4064 | ||||
4065 | // Patterns like [fadd,fsub] can be combined into a single instruction in | |||
4066 | // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need | |||
4067 | // to take into account their order when looking for the most used order. | |||
4068 | if (TE->isAltShuffle()) { | |||
4069 | VectorType *VecTy = | |||
4070 | FixedVectorType::get(TE->Scalars[0]->getType(), TE->Scalars.size()); | |||
4071 | unsigned Opcode0 = TE->getOpcode(); | |||
4072 | unsigned Opcode1 = TE->getAltOpcode(); | |||
4073 | // The opcode mask selects between the two opcodes. | |||
4074 | SmallBitVector OpcodeMask(TE->Scalars.size(), false); | |||
4075 | for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) | |||
4076 | if (cast<Instruction>(TE->Scalars[Lane])->getOpcode() == Opcode1) | |||
4077 | OpcodeMask.set(Lane); | |||
4078 | // If this pattern is supported by the target then we consider the order. | |||
4079 | if (TTIRef.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) { | |||
4080 | VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); | |||
4081 | AltShufflesToOrders.try_emplace(TE.get(), OrdersType()); | |||
4082 | } | |||
4083 | // TODO: Check the reverse order too. | |||
4084 | } | |||
4085 | ||||
4086 | if (Optional<OrdersType> CurrentOrder = | |||
4087 | getReorderingData(*TE, /*TopToBottom=*/true)) { | |||
4088 | // Do not include ordering for nodes used in the alt opcode vectorization, | |||
4089 | // better to reorder them during bottom-to-top stage. If follow the order | |||
4090 | // here, it causes reordering of the whole graph though actually it is | |||
4091 | // profitable just to reorder the subgraph that starts from the alternate | |||
4092 | // opcode vectorization node. Such nodes already end-up with the shuffle | |||
4093 | // instruction and it is just enough to change this shuffle rather than | |||
4094 | // rotate the scalars for the whole graph. | |||
4095 | unsigned Cnt = 0; | |||
4096 | const TreeEntry *UserTE = TE.get(); | |||
4097 | while (UserTE && Cnt < RecursionMaxDepth) { | |||
4098 | if (UserTE->UserTreeIndices.size() != 1) | |||
4099 | break; | |||
4100 | if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { | |||
4101 | return EI.UserTE->State == TreeEntry::Vectorize && | |||
4102 | EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; | |||
4103 | })) | |||
4104 | return; | |||
4105 | UserTE = UserTE->UserTreeIndices.back().UserTE; | |||
4106 | ++Cnt; | |||
4107 | } | |||
4108 | VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get()); | |||
4109 | if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty()) | |||
4110 | GathersToOrders.try_emplace(TE.get(), *CurrentOrder); | |||
4111 | if (TE->State == TreeEntry::Vectorize && | |||
4112 | TE->getOpcode() == Instruction::PHI) | |||
4113 | PhisToOrders.try_emplace(TE.get(), *CurrentOrder); | |||
4114 | } | |||
4115 | }); | |||
4116 | ||||
4117 | // Reorder the graph nodes according to their vectorization factor. | |||
4118 | for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; | |||
4119 | VF /= 2) { | |||
4120 | auto It = VFToOrderedEntries.find(VF); | |||
4121 | if (It == VFToOrderedEntries.end()) | |||
4122 | continue; | |||
4123 | // Try to find the most profitable order. We just are looking for the most | |||
4124 | // used order and reorder scalar elements in the nodes according to this | |||
4125 | // mostly used order. | |||
4126 | ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); | |||
4127 | // All operands are reordered and used only in this node - propagate the | |||
4128 | // most used order to the user node. | |||
4129 | MapVector<OrdersType, unsigned, | |||
4130 | DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> | |||
4131 | OrdersUses; | |||
4132 | SmallPtrSet<const TreeEntry *, 4> VisitedOps; | |||
4133 | for (const TreeEntry *OpTE : OrderedEntries) { | |||
4134 | // No need to reorder this nodes, still need to extend and to use shuffle, | |||
4135 | // just need to merge reordering shuffle and the reuse shuffle. | |||
4136 | if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE)) | |||
4137 | continue; | |||
4138 | // Count number of orders uses. | |||
4139 | const auto &Order = [OpTE, &GathersToOrders, &AltShufflesToOrders, | |||
4140 | &PhisToOrders]() -> const OrdersType & { | |||
4141 | if (OpTE->State == TreeEntry::NeedToGather || | |||
4142 | !OpTE->ReuseShuffleIndices.empty()) { | |||
4143 | auto It = GathersToOrders.find(OpTE); | |||
4144 | if (It != GathersToOrders.end()) | |||
4145 | return It->second; | |||
4146 | } | |||
4147 | if (OpTE->isAltShuffle()) { | |||
4148 | auto It = AltShufflesToOrders.find(OpTE); | |||
4149 | if (It != AltShufflesToOrders.end()) | |||
4150 | return It->second; | |||
4151 | } | |||
4152 | if (OpTE->State == TreeEntry::Vectorize && | |||
4153 | OpTE->getOpcode() == Instruction::PHI) { | |||
4154 | auto It = PhisToOrders.find(OpTE); | |||
4155 | if (It != PhisToOrders.end()) | |||
4156 | return It->second; | |||
4157 | } | |||
4158 | return OpTE->ReorderIndices; | |||
4159 | }(); | |||
4160 | // First consider the order of the external scalar users. | |||
4161 | auto It = ExternalUserReorderMap.find(OpTE); | |||
4162 | if (It != ExternalUserReorderMap.end()) { | |||
4163 | const auto &ExternalUserReorderIndices = It->second; | |||
4164 | // If the OpTE vector factor != number of scalars - use natural order, | |||
4165 | // it is an attempt to reorder node with reused scalars but with | |||
4166 | // external uses. | |||
4167 | if (OpTE->getVectorFactor() != OpTE->Scalars.size()) { | |||
4168 | OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second += | |||
4169 | ExternalUserReorderIndices.size(); | |||
4170 | } else { | |||
4171 | for (const OrdersType &ExtOrder : ExternalUserReorderIndices) | |||
4172 | ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second; | |||
4173 | } | |||
4174 | // No other useful reorder data in this entry. | |||
4175 | if (Order.empty()) | |||
4176 | continue; | |||
4177 | } | |||
4178 | // Stores actually store the mask, not the order, need to invert. | |||
4179 | if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && | |||
4180 | OpTE->getOpcode() == Instruction::Store && !Order.empty()) { | |||
4181 | SmallVector<int> Mask; | |||
4182 | inversePermutation(Order, Mask); | |||
4183 | unsigned E = Order.size(); | |||
4184 | OrdersType CurrentOrder(E, E); | |||
4185 | transform(Mask, CurrentOrder.begin(), [E](int Idx) { | |||
4186 | return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); | |||
4187 | }); | |||
4188 | fixupOrderingIndices(CurrentOrder); | |||
4189 | ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; | |||
4190 | } else { | |||
4191 | ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; | |||
4192 | } | |||
4193 | } | |||
4194 | // Set order of the user node. | |||
4195 | if (OrdersUses.empty()) | |||
4196 | continue; | |||
4197 | // Choose the most used order. | |||
4198 | ArrayRef<unsigned> BestOrder = OrdersUses.front().first; | |||
4199 | unsigned Cnt = OrdersUses.front().second; | |||
4200 | for (const auto &Pair : drop_begin(OrdersUses)) { | |||
4201 | if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { | |||
4202 | BestOrder = Pair.first; | |||
4203 | Cnt = Pair.second; | |||
4204 | } | |||
4205 | } | |||
4206 | // Set order of the user node. | |||
4207 | if (BestOrder.empty()) | |||
4208 | continue; | |||
4209 | SmallVector<int> Mask; | |||
4210 | inversePermutation(BestOrder, Mask); | |||
4211 | SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); | |||
4212 | unsigned E = BestOrder.size(); | |||
4213 | transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { | |||
4214 | return I < E ? static_cast<int>(I) : UndefMaskElem; | |||
4215 | }); | |||
4216 | // Do an actual reordering, if profitable. | |||
4217 | for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { | |||
4218 | // Just do the reordering for the nodes with the given VF. | |||
4219 | if (TE->Scalars.size() != VF) { | |||
4220 | if (TE->ReuseShuffleIndices.size() == VF) { | |||
4221 | // Need to reorder the reuses masks of the operands with smaller VF to | |||
4222 | // be able to find the match between the graph nodes and scalar | |||
4223 | // operands of the given node during vectorization/cost estimation. | |||
4224 | assert(all_of(TE->UserTreeIndices,(static_cast <bool> (all_of(TE->UserTreeIndices, [VF , &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars .size() == VF || EI.UserTE->Scalars.size() == TE->Scalars .size(); }) && "All users must be of VF size.") ? void (0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4230, __extension__ __PRETTY_FUNCTION__)) | |||
4225 | [VF, &TE](const EdgeInfo &EI) {(static_cast <bool> (all_of(TE->UserTreeIndices, [VF , &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars .size() == VF || EI.UserTE->Scalars.size() == TE->Scalars .size(); }) && "All users must be of VF size.") ? void (0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4230, __extension__ __PRETTY_FUNCTION__)) | |||
4226 | return EI.UserTE->Scalars.size() == VF ||(static_cast <bool> (all_of(TE->UserTreeIndices, [VF , &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars .size() == VF || EI.UserTE->Scalars.size() == TE->Scalars .size(); }) && "All users must be of VF size.") ? void (0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4230, __extension__ __PRETTY_FUNCTION__)) | |||
4227 | EI.UserTE->Scalars.size() ==(static_cast <bool> (all_of(TE->UserTreeIndices, [VF , &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars .size() == VF || EI.UserTE->Scalars.size() == TE->Scalars .size(); }) && "All users must be of VF size.") ? void (0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4230, __extension__ __PRETTY_FUNCTION__)) | |||
4228 | TE->Scalars.size();(static_cast <bool> (all_of(TE->UserTreeIndices, [VF , &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars .size() == VF || EI.UserTE->Scalars.size() == TE->Scalars .size(); }) && "All users must be of VF size.") ? void (0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4230, __extension__ __PRETTY_FUNCTION__)) | |||
4229 | }) &&(static_cast <bool> (all_of(TE->UserTreeIndices, [VF , &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars .size() == VF || EI.UserTE->Scalars.size() == TE->Scalars .size(); }) && "All users must be of VF size.") ? void (0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4230, __extension__ __PRETTY_FUNCTION__)) | |||
4230 | "All users must be of VF size.")(static_cast <bool> (all_of(TE->UserTreeIndices, [VF , &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars .size() == VF || EI.UserTE->Scalars.size() == TE->Scalars .size(); }) && "All users must be of VF size.") ? void (0) : __assert_fail ("all_of(TE->UserTreeIndices, [VF, &TE](const EdgeInfo &EI) { return EI.UserTE->Scalars.size() == VF || EI.UserTE->Scalars.size() == TE->Scalars.size(); }) && \"All users must be of VF size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4230, __extension__ __PRETTY_FUNCTION__)); | |||
4231 | // Update ordering of the operands with the smaller VF than the given | |||
4232 | // one. | |||
4233 | reorderNodeWithReuses(*TE, Mask); | |||
4234 | } | |||
4235 | continue; | |||
4236 | } | |||
4237 | if (TE->State == TreeEntry::Vectorize && | |||
4238 | isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, | |||
4239 | InsertElementInst>(TE->getMainOp()) && | |||
4240 | !TE->isAltShuffle()) { | |||
4241 | // Build correct orders for extract{element,value}, loads and | |||
4242 | // stores. | |||
4243 | reorderOrder(TE->ReorderIndices, Mask); | |||
4244 | if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) | |||
4245 | TE->reorderOperands(Mask); | |||
4246 | } else { | |||
4247 | // Reorder the node and its operands. | |||
4248 | TE->reorderOperands(Mask); | |||
4249 | assert(TE->ReorderIndices.empty() &&(static_cast <bool> (TE->ReorderIndices.empty() && "Expected empty reorder sequence.") ? void (0) : __assert_fail ("TE->ReorderIndices.empty() && \"Expected empty reorder sequence.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4250, __extension__ __PRETTY_FUNCTION__)) | |||
4250 | "Expected empty reorder sequence.")(static_cast <bool> (TE->ReorderIndices.empty() && "Expected empty reorder sequence.") ? void (0) : __assert_fail ("TE->ReorderIndices.empty() && \"Expected empty reorder sequence.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4250, __extension__ __PRETTY_FUNCTION__)); | |||
4251 | reorderScalars(TE->Scalars, Mask); | |||
4252 | } | |||
4253 | if (!TE->ReuseShuffleIndices.empty()) { | |||
4254 | // Apply reversed order to keep the original ordering of the reused | |||
4255 | // elements to avoid extra reorder indices shuffling. | |||
4256 | OrdersType CurrentOrder; | |||
4257 | reorderOrder(CurrentOrder, MaskOrder); | |||
4258 | SmallVector<int> NewReuses; | |||
4259 | inversePermutation(CurrentOrder, NewReuses); | |||
4260 | addMask(NewReuses, TE->ReuseShuffleIndices); | |||
4261 | TE->ReuseShuffleIndices.swap(NewReuses); | |||
4262 | } | |||
4263 | } | |||
4264 | } | |||
4265 | } | |||
4266 | ||||
4267 | bool BoUpSLP::canReorderOperands( | |||
4268 | TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, | |||
4269 | ArrayRef<TreeEntry *> ReorderableGathers, | |||
4270 | SmallVectorImpl<TreeEntry *> &GatherOps) { | |||
4271 | for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) { | |||
4272 | if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) { | |||
4273 | return OpData.first == I && | |||
4274 | OpData.second->State == TreeEntry::Vectorize; | |||
4275 | })) | |||
4276 | continue; | |||
4277 | if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) { | |||
4278 | // Do not reorder if operand node is used by many user nodes. | |||
4279 | if (any_of(TE->UserTreeIndices, | |||
4280 | [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; })) | |||
4281 | return false; | |||
4282 | // Add the node to the list of the ordered nodes with the identity | |||
4283 | // order. | |||
4284 | Edges.emplace_back(I, TE); | |||
4285 | // Add ScatterVectorize nodes to the list of operands, where just | |||
4286 | // reordering of the scalars is required. Similar to the gathers, so | |||
4287 | // simply add to the list of gathered ops. | |||
4288 | // If there are reused scalars, process this node as a regular vectorize | |||
4289 | // node, just reorder reuses mask. | |||
4290 | if (TE->State != TreeEntry::Vectorize && TE->ReuseShuffleIndices.empty()) | |||
4291 | GatherOps.push_back(TE); | |||
4292 | continue; | |||
4293 | } | |||
4294 | TreeEntry *Gather = nullptr; | |||
4295 | if (count_if(ReorderableGathers, | |||
4296 | [&Gather, UserTE, I](TreeEntry *TE) { | |||
4297 | assert(TE->State != TreeEntry::Vectorize &&(static_cast <bool> (TE->State != TreeEntry::Vectorize && "Only non-vectorized nodes are expected.") ? void (0) : __assert_fail ("TE->State != TreeEntry::Vectorize && \"Only non-vectorized nodes are expected.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4298, __extension__ __PRETTY_FUNCTION__)) | |||
4298 | "Only non-vectorized nodes are expected.")(static_cast <bool> (TE->State != TreeEntry::Vectorize && "Only non-vectorized nodes are expected.") ? void (0) : __assert_fail ("TE->State != TreeEntry::Vectorize && \"Only non-vectorized nodes are expected.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4298, __extension__ __PRETTY_FUNCTION__)); | |||
4299 | if (any_of(TE->UserTreeIndices, | |||
4300 | [UserTE, I](const EdgeInfo &EI) { | |||
4301 | return EI.UserTE == UserTE && EI.EdgeIdx == I; | |||
4302 | })) { | |||
4303 | assert(TE->isSame(UserTE->getOperand(I)) &&(static_cast <bool> (TE->isSame(UserTE->getOperand (I)) && "Operand entry does not match operands.") ? void (0) : __assert_fail ("TE->isSame(UserTE->getOperand(I)) && \"Operand entry does not match operands.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4304, __extension__ __PRETTY_FUNCTION__)) | |||
4304 | "Operand entry does not match operands.")(static_cast <bool> (TE->isSame(UserTE->getOperand (I)) && "Operand entry does not match operands.") ? void (0) : __assert_fail ("TE->isSame(UserTE->getOperand(I)) && \"Operand entry does not match operands.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4304, __extension__ __PRETTY_FUNCTION__)); | |||
4305 | Gather = TE; | |||
4306 | return true; | |||
4307 | } | |||
4308 | return false; | |||
4309 | }) > 1 && | |||
4310 | !all_of(UserTE->getOperand(I), isConstant)) | |||
4311 | return false; | |||
4312 | if (Gather) | |||
4313 | GatherOps.push_back(Gather); | |||
4314 | } | |||
4315 | return true; | |||
4316 | } | |||
4317 | ||||
4318 | void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { | |||
4319 | SetVector<TreeEntry *> OrderedEntries; | |||
4320 | DenseMap<const TreeEntry *, OrdersType> GathersToOrders; | |||
4321 | // Find all reorderable leaf nodes with the given VF. | |||
4322 | // Currently the are vectorized loads,extracts without alternate operands + | |||
4323 | // some gathering of extracts. | |||
4324 | SmallVector<TreeEntry *> NonVectorized; | |||
4325 | for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, | |||
4326 | &NonVectorized]( | |||
4327 | const std::unique_ptr<TreeEntry> &TE) { | |||
4328 | if (TE->State != TreeEntry::Vectorize) | |||
4329 | NonVectorized.push_back(TE.get()); | |||
4330 | if (Optional<OrdersType> CurrentOrder = | |||
4331 | getReorderingData(*TE, /*TopToBottom=*/false)) { | |||
4332 | OrderedEntries.insert(TE.get()); | |||
4333 | if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty()) | |||
4334 | GathersToOrders.try_emplace(TE.get(), *CurrentOrder); | |||
4335 | } | |||
4336 | }); | |||
4337 | ||||
4338 | // 1. Propagate order to the graph nodes, which use only reordered nodes. | |||
4339 | // I.e., if the node has operands, that are reordered, try to make at least | |||
4340 | // one operand order in the natural order and reorder others + reorder the | |||
4341 | // user node itself. | |||
4342 | SmallPtrSet<const TreeEntry *, 4> Visited; | |||
4343 | while (!OrderedEntries.empty()) { | |||
4344 | // 1. Filter out only reordered nodes. | |||
4345 | // 2. If the entry has multiple uses - skip it and jump to the next node. | |||
4346 | DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; | |||
4347 | SmallVector<TreeEntry *> Filtered; | |||
4348 | for (TreeEntry *TE : OrderedEntries) { | |||
4349 | if (!(TE->State == TreeEntry::Vectorize || | |||
4350 | (TE->State == TreeEntry::NeedToGather && | |||
4351 | GathersToOrders.count(TE))) || | |||
4352 | TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || | |||
4353 | !all_of(drop_begin(TE->UserTreeIndices), | |||
4354 | [TE](const EdgeInfo &EI) { | |||
4355 | return EI.UserTE == TE->UserTreeIndices.front().UserTE; | |||
4356 | }) || | |||
4357 | !Visited.insert(TE).second) { | |||
4358 | Filtered.push_back(TE); | |||
4359 | continue; | |||
4360 | } | |||
4361 | // Build a map between user nodes and their operands order to speedup | |||
4362 | // search. The graph currently does not provide this dependency directly. | |||
4363 | for (EdgeInfo &EI : TE->UserTreeIndices) { | |||
4364 | TreeEntry *UserTE = EI.UserTE; | |||
4365 | auto It = Users.find(UserTE); | |||
4366 | if (It == Users.end()) | |||
4367 | It = Users.insert({UserTE, {}}).first; | |||
4368 | It->second.emplace_back(EI.EdgeIdx, TE); | |||
4369 | } | |||
4370 | } | |||
4371 | // Erase filtered entries. | |||
4372 | for_each(Filtered, | |||
4373 | [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); | |||
4374 | SmallVector< | |||
4375 | std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>> | |||
4376 | UsersVec(Users.begin(), Users.end()); | |||
4377 | sort(UsersVec, [](const auto &Data1, const auto &Data2) { | |||
4378 | return Data1.first->Idx > Data2.first->Idx; | |||
4379 | }); | |||
4380 | for (auto &Data : UsersVec) { | |||
4381 | // Check that operands are used only in the User node. | |||
4382 | SmallVector<TreeEntry *> GatherOps; | |||
4383 | if (!canReorderOperands(Data.first, Data.second, NonVectorized, | |||
4384 | GatherOps)) { | |||
4385 | for_each(Data.second, | |||
4386 | [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { | |||
4387 | OrderedEntries.remove(Op.second); | |||
4388 | }); | |||
4389 | continue; | |||
4390 | } | |||
4391 | // All operands are reordered and used only in this node - propagate the | |||
4392 | // most used order to the user node. | |||
4393 | MapVector<OrdersType, unsigned, | |||
4394 | DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> | |||
4395 | OrdersUses; | |||
4396 | // Do the analysis for each tree entry only once, otherwise the order of | |||
4397 | // the same node my be considered several times, though might be not | |||
4398 | // profitable. | |||
4399 | SmallPtrSet<const TreeEntry *, 4> VisitedOps; | |||
4400 | SmallPtrSet<const TreeEntry *, 4> VisitedUsers; | |||
4401 | for (const auto &Op : Data.second) { | |||
4402 | TreeEntry *OpTE = Op.second; | |||
4403 | if (!VisitedOps.insert(OpTE).second) | |||
4404 | continue; | |||
4405 | if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE)) | |||
4406 | continue; | |||
4407 | const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { | |||
4408 | if (OpTE->State == TreeEntry::NeedToGather || | |||
4409 | !OpTE->ReuseShuffleIndices.empty()) | |||
4410 | return GathersToOrders.find(OpTE)->second; | |||
4411 | return OpTE->ReorderIndices; | |||
4412 | }(); | |||
4413 | unsigned NumOps = count_if( | |||
4414 | Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) { | |||
4415 | return P.second == OpTE; | |||
4416 | }); | |||
4417 | // Stores actually store the mask, not the order, need to invert. | |||
4418 | if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && | |||
4419 | OpTE->getOpcode() == Instruction::Store && !Order.empty()) { | |||
4420 | SmallVector<int> Mask; | |||
4421 | inversePermutation(Order, Mask); | |||
4422 | unsigned E = Order.size(); | |||
4423 | OrdersType CurrentOrder(E, E); | |||
4424 | transform(Mask, CurrentOrder.begin(), [E](int Idx) { | |||
4425 | return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); | |||
4426 | }); | |||
4427 | fixupOrderingIndices(CurrentOrder); | |||
4428 | OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second += | |||
4429 | NumOps; | |||
4430 | } else { | |||
4431 | OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps; | |||
4432 | } | |||
4433 | auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0)); | |||
4434 | const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders]( | |||
4435 | const TreeEntry *TE) { | |||
4436 | if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() || | |||
4437 | (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) || | |||
4438 | (IgnoreReorder && TE->Idx == 0)) | |||
4439 | return true; | |||
4440 | if (TE->State == TreeEntry::NeedToGather) { | |||
4441 | auto It = GathersToOrders.find(TE); | |||
4442 | if (It != GathersToOrders.end()) | |||
4443 | return !It->second.empty(); | |||
4444 | return true; | |||
4445 | } | |||
4446 | return false; | |||
4447 | }; | |||
4448 | for (const EdgeInfo &EI : OpTE->UserTreeIndices) { | |||
4449 | TreeEntry *UserTE = EI.UserTE; | |||
4450 | if (!VisitedUsers.insert(UserTE).second) | |||
4451 | continue; | |||
4452 | // May reorder user node if it requires reordering, has reused | |||
4453 | // scalars, is an alternate op vectorize node or its op nodes require | |||
4454 | // reordering. | |||
4455 | if (AllowsReordering(UserTE)) | |||
4456 | continue; | |||
4457 | // Check if users allow reordering. | |||
4458 | // Currently look up just 1 level of operands to avoid increase of | |||
4459 | // the compile time. | |||
4460 | // Profitable to reorder if definitely more operands allow | |||
4461 | // reordering rather than those with natural order. | |||
4462 | ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE]; | |||
4463 | if (static_cast<unsigned>(count_if( | |||
4464 | Ops, [UserTE, &AllowsReordering]( | |||
4465 | const std::pair<unsigned, TreeEntry *> &Op) { | |||
4466 | return AllowsReordering(Op.second) && | |||
4467 | all_of(Op.second->UserTreeIndices, | |||
4468 | [UserTE](const EdgeInfo &EI) { | |||
4469 | return EI.UserTE == UserTE; | |||
4470 | }); | |||
4471 | })) <= Ops.size() / 2) | |||
4472 | ++Res.first->second; | |||
4473 | } | |||
4474 | } | |||
4475 | // If no orders - skip current nodes and jump to the next one, if any. | |||
4476 | if (OrdersUses.empty()) { | |||
4477 | for_each(Data.second, | |||
4478 | [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { | |||
4479 | OrderedEntries.remove(Op.second); | |||
4480 | }); | |||
4481 | continue; | |||
4482 | } | |||
4483 | // Choose the best order. | |||
4484 | ArrayRef<unsigned> BestOrder = OrdersUses.front().first; | |||
4485 | unsigned Cnt = OrdersUses.front().second; | |||
4486 | for (const auto &Pair : drop_begin(OrdersUses)) { | |||
4487 | if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { | |||
4488 | BestOrder = Pair.first; | |||
4489 | Cnt = Pair.second; | |||
4490 | } | |||
4491 | } | |||
4492 | // Set order of the user node (reordering of operands and user nodes). | |||
4493 | if (BestOrder.empty()) { | |||
4494 | for_each(Data.second, | |||
4495 | [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { | |||
4496 | OrderedEntries.remove(Op.second); | |||
4497 | }); | |||
4498 | continue; | |||
4499 | } | |||
4500 | // Erase operands from OrderedEntries list and adjust their orders. | |||
4501 | VisitedOps.clear(); | |||
4502 | SmallVector<int> Mask; | |||
4503 | inversePermutation(BestOrder, Mask); | |||
4504 | SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); | |||
4505 | unsigned E = BestOrder.size(); | |||
4506 | transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { | |||
4507 | return I < E ? static_cast<int>(I) : UndefMaskElem; | |||
4508 | }); | |||
4509 | for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { | |||
4510 | TreeEntry *TE = Op.second; | |||
4511 | OrderedEntries.remove(TE); | |||
4512 | if (!VisitedOps.insert(TE).second) | |||
4513 | continue; | |||
4514 | if (TE->ReuseShuffleIndices.size() == BestOrder.size()) { | |||
4515 | reorderNodeWithReuses(*TE, Mask); | |||
4516 | continue; | |||
4517 | } | |||
4518 | // Gathers are processed separately. | |||
4519 | if (TE->State != TreeEntry::Vectorize) | |||
4520 | continue; | |||
4521 | assert((BestOrder.size() == TE->ReorderIndices.size() ||(static_cast <bool> ((BestOrder.size() == TE->ReorderIndices .size() || TE->ReorderIndices.empty()) && "Non-matching sizes of user/operand entries." ) ? void (0) : __assert_fail ("(BestOrder.size() == TE->ReorderIndices.size() || TE->ReorderIndices.empty()) && \"Non-matching sizes of user/operand entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4523, __extension__ __PRETTY_FUNCTION__)) | |||
4522 | TE->ReorderIndices.empty()) &&(static_cast <bool> ((BestOrder.size() == TE->ReorderIndices .size() || TE->ReorderIndices.empty()) && "Non-matching sizes of user/operand entries." ) ? void (0) : __assert_fail ("(BestOrder.size() == TE->ReorderIndices.size() || TE->ReorderIndices.empty()) && \"Non-matching sizes of user/operand entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4523, __extension__ __PRETTY_FUNCTION__)) | |||
4523 | "Non-matching sizes of user/operand entries.")(static_cast <bool> ((BestOrder.size() == TE->ReorderIndices .size() || TE->ReorderIndices.empty()) && "Non-matching sizes of user/operand entries." ) ? void (0) : __assert_fail ("(BestOrder.size() == TE->ReorderIndices.size() || TE->ReorderIndices.empty()) && \"Non-matching sizes of user/operand entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4523, __extension__ __PRETTY_FUNCTION__)); | |||
4524 | reorderOrder(TE->ReorderIndices, Mask); | |||
4525 | if (IgnoreReorder && TE == VectorizableTree.front().get()) | |||
4526 | IgnoreReorder = false; | |||
4527 | } | |||
4528 | // For gathers just need to reorder its scalars. | |||
4529 | for (TreeEntry *Gather : GatherOps) { | |||
4530 | assert(Gather->ReorderIndices.empty() &&(static_cast <bool> (Gather->ReorderIndices.empty() && "Unexpected reordering of gathers.") ? void (0) : __assert_fail ("Gather->ReorderIndices.empty() && \"Unexpected reordering of gathers.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4531, __extension__ __PRETTY_FUNCTION__)) | |||
4531 | "Unexpected reordering of gathers.")(static_cast <bool> (Gather->ReorderIndices.empty() && "Unexpected reordering of gathers.") ? void (0) : __assert_fail ("Gather->ReorderIndices.empty() && \"Unexpected reordering of gathers.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4531, __extension__ __PRETTY_FUNCTION__)); | |||
4532 | if (!Gather->ReuseShuffleIndices.empty()) { | |||
4533 | // Just reorder reuses indices. | |||
4534 | reorderReuses(Gather->ReuseShuffleIndices, Mask); | |||
4535 | continue; | |||
4536 | } | |||
4537 | reorderScalars(Gather->Scalars, Mask); | |||
4538 | OrderedEntries.remove(Gather); | |||
4539 | } | |||
4540 | // Reorder operands of the user node and set the ordering for the user | |||
4541 | // node itself. | |||
4542 | if (Data.first->State != TreeEntry::Vectorize || | |||
4543 | !isa<ExtractElementInst, ExtractValueInst, LoadInst>( | |||
4544 | Data.first->getMainOp()) || | |||
4545 | Data.first->isAltShuffle()) | |||
4546 | Data.first->reorderOperands(Mask); | |||
4547 | if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || | |||
4548 | Data.first->isAltShuffle()) { | |||
4549 | reorderScalars(Data.first->Scalars, Mask); | |||
4550 | reorderOrder(Data.first->ReorderIndices, MaskOrder); | |||
4551 | if (Data.first->ReuseShuffleIndices.empty() && | |||
4552 | !Data.first->ReorderIndices.empty() && | |||
4553 | !Data.first->isAltShuffle()) { | |||
4554 | // Insert user node to the list to try to sink reordering deeper in | |||
4555 | // the graph. | |||
4556 | OrderedEntries.insert(Data.first); | |||
4557 | } | |||
4558 | } else { | |||
4559 | reorderOrder(Data.first->ReorderIndices, Mask); | |||
4560 | } | |||
4561 | } | |||
4562 | } | |||
4563 | // If the reordering is unnecessary, just remove the reorder. | |||
4564 | if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && | |||
4565 | VectorizableTree.front()->ReuseShuffleIndices.empty()) | |||
4566 | VectorizableTree.front()->ReorderIndices.clear(); | |||
4567 | } | |||
4568 | ||||
4569 | void BoUpSLP::buildExternalUses( | |||
4570 | const ExtraValueToDebugLocsMap &ExternallyUsedValues) { | |||
4571 | // Collect the values that we need to extract from the tree. | |||
4572 | for (auto &TEPtr : VectorizableTree) { | |||
4573 | TreeEntry *Entry = TEPtr.get(); | |||
4574 | ||||
4575 | // No need to handle users of gathered values. | |||
4576 | if (Entry->State == TreeEntry::NeedToGather) | |||
4577 | continue; | |||
4578 | ||||
4579 | // For each lane: | |||
4580 | for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { | |||
4581 | Value *Scalar = Entry->Scalars[Lane]; | |||
4582 | int FoundLane = Entry->findLaneForValue(Scalar); | |||
4583 | ||||
4584 | // Check if the scalar is externally used as an extra arg. | |||
4585 | auto ExtI = ExternallyUsedValues.find(Scalar); | |||
4586 | if (ExtI != ExternallyUsedValues.end()) { | |||
4587 | LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Need to extract: Extra arg from lane " << Lane << " from " << *Scalar << ".\n" ; } } while (false) | |||
4588 | << Lane << " from " << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Need to extract: Extra arg from lane " << Lane << " from " << *Scalar << ".\n" ; } } while (false); | |||
4589 | ExternalUses.emplace_back(Scalar, nullptr, FoundLane); | |||
4590 | } | |||
4591 | for (User *U : Scalar->users()) { | |||
4592 | LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Checking user:" << *U << ".\n"; } } while (false); | |||
4593 | ||||
4594 | Instruction *UserInst = dyn_cast<Instruction>(U); | |||
4595 | if (!UserInst) | |||
4596 | continue; | |||
4597 | ||||
4598 | if (isDeleted(UserInst)) | |||
4599 | continue; | |||
4600 | ||||
4601 | // Skip in-tree scalars that become vectors | |||
4602 | if (TreeEntry *UseEntry = getTreeEntry(U)) { | |||
4603 | Value *UseScalar = UseEntry->Scalars[0]; | |||
4604 | // Some in-tree scalars will remain as scalar in vectorized | |||
4605 | // instructions. If that is the case, the one in Lane 0 will | |||
4606 | // be used. | |||
4607 | if (UseScalar != U || | |||
4608 | UseEntry->State == TreeEntry::ScatterVectorize || | |||
4609 | !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { | |||
4610 | LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *Udo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: \tInternal user will be removed:" << *U << ".\n"; } } while (false) | |||
4611 | << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: \tInternal user will be removed:" << *U << ".\n"; } } while (false); | |||
4612 | assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state")(static_cast <bool> (UseEntry->State != TreeEntry::NeedToGather && "Bad state") ? void (0) : __assert_fail ("UseEntry->State != TreeEntry::NeedToGather && \"Bad state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4612, __extension__ __PRETTY_FUNCTION__)); | |||
4613 | continue; | |||
4614 | } | |||
4615 | } | |||
4616 | ||||
4617 | // Ignore users in the user ignore list. | |||
4618 | if (UserIgnoreList && UserIgnoreList->contains(UserInst)) | |||
4619 | continue; | |||
4620 | ||||
4621 | LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Need to extract:" << * U << " from lane " << Lane << " from " << *Scalar << ".\n"; } } while (false) | |||
4622 | << Lane << " from " << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Need to extract:" << * U << " from lane " << Lane << " from " << *Scalar << ".\n"; } } while (false); | |||
4623 | ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); | |||
4624 | } | |||
4625 | } | |||
4626 | } | |||
4627 | } | |||
4628 | ||||
4629 | DenseMap<Value *, SmallVector<StoreInst *, 4>> | |||
4630 | BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const { | |||
4631 | DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap; | |||
4632 | for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) { | |||
4633 | Value *V = TE->Scalars[Lane]; | |||
4634 | // To save compilation time we don't visit if we have too many users. | |||
4635 | static constexpr unsigned UsersLimit = 4; | |||
4636 | if (V->hasNUsesOrMore(UsersLimit)) | |||
4637 | break; | |||
4638 | ||||
4639 | // Collect stores per pointer object. | |||
4640 | for (User *U : V->users()) { | |||
4641 | auto *SI = dyn_cast<StoreInst>(U); | |||
4642 | if (SI == nullptr || !SI->isSimple() || | |||
4643 | !isValidElementType(SI->getValueOperand()->getType())) | |||
4644 | continue; | |||
4645 | // Skip entry if already | |||
4646 | if (getTreeEntry(U)) | |||
4647 | continue; | |||
4648 | ||||
4649 | Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); | |||
4650 | auto &StoresVec = PtrToStoresMap[Ptr]; | |||
4651 | // For now just keep one store per pointer object per lane. | |||
4652 | // TODO: Extend this to support multiple stores per pointer per lane | |||
4653 | if (StoresVec.size() > Lane) | |||
4654 | continue; | |||
4655 | // Skip if in different BBs. | |||
4656 | if (!StoresVec.empty() && | |||
4657 | SI->getParent() != StoresVec.back()->getParent()) | |||
4658 | continue; | |||
4659 | // Make sure that the stores are of the same type. | |||
4660 | if (!StoresVec.empty() && | |||
4661 | SI->getValueOperand()->getType() != | |||
4662 | StoresVec.back()->getValueOperand()->getType()) | |||
4663 | continue; | |||
4664 | StoresVec.push_back(SI); | |||
4665 | } | |||
4666 | } | |||
4667 | return PtrToStoresMap; | |||
4668 | } | |||
4669 | ||||
4670 | bool BoUpSLP::canFormVector(const SmallVector<StoreInst *, 4> &StoresVec, | |||
4671 | OrdersType &ReorderIndices) const { | |||
4672 | // We check whether the stores in StoreVec can form a vector by sorting them | |||
4673 | // and checking whether they are consecutive. | |||
4674 | ||||
4675 | // To avoid calling getPointersDiff() while sorting we create a vector of | |||
4676 | // pairs {store, offset from first} and sort this instead. | |||
4677 | SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size()); | |||
4678 | StoreInst *S0 = StoresVec[0]; | |||
4679 | StoreOffsetVec[0] = {S0, 0}; | |||
4680 | Type *S0Ty = S0->getValueOperand()->getType(); | |||
4681 | Value *S0Ptr = S0->getPointerOperand(); | |||
4682 | for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) { | |||
4683 | StoreInst *SI = StoresVec[Idx]; | |||
4684 | Optional<int> Diff = | |||
4685 | getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(), | |||
4686 | SI->getPointerOperand(), *DL, *SE, | |||
4687 | /*StrictCheck=*/true); | |||
4688 | // We failed to compare the pointers so just abandon this StoresVec. | |||
4689 | if (!Diff) | |||
4690 | return false; | |||
4691 | StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff}; | |||
4692 | } | |||
4693 | ||||
4694 | // Sort the vector based on the pointers. We create a copy because we may | |||
4695 | // need the original later for calculating the reorder (shuffle) indices. | |||
4696 | stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1, | |||
4697 | const std::pair<StoreInst *, int> &Pair2) { | |||
4698 | int Offset1 = Pair1.second; | |||
4699 | int Offset2 = Pair2.second; | |||
4700 | return Offset1 < Offset2; | |||
4701 | }); | |||
4702 | ||||
4703 | // Check if the stores are consecutive by checking if their difference is 1. | |||
4704 | for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size())) | |||
4705 | if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1) | |||
4706 | return false; | |||
4707 | ||||
4708 | // Calculate the shuffle indices according to their offset against the sorted | |||
4709 | // StoreOffsetVec. | |||
4710 | ReorderIndices.reserve(StoresVec.size()); | |||
4711 | for (StoreInst *SI : StoresVec) { | |||
4712 | unsigned Idx = find_if(StoreOffsetVec, | |||
4713 | [SI](const std::pair<StoreInst *, int> &Pair) { | |||
4714 | return Pair.first == SI; | |||
4715 | }) - | |||
4716 | StoreOffsetVec.begin(); | |||
4717 | ReorderIndices.push_back(Idx); | |||
4718 | } | |||
4719 | // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in | |||
4720 | // reorderTopToBottom() and reorderBottomToTop(), so we are following the | |||
4721 | // same convention here. | |||
4722 | auto IsIdentityOrder = [](const OrdersType &Order) { | |||
4723 | for (unsigned Idx : seq<unsigned>(0, Order.size())) | |||
4724 | if (Idx != Order[Idx]) | |||
4725 | return false; | |||
4726 | return true; | |||
4727 | }; | |||
4728 | if (IsIdentityOrder(ReorderIndices)) | |||
4729 | ReorderIndices.clear(); | |||
4730 | ||||
4731 | return true; | |||
4732 | } | |||
4733 | ||||
4734 | #ifndef NDEBUG | |||
4735 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) static void dumpOrder(const BoUpSLP::OrdersType &Order) { | |||
4736 | for (unsigned Idx : Order) | |||
4737 | dbgs() << Idx << ", "; | |||
4738 | dbgs() << "\n"; | |||
4739 | } | |||
4740 | #endif | |||
4741 | ||||
4742 | SmallVector<BoUpSLP::OrdersType, 1> | |||
4743 | BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const { | |||
4744 | unsigned NumLanes = TE->Scalars.size(); | |||
4745 | ||||
4746 | DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap = | |||
4747 | collectUserStores(TE); | |||
4748 | ||||
4749 | // Holds the reorder indices for each candidate store vector that is a user of | |||
4750 | // the current TreeEntry. | |||
4751 | SmallVector<OrdersType, 1> ExternalReorderIndices; | |||
4752 | ||||
4753 | // Now inspect the stores collected per pointer and look for vectorization | |||
4754 | // candidates. For each candidate calculate the reorder index vector and push | |||
4755 | // it into `ExternalReorderIndices` | |||
4756 | for (const auto &Pair : PtrToStoresMap) { | |||
4757 | auto &StoresVec = Pair.second; | |||
4758 | // If we have fewer than NumLanes stores, then we can't form a vector. | |||
4759 | if (StoresVec.size() != NumLanes) | |||
4760 | continue; | |||
4761 | ||||
4762 | // If the stores are not consecutive then abandon this StoresVec. | |||
4763 | OrdersType ReorderIndices; | |||
4764 | if (!canFormVector(StoresVec, ReorderIndices)) | |||
4765 | continue; | |||
4766 | ||||
4767 | // We now know that the scalars in StoresVec can form a vector instruction, | |||
4768 | // so set the reorder indices. | |||
4769 | ExternalReorderIndices.push_back(ReorderIndices); | |||
4770 | } | |||
4771 | return ExternalReorderIndices; | |||
4772 | } | |||
4773 | ||||
4774 | void BoUpSLP::buildTree(ArrayRef<Value *> Roots, | |||
4775 | const SmallDenseSet<Value *> &UserIgnoreLst) { | |||
4776 | deleteTree(); | |||
4777 | UserIgnoreList = &UserIgnoreLst; | |||
4778 | if (!allSameType(Roots)) | |||
4779 | return; | |||
4780 | buildTree_rec(Roots, 0, EdgeInfo()); | |||
4781 | } | |||
4782 | ||||
4783 | void BoUpSLP::buildTree(ArrayRef<Value *> Roots) { | |||
4784 | deleteTree(); | |||
4785 | if (!allSameType(Roots)) | |||
4786 | return; | |||
4787 | buildTree_rec(Roots, 0, EdgeInfo()); | |||
4788 | } | |||
4789 | ||||
4790 | /// \return true if the specified list of values has only one instruction that | |||
4791 | /// requires scheduling, false otherwise. | |||
4792 | #ifndef NDEBUG | |||
4793 | static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) { | |||
4794 | Value *NeedsScheduling = nullptr; | |||
4795 | for (Value *V : VL) { | |||
4796 | if (doesNotNeedToBeScheduled(V)) | |||
4797 | continue; | |||
4798 | if (!NeedsScheduling) { | |||
4799 | NeedsScheduling = V; | |||
4800 | continue; | |||
4801 | } | |||
4802 | return false; | |||
4803 | } | |||
4804 | return NeedsScheduling; | |||
4805 | } | |||
4806 | #endif | |||
4807 | ||||
4808 | /// Generates key/subkey pair for the given value to provide effective sorting | |||
4809 | /// of the values and better detection of the vectorizable values sequences. The | |||
4810 | /// keys/subkeys can be used for better sorting of the values themselves (keys) | |||
4811 | /// and in values subgroups (subkeys). | |||
4812 | static std::pair<size_t, size_t> generateKeySubkey( | |||
4813 | Value *V, const TargetLibraryInfo *TLI, | |||
4814 | function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator, | |||
4815 | bool AllowAlternate) { | |||
4816 | hash_code Key = hash_value(V->getValueID() + 2); | |||
4817 | hash_code SubKey = hash_value(0); | |||
4818 | // Sort the loads by the distance between the pointers. | |||
4819 | if (auto *LI = dyn_cast<LoadInst>(V)) { | |||
4820 | Key = hash_combine(LI->getType(), hash_value(Instruction::Load), Key); | |||
4821 | if (LI->isSimple()) | |||
4822 | SubKey = hash_value(LoadsSubkeyGenerator(Key, LI)); | |||
4823 | else | |||
4824 | Key = SubKey = hash_value(LI); | |||
4825 | } else if (isVectorLikeInstWithConstOps(V)) { | |||
4826 | // Sort extracts by the vector operands. | |||
4827 | if (isa<ExtractElementInst, UndefValue>(V)) | |||
4828 | Key = hash_value(Value::UndefValueVal + 1); | |||
4829 | if (auto *EI = dyn_cast<ExtractElementInst>(V)) { | |||
4830 | if (!isUndefVector(EI->getVectorOperand()).all() && | |||
4831 | !isa<UndefValue>(EI->getIndexOperand())) | |||
4832 | SubKey = hash_value(EI->getVectorOperand()); | |||
4833 | } | |||
4834 | } else if (auto *I = dyn_cast<Instruction>(V)) { | |||
4835 | // Sort other instructions just by the opcodes except for CMPInst. | |||
4836 | // For CMP also sort by the predicate kind. | |||
4837 | if ((isa<BinaryOperator, CastInst>(I)) && | |||
4838 | isValidForAlternation(I->getOpcode())) { | |||
4839 | if (AllowAlternate) | |||
4840 | Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0); | |||
4841 | else | |||
4842 | Key = hash_combine(hash_value(I->getOpcode()), Key); | |||
4843 | SubKey = hash_combine( | |||
4844 | hash_value(I->getOpcode()), hash_value(I->getType()), | |||
4845 | hash_value(isa<BinaryOperator>(I) | |||
4846 | ? I->getType() | |||
4847 | : cast<CastInst>(I)->getOperand(0)->getType())); | |||
4848 | // For casts, look through the only operand to improve compile time. | |||
4849 | if (isa<CastInst>(I)) { | |||
4850 | std::pair<size_t, size_t> OpVals = | |||
4851 | generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator, | |||
4852 | /*AllowAlternate=*/true); | |||
4853 | Key = hash_combine(OpVals.first, Key); | |||
4854 | SubKey = hash_combine(OpVals.first, SubKey); | |||
4855 | } | |||
4856 | } else if (auto *CI = dyn_cast<CmpInst>(I)) { | |||
4857 | CmpInst::Predicate Pred = CI->getPredicate(); | |||
4858 | if (CI->isCommutative()) | |||
4859 | Pred = std::min(Pred, CmpInst::getInversePredicate(Pred)); | |||
4860 | CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred); | |||
4861 | SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred), | |||
4862 | hash_value(SwapPred), | |||
4863 | hash_value(CI->getOperand(0)->getType())); | |||
4864 | } else if (auto *Call = dyn_cast<CallInst>(I)) { | |||
4865 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI); | |||
4866 | if (isTriviallyVectorizable(ID)) { | |||
4867 | SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID)); | |||
4868 | } else if (!VFDatabase(*Call).getMappings(*Call).empty()) { | |||
4869 | SubKey = hash_combine(hash_value(I->getOpcode()), | |||
4870 | hash_value(Call->getCalledFunction())); | |||
4871 | } else { | |||
4872 | Key = hash_combine(hash_value(Call), Key); | |||
4873 | SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call)); | |||
4874 | } | |||
4875 | for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos()) | |||
4876 | SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End), | |||
4877 | hash_value(Op.Tag), SubKey); | |||
4878 | } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) { | |||
4879 | if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1))) | |||
4880 | SubKey = hash_value(Gep->getPointerOperand()); | |||
4881 | else | |||
4882 | SubKey = hash_value(Gep); | |||
4883 | } else if (BinaryOperator::isIntDivRem(I->getOpcode()) && | |||
4884 | !isa<ConstantInt>(I->getOperand(1))) { | |||
4885 | // Do not try to vectorize instructions with potentially high cost. | |||
4886 | SubKey = hash_value(I); | |||
4887 | } else { | |||
4888 | SubKey = hash_value(I->getOpcode()); | |||
4889 | } | |||
4890 | Key = hash_combine(hash_value(I->getParent()), Key); | |||
4891 | } | |||
4892 | return std::make_pair(Key, SubKey); | |||
4893 | } | |||
4894 | ||||
4895 | /// Checks if the specified instruction \p I is an alternate operation for | |||
4896 | /// the given \p MainOp and \p AltOp instructions. | |||
4897 | static bool isAlternateInstruction(const Instruction *I, | |||
4898 | const Instruction *MainOp, | |||
4899 | const Instruction *AltOp, | |||
4900 | const TargetLibraryInfo &TLI); | |||
4901 | ||||
4902 | void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, | |||
4903 | const EdgeInfo &UserTreeIdx) { | |||
4904 | assert((allConstant(VL) || allSameType(VL)) && "Invalid types!")(static_cast <bool> ((allConstant(VL) || allSameType(VL )) && "Invalid types!") ? void (0) : __assert_fail ("(allConstant(VL) || allSameType(VL)) && \"Invalid types!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 4904, __extension__ __PRETTY_FUNCTION__)); | |||
4905 | ||||
4906 | SmallVector<int> ReuseShuffleIndicies; | |||
4907 | SmallVector<Value *> UniqueValues; | |||
4908 | auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, | |||
4909 | &UserTreeIdx, | |||
4910 | this](const InstructionsState &S) { | |||
4911 | // Check that every instruction appears once in this bundle. | |||
4912 | DenseMap<Value *, unsigned> UniquePositions(VL.size()); | |||
4913 | for (Value *V : VL) { | |||
4914 | if (isConstant(V)) { | |||
4915 | ReuseShuffleIndicies.emplace_back( | |||
4916 | isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); | |||
4917 | UniqueValues.emplace_back(V); | |||
4918 | continue; | |||
4919 | } | |||
4920 | auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); | |||
4921 | ReuseShuffleIndicies.emplace_back(Res.first->second); | |||
4922 | if (Res.second) | |||
4923 | UniqueValues.emplace_back(V); | |||
4924 | } | |||
4925 | size_t NumUniqueScalarValues = UniqueValues.size(); | |||
4926 | if (NumUniqueScalarValues == VL.size()) { | |||
4927 | ReuseShuffleIndicies.clear(); | |||
4928 | } else { | |||
4929 | LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Shuffle for reused scalars.\n" ; } } while (false); | |||
4930 | if (NumUniqueScalarValues <= 1 || | |||
4931 | (UniquePositions.size() == 1 && all_of(UniqueValues, | |||
4932 | [](Value *V) { | |||
4933 | return isa<UndefValue>(V) || | |||
4934 | !isConstant(V); | |||
4935 | })) || | |||
4936 | !llvm::isPowerOf2_32(NumUniqueScalarValues)) { | |||
4937 | LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Scalar used twice in bundle.\n" ; } } while (false); | |||
4938 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); | |||
4939 | return false; | |||
4940 | } | |||
4941 | VL = UniqueValues; | |||
4942 | } | |||
4943 | return true; | |||
4944 | }; | |||
4945 | ||||
4946 | InstructionsState S = getSameOpcode(VL, *TLI); | |||
4947 | ||||
4948 | // Gather if we hit the RecursionMaxDepth, unless this is a load (or z/sext of | |||
4949 | // a load), in which case peek through to include it in the tree, without | |||
4950 | // ballooning over-budget. | |||
4951 | if (Depth >= RecursionMaxDepth && | |||
4952 | !(S.MainOp && isa<Instruction>(S.MainOp) && S.MainOp == S.AltOp && | |||
4953 | VL.size() >= 4 && | |||
4954 | (match(S.MainOp, m_Load(m_Value())) || all_of(VL, [&S](const Value *I) { | |||
4955 | return match(I, | |||
4956 | m_OneUse(m_ZExtOrSExt(m_OneUse(m_Load(m_Value()))))) && | |||
4957 | cast<Instruction>(I)->getOpcode() == | |||
4958 | cast<Instruction>(S.MainOp)->getOpcode(); | |||
4959 | })))) { | |||
4960 | LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering due to max recursion depth.\n" ; } } while (false); | |||
4961 | if (TryToFindDuplicates(S)) | |||
4962 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
4963 | ReuseShuffleIndicies); | |||
4964 | return; | |||
4965 | } | |||
4966 | ||||
4967 | // Don't handle scalable vectors | |||
4968 | if (S.getOpcode() == Instruction::ExtractElement && | |||
4969 | isa<ScalableVectorType>( | |||
4970 | cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { | |||
4971 | LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering due to scalable vector type.\n" ; } } while (false); | |||
4972 | if (TryToFindDuplicates(S)) | |||
4973 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
4974 | ReuseShuffleIndicies); | |||
4975 | return; | |||
4976 | } | |||
4977 | ||||
4978 | // Don't handle vectors. | |||
4979 | if (S.OpValue->getType()->isVectorTy() && | |||
4980 | !isa<InsertElementInst>(S.OpValue)) { | |||
4981 | LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering due to vector type.\n" ; } } while (false); | |||
4982 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); | |||
4983 | return; | |||
4984 | } | |||
4985 | ||||
4986 | if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) | |||
4987 | if (SI->getValueOperand()->getType()->isVectorTy()) { | |||
4988 | LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering due to store vector type.\n" ; } } while (false); | |||
4989 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); | |||
4990 | return; | |||
4991 | } | |||
4992 | ||||
4993 | // If all of the operands are identical or constant we have a simple solution. | |||
4994 | // If we deal with insert/extract instructions, they all must have constant | |||
4995 | // indices, otherwise we should gather them, not try to vectorize. | |||
4996 | // If alternate op node with 2 elements with gathered operands - do not | |||
4997 | // vectorize. | |||
4998 | auto &&NotProfitableForVectorization = [&S, this, | |||
4999 | Depth](ArrayRef<Value *> VL) { | |||
5000 | if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2) | |||
5001 | return false; | |||
5002 | if (VectorizableTree.size() < MinTreeSize) | |||
5003 | return false; | |||
5004 | if (Depth >= RecursionMaxDepth - 1) | |||
5005 | return true; | |||
5006 | // Check if all operands are extracts, part of vector node or can build a | |||
5007 | // regular vectorize node. | |||
5008 | SmallVector<unsigned, 2> InstsCount(VL.size(), 0); | |||
5009 | for (Value *V : VL) { | |||
5010 | auto *I = cast<Instruction>(V); | |||
5011 | InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) { | |||
5012 | return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op); | |||
5013 | })); | |||
5014 | } | |||
5015 | bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp); | |||
5016 | if ((IsCommutative && | |||
5017 | std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) || | |||
5018 | (!IsCommutative && | |||
5019 | all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; }))) | |||
5020 | return true; | |||
5021 | assert(VL.size() == 2 && "Expected only 2 alternate op instructions.")(static_cast <bool> (VL.size() == 2 && "Expected only 2 alternate op instructions." ) ? void (0) : __assert_fail ("VL.size() == 2 && \"Expected only 2 alternate op instructions.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5021, __extension__ __PRETTY_FUNCTION__)); | |||
5022 | SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates; | |||
5023 | auto *I1 = cast<Instruction>(VL.front()); | |||
5024 | auto *I2 = cast<Instruction>(VL.back()); | |||
5025 | for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) | |||
5026 | Candidates.emplace_back().emplace_back(I1->getOperand(Op), | |||
5027 | I2->getOperand(Op)); | |||
5028 | if (static_cast<unsigned>(count_if( | |||
5029 | Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { | |||
5030 | return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); | |||
5031 | })) >= S.MainOp->getNumOperands() / 2) | |||
5032 | return false; | |||
5033 | if (S.MainOp->getNumOperands() > 2) | |||
5034 | return true; | |||
5035 | if (IsCommutative) { | |||
5036 | // Check permuted operands. | |||
5037 | Candidates.clear(); | |||
5038 | for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) | |||
5039 | Candidates.emplace_back().emplace_back(I1->getOperand(Op), | |||
5040 | I2->getOperand((Op + 1) % E)); | |||
5041 | if (any_of( | |||
5042 | Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { | |||
5043 | return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); | |||
5044 | })) | |||
5045 | return false; | |||
5046 | } | |||
5047 | return true; | |||
5048 | }; | |||
5049 | SmallVector<unsigned> SortedIndices; | |||
5050 | BasicBlock *BB = nullptr; | |||
5051 | bool IsScatterVectorizeUserTE = | |||
5052 | UserTreeIdx.UserTE && | |||
5053 | UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize; | |||
5054 | bool AreAllSameInsts = | |||
5055 | (S.getOpcode() && allSameBlock(VL)) || | |||
5056 | (S.OpValue->getType()->isPointerTy() && IsScatterVectorizeUserTE && | |||
5057 | VL.size() > 2 && | |||
5058 | all_of(VL, | |||
5059 | [&BB](Value *V) { | |||
5060 | auto *I = dyn_cast<GetElementPtrInst>(V); | |||
5061 | if (!I) | |||
5062 | return doesNotNeedToBeScheduled(V); | |||
5063 | if (!BB) | |||
5064 | BB = I->getParent(); | |||
5065 | return BB == I->getParent() && I->getNumOperands() == 2; | |||
5066 | }) && | |||
5067 | BB && | |||
5068 | sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL, *SE, | |||
5069 | SortedIndices)); | |||
5070 | if (!AreAllSameInsts || allConstant(VL) || isSplat(VL) || | |||
5071 | (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>( | |||
5072 | S.OpValue) && | |||
5073 | !all_of(VL, isVectorLikeInstWithConstOps)) || | |||
5074 | NotProfitableForVectorization(VL)) { | |||
5075 | LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n" ; } } while (false); | |||
5076 | if (TryToFindDuplicates(S)) | |||
5077 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5078 | ReuseShuffleIndicies); | |||
5079 | return; | |||
5080 | } | |||
5081 | ||||
5082 | // We now know that this is a vector of instructions of the same type from | |||
5083 | // the same block. | |||
5084 | ||||
5085 | // Don't vectorize ephemeral values. | |||
5086 | if (!EphValues.empty()) { | |||
5087 | for (Value *V : VL) { | |||
5088 | if (EphValues.count(V)) { | |||
5089 | LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: The instruction (" << * V << ") is ephemeral.\n"; } } while (false) | |||
5090 | << ") is ephemeral.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: The instruction (" << * V << ") is ephemeral.\n"; } } while (false); | |||
5091 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); | |||
5092 | return; | |||
5093 | } | |||
5094 | } | |||
5095 | } | |||
5096 | ||||
5097 | // Check if this is a duplicate of another entry. | |||
5098 | if (TreeEntry *E = getTreeEntry(S.OpValue)) { | |||
5099 | LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"; } } while (false); | |||
5100 | if (!E->isSame(VL)) { | |||
5101 | LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering due to partial overlap.\n" ; } } while (false); | |||
5102 | if (TryToFindDuplicates(S)) | |||
5103 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5104 | ReuseShuffleIndicies); | |||
5105 | return; | |||
5106 | } | |||
5107 | // Record the reuse of the tree node. FIXME, currently this is only used to | |||
5108 | // properly draw the graph rather than for the actual vectorization. | |||
5109 | E->UserTreeIndices.push_back(UserTreeIdx); | |||
5110 | LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValuedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue << ".\n"; } } while (false) | |||
5111 | << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue << ".\n"; } } while (false); | |||
5112 | return; | |||
5113 | } | |||
5114 | ||||
5115 | // Check that none of the instructions in the bundle are already in the tree. | |||
5116 | for (Value *V : VL) { | |||
5117 | if (!IsScatterVectorizeUserTE && !isa<Instruction>(V)) | |||
5118 | continue; | |||
5119 | if (getTreeEntry(V)) { | |||
5120 | LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: The instruction (" << * V << ") is already in tree.\n"; } } while (false) | |||
5121 | << ") is already in tree.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: The instruction (" << * V << ") is already in tree.\n"; } } while (false); | |||
5122 | if (TryToFindDuplicates(S)) | |||
5123 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5124 | ReuseShuffleIndicies); | |||
5125 | return; | |||
5126 | } | |||
5127 | } | |||
5128 | ||||
5129 | // The reduction nodes (stored in UserIgnoreList) also should stay scalar. | |||
5130 | if (UserIgnoreList && !UserIgnoreList->empty()) { | |||
5131 | for (Value *V : VL) { | |||
5132 | if (UserIgnoreList && UserIgnoreList->contains(V)) { | |||
5133 | LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering due to gathered scalar.\n" ; } } while (false); | |||
5134 | if (TryToFindDuplicates(S)) | |||
5135 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5136 | ReuseShuffleIndicies); | |||
5137 | return; | |||
5138 | } | |||
5139 | } | |||
5140 | } | |||
5141 | ||||
5142 | // Special processing for sorted pointers for ScatterVectorize node with | |||
5143 | // constant indeces only. | |||
5144 | if (AreAllSameInsts && UserTreeIdx.UserTE && | |||
5145 | UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize && | |||
5146 | !(S.getOpcode() && allSameBlock(VL))) { | |||
5147 | assert(S.OpValue->getType()->isPointerTy() &&(static_cast <bool> (S.OpValue->getType()->isPointerTy () && count_if(VL, [](Value *V) { return isa<GetElementPtrInst >(V); }) >= 2 && "Expected pointers only.") ? void (0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5150, __extension__ __PRETTY_FUNCTION__)) | |||
5148 | count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >=(static_cast <bool> (S.OpValue->getType()->isPointerTy () && count_if(VL, [](Value *V) { return isa<GetElementPtrInst >(V); }) >= 2 && "Expected pointers only.") ? void (0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5150, __extension__ __PRETTY_FUNCTION__)) | |||
5149 | 2 &&(static_cast <bool> (S.OpValue->getType()->isPointerTy () && count_if(VL, [](Value *V) { return isa<GetElementPtrInst >(V); }) >= 2 && "Expected pointers only.") ? void (0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5150, __extension__ __PRETTY_FUNCTION__)) | |||
5150 | "Expected pointers only.")(static_cast <bool> (S.OpValue->getType()->isPointerTy () && count_if(VL, [](Value *V) { return isa<GetElementPtrInst >(V); }) >= 2 && "Expected pointers only.") ? void (0) : __assert_fail ("S.OpValue->getType()->isPointerTy() && count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 2 && \"Expected pointers only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5150, __extension__ __PRETTY_FUNCTION__)); | |||
5151 | // Reset S to make it GetElementPtr kind of node. | |||
5152 | const auto *It = find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }); | |||
5153 | assert(It != VL.end() && "Expected at least one GEP.")(static_cast <bool> (It != VL.end() && "Expected at least one GEP." ) ? void (0) : __assert_fail ("It != VL.end() && \"Expected at least one GEP.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5153, __extension__ __PRETTY_FUNCTION__)); | |||
5154 | S = getSameOpcode(*It, *TLI); | |||
5155 | } | |||
5156 | ||||
5157 | // Check that all of the users of the scalars that we want to vectorize are | |||
5158 | // schedulable. | |||
5159 | auto *VL0 = cast<Instruction>(S.OpValue); | |||
5160 | BB = VL0->getParent(); | |||
5161 | ||||
5162 | if (!DT->isReachableFromEntry(BB)) { | |||
5163 | // Don't go into unreachable blocks. They may contain instructions with | |||
5164 | // dependency cycles which confuse the final scheduling. | |||
5165 | LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: bundle in unreachable block.\n" ; } } while (false); | |||
5166 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); | |||
5167 | return; | |||
5168 | } | |||
5169 | ||||
5170 | // Don't go into catchswitch blocks, which can happen with PHIs. | |||
5171 | // Such blocks can only have PHIs and the catchswitch. There is no | |||
5172 | // place to insert a shuffle if we need to, so just avoid that issue. | |||
5173 | if (isa<CatchSwitchInst>(BB->getTerminator())) { | |||
5174 | LLVM_DEBUG(dbgs() << "SLP: bundle in catchswitch block.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: bundle in catchswitch block.\n" ; } } while (false); | |||
5175 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); | |||
5176 | return; | |||
5177 | } | |||
5178 | ||||
5179 | // Check that every instruction appears once in this bundle. | |||
5180 | if (!TryToFindDuplicates(S)) | |||
5181 | return; | |||
5182 | ||||
5183 | auto &BSRef = BlocksSchedules[BB]; | |||
5184 | if (!BSRef) | |||
5185 | BSRef = std::make_unique<BlockScheduling>(BB); | |||
5186 | ||||
5187 | BlockScheduling &BS = *BSRef; | |||
5188 | ||||
5189 | Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); | |||
5190 | #ifdef EXPENSIVE_CHECKS | |||
5191 | // Make sure we didn't break any internal invariants | |||
5192 | BS.verify(); | |||
5193 | #endif | |||
5194 | if (!Bundle) { | |||
5195 | LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: We are not able to schedule this bundle!\n" ; } } while (false); | |||
5196 | assert((!BS.getScheduleData(VL0) ||(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData (VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure" ) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5198, __extension__ __PRETTY_FUNCTION__)) | |||
5197 | !BS.getScheduleData(VL0)->isPartOfBundle()) &&(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData (VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure" ) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5198, __extension__ __PRETTY_FUNCTION__)) | |||
5198 | "tryScheduleBundle should cancelScheduling on failure")(static_cast <bool> ((!BS.getScheduleData(VL0) || !BS.getScheduleData (VL0)->isPartOfBundle()) && "tryScheduleBundle should cancelScheduling on failure" ) ? void (0) : __assert_fail ("(!BS.getScheduleData(VL0) || !BS.getScheduleData(VL0)->isPartOfBundle()) && \"tryScheduleBundle should cancelScheduling on failure\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5198, __extension__ __PRETTY_FUNCTION__)); | |||
5199 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5200 | ReuseShuffleIndicies); | |||
5201 | return; | |||
5202 | } | |||
5203 | LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: We are able to schedule this bundle.\n" ; } } while (false); | |||
5204 | ||||
5205 | unsigned ShuffleOrOp = S.isAltShuffle() ? | |||
5206 | (unsigned) Instruction::ShuffleVector : S.getOpcode(); | |||
5207 | switch (ShuffleOrOp) { | |||
5208 | case Instruction::PHI: { | |||
5209 | auto *PH = cast<PHINode>(VL0); | |||
5210 | ||||
5211 | // Check for terminator values (e.g. invoke). | |||
5212 | for (Value *V : VL) | |||
5213 | for (Value *Incoming : cast<PHINode>(V)->incoming_values()) { | |||
5214 | Instruction *Term = dyn_cast<Instruction>(Incoming); | |||
5215 | if (Term && Term->isTerminator()) { | |||
5216 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Need to swizzle PHINodes (terminator use).\n" ; } } while (false) | |||
5217 | << "SLP: Need to swizzle PHINodes (terminator use).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Need to swizzle PHINodes (terminator use).\n" ; } } while (false); | |||
5218 | BS.cancelScheduling(VL, VL0); | |||
5219 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5220 | ReuseShuffleIndicies); | |||
5221 | return; | |||
5222 | } | |||
5223 | } | |||
5224 | ||||
5225 | TreeEntry *TE = | |||
5226 | newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); | |||
5227 | LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of PHINodes.\n" ; } } while (false); | |||
5228 | ||||
5229 | // Keeps the reordered operands to avoid code duplication. | |||
5230 | SmallVector<ValueList, 2> OperandsVec; | |||
5231 | for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { | |||
5232 | if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { | |||
5233 | ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); | |||
5234 | TE->setOperand(I, Operands); | |||
5235 | OperandsVec.push_back(Operands); | |||
5236 | continue; | |||
5237 | } | |||
5238 | ValueList Operands; | |||
5239 | // Prepare the operand vector. | |||
5240 | for (Value *V : VL) | |||
5241 | Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( | |||
5242 | PH->getIncomingBlock(I))); | |||
5243 | TE->setOperand(I, Operands); | |||
5244 | OperandsVec.push_back(Operands); | |||
5245 | } | |||
5246 | for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) | |||
5247 | buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); | |||
5248 | return; | |||
5249 | } | |||
5250 | case Instruction::ExtractValue: | |||
5251 | case Instruction::ExtractElement: { | |||
5252 | OrdersType CurrentOrder; | |||
5253 | bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); | |||
5254 | if (Reuse) { | |||
5255 | LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Reusing or shuffling extract sequence.\n" ; } } while (false); | |||
5256 | newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5257 | ReuseShuffleIndicies); | |||
5258 | // This is a special case, as it does not gather, but at the same time | |||
5259 | // we are not extending buildTree_rec() towards the operands. | |||
5260 | ValueList Op0; | |||
5261 | Op0.assign(VL.size(), VL0->getOperand(0)); | |||
5262 | VectorizableTree.back()->setOperand(0, Op0); | |||
5263 | return; | |||
5264 | } | |||
5265 | if (!CurrentOrder.empty()) { | |||
5266 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " "with order"; for (unsigned Idx : CurrentOrder) dbgs() << " " << Idx; dbgs() << "\n"; }; } } while (false) | |||
5267 | dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " "with order"; for (unsigned Idx : CurrentOrder) dbgs() << " " << Idx; dbgs() << "\n"; }; } } while (false) | |||
5268 | "with order";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " "with order"; for (unsigned Idx : CurrentOrder) dbgs() << " " << Idx; dbgs() << "\n"; }; } } while (false) | |||
5269 | for (unsigned Idx : CurrentOrder)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " "with order"; for (unsigned Idx : CurrentOrder) dbgs() << " " << Idx; dbgs() << "\n"; }; } } while (false) | |||
5270 | dbgs() << " " << Idx;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " "with order"; for (unsigned Idx : CurrentOrder) dbgs() << " " << Idx; dbgs() << "\n"; }; } } while (false) | |||
5271 | dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " "with order"; for (unsigned Idx : CurrentOrder) dbgs() << " " << Idx; dbgs() << "\n"; }; } } while (false) | |||
5272 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " "with order"; for (unsigned Idx : CurrentOrder) dbgs() << " " << Idx; dbgs() << "\n"; }; } } while (false); | |||
5273 | fixupOrderingIndices(CurrentOrder); | |||
5274 | // Insert new order with initial value 0, if it does not exist, | |||
5275 | // otherwise return the iterator to the existing one. | |||
5276 | newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5277 | ReuseShuffleIndicies, CurrentOrder); | |||
5278 | // This is a special case, as it does not gather, but at the same time | |||
5279 | // we are not extending buildTree_rec() towards the operands. | |||
5280 | ValueList Op0; | |||
5281 | Op0.assign(VL.size(), VL0->getOperand(0)); | |||
5282 | VectorizableTree.back()->setOperand(0, Op0); | |||
5283 | return; | |||
5284 | } | |||
5285 | LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gather extract sequence.\n"; } } while (false); | |||
5286 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5287 | ReuseShuffleIndicies); | |||
5288 | BS.cancelScheduling(VL, VL0); | |||
5289 | return; | |||
5290 | } | |||
5291 | case Instruction::InsertElement: { | |||
5292 | assert(ReuseShuffleIndicies.empty() && "All inserts should be unique")(static_cast <bool> (ReuseShuffleIndicies.empty() && "All inserts should be unique") ? void (0) : __assert_fail ( "ReuseShuffleIndicies.empty() && \"All inserts should be unique\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5292, __extension__ __PRETTY_FUNCTION__)); | |||
5293 | ||||
5294 | // Check that we have a buildvector and not a shuffle of 2 or more | |||
5295 | // different vectors. | |||
5296 | ValueSet SourceVectors; | |||
5297 | for (Value *V : VL) { | |||
5298 | SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); | |||
5299 | assert(getInsertIndex(V) != None && "Non-constant or undef index?")(static_cast <bool> (getInsertIndex(V) != None && "Non-constant or undef index?") ? void (0) : __assert_fail ( "getInsertIndex(V) != None && \"Non-constant or undef index?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5299, __extension__ __PRETTY_FUNCTION__)); | |||
5300 | } | |||
5301 | ||||
5302 | if (count_if(VL, [&SourceVectors](Value *V) { | |||
5303 | return !SourceVectors.contains(V); | |||
5304 | }) >= 2) { | |||
5305 | // Found 2nd source vector - cancel. | |||
5306 | LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gather of insertelement vectors with " "different source vectors.\n"; } } while (false) | |||
5307 | "different source vectors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gather of insertelement vectors with " "different source vectors.\n"; } } while (false); | |||
5308 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); | |||
5309 | BS.cancelScheduling(VL, VL0); | |||
5310 | return; | |||
5311 | } | |||
5312 | ||||
5313 | auto OrdCompare = [](const std::pair<int, int> &P1, | |||
5314 | const std::pair<int, int> &P2) { | |||
5315 | return P1.first > P2.first; | |||
5316 | }; | |||
5317 | PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, | |||
5318 | decltype(OrdCompare)> | |||
5319 | Indices(OrdCompare); | |||
5320 | for (int I = 0, E = VL.size(); I < E; ++I) { | |||
5321 | unsigned Idx = *getInsertIndex(VL[I]); | |||
5322 | Indices.emplace(Idx, I); | |||
5323 | } | |||
5324 | OrdersType CurrentOrder(VL.size(), VL.size()); | |||
5325 | bool IsIdentity = true; | |||
5326 | for (int I = 0, E = VL.size(); I < E; ++I) { | |||
5327 | CurrentOrder[Indices.top().second] = I; | |||
5328 | IsIdentity &= Indices.top().second == I; | |||
5329 | Indices.pop(); | |||
5330 | } | |||
5331 | if (IsIdentity) | |||
5332 | CurrentOrder.clear(); | |||
5333 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5334 | None, CurrentOrder); | |||
5335 | LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added inserts bundle.\n"; } } while (false); | |||
5336 | ||||
5337 | constexpr int NumOps = 2; | |||
5338 | ValueList VectorOperands[NumOps]; | |||
5339 | for (int I = 0; I < NumOps; ++I) { | |||
5340 | for (Value *V : VL) | |||
5341 | VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); | |||
5342 | ||||
5343 | TE->setOperand(I, VectorOperands[I]); | |||
5344 | } | |||
5345 | buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); | |||
5346 | return; | |||
5347 | } | |||
5348 | case Instruction::Load: { | |||
5349 | // Check that a vectorized load would load the same memory as a scalar | |||
5350 | // load. For example, we don't want to vectorize loads that are smaller | |||
5351 | // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM | |||
5352 | // treats loading/storing it as an i8 struct. If we vectorize loads/stores | |||
5353 | // from such a struct, we read/write packed bits disagreeing with the | |||
5354 | // unvectorized version. | |||
5355 | SmallVector<Value *> PointerOps; | |||
5356 | OrdersType CurrentOrder; | |||
5357 | TreeEntry *TE = nullptr; | |||
5358 | switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, *LI, *TLI, | |||
5359 | CurrentOrder, PointerOps)) { | |||
5360 | case LoadsState::Vectorize: | |||
5361 | if (CurrentOrder.empty()) { | |||
5362 | // Original loads are consecutive and does not require reordering. | |||
5363 | TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5364 | ReuseShuffleIndicies); | |||
5365 | LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of loads.\n"; } } while (false); | |||
5366 | } else { | |||
5367 | fixupOrderingIndices(CurrentOrder); | |||
5368 | // Need to reorder. | |||
5369 | TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5370 | ReuseShuffleIndicies, CurrentOrder); | |||
5371 | LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of jumbled loads.\n" ; } } while (false); | |||
5372 | } | |||
5373 | TE->setOperandsInOrder(); | |||
5374 | break; | |||
5375 | case LoadsState::ScatterVectorize: | |||
5376 | // Vectorizing non-consecutive loads with `llvm.masked.gather`. | |||
5377 | TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, | |||
5378 | UserTreeIdx, ReuseShuffleIndicies); | |||
5379 | TE->setOperandsInOrder(); | |||
5380 | buildTree_rec(PointerOps, Depth + 1, {TE, 0}); | |||
5381 | LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of non-consecutive loads.\n" ; } } while (false); | |||
5382 | break; | |||
5383 | case LoadsState::Gather: | |||
5384 | BS.cancelScheduling(VL, VL0); | |||
5385 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5386 | ReuseShuffleIndicies); | |||
5387 | #ifndef NDEBUG | |||
5388 | Type *ScalarTy = VL0->getType(); | |||
5389 | if (DL->getTypeSizeInBits(ScalarTy) != | |||
5390 | DL->getTypeAllocSizeInBits(ScalarTy)) | |||
5391 | LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering loads of non-packed type.\n" ; } } while (false); | |||
5392 | else if (any_of(VL, [](Value *V) { | |||
5393 | return !cast<LoadInst>(V)->isSimple(); | |||
5394 | })) | |||
5395 | LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering non-simple loads.\n" ; } } while (false); | |||
5396 | else | |||
5397 | LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering non-consecutive loads.\n" ; } } while (false); | |||
5398 | #endif // NDEBUG | |||
5399 | break; | |||
5400 | } | |||
5401 | return; | |||
5402 | } | |||
5403 | case Instruction::ZExt: | |||
5404 | case Instruction::SExt: | |||
5405 | case Instruction::FPToUI: | |||
5406 | case Instruction::FPToSI: | |||
5407 | case Instruction::FPExt: | |||
5408 | case Instruction::PtrToInt: | |||
5409 | case Instruction::IntToPtr: | |||
5410 | case Instruction::SIToFP: | |||
5411 | case Instruction::UIToFP: | |||
5412 | case Instruction::Trunc: | |||
5413 | case Instruction::FPTrunc: | |||
5414 | case Instruction::BitCast: { | |||
5415 | Type *SrcTy = VL0->getOperand(0)->getType(); | |||
5416 | for (Value *V : VL) { | |||
5417 | Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); | |||
5418 | if (Ty != SrcTy || !isValidElementType(Ty)) { | |||
5419 | BS.cancelScheduling(VL, VL0); | |||
5420 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5421 | ReuseShuffleIndicies); | |||
5422 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering casts with different src types.\n" ; } } while (false) | |||
5423 | << "SLP: Gathering casts with different src types.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering casts with different src types.\n" ; } } while (false); | |||
5424 | return; | |||
5425 | } | |||
5426 | } | |||
5427 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5428 | ReuseShuffleIndicies); | |||
5429 | LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of casts.\n"; } } while (false); | |||
5430 | ||||
5431 | TE->setOperandsInOrder(); | |||
5432 | for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { | |||
5433 | ValueList Operands; | |||
5434 | // Prepare the operand vector. | |||
5435 | for (Value *V : VL) | |||
5436 | Operands.push_back(cast<Instruction>(V)->getOperand(i)); | |||
5437 | ||||
5438 | buildTree_rec(Operands, Depth + 1, {TE, i}); | |||
5439 | } | |||
5440 | return; | |||
5441 | } | |||
5442 | case Instruction::ICmp: | |||
5443 | case Instruction::FCmp: { | |||
5444 | // Check that all of the compares have the same predicate. | |||
5445 | CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); | |||
5446 | CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); | |||
5447 | Type *ComparedTy = VL0->getOperand(0)->getType(); | |||
5448 | for (Value *V : VL) { | |||
5449 | CmpInst *Cmp = cast<CmpInst>(V); | |||
5450 | if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || | |||
5451 | Cmp->getOperand(0)->getType() != ComparedTy) { | |||
5452 | BS.cancelScheduling(VL, VL0); | |||
5453 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5454 | ReuseShuffleIndicies); | |||
5455 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering cmp with different predicate.\n" ; } } while (false) | |||
5456 | << "SLP: Gathering cmp with different predicate.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering cmp with different predicate.\n" ; } } while (false); | |||
5457 | return; | |||
5458 | } | |||
5459 | } | |||
5460 | ||||
5461 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5462 | ReuseShuffleIndicies); | |||
5463 | LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of compares.\n" ; } } while (false); | |||
5464 | ||||
5465 | ValueList Left, Right; | |||
5466 | if (cast<CmpInst>(VL0)->isCommutative()) { | |||
5467 | // Commutative predicate - collect + sort operands of the instructions | |||
5468 | // so that each side is more likely to have the same opcode. | |||
5469 | assert(P0 == SwapP0 && "Commutative Predicate mismatch")(static_cast <bool> (P0 == SwapP0 && "Commutative Predicate mismatch" ) ? void (0) : __assert_fail ("P0 == SwapP0 && \"Commutative Predicate mismatch\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5469, __extension__ __PRETTY_FUNCTION__)); | |||
5470 | reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE, *this); | |||
5471 | } else { | |||
5472 | // Collect operands - commute if it uses the swapped predicate. | |||
5473 | for (Value *V : VL) { | |||
5474 | auto *Cmp = cast<CmpInst>(V); | |||
5475 | Value *LHS = Cmp->getOperand(0); | |||
5476 | Value *RHS = Cmp->getOperand(1); | |||
5477 | if (Cmp->getPredicate() != P0) | |||
5478 | std::swap(LHS, RHS); | |||
5479 | Left.push_back(LHS); | |||
5480 | Right.push_back(RHS); | |||
5481 | } | |||
5482 | } | |||
5483 | TE->setOperand(0, Left); | |||
5484 | TE->setOperand(1, Right); | |||
5485 | buildTree_rec(Left, Depth + 1, {TE, 0}); | |||
5486 | buildTree_rec(Right, Depth + 1, {TE, 1}); | |||
5487 | return; | |||
5488 | } | |||
5489 | case Instruction::Select: | |||
5490 | case Instruction::FNeg: | |||
5491 | case Instruction::Add: | |||
5492 | case Instruction::FAdd: | |||
5493 | case Instruction::Sub: | |||
5494 | case Instruction::FSub: | |||
5495 | case Instruction::Mul: | |||
5496 | case Instruction::FMul: | |||
5497 | case Instruction::UDiv: | |||
5498 | case Instruction::SDiv: | |||
5499 | case Instruction::FDiv: | |||
5500 | case Instruction::URem: | |||
5501 | case Instruction::SRem: | |||
5502 | case Instruction::FRem: | |||
5503 | case Instruction::Shl: | |||
5504 | case Instruction::LShr: | |||
5505 | case Instruction::AShr: | |||
5506 | case Instruction::And: | |||
5507 | case Instruction::Or: | |||
5508 | case Instruction::Xor: { | |||
5509 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5510 | ReuseShuffleIndicies); | |||
5511 | LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of un/bin op.\n" ; } } while (false); | |||
5512 | ||||
5513 | // Sort operands of the instructions so that each side is more likely to | |||
5514 | // have the same opcode. | |||
5515 | if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { | |||
5516 | ValueList Left, Right; | |||
5517 | reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE, *this); | |||
5518 | TE->setOperand(0, Left); | |||
5519 | TE->setOperand(1, Right); | |||
5520 | buildTree_rec(Left, Depth + 1, {TE, 0}); | |||
5521 | buildTree_rec(Right, Depth + 1, {TE, 1}); | |||
5522 | return; | |||
5523 | } | |||
5524 | ||||
5525 | TE->setOperandsInOrder(); | |||
5526 | for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { | |||
5527 | ValueList Operands; | |||
5528 | // Prepare the operand vector. | |||
5529 | for (Value *V : VL) | |||
5530 | Operands.push_back(cast<Instruction>(V)->getOperand(i)); | |||
5531 | ||||
5532 | buildTree_rec(Operands, Depth + 1, {TE, i}); | |||
5533 | } | |||
5534 | return; | |||
5535 | } | |||
5536 | case Instruction::GetElementPtr: { | |||
5537 | // We don't combine GEPs with complicated (nested) indexing. | |||
5538 | for (Value *V : VL) { | |||
5539 | auto *I = dyn_cast<GetElementPtrInst>(V); | |||
5540 | if (!I) | |||
5541 | continue; | |||
5542 | if (I->getNumOperands() != 2) { | |||
5543 | LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n" ; } } while (false); | |||
5544 | BS.cancelScheduling(VL, VL0); | |||
5545 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5546 | ReuseShuffleIndicies); | |||
5547 | return; | |||
5548 | } | |||
5549 | } | |||
5550 | ||||
5551 | // We can't combine several GEPs into one vector if they operate on | |||
5552 | // different types. | |||
5553 | Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType(); | |||
5554 | for (Value *V : VL) { | |||
5555 | auto *GEP = dyn_cast<GEPOperator>(V); | |||
5556 | if (!GEP) | |||
5557 | continue; | |||
5558 | Type *CurTy = GEP->getSourceElementType(); | |||
5559 | if (Ty0 != CurTy) { | |||
5560 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: not-vectorizable GEP (different types).\n" ; } } while (false) | |||
5561 | << "SLP: not-vectorizable GEP (different types).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: not-vectorizable GEP (different types).\n" ; } } while (false); | |||
5562 | BS.cancelScheduling(VL, VL0); | |||
5563 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5564 | ReuseShuffleIndicies); | |||
5565 | return; | |||
5566 | } | |||
5567 | } | |||
5568 | ||||
5569 | // We don't combine GEPs with non-constant indexes. | |||
5570 | Type *Ty1 = VL0->getOperand(1)->getType(); | |||
5571 | for (Value *V : VL) { | |||
5572 | auto *I = dyn_cast<GetElementPtrInst>(V); | |||
5573 | if (!I) | |||
5574 | continue; | |||
5575 | auto *Op = I->getOperand(1); | |||
5576 | if ((!IsScatterVectorizeUserTE && !isa<ConstantInt>(Op)) || | |||
5577 | (Op->getType() != Ty1 && | |||
5578 | ((IsScatterVectorizeUserTE && !isa<ConstantInt>(Op)) || | |||
5579 | Op->getType()->getScalarSizeInBits() > | |||
5580 | DL->getIndexSizeInBits( | |||
5581 | V->getType()->getPointerAddressSpace())))) { | |||
5582 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n" ; } } while (false) | |||
5583 | << "SLP: not-vectorizable GEP (non-constant indexes).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n" ; } } while (false); | |||
5584 | BS.cancelScheduling(VL, VL0); | |||
5585 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5586 | ReuseShuffleIndicies); | |||
5587 | return; | |||
5588 | } | |||
5589 | } | |||
5590 | ||||
5591 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5592 | ReuseShuffleIndicies); | |||
5593 | LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of GEPs.\n"; } } while (false); | |||
5594 | SmallVector<ValueList, 2> Operands(2); | |||
5595 | // Prepare the operand vector for pointer operands. | |||
5596 | for (Value *V : VL) { | |||
5597 | auto *GEP = dyn_cast<GetElementPtrInst>(V); | |||
5598 | if (!GEP) { | |||
5599 | Operands.front().push_back(V); | |||
5600 | continue; | |||
5601 | } | |||
5602 | Operands.front().push_back(GEP->getPointerOperand()); | |||
5603 | } | |||
5604 | TE->setOperand(0, Operands.front()); | |||
5605 | // Need to cast all indices to the same type before vectorization to | |||
5606 | // avoid crash. | |||
5607 | // Required to be able to find correct matches between different gather | |||
5608 | // nodes and reuse the vectorized values rather than trying to gather them | |||
5609 | // again. | |||
5610 | int IndexIdx = 1; | |||
5611 | Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); | |||
5612 | Type *Ty = all_of(VL, | |||
5613 | [VL0Ty, IndexIdx](Value *V) { | |||
5614 | auto *GEP = dyn_cast<GetElementPtrInst>(V); | |||
5615 | if (!GEP) | |||
5616 | return true; | |||
5617 | return VL0Ty == GEP->getOperand(IndexIdx)->getType(); | |||
5618 | }) | |||
5619 | ? VL0Ty | |||
5620 | : DL->getIndexType(cast<GetElementPtrInst>(VL0) | |||
5621 | ->getPointerOperandType() | |||
5622 | ->getScalarType()); | |||
5623 | // Prepare the operand vector. | |||
5624 | for (Value *V : VL) { | |||
5625 | auto *I = dyn_cast<GetElementPtrInst>(V); | |||
5626 | if (!I) { | |||
5627 | Operands.back().push_back( | |||
5628 | ConstantInt::get(Ty, 0, /*isSigned=*/false)); | |||
5629 | continue; | |||
5630 | } | |||
5631 | auto *Op = I->getOperand(IndexIdx); | |||
5632 | auto *CI = dyn_cast<ConstantInt>(Op); | |||
5633 | if (!CI) | |||
5634 | Operands.back().push_back(Op); | |||
5635 | else | |||
5636 | Operands.back().push_back(ConstantExpr::getIntegerCast( | |||
5637 | CI, Ty, CI->getValue().isSignBitSet())); | |||
5638 | } | |||
5639 | TE->setOperand(IndexIdx, Operands.back()); | |||
5640 | ||||
5641 | for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) | |||
5642 | buildTree_rec(Operands[I], Depth + 1, {TE, I}); | |||
5643 | return; | |||
5644 | } | |||
5645 | case Instruction::Store: { | |||
5646 | // Check if the stores are consecutive or if we need to swizzle them. | |||
5647 | llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); | |||
5648 | // Avoid types that are padded when being allocated as scalars, while | |||
5649 | // being packed together in a vector (such as i1). | |||
5650 | if (DL->getTypeSizeInBits(ScalarTy) != | |||
5651 | DL->getTypeAllocSizeInBits(ScalarTy)) { | |||
5652 | BS.cancelScheduling(VL, VL0); | |||
5653 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5654 | ReuseShuffleIndicies); | |||
5655 | LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering stores of non-packed type.\n" ; } } while (false); | |||
5656 | return; | |||
5657 | } | |||
5658 | // Make sure all stores in the bundle are simple - we can't vectorize | |||
5659 | // atomic or volatile stores. | |||
5660 | SmallVector<Value *, 4> PointerOps(VL.size()); | |||
5661 | ValueList Operands(VL.size()); | |||
5662 | auto POIter = PointerOps.begin(); | |||
5663 | auto OIter = Operands.begin(); | |||
5664 | for (Value *V : VL) { | |||
5665 | auto *SI = cast<StoreInst>(V); | |||
5666 | if (!SI->isSimple()) { | |||
5667 | BS.cancelScheduling(VL, VL0); | |||
5668 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5669 | ReuseShuffleIndicies); | |||
5670 | LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering non-simple stores.\n" ; } } while (false); | |||
5671 | return; | |||
5672 | } | |||
5673 | *POIter = SI->getPointerOperand(); | |||
5674 | *OIter = SI->getValueOperand(); | |||
5675 | ++POIter; | |||
5676 | ++OIter; | |||
5677 | } | |||
5678 | ||||
5679 | OrdersType CurrentOrder; | |||
5680 | // Check the order of pointer operands. | |||
5681 | if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { | |||
5682 | Value *Ptr0; | |||
5683 | Value *PtrN; | |||
5684 | if (CurrentOrder.empty()) { | |||
5685 | Ptr0 = PointerOps.front(); | |||
5686 | PtrN = PointerOps.back(); | |||
5687 | } else { | |||
5688 | Ptr0 = PointerOps[CurrentOrder.front()]; | |||
5689 | PtrN = PointerOps[CurrentOrder.back()]; | |||
5690 | } | |||
5691 | Optional<int> Dist = | |||
5692 | getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); | |||
5693 | // Check that the sorted pointer operands are consecutive. | |||
5694 | if (static_cast<unsigned>(*Dist) == VL.size() - 1) { | |||
5695 | if (CurrentOrder.empty()) { | |||
5696 | // Original stores are consecutive and does not require reordering. | |||
5697 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, | |||
5698 | UserTreeIdx, ReuseShuffleIndicies); | |||
5699 | TE->setOperandsInOrder(); | |||
5700 | buildTree_rec(Operands, Depth + 1, {TE, 0}); | |||
5701 | LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of stores.\n" ; } } while (false); | |||
5702 | } else { | |||
5703 | fixupOrderingIndices(CurrentOrder); | |||
5704 | TreeEntry *TE = | |||
5705 | newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5706 | ReuseShuffleIndicies, CurrentOrder); | |||
5707 | TE->setOperandsInOrder(); | |||
5708 | buildTree_rec(Operands, Depth + 1, {TE, 0}); | |||
5709 | LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a vector of jumbled stores.\n" ; } } while (false); | |||
5710 | } | |||
5711 | return; | |||
5712 | } | |||
5713 | } | |||
5714 | ||||
5715 | BS.cancelScheduling(VL, VL0); | |||
5716 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5717 | ReuseShuffleIndicies); | |||
5718 | LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Non-consecutive store.\n"; } } while (false); | |||
5719 | return; | |||
5720 | } | |||
5721 | case Instruction::Call: { | |||
5722 | // Check if the calls are all to the same vectorizable intrinsic or | |||
5723 | // library function. | |||
5724 | CallInst *CI = cast<CallInst>(VL0); | |||
5725 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
5726 | ||||
5727 | VFShape Shape = VFShape::get( | |||
5728 | *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), | |||
5729 | false /*HasGlobalPred*/); | |||
5730 | Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); | |||
5731 | ||||
5732 | if (!VecFunc && !isTriviallyVectorizable(ID)) { | |||
5733 | BS.cancelScheduling(VL, VL0); | |||
5734 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5735 | ReuseShuffleIndicies); | |||
5736 | LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Non-vectorizable call.\n"; } } while (false); | |||
5737 | return; | |||
5738 | } | |||
5739 | Function *F = CI->getCalledFunction(); | |||
5740 | unsigned NumArgs = CI->arg_size(); | |||
5741 | SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); | |||
5742 | for (unsigned j = 0; j != NumArgs; ++j) | |||
5743 | if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) | |||
5744 | ScalarArgs[j] = CI->getArgOperand(j); | |||
5745 | for (Value *V : VL) { | |||
5746 | CallInst *CI2 = dyn_cast<CallInst>(V); | |||
5747 | if (!CI2 || CI2->getCalledFunction() != F || | |||
5748 | getVectorIntrinsicIDForCall(CI2, TLI) != ID || | |||
5749 | (VecFunc && | |||
5750 | VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || | |||
5751 | !CI->hasIdenticalOperandBundleSchema(*CI2)) { | |||
5752 | BS.cancelScheduling(VL, VL0); | |||
5753 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5754 | ReuseShuffleIndicies); | |||
5755 | LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: mismatched calls:" << * CI << "!=" << *V << "\n"; } } while (false) | |||
5756 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: mismatched calls:" << * CI << "!=" << *V << "\n"; } } while (false); | |||
5757 | return; | |||
5758 | } | |||
5759 | // Some intrinsics have scalar arguments and should be same in order for | |||
5760 | // them to be vectorized. | |||
5761 | for (unsigned j = 0; j != NumArgs; ++j) { | |||
5762 | if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) { | |||
5763 | Value *A1J = CI2->getArgOperand(j); | |||
5764 | if (ScalarArgs[j] != A1J) { | |||
5765 | BS.cancelScheduling(VL, VL0); | |||
5766 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5767 | ReuseShuffleIndicies); | |||
5768 | LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: mismatched arguments in call:" << *CI << " argument " << ScalarArgs[j] << "!=" << A1J << "\n"; } } while (false) | |||
5769 | << " argument " << ScalarArgs[j] << "!=" << A1Jdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: mismatched arguments in call:" << *CI << " argument " << ScalarArgs[j] << "!=" << A1J << "\n"; } } while (false) | |||
5770 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: mismatched arguments in call:" << *CI << " argument " << ScalarArgs[j] << "!=" << A1J << "\n"; } } while (false); | |||
5771 | return; | |||
5772 | } | |||
5773 | } | |||
5774 | } | |||
5775 | // Verify that the bundle operands are identical between the two calls. | |||
5776 | if (CI->hasOperandBundles() && | |||
5777 | !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), | |||
5778 | CI->op_begin() + CI->getBundleOperandsEndIndex(), | |||
5779 | CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { | |||
5780 | BS.cancelScheduling(VL, VL0); | |||
5781 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5782 | ReuseShuffleIndicies); | |||
5783 | LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!=" << *V << '\n'; } } while (false) | |||
5784 | << *CI << "!=" << *V << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: mismatched bundle operands in calls:" << *CI << "!=" << *V << '\n'; } } while (false); | |||
5785 | return; | |||
5786 | } | |||
5787 | } | |||
5788 | ||||
5789 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5790 | ReuseShuffleIndicies); | |||
5791 | TE->setOperandsInOrder(); | |||
5792 | for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { | |||
5793 | // For scalar operands no need to to create an entry since no need to | |||
5794 | // vectorize it. | |||
5795 | if (isVectorIntrinsicWithScalarOpAtArg(ID, i)) | |||
5796 | continue; | |||
5797 | ValueList Operands; | |||
5798 | // Prepare the operand vector. | |||
5799 | for (Value *V : VL) { | |||
5800 | auto *CI2 = cast<CallInst>(V); | |||
5801 | Operands.push_back(CI2->getArgOperand(i)); | |||
5802 | } | |||
5803 | buildTree_rec(Operands, Depth + 1, {TE, i}); | |||
5804 | } | |||
5805 | return; | |||
5806 | } | |||
5807 | case Instruction::ShuffleVector: { | |||
5808 | // If this is not an alternate sequence of opcode like add-sub | |||
5809 | // then do not vectorize this instruction. | |||
5810 | if (!S.isAltShuffle()) { | |||
5811 | BS.cancelScheduling(VL, VL0); | |||
5812 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5813 | ReuseShuffleIndicies); | |||
5814 | LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: ShuffleVector are not vectorized.\n" ; } } while (false); | |||
5815 | return; | |||
5816 | } | |||
5817 | TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, | |||
5818 | ReuseShuffleIndicies); | |||
5819 | LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: added a ShuffleVector op.\n" ; } } while (false); | |||
5820 | ||||
5821 | // Reorder operands if reordering would enable vectorization. | |||
5822 | auto *CI = dyn_cast<CmpInst>(VL0); | |||
5823 | if (isa<BinaryOperator>(VL0) || CI) { | |||
5824 | ValueList Left, Right; | |||
5825 | if (!CI || all_of(VL, [](Value *V) { | |||
5826 | return cast<CmpInst>(V)->isCommutative(); | |||
5827 | })) { | |||
5828 | reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE, | |||
5829 | *this); | |||
5830 | } else { | |||
5831 | auto *MainCI = cast<CmpInst>(S.MainOp); | |||
5832 | auto *AltCI = cast<CmpInst>(S.AltOp); | |||
5833 | CmpInst::Predicate MainP = MainCI->getPredicate(); | |||
5834 | CmpInst::Predicate AltP = AltCI->getPredicate(); | |||
5835 | assert(MainP != AltP &&(static_cast <bool> (MainP != AltP && "Expected different main/alternate predicates." ) ? void (0) : __assert_fail ("MainP != AltP && \"Expected different main/alternate predicates.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5836, __extension__ __PRETTY_FUNCTION__)) | |||
5836 | "Expected different main/alternate predicates.")(static_cast <bool> (MainP != AltP && "Expected different main/alternate predicates." ) ? void (0) : __assert_fail ("MainP != AltP && \"Expected different main/alternate predicates.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5836, __extension__ __PRETTY_FUNCTION__)); | |||
5837 | // Collect operands - commute if it uses the swapped predicate or | |||
5838 | // alternate operation. | |||
5839 | for (Value *V : VL) { | |||
5840 | auto *Cmp = cast<CmpInst>(V); | |||
5841 | Value *LHS = Cmp->getOperand(0); | |||
5842 | Value *RHS = Cmp->getOperand(1); | |||
5843 | ||||
5844 | if (isAlternateInstruction(Cmp, MainCI, AltCI, *TLI)) { | |||
5845 | if (AltP == CmpInst::getSwappedPredicate(Cmp->getPredicate())) | |||
5846 | std::swap(LHS, RHS); | |||
5847 | } else { | |||
5848 | if (MainP == CmpInst::getSwappedPredicate(Cmp->getPredicate())) | |||
5849 | std::swap(LHS, RHS); | |||
5850 | } | |||
5851 | Left.push_back(LHS); | |||
5852 | Right.push_back(RHS); | |||
5853 | } | |||
5854 | } | |||
5855 | TE->setOperand(0, Left); | |||
5856 | TE->setOperand(1, Right); | |||
5857 | buildTree_rec(Left, Depth + 1, {TE, 0}); | |||
5858 | buildTree_rec(Right, Depth + 1, {TE, 1}); | |||
5859 | return; | |||
5860 | } | |||
5861 | ||||
5862 | TE->setOperandsInOrder(); | |||
5863 | for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { | |||
5864 | ValueList Operands; | |||
5865 | // Prepare the operand vector. | |||
5866 | for (Value *V : VL) | |||
5867 | Operands.push_back(cast<Instruction>(V)->getOperand(i)); | |||
5868 | ||||
5869 | buildTree_rec(Operands, Depth + 1, {TE, i}); | |||
5870 | } | |||
5871 | return; | |||
5872 | } | |||
5873 | default: | |||
5874 | BS.cancelScheduling(VL, VL0); | |||
5875 | newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, | |||
5876 | ReuseShuffleIndicies); | |||
5877 | LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Gathering unknown instruction.\n" ; } } while (false); | |||
5878 | return; | |||
5879 | } | |||
5880 | } | |||
5881 | ||||
5882 | unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { | |||
5883 | unsigned N = 1; | |||
5884 | Type *EltTy = T; | |||
5885 | ||||
5886 | while (isa<StructType, ArrayType, VectorType>(EltTy)) { | |||
5887 | if (auto *ST = dyn_cast<StructType>(EltTy)) { | |||
5888 | // Check that struct is homogeneous. | |||
5889 | for (const auto *Ty : ST->elements()) | |||
5890 | if (Ty != *ST->element_begin()) | |||
5891 | return 0; | |||
5892 | N *= ST->getNumElements(); | |||
5893 | EltTy = *ST->element_begin(); | |||
5894 | } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { | |||
5895 | N *= AT->getNumElements(); | |||
5896 | EltTy = AT->getElementType(); | |||
5897 | } else { | |||
5898 | auto *VT = cast<FixedVectorType>(EltTy); | |||
5899 | N *= VT->getNumElements(); | |||
5900 | EltTy = VT->getElementType(); | |||
5901 | } | |||
5902 | } | |||
5903 | ||||
5904 | if (!isValidElementType(EltTy)) | |||
5905 | return 0; | |||
5906 | uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); | |||
5907 | if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) | |||
5908 | return 0; | |||
5909 | return N; | |||
5910 | } | |||
5911 | ||||
5912 | bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, | |||
5913 | SmallVectorImpl<unsigned> &CurrentOrder) const { | |||
5914 | const auto *It = find_if(VL, [](Value *V) { | |||
5915 | return isa<ExtractElementInst, ExtractValueInst>(V); | |||
5916 | }); | |||
5917 | assert(It != VL.end() && "Expected at least one extract instruction.")(static_cast <bool> (It != VL.end() && "Expected at least one extract instruction." ) ? void (0) : __assert_fail ("It != VL.end() && \"Expected at least one extract instruction.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5917, __extension__ __PRETTY_FUNCTION__)); | |||
5918 | auto *E0 = cast<Instruction>(*It); | |||
5919 | assert(all_of(VL,(static_cast <bool> (all_of(VL, [](Value *V) { return isa <UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && "Invalid opcode") ? void (0) : __assert_fail ( "all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5924, __extension__ __PRETTY_FUNCTION__)) | |||
5920 | [](Value *V) {(static_cast <bool> (all_of(VL, [](Value *V) { return isa <UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && "Invalid opcode") ? void (0) : __assert_fail ( "all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5924, __extension__ __PRETTY_FUNCTION__)) | |||
5921 | return isa<UndefValue, ExtractElementInst, ExtractValueInst>((static_cast <bool> (all_of(VL, [](Value *V) { return isa <UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && "Invalid opcode") ? void (0) : __assert_fail ( "all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5924, __extension__ __PRETTY_FUNCTION__)) | |||
5922 | V);(static_cast <bool> (all_of(VL, [](Value *V) { return isa <UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && "Invalid opcode") ? void (0) : __assert_fail ( "all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5924, __extension__ __PRETTY_FUNCTION__)) | |||
5923 | }) &&(static_cast <bool> (all_of(VL, [](Value *V) { return isa <UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && "Invalid opcode") ? void (0) : __assert_fail ( "all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5924, __extension__ __PRETTY_FUNCTION__)) | |||
5924 | "Invalid opcode")(static_cast <bool> (all_of(VL, [](Value *V) { return isa <UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && "Invalid opcode") ? void (0) : __assert_fail ( "all_of(VL, [](Value *V) { return isa<UndefValue, ExtractElementInst, ExtractValueInst>( V); }) && \"Invalid opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 5924, __extension__ __PRETTY_FUNCTION__)); | |||
5925 | // Check if all of the extracts come from the same vector and from the | |||
5926 | // correct offset. | |||
5927 | Value *Vec = E0->getOperand(0); | |||
5928 | ||||
5929 | CurrentOrder.clear(); | |||
5930 | ||||
5931 | // We have to extract from a vector/aggregate with the same number of elements. | |||
5932 | unsigned NElts; | |||
5933 | if (E0->getOpcode() == Instruction::ExtractValue) { | |||
5934 | const DataLayout &DL = E0->getModule()->getDataLayout(); | |||
5935 | NElts = canMapToVector(Vec->getType(), DL); | |||
5936 | if (!NElts) | |||
5937 | return false; | |||
5938 | // Check if load can be rewritten as load of vector. | |||
5939 | LoadInst *LI = dyn_cast<LoadInst>(Vec); | |||
5940 | if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) | |||
5941 | return false; | |||
5942 | } else { | |||
5943 | NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); | |||
5944 | } | |||
5945 | ||||
5946 | if (NElts != VL.size()) | |||
5947 | return false; | |||
5948 | ||||
5949 | // Check that all of the indices extract from the correct offset. | |||
5950 | bool ShouldKeepOrder = true; | |||
5951 | unsigned E = VL.size(); | |||
5952 | // Assign to all items the initial value E + 1 so we can check if the extract | |||
5953 | // instruction index was used already. | |||
5954 | // Also, later we can check that all the indices are used and we have a | |||
5955 | // consecutive access in the extract instructions, by checking that no | |||
5956 | // element of CurrentOrder still has value E + 1. | |||
5957 | CurrentOrder.assign(E, E); | |||
5958 | unsigned I = 0; | |||
5959 | for (; I < E; ++I) { | |||
5960 | auto *Inst = dyn_cast<Instruction>(VL[I]); | |||
5961 | if (!Inst) | |||
5962 | continue; | |||
5963 | if (Inst->getOperand(0) != Vec) | |||
5964 | break; | |||
5965 | if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) | |||
5966 | if (isa<UndefValue>(EE->getIndexOperand())) | |||
5967 | continue; | |||
5968 | Optional<unsigned> Idx = getExtractIndex(Inst); | |||
5969 | if (!Idx) | |||
5970 | break; | |||
5971 | const unsigned ExtIdx = *Idx; | |||
5972 | if (ExtIdx != I) { | |||
5973 | if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) | |||
5974 | break; | |||
5975 | ShouldKeepOrder = false; | |||
5976 | CurrentOrder[ExtIdx] = I; | |||
5977 | } else { | |||
5978 | if (CurrentOrder[I] != E) | |||
5979 | break; | |||
5980 | CurrentOrder[I] = I; | |||
5981 | } | |||
5982 | } | |||
5983 | if (I < E) { | |||
5984 | CurrentOrder.clear(); | |||
5985 | return false; | |||
5986 | } | |||
5987 | if (ShouldKeepOrder) | |||
5988 | CurrentOrder.clear(); | |||
5989 | ||||
5990 | return ShouldKeepOrder; | |||
5991 | } | |||
5992 | ||||
5993 | bool BoUpSLP::areAllUsersVectorized(Instruction *I, | |||
5994 | ArrayRef<Value *> VectorizedVals) const { | |||
5995 | return (I->hasOneUse() && is_contained(VectorizedVals, I)) || | |||
5996 | all_of(I->users(), [this](User *U) { | |||
5997 | return ScalarToTreeEntry.count(U) > 0 || | |||
5998 | isVectorLikeInstWithConstOps(U) || | |||
5999 | (isa<ExtractElementInst>(U) && MustGather.contains(U)); | |||
6000 | }); | |||
6001 | } | |||
6002 | ||||
6003 | static std::pair<InstructionCost, InstructionCost> | |||
6004 | getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, | |||
6005 | TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { | |||
6006 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
6007 | ||||
6008 | // Calculate the cost of the scalar and vector calls. | |||
6009 | SmallVector<Type *, 4> VecTys; | |||
6010 | for (Use &Arg : CI->args()) | |||
6011 | VecTys.push_back( | |||
6012 | FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); | |||
6013 | FastMathFlags FMF; | |||
6014 | if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) | |||
6015 | FMF = FPCI->getFastMathFlags(); | |||
6016 | SmallVector<const Value *> Arguments(CI->args()); | |||
6017 | IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, | |||
6018 | dyn_cast<IntrinsicInst>(CI)); | |||
6019 | auto IntrinsicCost = | |||
6020 | TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); | |||
6021 | ||||
6022 | auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( | |||
6023 | VecTy->getNumElements())), | |||
6024 | false /*HasGlobalPred*/); | |||
6025 | Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); | |||
6026 | auto LibCost = IntrinsicCost; | |||
6027 | if (!CI->isNoBuiltin() && VecFunc) { | |||
6028 | // Calculate the cost of the vector library call. | |||
6029 | // If the corresponding vector call is cheaper, return its cost. | |||
6030 | LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, | |||
6031 | TTI::TCK_RecipThroughput); | |||
6032 | } | |||
6033 | return {IntrinsicCost, LibCost}; | |||
6034 | } | |||
6035 | ||||
6036 | /// Compute the cost of creating a vector of type \p VecTy containing the | |||
6037 | /// extracted values from \p VL. | |||
6038 | static InstructionCost | |||
6039 | computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, | |||
6040 | TargetTransformInfo::ShuffleKind ShuffleKind, | |||
6041 | ArrayRef<int> Mask, TargetTransformInfo &TTI) { | |||
6042 | unsigned NumOfParts = TTI.getNumberOfParts(VecTy); | |||
6043 | ||||
6044 | if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || | |||
6045 | VecTy->getNumElements() < NumOfParts) | |||
6046 | return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); | |||
6047 | ||||
6048 | bool AllConsecutive = true; | |||
6049 | unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; | |||
6050 | unsigned Idx = -1; | |||
6051 | InstructionCost Cost = 0; | |||
6052 | ||||
6053 | // Process extracts in blocks of EltsPerVector to check if the source vector | |||
6054 | // operand can be re-used directly. If not, add the cost of creating a shuffle | |||
6055 | // to extract the values into a vector register. | |||
6056 | SmallVector<int> RegMask(EltsPerVector, UndefMaskElem); | |||
6057 | for (auto *V : VL) { | |||
6058 | ++Idx; | |||
6059 | ||||
6060 | // Reached the start of a new vector registers. | |||
6061 | if (Idx % EltsPerVector == 0) { | |||
6062 | RegMask.assign(EltsPerVector, UndefMaskElem); | |||
6063 | AllConsecutive = true; | |||
6064 | continue; | |||
6065 | } | |||
6066 | ||||
6067 | // Need to exclude undefs from analysis. | |||
6068 | if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) | |||
6069 | continue; | |||
6070 | ||||
6071 | // Check all extracts for a vector register on the target directly | |||
6072 | // extract values in order. | |||
6073 | unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); | |||
6074 | if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { | |||
6075 | unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); | |||
6076 | AllConsecutive &= PrevIdx + 1 == CurrentIdx && | |||
6077 | CurrentIdx % EltsPerVector == Idx % EltsPerVector; | |||
6078 | RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector; | |||
6079 | } | |||
6080 | ||||
6081 | if (AllConsecutive) | |||
6082 | continue; | |||
6083 | ||||
6084 | // Skip all indices, except for the last index per vector block. | |||
6085 | if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) | |||
6086 | continue; | |||
6087 | ||||
6088 | // If we have a series of extracts which are not consecutive and hence | |||
6089 | // cannot re-use the source vector register directly, compute the shuffle | |||
6090 | // cost to extract the vector with EltsPerVector elements. | |||
6091 | Cost += TTI.getShuffleCost( | |||
6092 | TargetTransformInfo::SK_PermuteSingleSrc, | |||
6093 | FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask); | |||
6094 | } | |||
6095 | return Cost; | |||
6096 | } | |||
6097 | ||||
6098 | /// Build shuffle mask for shuffle graph entries and lists of main and alternate | |||
6099 | /// operations operands. | |||
6100 | static void | |||
6101 | buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, | |||
6102 | ArrayRef<int> ReusesIndices, | |||
6103 | const function_ref<bool(Instruction *)> IsAltOp, | |||
6104 | SmallVectorImpl<int> &Mask, | |||
6105 | SmallVectorImpl<Value *> *OpScalars = nullptr, | |||
6106 | SmallVectorImpl<Value *> *AltScalars = nullptr) { | |||
6107 | unsigned Sz = VL.size(); | |||
6108 | Mask.assign(Sz, UndefMaskElem); | |||
6109 | SmallVector<int> OrderMask; | |||
6110 | if (!ReorderIndices.empty()) | |||
6111 | inversePermutation(ReorderIndices, OrderMask); | |||
6112 | for (unsigned I = 0; I < Sz; ++I) { | |||
6113 | unsigned Idx = I; | |||
6114 | if (!ReorderIndices.empty()) | |||
6115 | Idx = OrderMask[I]; | |||
6116 | auto *OpInst = cast<Instruction>(VL[Idx]); | |||
6117 | if (IsAltOp(OpInst)) { | |||
6118 | Mask[I] = Sz + Idx; | |||
6119 | if (AltScalars) | |||
6120 | AltScalars->push_back(OpInst); | |||
6121 | } else { | |||
6122 | Mask[I] = Idx; | |||
6123 | if (OpScalars) | |||
6124 | OpScalars->push_back(OpInst); | |||
6125 | } | |||
6126 | } | |||
6127 | if (!ReusesIndices.empty()) { | |||
6128 | SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); | |||
6129 | transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { | |||
6130 | return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; | |||
6131 | }); | |||
6132 | Mask.swap(NewMask); | |||
6133 | } | |||
6134 | } | |||
6135 | ||||
6136 | static bool isAlternateInstruction(const Instruction *I, | |||
6137 | const Instruction *MainOp, | |||
6138 | const Instruction *AltOp, | |||
6139 | const TargetLibraryInfo &TLI) { | |||
6140 | if (auto *MainCI = dyn_cast<CmpInst>(MainOp)) { | |||
6141 | auto *AltCI = cast<CmpInst>(AltOp); | |||
6142 | CmpInst::Predicate MainP = MainCI->getPredicate(); | |||
6143 | CmpInst::Predicate AltP = AltCI->getPredicate(); | |||
6144 | assert(MainP != AltP && "Expected different main/alternate predicates.")(static_cast <bool> (MainP != AltP && "Expected different main/alternate predicates." ) ? void (0) : __assert_fail ("MainP != AltP && \"Expected different main/alternate predicates.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6144, __extension__ __PRETTY_FUNCTION__)); | |||
6145 | auto *CI = cast<CmpInst>(I); | |||
6146 | if (isCmpSameOrSwapped(MainCI, CI, TLI)) | |||
6147 | return false; | |||
6148 | if (isCmpSameOrSwapped(AltCI, CI, TLI)) | |||
6149 | return true; | |||
6150 | CmpInst::Predicate P = CI->getPredicate(); | |||
6151 | CmpInst::Predicate SwappedP = CmpInst::getSwappedPredicate(P); | |||
6152 | ||||
6153 | assert((MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) &&(static_cast <bool> ((MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && "CmpInst expected to match either main or alternate predicate or " "their swap.") ? void (0) : __assert_fail ("(MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && \"CmpInst expected to match either main or alternate predicate or \" \"their swap.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6155, __extension__ __PRETTY_FUNCTION__)) | |||
6154 | "CmpInst expected to match either main or alternate predicate or "(static_cast <bool> ((MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && "CmpInst expected to match either main or alternate predicate or " "their swap.") ? void (0) : __assert_fail ("(MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && \"CmpInst expected to match either main or alternate predicate or \" \"their swap.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6155, __extension__ __PRETTY_FUNCTION__)) | |||
6155 | "their swap.")(static_cast <bool> ((MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && "CmpInst expected to match either main or alternate predicate or " "their swap.") ? void (0) : __assert_fail ("(MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) && \"CmpInst expected to match either main or alternate predicate or \" \"their swap.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6155, __extension__ __PRETTY_FUNCTION__)); | |||
6156 | (void)AltP; | |||
6157 | return MainP != P && MainP != SwappedP; | |||
6158 | } | |||
6159 | return I->getOpcode() == AltOp->getOpcode(); | |||
6160 | } | |||
6161 | ||||
6162 | TTI::OperandValueInfo BoUpSLP::getOperandInfo(ArrayRef<Value *> VL, | |||
6163 | unsigned OpIdx) { | |||
6164 | assert(!VL.empty())(static_cast <bool> (!VL.empty()) ? void (0) : __assert_fail ("!VL.empty()", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp" , 6164, __extension__ __PRETTY_FUNCTION__)); | |||
6165 | const auto *I0 = cast<Instruction>(*find_if(VL, Instruction::classof)); | |||
6166 | const auto *Op0 = I0->getOperand(OpIdx); | |||
6167 | ||||
6168 | const bool IsConstant = all_of(VL, [&](Value *V) { | |||
6169 | // TODO: We should allow undef elements here | |||
6170 | const auto *I = dyn_cast<Instruction>(V); | |||
6171 | if (!I) | |||
6172 | return true; | |||
6173 | auto *Op = I->getOperand(OpIdx); | |||
6174 | return isConstant(Op) && !isa<UndefValue>(Op); | |||
6175 | }); | |||
6176 | const bool IsUniform = all_of(VL, [&](Value *V) { | |||
6177 | // TODO: We should allow undef elements here | |||
6178 | const auto *I = dyn_cast<Instruction>(V); | |||
6179 | if (!I) | |||
6180 | return false; | |||
6181 | return I->getOperand(OpIdx) == Op0; | |||
6182 | }); | |||
6183 | const bool IsPowerOfTwo = all_of(VL, [&](Value *V) { | |||
6184 | // TODO: We should allow undef elements here | |||
6185 | const auto *I = dyn_cast<Instruction>(V); | |||
6186 | if (!I) { | |||
6187 | assert((isa<UndefValue>(V) ||(static_cast <bool> ((isa<UndefValue>(V) || I0-> getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP." ) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6189, __extension__ __PRETTY_FUNCTION__)) | |||
6188 | I0->getOpcode() == Instruction::GetElementPtr) &&(static_cast <bool> ((isa<UndefValue>(V) || I0-> getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP." ) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6189, __extension__ __PRETTY_FUNCTION__)) | |||
6189 | "Expected undef or GEP.")(static_cast <bool> ((isa<UndefValue>(V) || I0-> getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP." ) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6189, __extension__ __PRETTY_FUNCTION__)); | |||
6190 | return true; | |||
6191 | } | |||
6192 | auto *Op = I->getOperand(OpIdx); | |||
6193 | if (auto *CI = dyn_cast<ConstantInt>(Op)) | |||
6194 | return CI->getValue().isPowerOf2(); | |||
6195 | return false; | |||
6196 | }); | |||
6197 | const bool IsNegatedPowerOfTwo = all_of(VL, [&](Value *V) { | |||
6198 | // TODO: We should allow undef elements here | |||
6199 | const auto *I = dyn_cast<Instruction>(V); | |||
6200 | if (!I) { | |||
6201 | assert((isa<UndefValue>(V) ||(static_cast <bool> ((isa<UndefValue>(V) || I0-> getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP." ) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6203, __extension__ __PRETTY_FUNCTION__)) | |||
6202 | I0->getOpcode() == Instruction::GetElementPtr) &&(static_cast <bool> ((isa<UndefValue>(V) || I0-> getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP." ) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6203, __extension__ __PRETTY_FUNCTION__)) | |||
6203 | "Expected undef or GEP.")(static_cast <bool> ((isa<UndefValue>(V) || I0-> getOpcode() == Instruction::GetElementPtr) && "Expected undef or GEP." ) ? void (0) : __assert_fail ("(isa<UndefValue>(V) || I0->getOpcode() == Instruction::GetElementPtr) && \"Expected undef or GEP.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6203, __extension__ __PRETTY_FUNCTION__)); | |||
6204 | return true; | |||
6205 | } | |||
6206 | const auto *Op = I->getOperand(OpIdx); | |||
6207 | if (auto *CI = dyn_cast<ConstantInt>(Op)) | |||
6208 | return CI->getValue().isNegatedPowerOf2(); | |||
6209 | return false; | |||
6210 | }); | |||
6211 | ||||
6212 | TTI::OperandValueKind VK = TTI::OK_AnyValue; | |||
6213 | if (IsConstant && IsUniform) | |||
6214 | VK = TTI::OK_UniformConstantValue; | |||
6215 | else if (IsConstant) | |||
6216 | VK = TTI::OK_NonUniformConstantValue; | |||
6217 | else if (IsUniform) | |||
6218 | VK = TTI::OK_UniformValue; | |||
6219 | ||||
6220 | TTI::OperandValueProperties VP = TTI::OP_None; | |||
6221 | VP = IsPowerOfTwo ? TTI::OP_PowerOf2 : VP; | |||
6222 | VP = IsNegatedPowerOfTwo ? TTI::OP_NegatedPowerOf2 : VP; | |||
6223 | ||||
6224 | return {VK, VP}; | |||
6225 | } | |||
6226 | ||||
6227 | InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, | |||
6228 | ArrayRef<Value *> VectorizedVals) { | |||
6229 | ArrayRef<Value *> VL = E->Scalars; | |||
6230 | ||||
6231 | Type *ScalarTy = VL[0]->getType(); | |||
6232 | if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) | |||
6233 | ScalarTy = SI->getValueOperand()->getType(); | |||
6234 | else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) | |||
6235 | ScalarTy = CI->getOperand(0)->getType(); | |||
6236 | else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) | |||
6237 | ScalarTy = IE->getOperand(1)->getType(); | |||
6238 | auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); | |||
6239 | TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; | |||
6240 | ||||
6241 | // If we have computed a smaller type for the expression, update VecTy so | |||
6242 | // that the costs will be accurate. | |||
6243 | if (MinBWs.count(VL[0])) | |||
6244 | VecTy = FixedVectorType::get( | |||
6245 | IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); | |||
6246 | unsigned EntryVF = E->getVectorFactor(); | |||
6247 | auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); | |||
6248 | ||||
6249 | bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); | |||
6250 | // FIXME: it tries to fix a problem with MSVC buildbots. | |||
6251 | TargetTransformInfo *TTI = this->TTI; | |||
6252 | auto AdjustExtractsCost = [=](InstructionCost &Cost) { | |||
6253 | DenseMap<Value *, int> ExtractVectorsTys; | |||
6254 | SmallPtrSet<Value *, 4> CheckedExtracts; | |||
6255 | for (auto *V : VL) { | |||
6256 | if (isa<UndefValue>(V)) | |||
6257 | continue; | |||
6258 | // If all users of instruction are going to be vectorized and this | |||
6259 | // instruction itself is not going to be vectorized, consider this | |||
6260 | // instruction as dead and remove its cost from the final cost of the | |||
6261 | // vectorized tree. | |||
6262 | // Also, avoid adjusting the cost for extractelements with multiple uses | |||
6263 | // in different graph entries. | |||
6264 | const TreeEntry *VE = getTreeEntry(V); | |||
6265 | if (!CheckedExtracts.insert(V).second || | |||
6266 | !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || | |||
6267 | (VE && VE != E)) | |||
6268 | continue; | |||
6269 | auto *EE = cast<ExtractElementInst>(V); | |||
6270 | Optional<unsigned> EEIdx = getExtractIndex(EE); | |||
6271 | if (!EEIdx) | |||
6272 | continue; | |||
6273 | unsigned Idx = *EEIdx; | |||
6274 | if (TTI->getNumberOfParts(VecTy) != | |||
6275 | TTI->getNumberOfParts(EE->getVectorOperandType())) { | |||
6276 | auto It = | |||
6277 | ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; | |||
6278 | It->getSecond() = std::min<int>(It->second, Idx); | |||
6279 | } | |||
6280 | // Take credit for instruction that will become dead. | |||
6281 | if (EE->hasOneUse()) { | |||
6282 | Instruction *Ext = EE->user_back(); | |||
6283 | if (isa<SExtInst, ZExtInst>(Ext) && all_of(Ext->users(), [](User *U) { | |||
6284 | return isa<GetElementPtrInst>(U); | |||
6285 | })) { | |||
6286 | // Use getExtractWithExtendCost() to calculate the cost of | |||
6287 | // extractelement/ext pair. | |||
6288 | Cost -= | |||
6289 | TTI->getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), | |||
6290 | EE->getVectorOperandType(), Idx); | |||
6291 | // Add back the cost of s|zext which is subtracted separately. | |||
6292 | Cost += TTI->getCastInstrCost( | |||
6293 | Ext->getOpcode(), Ext->getType(), EE->getType(), | |||
6294 | TTI::getCastContextHint(Ext), CostKind, Ext); | |||
6295 | continue; | |||
6296 | } | |||
6297 | } | |||
6298 | Cost -= TTI->getVectorInstrCost(*EE, EE->getVectorOperandType(), Idx); | |||
6299 | } | |||
6300 | // Add a cost for subvector extracts/inserts if required. | |||
6301 | for (const auto &Data : ExtractVectorsTys) { | |||
6302 | auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); | |||
6303 | unsigned NumElts = VecTy->getNumElements(); | |||
6304 | if (Data.second % NumElts == 0) | |||
6305 | continue; | |||
6306 | if (TTI->getNumberOfParts(EEVTy) > TTI->getNumberOfParts(VecTy)) { | |||
6307 | unsigned Idx = (Data.second / NumElts) * NumElts; | |||
6308 | unsigned EENumElts = EEVTy->getNumElements(); | |||
6309 | if (Idx + NumElts <= EENumElts) { | |||
6310 | Cost += TTI->getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, | |||
6311 | EEVTy, None, CostKind, Idx, VecTy); | |||
6312 | } else { | |||
6313 | // Need to round up the subvector type vectorization factor to avoid a | |||
6314 | // crash in cost model functions. Make SubVT so that Idx + VF of SubVT | |||
6315 | // <= EENumElts. | |||
6316 | auto *SubVT = | |||
6317 | FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); | |||
6318 | Cost += TTI->getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, | |||
6319 | EEVTy, None, CostKind, Idx, SubVT); | |||
6320 | } | |||
6321 | } else { | |||
6322 | Cost += TTI->getShuffleCost(TargetTransformInfo::SK_InsertSubvector, | |||
6323 | VecTy, None, CostKind, 0, EEVTy); | |||
6324 | } | |||
6325 | } | |||
6326 | }; | |||
6327 | if (E->State == TreeEntry::NeedToGather) { | |||
6328 | if (allConstant(VL)) | |||
6329 | return 0; | |||
6330 | if (isa<InsertElementInst>(VL[0])) | |||
6331 | return InstructionCost::getInvalid(); | |||
6332 | SmallVector<int> Mask; | |||
6333 | SmallVector<const TreeEntry *> Entries; | |||
6334 | Optional<TargetTransformInfo::ShuffleKind> Shuffle = | |||
6335 | isGatherShuffledEntry(E, Mask, Entries); | |||
6336 | if (Shuffle) { | |||
6337 | InstructionCost GatherCost = 0; | |||
6338 | if (ShuffleVectorInst::isIdentityMask(Mask)) { | |||
6339 | // Perfect match in the graph, will reuse the previously vectorized | |||
6340 | // node. Cost is 0. | |||
6341 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with " << *VL.front() << ".\n"; } } while (false) | |||
6342 | dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with " << *VL.front() << ".\n"; } } while (false) | |||
6343 | << "SLP: perfect diamond match for gather bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with " << *VL.front() << ".\n"; } } while (false) | |||
6344 | << *VL.front() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: perfect diamond match for gather bundle that starts with " << *VL.front() << ".\n"; } } while (false); | |||
6345 | if (NeedToShuffleReuses) | |||
6346 | GatherCost = | |||
6347 | TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, | |||
6348 | FinalVecTy, E->ReuseShuffleIndices); | |||
6349 | } else { | |||
6350 | LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: shuffled " << Entries. size() << " entries for bundle that starts with " << *VL.front() << ".\n"; } } while (false) | |||
6351 | << " entries for bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: shuffled " << Entries. size() << " entries for bundle that starts with " << *VL.front() << ".\n"; } } while (false) | |||
6352 | << *VL.front() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: shuffled " << Entries. size() << " entries for bundle that starts with " << *VL.front() << ".\n"; } } while (false); | |||
6353 | // Detected that instead of gather we can emit a shuffle of single/two | |||
6354 | // previously vectorized nodes. Add the cost of the permutation rather | |||
6355 | // than gather. | |||
6356 | ::addMask(Mask, E->ReuseShuffleIndices); | |||
6357 | GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); | |||
6358 | } | |||
6359 | return GatherCost; | |||
6360 | } | |||
6361 | if ((E->getOpcode() == Instruction::ExtractElement || | |||
6362 | all_of(E->Scalars, | |||
6363 | [](Value *V) { | |||
6364 | return isa<ExtractElementInst, UndefValue>(V); | |||
6365 | })) && | |||
6366 | allSameType(VL)) { | |||
6367 | // Check that gather of extractelements can be represented as just a | |||
6368 | // shuffle of a single/two vectors the scalars are extracted from. | |||
6369 | SmallVector<int> Mask; | |||
6370 | Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = | |||
6371 | isFixedVectorShuffle(VL, Mask); | |||
6372 | if (ShuffleKind) { | |||
6373 | // Found the bunch of extractelement instructions that must be gathered | |||
6374 | // into a vector and can be represented as a permutation elements in a | |||
6375 | // single input vector or of 2 input vectors. | |||
6376 | InstructionCost Cost = | |||
6377 | computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); | |||
6378 | AdjustExtractsCost(Cost); | |||
6379 | if (NeedToShuffleReuses) | |||
6380 | Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, | |||
6381 | FinalVecTy, E->ReuseShuffleIndices); | |||
6382 | return Cost; | |||
6383 | } | |||
6384 | } | |||
6385 | if (isSplat(VL)) { | |||
6386 | // Found the broadcasting of the single scalar, calculate the cost as the | |||
6387 | // broadcast. | |||
6388 | assert(VecTy == FinalVecTy &&(static_cast <bool> (VecTy == FinalVecTy && "No reused scalars expected for broadcast." ) ? void (0) : __assert_fail ("VecTy == FinalVecTy && \"No reused scalars expected for broadcast.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6389, __extension__ __PRETTY_FUNCTION__)) | |||
6389 | "No reused scalars expected for broadcast.")(static_cast <bool> (VecTy == FinalVecTy && "No reused scalars expected for broadcast." ) ? void (0) : __assert_fail ("VecTy == FinalVecTy && \"No reused scalars expected for broadcast.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6389, __extension__ __PRETTY_FUNCTION__)); | |||
6390 | return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, | |||
6391 | /*Mask=*/None, CostKind, /*Index=*/0, | |||
6392 | /*SubTp=*/nullptr, /*Args=*/VL[0]); | |||
6393 | } | |||
6394 | InstructionCost ReuseShuffleCost = 0; | |||
6395 | if (NeedToShuffleReuses) | |||
6396 | ReuseShuffleCost = TTI->getShuffleCost( | |||
6397 | TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); | |||
6398 | // Improve gather cost for gather of loads, if we can group some of the | |||
6399 | // loads into vector loads. | |||
6400 | if (VL.size() > 2 && E->getOpcode() == Instruction::Load && | |||
6401 | !E->isAltShuffle()) { | |||
6402 | BoUpSLP::ValueSet VectorizedLoads; | |||
6403 | unsigned StartIdx = 0; | |||
6404 | unsigned VF = VL.size() / 2; | |||
6405 | unsigned VectorizedCnt = 0; | |||
6406 | unsigned ScatterVectorizeCnt = 0; | |||
6407 | const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); | |||
6408 | for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { | |||
6409 | for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; | |||
6410 | Cnt += VF) { | |||
6411 | ArrayRef<Value *> Slice = VL.slice(Cnt, VF); | |||
6412 | if (!VectorizedLoads.count(Slice.front()) && | |||
6413 | !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { | |||
6414 | SmallVector<Value *> PointerOps; | |||
6415 | OrdersType CurrentOrder; | |||
6416 | LoadsState LS = | |||
6417 | canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, *SE, *LI, | |||
6418 | *TLI, CurrentOrder, PointerOps); | |||
6419 | switch (LS) { | |||
6420 | case LoadsState::Vectorize: | |||
6421 | case LoadsState::ScatterVectorize: | |||
6422 | // Mark the vectorized loads so that we don't vectorize them | |||
6423 | // again. | |||
6424 | if (LS == LoadsState::Vectorize) | |||
6425 | ++VectorizedCnt; | |||
6426 | else | |||
6427 | ++ScatterVectorizeCnt; | |||
6428 | VectorizedLoads.insert(Slice.begin(), Slice.end()); | |||
6429 | // If we vectorized initial block, no need to try to vectorize it | |||
6430 | // again. | |||
6431 | if (Cnt == StartIdx) | |||
6432 | StartIdx += VF; | |||
6433 | break; | |||
6434 | case LoadsState::Gather: | |||
6435 | break; | |||
6436 | } | |||
6437 | } | |||
6438 | } | |||
6439 | // Check if the whole array was vectorized already - exit. | |||
6440 | if (StartIdx >= VL.size()) | |||
6441 | break; | |||
6442 | // Found vectorizable parts - exit. | |||
6443 | if (!VectorizedLoads.empty()) | |||
6444 | break; | |||
6445 | } | |||
6446 | if (!VectorizedLoads.empty()) { | |||
6447 | InstructionCost GatherCost = 0; | |||
6448 | unsigned NumParts = TTI->getNumberOfParts(VecTy); | |||
6449 | bool NeedInsertSubvectorAnalysis = | |||
6450 | !NumParts || (VL.size() / VF) > NumParts; | |||
6451 | // Get the cost for gathered loads. | |||
6452 | for (unsigned I = 0, End = VL.size(); I < End; I += VF) { | |||
6453 | if (VectorizedLoads.contains(VL[I])) | |||
6454 | continue; | |||
6455 | GatherCost += getGatherCost(VL.slice(I, VF)); | |||
6456 | } | |||
6457 | // The cost for vectorized loads. | |||
6458 | InstructionCost ScalarsCost = 0; | |||
6459 | for (Value *V : VectorizedLoads) { | |||
6460 | auto *LI = cast<LoadInst>(V); | |||
6461 | ScalarsCost += | |||
6462 | TTI->getMemoryOpCost(Instruction::Load, LI->getType(), | |||
6463 | LI->getAlign(), LI->getPointerAddressSpace(), | |||
6464 | CostKind, TTI::OperandValueInfo(), LI); | |||
6465 | } | |||
6466 | auto *LI = cast<LoadInst>(E->getMainOp()); | |||
6467 | auto *LoadTy = FixedVectorType::get(LI->getType(), VF); | |||
6468 | Align Alignment = LI->getAlign(); | |||
6469 | GatherCost += | |||
6470 | VectorizedCnt * | |||
6471 | TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, | |||
6472 | LI->getPointerAddressSpace(), CostKind, | |||
6473 | TTI::OperandValueInfo(), LI); | |||
6474 | GatherCost += ScatterVectorizeCnt * | |||
6475 | TTI->getGatherScatterOpCost( | |||
6476 | Instruction::Load, LoadTy, LI->getPointerOperand(), | |||
6477 | /*VariableMask=*/false, Alignment, CostKind, LI); | |||
6478 | if (NeedInsertSubvectorAnalysis) { | |||
6479 | // Add the cost for the subvectors insert. | |||
6480 | for (int I = VF, E = VL.size(); I < E; I += VF) | |||
6481 | GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, | |||
6482 | None, CostKind, I, LoadTy); | |||
6483 | } | |||
6484 | return ReuseShuffleCost + GatherCost - ScalarsCost; | |||
6485 | } | |||
6486 | } | |||
6487 | return ReuseShuffleCost + getGatherCost(VL); | |||
6488 | } | |||
6489 | InstructionCost CommonCost = 0; | |||
6490 | SmallVector<int> Mask; | |||
6491 | if (!E->ReorderIndices.empty()) { | |||
6492 | SmallVector<int> NewMask; | |||
6493 | if (E->getOpcode() == Instruction::Store) { | |||
6494 | // For stores the order is actually a mask. | |||
6495 | NewMask.resize(E->ReorderIndices.size()); | |||
6496 | copy(E->ReorderIndices, NewMask.begin()); | |||
6497 | } else { | |||
6498 | inversePermutation(E->ReorderIndices, NewMask); | |||
6499 | } | |||
6500 | ::addMask(Mask, NewMask); | |||
6501 | } | |||
6502 | if (NeedToShuffleReuses) | |||
6503 | ::addMask(Mask, E->ReuseShuffleIndices); | |||
6504 | if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) | |||
6505 | CommonCost = | |||
6506 | TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); | |||
6507 | assert((E->State == TreeEntry::Vectorize ||(static_cast <bool> ((E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && "Unhandled state" ) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6509, __extension__ __PRETTY_FUNCTION__)) | |||
6508 | E->State == TreeEntry::ScatterVectorize) &&(static_cast <bool> ((E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && "Unhandled state" ) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6509, __extension__ __PRETTY_FUNCTION__)) | |||
6509 | "Unhandled state")(static_cast <bool> ((E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && "Unhandled state" ) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6509, __extension__ __PRETTY_FUNCTION__)); | |||
6510 | assert(E->getOpcode() &&(static_cast <bool> (E->getOpcode() && ((allSameType (VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction ::GetElementPtr && E->getMainOp()->getType()-> isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail ("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6514, __extension__ __PRETTY_FUNCTION__)) | |||
6511 | ((allSameType(VL) && allSameBlock(VL)) ||(static_cast <bool> (E->getOpcode() && ((allSameType (VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction ::GetElementPtr && E->getMainOp()->getType()-> isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail ("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6514, __extension__ __PRETTY_FUNCTION__)) | |||
6512 | (E->getOpcode() == Instruction::GetElementPtr &&(static_cast <bool> (E->getOpcode() && ((allSameType (VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction ::GetElementPtr && E->getMainOp()->getType()-> isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail ("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6514, __extension__ __PRETTY_FUNCTION__)) | |||
6513 | E->getMainOp()->getType()->isPointerTy())) &&(static_cast <bool> (E->getOpcode() && ((allSameType (VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction ::GetElementPtr && E->getMainOp()->getType()-> isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail ("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6514, __extension__ __PRETTY_FUNCTION__)) | |||
6514 | "Invalid VL")(static_cast <bool> (E->getOpcode() && ((allSameType (VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction ::GetElementPtr && E->getMainOp()->getType()-> isPointerTy())) && "Invalid VL") ? void (0) : __assert_fail ("E->getOpcode() && ((allSameType(VL) && allSameBlock(VL)) || (E->getOpcode() == Instruction::GetElementPtr && E->getMainOp()->getType()->isPointerTy())) && \"Invalid VL\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6514, __extension__ __PRETTY_FUNCTION__)); | |||
6515 | Instruction *VL0 = E->getMainOp(); | |||
6516 | unsigned ShuffleOrOp = | |||
6517 | E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); | |||
6518 | const unsigned Sz = VL.size(); | |||
6519 | auto GetCostDiff = | |||
6520 | [=](function_ref<InstructionCost(unsigned)> ScalarEltCost, | |||
6521 | function_ref<InstructionCost(InstructionCost)> VectorCost) { | |||
6522 | // Calculate the cost of this instruction. | |||
6523 | InstructionCost ScalarCost = 0; | |||
6524 | if (isa<CastInst, CmpInst, SelectInst, CallInst>(VL0)) { | |||
6525 | // For some of the instructions no need to calculate cost for each | |||
6526 | // particular instruction, we can use the cost of the single | |||
6527 | // instruction x total number of scalar instructions. | |||
6528 | ScalarCost = Sz * ScalarEltCost(0); | |||
6529 | } else { | |||
6530 | for (unsigned I = 0; I < Sz; ++I) | |||
6531 | ScalarCost += ScalarEltCost(I); | |||
6532 | } | |||
6533 | ||||
6534 | InstructionCost VecCost = VectorCost(CommonCost); | |||
6535 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dumpTreeCosts(E, CommonCost, VecCost - CommonCost, ScalarCost); } } while (false) | |||
6536 | dumpTreeCosts(E, CommonCost, VecCost - CommonCost, ScalarCost))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dumpTreeCosts(E, CommonCost, VecCost - CommonCost, ScalarCost); } } while (false); | |||
6537 | // Disable warnings for `this` and `E` are unused. Required for | |||
6538 | // `dumpTreeCosts`. | |||
6539 | (void)this; | |||
6540 | (void)E; | |||
6541 | return VecCost - ScalarCost; | |||
6542 | }; | |||
6543 | switch (ShuffleOrOp) { | |||
6544 | case Instruction::PHI: { | |||
6545 | // Count reused scalars. | |||
6546 | InstructionCost ScalarCost = 0; | |||
6547 | SmallPtrSet<const TreeEntry *, 4> CountedOps; | |||
6548 | for (Value *V : VL) { | |||
6549 | auto *PHI = dyn_cast<PHINode>(V); | |||
6550 | if (!PHI) | |||
6551 | continue; | |||
6552 | ||||
6553 | ValueList Operands(PHI->getNumIncomingValues(), nullptr); | |||
6554 | for (unsigned I = 0, N = PHI->getNumIncomingValues(); I < N; ++I) { | |||
6555 | Value *Op = PHI->getIncomingValue(I); | |||
6556 | Operands[I] = Op; | |||
6557 | } | |||
6558 | if (const TreeEntry *OpTE = getTreeEntry(Operands.front())) | |||
6559 | if (OpTE->isSame(Operands) && CountedOps.insert(OpTE).second) | |||
6560 | if (!OpTE->ReuseShuffleIndices.empty()) | |||
6561 | ScalarCost += TTI::TCC_Basic * (OpTE->ReuseShuffleIndices.size() - | |||
6562 | OpTE->Scalars.size()); | |||
6563 | } | |||
6564 | ||||
6565 | return CommonCost - ScalarCost; | |||
6566 | } | |||
6567 | case Instruction::ExtractValue: | |||
6568 | case Instruction::ExtractElement: { | |||
6569 | auto GetScalarCost = [=](unsigned Idx) { | |||
6570 | auto *I = cast<Instruction>(VL[Idx]); | |||
6571 | VectorType *SrcVecTy; | |||
6572 | if (ShuffleOrOp == Instruction::ExtractElement) { | |||
6573 | auto *EE = cast<ExtractElementInst>(I); | |||
6574 | SrcVecTy = EE->getVectorOperandType(); | |||
6575 | } else { | |||
6576 | auto *EV = cast<ExtractValueInst>(I); | |||
6577 | Type *AggregateTy = EV->getAggregateOperand()->getType(); | |||
6578 | unsigned NumElts; | |||
6579 | if (auto *ATy = dyn_cast<ArrayType>(AggregateTy)) | |||
6580 | NumElts = ATy->getNumElements(); | |||
6581 | else | |||
6582 | NumElts = AggregateTy->getStructNumElements(); | |||
6583 | SrcVecTy = FixedVectorType::get(ScalarTy, NumElts); | |||
6584 | } | |||
6585 | if (I->hasOneUse()) { | |||
6586 | Instruction *Ext = I->user_back(); | |||
6587 | if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && | |||
6588 | all_of(Ext->users(), | |||
6589 | [](User *U) { return isa<GetElementPtrInst>(U); })) { | |||
6590 | // Use getExtractWithExtendCost() to calculate the cost of | |||
6591 | // extractelement/ext pair. | |||
6592 | InstructionCost Cost = TTI->getExtractWithExtendCost( | |||
6593 | Ext->getOpcode(), Ext->getType(), SrcVecTy, *getExtractIndex(I)); | |||
6594 | // Subtract the cost of s|zext which is subtracted separately. | |||
6595 | Cost -= TTI->getCastInstrCost( | |||
6596 | Ext->getOpcode(), Ext->getType(), I->getType(), | |||
6597 | TTI::getCastContextHint(Ext), CostKind, Ext); | |||
6598 | return Cost; | |||
6599 | } | |||
6600 | } | |||
6601 | return TTI->getVectorInstrCost(Instruction::ExtractElement, SrcVecTy, | |||
6602 | *getExtractIndex(I)); | |||
6603 | }; | |||
6604 | auto GetVectorCost = [](InstructionCost CommonCost) { return CommonCost; }; | |||
6605 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
6606 | } | |||
6607 | case Instruction::InsertElement: { | |||
6608 | assert(E->ReuseShuffleIndices.empty() &&(static_cast <bool> (E->ReuseShuffleIndices.empty() && "Unique insertelements only are expected.") ? void (0) : __assert_fail ("E->ReuseShuffleIndices.empty() && \"Unique insertelements only are expected.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6609, __extension__ __PRETTY_FUNCTION__)) | |||
6609 | "Unique insertelements only are expected.")(static_cast <bool> (E->ReuseShuffleIndices.empty() && "Unique insertelements only are expected.") ? void (0) : __assert_fail ("E->ReuseShuffleIndices.empty() && \"Unique insertelements only are expected.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6609, __extension__ __PRETTY_FUNCTION__)); | |||
6610 | auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); | |||
6611 | unsigned const NumElts = SrcVecTy->getNumElements(); | |||
6612 | unsigned const NumScalars = VL.size(); | |||
6613 | ||||
6614 | unsigned NumOfParts = TTI->getNumberOfParts(SrcVecTy); | |||
6615 | ||||
6616 | SmallVector<int> InsertMask(NumElts, UndefMaskElem); | |||
6617 | unsigned OffsetBeg = *getInsertIndex(VL.front()); | |||
6618 | unsigned OffsetEnd = OffsetBeg; | |||
6619 | InsertMask[OffsetBeg] = 0; | |||
6620 | for (auto [I, V] : enumerate(VL.drop_front())) { | |||
6621 | unsigned Idx = *getInsertIndex(V); | |||
6622 | if (OffsetBeg > Idx) | |||
6623 | OffsetBeg = Idx; | |||
6624 | else if (OffsetEnd < Idx) | |||
6625 | OffsetEnd = Idx; | |||
6626 | InsertMask[Idx] = I + 1; | |||
6627 | } | |||
6628 | unsigned VecScalarsSz = PowerOf2Ceil(NumElts); | |||
6629 | if (NumOfParts > 0) | |||
6630 | VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts); | |||
6631 | unsigned VecSz = (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) * | |||
6632 | VecScalarsSz; | |||
6633 | unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz); | |||
6634 | unsigned InsertVecSz = std::min<unsigned>( | |||
6635 | PowerOf2Ceil(OffsetEnd - OffsetBeg + 1), | |||
6636 | ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) * VecScalarsSz); | |||
6637 | bool IsWholeSubvector = | |||
6638 | OffsetBeg == Offset && ((OffsetEnd + 1) % VecScalarsSz == 0); | |||
6639 | // Check if we can safely insert a subvector. If it is not possible, just | |||
6640 | // generate a whole-sized vector and shuffle the source vector and the new | |||
6641 | // subvector. | |||
6642 | if (OffsetBeg + InsertVecSz > VecSz) { | |||
6643 | // Align OffsetBeg to generate correct mask. | |||
6644 | OffsetBeg = alignDown(OffsetBeg, VecSz, Offset); | |||
6645 | InsertVecSz = VecSz; | |||
6646 | } | |||
6647 | ||||
6648 | APInt DemandedElts = APInt::getZero(NumElts); | |||
6649 | // TODO: Add support for Instruction::InsertValue. | |||
6650 | SmallVector<int> Mask; | |||
6651 | if (!E->ReorderIndices.empty()) { | |||
6652 | inversePermutation(E->ReorderIndices, Mask); | |||
6653 | Mask.append(InsertVecSz - Mask.size(), UndefMaskElem); | |||
6654 | } else { | |||
6655 | Mask.assign(VecSz, UndefMaskElem); | |||
6656 | std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0); | |||
6657 | } | |||
6658 | bool IsIdentity = true; | |||
6659 | SmallVector<int> PrevMask(InsertVecSz, UndefMaskElem); | |||
6660 | Mask.swap(PrevMask); | |||
6661 | for (unsigned I = 0; I < NumScalars; ++I) { | |||
6662 | unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]); | |||
6663 | DemandedElts.setBit(InsertIdx); | |||
6664 | IsIdentity &= InsertIdx - OffsetBeg == I; | |||
6665 | Mask[InsertIdx - OffsetBeg] = I; | |||
6666 | } | |||
6667 | assert(Offset < NumElts && "Failed to find vector index offset")(static_cast <bool> (Offset < NumElts && "Failed to find vector index offset" ) ? void (0) : __assert_fail ("Offset < NumElts && \"Failed to find vector index offset\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6667, __extension__ __PRETTY_FUNCTION__)); | |||
6668 | ||||
6669 | InstructionCost Cost = 0; | |||
6670 | Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, | |||
6671 | /*Insert*/ true, /*Extract*/ false); | |||
6672 | ||||
6673 | // First cost - resize to actual vector size if not identity shuffle or | |||
6674 | // need to shift the vector. | |||
6675 | // Do not calculate the cost if the actual size is the register size and | |||
6676 | // we can merge this shuffle with the following SK_Select. | |||
6677 | auto *InsertVecTy = | |||
6678 | FixedVectorType::get(SrcVecTy->getElementType(), InsertVecSz); | |||
6679 | if (!IsIdentity) | |||
6680 | Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, | |||
6681 | InsertVecTy, Mask); | |||
6682 | auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { | |||
6683 | return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); | |||
6684 | })); | |||
6685 | // Second cost - permutation with subvector, if some elements are from the | |||
6686 | // initial vector or inserting a subvector. | |||
6687 | // TODO: Implement the analysis of the FirstInsert->getOperand(0) | |||
6688 | // subvector of ActualVecTy. | |||
6689 | SmallBitVector InMask = | |||
6690 | isUndefVector(FirstInsert->getOperand(0), InsertMask); | |||
6691 | if (!InMask.all() && NumScalars != NumElts && !IsWholeSubvector) { | |||
6692 | if (InsertVecSz != VecSz) { | |||
6693 | auto *ActualVecTy = | |||
6694 | FixedVectorType::get(SrcVecTy->getElementType(), VecSz); | |||
6695 | Cost += TTI->getShuffleCost(TTI::SK_InsertSubvector, ActualVecTy, None, | |||
6696 | CostKind, OffsetBeg - Offset, InsertVecTy); | |||
6697 | } else { | |||
6698 | for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I) | |||
6699 | Mask[I] = InMask.test(I) ? UndefMaskElem : I; | |||
6700 | for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset; | |||
6701 | I <= End; ++I) | |||
6702 | if (Mask[I] != UndefMaskElem) | |||
6703 | Mask[I] = I + VecSz; | |||
6704 | for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I) | |||
6705 | Mask[I] = | |||
6706 | ((I >= InMask.size()) || InMask.test(I)) ? UndefMaskElem : I; | |||
6707 | Cost += TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, InsertVecTy, Mask); | |||
6708 | } | |||
6709 | } | |||
6710 | return Cost; | |||
6711 | } | |||
6712 | case Instruction::ZExt: | |||
6713 | case Instruction::SExt: | |||
6714 | case Instruction::FPToUI: | |||
6715 | case Instruction::FPToSI: | |||
6716 | case Instruction::FPExt: | |||
6717 | case Instruction::PtrToInt: | |||
6718 | case Instruction::IntToPtr: | |||
6719 | case Instruction::SIToFP: | |||
6720 | case Instruction::UIToFP: | |||
6721 | case Instruction::Trunc: | |||
6722 | case Instruction::FPTrunc: | |||
6723 | case Instruction::BitCast: { | |||
6724 | auto GetScalarCost = [=](unsigned Idx) { | |||
6725 | auto *VI = cast<Instruction>(VL[Idx]); | |||
6726 | return TTI->getCastInstrCost(E->getOpcode(), ScalarTy, | |||
6727 | VI->getOperand(0)->getType(), | |||
6728 | TTI::getCastContextHint(VI), CostKind, VI); | |||
6729 | }; | |||
6730 | auto GetVectorCost = [=](InstructionCost CommonCost) { | |||
6731 | Type *SrcTy = VL0->getOperand(0)->getType(); | |||
6732 | auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); | |||
6733 | InstructionCost VecCost = CommonCost; | |||
6734 | // Check if the values are candidates to demote. | |||
6735 | if (!MinBWs.count(VL0) || VecTy != SrcVecTy) | |||
6736 | VecCost += | |||
6737 | TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy, | |||
6738 | TTI::getCastContextHint(VL0), CostKind, VL0); | |||
6739 | return VecCost; | |||
6740 | }; | |||
6741 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
6742 | } | |||
6743 | case Instruction::FCmp: | |||
6744 | case Instruction::ICmp: | |||
6745 | case Instruction::Select: { | |||
6746 | CmpInst::Predicate VecPred, SwappedVecPred; | |||
6747 | auto MatchCmp = m_Cmp(VecPred, m_Value(), m_Value()); | |||
6748 | if (match(VL0, m_Select(MatchCmp, m_Value(), m_Value())) || | |||
6749 | match(VL0, MatchCmp)) | |||
6750 | SwappedVecPred = CmpInst::getSwappedPredicate(VecPred); | |||
6751 | else | |||
6752 | SwappedVecPred = VecPred = ScalarTy->isFloatingPointTy() | |||
6753 | ? CmpInst::BAD_FCMP_PREDICATE | |||
6754 | : CmpInst::BAD_ICMP_PREDICATE; | |||
6755 | auto GetScalarCost = [&](unsigned Idx) { | |||
6756 | auto *VI = cast<Instruction>(VL[Idx]); | |||
6757 | CmpInst::Predicate CurrentPred = ScalarTy->isFloatingPointTy() | |||
6758 | ? CmpInst::BAD_FCMP_PREDICATE | |||
6759 | : CmpInst::BAD_ICMP_PREDICATE; | |||
6760 | auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); | |||
6761 | if ((!match(VI, m_Select(MatchCmp, m_Value(), m_Value())) && | |||
6762 | !match(VI, MatchCmp)) || | |||
6763 | (CurrentPred != VecPred && CurrentPred != SwappedVecPred)) | |||
6764 | VecPred = SwappedVecPred = ScalarTy->isFloatingPointTy() | |||
6765 | ? CmpInst::BAD_FCMP_PREDICATE | |||
6766 | : CmpInst::BAD_ICMP_PREDICATE; | |||
6767 | ||||
6768 | return TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, | |||
6769 | Builder.getInt1Ty(), CurrentPred, CostKind, | |||
6770 | VI); | |||
6771 | }; | |||
6772 | auto GetVectorCost = [&](InstructionCost CommonCost) { | |||
6773 | auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); | |||
6774 | ||||
6775 | InstructionCost VecCost = TTI->getCmpSelInstrCost( | |||
6776 | E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); | |||
6777 | // Check if it is possible and profitable to use min/max for selects | |||
6778 | // in VL. | |||
6779 | // | |||
6780 | auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); | |||
6781 | if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { | |||
6782 | IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, | |||
6783 | {VecTy, VecTy}); | |||
6784 | InstructionCost IntrinsicCost = | |||
6785 | TTI->getIntrinsicInstrCost(CostAttrs, CostKind); | |||
6786 | // If the selects are the only uses of the compares, they will be | |||
6787 | // dead and we can adjust the cost by removing their cost. | |||
6788 | if (IntrinsicAndUse.second) | |||
6789 | IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, | |||
6790 | MaskTy, VecPred, CostKind); | |||
6791 | VecCost = std::min(VecCost, IntrinsicCost); | |||
6792 | } | |||
6793 | return VecCost + CommonCost; | |||
6794 | }; | |||
6795 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
6796 | } | |||
6797 | case Instruction::FNeg: | |||
6798 | case Instruction::Add: | |||
6799 | case Instruction::FAdd: | |||
6800 | case Instruction::Sub: | |||
6801 | case Instruction::FSub: | |||
6802 | case Instruction::Mul: | |||
6803 | case Instruction::FMul: | |||
6804 | case Instruction::UDiv: | |||
6805 | case Instruction::SDiv: | |||
6806 | case Instruction::FDiv: | |||
6807 | case Instruction::URem: | |||
6808 | case Instruction::SRem: | |||
6809 | case Instruction::FRem: | |||
6810 | case Instruction::Shl: | |||
6811 | case Instruction::LShr: | |||
6812 | case Instruction::AShr: | |||
6813 | case Instruction::And: | |||
6814 | case Instruction::Or: | |||
6815 | case Instruction::Xor: | |||
6816 | case Instruction::GetElementPtr: { | |||
6817 | unsigned Opcode = ShuffleOrOp == Instruction::GetElementPtr | |||
6818 | ? static_cast<unsigned>(Instruction::Add) | |||
6819 | : ShuffleOrOp; | |||
6820 | auto GetScalarCost = [=](unsigned Idx) { | |||
6821 | auto *VI = dyn_cast<Instruction>(VL[Idx]); | |||
6822 | // GEPs may contain just addresses without instructions, consider | |||
6823 | // their cost 0. | |||
6824 | if (!VI) | |||
6825 | return InstructionCost(); | |||
6826 | unsigned OpIdx = isa<UnaryOperator>(VI) ? 0 : 1; | |||
6827 | TTI::OperandValueInfo Op1Info = TTI::getOperandInfo(VI->getOperand(0)); | |||
6828 | TTI::OperandValueInfo Op2Info = | |||
6829 | TTI::getOperandInfo(VI->getOperand(OpIdx)); | |||
6830 | SmallVector<const Value *> Operands(VI->operand_values()); | |||
6831 | return TTI->getArithmeticInstrCost(Opcode, ScalarTy, CostKind, Op1Info, | |||
6832 | Op2Info, Operands, VI); | |||
6833 | }; | |||
6834 | auto GetVectorCost = [=](InstructionCost CommonCost) { | |||
6835 | unsigned OpIdx = isa<UnaryOperator>(VL0) ? 0 : 1; | |||
6836 | TTI::OperandValueInfo Op1Info = getOperandInfo(VL, 0); | |||
6837 | TTI::OperandValueInfo Op2Info = getOperandInfo(VL, OpIdx); | |||
6838 | return TTI->getArithmeticInstrCost(Opcode, VecTy, CostKind, Op1Info, | |||
6839 | Op2Info) + | |||
6840 | CommonCost; | |||
6841 | }; | |||
6842 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
6843 | } | |||
6844 | case Instruction::Load: { | |||
6845 | auto GetScalarCost = [=](unsigned Idx) { | |||
6846 | auto *VI = cast<LoadInst>(VL[Idx]); | |||
6847 | InstructionCost GEPCost = 0; | |||
6848 | if (VI != VL0) { | |||
6849 | auto *Ptr = dyn_cast<GetElementPtrInst>(VI->getPointerOperand()); | |||
6850 | if (Ptr && Ptr->hasOneUse() && !Ptr->hasAllConstantIndices()) | |||
6851 | GEPCost = TTI->getArithmeticInstrCost(Instruction::Add, | |||
6852 | Ptr->getType(), CostKind); | |||
6853 | } | |||
6854 | return GEPCost + | |||
6855 | TTI->getMemoryOpCost(Instruction::Load, ScalarTy, VI->getAlign(), | |||
6856 | VI->getPointerAddressSpace(), CostKind, | |||
6857 | TTI::OperandValueInfo(), VI); | |||
6858 | }; | |||
6859 | auto GetVectorCost = [=](InstructionCost CommonCost) { | |||
6860 | auto *LI0 = cast<LoadInst>(VL0); | |||
6861 | InstructionCost VecLdCost; | |||
6862 | if (E->State == TreeEntry::Vectorize) { | |||
6863 | VecLdCost = TTI->getMemoryOpCost( | |||
6864 | Instruction::Load, VecTy, LI0->getAlign(), | |||
6865 | LI0->getPointerAddressSpace(), CostKind, TTI::OperandValueInfo()); | |||
6866 | } else { | |||
6867 | assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState")(static_cast <bool> (E->State == TreeEntry::ScatterVectorize && "Unknown EntryState") ? void (0) : __assert_fail ( "E->State == TreeEntry::ScatterVectorize && \"Unknown EntryState\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6867, __extension__ __PRETTY_FUNCTION__)); | |||
6868 | Align CommonAlignment = LI0->getAlign(); | |||
6869 | for (Value *V : VL) | |||
6870 | CommonAlignment = | |||
6871 | std::min(CommonAlignment, cast<LoadInst>(V)->getAlign()); | |||
6872 | VecLdCost = TTI->getGatherScatterOpCost( | |||
6873 | Instruction::Load, VecTy, LI0->getPointerOperand(), | |||
6874 | /*VariableMask=*/false, CommonAlignment, CostKind); | |||
6875 | } | |||
6876 | return VecLdCost + CommonCost; | |||
6877 | }; | |||
6878 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
6879 | } | |||
6880 | case Instruction::Store: { | |||
6881 | bool IsReorder = !E->ReorderIndices.empty(); | |||
6882 | auto *SI = cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); | |||
6883 | auto GetScalarCost = [=](unsigned Idx) { | |||
6884 | auto *VI = cast<StoreInst>(VL[Idx]); | |||
6885 | InstructionCost GEPCost = 0; | |||
6886 | if (VI != SI) { | |||
6887 | auto *Ptr = dyn_cast<GetElementPtrInst>(VI->getPointerOperand()); | |||
6888 | if (Ptr && Ptr->hasOneUse() && !Ptr->hasAllConstantIndices()) | |||
6889 | GEPCost = TTI->getArithmeticInstrCost(Instruction::Add, | |||
6890 | Ptr->getType(), CostKind); | |||
6891 | } | |||
6892 | TTI::OperandValueInfo OpInfo = getOperandInfo(VI, 0); | |||
6893 | return GEPCost + TTI->getMemoryOpCost( | |||
6894 | Instruction::Store, ScalarTy, VI->getAlign(), | |||
6895 | VI->getPointerAddressSpace(), CostKind, OpInfo, VI); | |||
6896 | }; | |||
6897 | auto GetVectorCost = [=](InstructionCost CommonCost) { | |||
6898 | // We know that we can merge the stores. Calculate the cost. | |||
6899 | TTI::OperandValueInfo OpInfo = getOperandInfo(VL, 0); | |||
6900 | return TTI->getMemoryOpCost(Instruction::Store, VecTy, SI->getAlign(), | |||
6901 | SI->getPointerAddressSpace(), CostKind, | |||
6902 | OpInfo) + | |||
6903 | CommonCost; | |||
6904 | }; | |||
6905 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
6906 | } | |||
6907 | case Instruction::Call: { | |||
6908 | auto GetScalarCost = [=](unsigned Idx) { | |||
6909 | auto *CI = cast<CallInst>(VL[Idx]); | |||
6910 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
6911 | if (ID != Intrinsic::not_intrinsic) { | |||
6912 | IntrinsicCostAttributes CostAttrs(ID, *CI, 1); | |||
6913 | return TTI->getIntrinsicInstrCost(CostAttrs, CostKind); | |||
6914 | } | |||
6915 | return TTI->getCallInstrCost(CI->getCalledFunction(), | |||
6916 | CI->getFunctionType()->getReturnType(), | |||
6917 | CI->getFunctionType()->params(), CostKind); | |||
6918 | }; | |||
6919 | auto GetVectorCost = [=](InstructionCost CommonCost) { | |||
6920 | auto *CI = cast<CallInst>(VL0); | |||
6921 | auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); | |||
6922 | return std::min(VecCallCosts.first, VecCallCosts.second) + CommonCost; | |||
6923 | }; | |||
6924 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
6925 | } | |||
6926 | case Instruction::ShuffleVector: { | |||
6927 | assert(E->isAltShuffle() &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6933, __extension__ __PRETTY_FUNCTION__)) | |||
6928 | ((Instruction::isBinaryOp(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6933, __extension__ __PRETTY_FUNCTION__)) | |||
6929 | Instruction::isBinaryOp(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6933, __extension__ __PRETTY_FUNCTION__)) | |||
6930 | (Instruction::isCast(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6933, __extension__ __PRETTY_FUNCTION__)) | |||
6931 | Instruction::isCast(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6933, __extension__ __PRETTY_FUNCTION__)) | |||
6932 | (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6933, __extension__ __PRETTY_FUNCTION__)) | |||
6933 | "Invalid Shuffle Vector Operand")(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6933, __extension__ __PRETTY_FUNCTION__)); | |||
6934 | // Try to find the previous shuffle node with the same operands and same | |||
6935 | // main/alternate ops. | |||
6936 | auto TryFindNodeWithEqualOperands = [=]() { | |||
6937 | for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { | |||
6938 | if (TE.get() == E) | |||
6939 | break; | |||
6940 | if (TE->isAltShuffle() && | |||
6941 | ((TE->getOpcode() == E->getOpcode() && | |||
6942 | TE->getAltOpcode() == E->getAltOpcode()) || | |||
6943 | (TE->getOpcode() == E->getAltOpcode() && | |||
6944 | TE->getAltOpcode() == E->getOpcode())) && | |||
6945 | TE->hasEqualOperands(*E)) | |||
6946 | return true; | |||
6947 | } | |||
6948 | return false; | |||
6949 | }; | |||
6950 | auto GetScalarCost = [=](unsigned Idx) { | |||
6951 | auto *VI = cast<Instruction>(VL[Idx]); | |||
6952 | assert(E->isOpcodeOrAlt(VI) && "Unexpected main/alternate opcode")(static_cast <bool> (E->isOpcodeOrAlt(VI) && "Unexpected main/alternate opcode") ? void (0) : __assert_fail ("E->isOpcodeOrAlt(VI) && \"Unexpected main/alternate opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6952, __extension__ __PRETTY_FUNCTION__)); | |||
6953 | (void)E; | |||
6954 | return TTI->getInstructionCost(VI, CostKind); | |||
6955 | }; | |||
6956 | // Need to clear CommonCost since the final shuffle cost is included into | |||
6957 | // vector cost. | |||
6958 | auto GetVectorCost = [&](InstructionCost) { | |||
6959 | // VecCost is equal to sum of the cost of creating 2 vectors | |||
6960 | // and the cost of creating shuffle. | |||
6961 | InstructionCost VecCost = 0; | |||
6962 | if (TryFindNodeWithEqualOperands()) { | |||
6963 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n" ; E->dump(); }; } } while (false) | |||
6964 | dbgs() << "SLP: diamond match for alternate node found.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n" ; E->dump(); }; } } while (false) | |||
6965 | E->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n" ; E->dump(); }; } } while (false) | |||
6966 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: diamond match for alternate node found.\n" ; E->dump(); }; } } while (false); | |||
6967 | // No need to add new vector costs here since we're going to reuse | |||
6968 | // same main/alternate vector ops, just do different shuffling. | |||
6969 | } else if (Instruction::isBinaryOp(E->getOpcode())) { | |||
6970 | VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); | |||
6971 | VecCost += | |||
6972 | TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, CostKind); | |||
6973 | } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { | |||
6974 | VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, | |||
6975 | Builder.getInt1Ty(), | |||
6976 | CI0->getPredicate(), CostKind, VL0); | |||
6977 | VecCost += TTI->getCmpSelInstrCost( | |||
6978 | E->getOpcode(), ScalarTy, Builder.getInt1Ty(), | |||
6979 | cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, | |||
6980 | E->getAltOp()); | |||
6981 | } else { | |||
6982 | Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); | |||
6983 | Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); | |||
6984 | auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); | |||
6985 | auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); | |||
6986 | VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, | |||
6987 | TTI::CastContextHint::None, CostKind); | |||
6988 | VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, | |||
6989 | TTI::CastContextHint::None, CostKind); | |||
6990 | } | |||
6991 | if (E->ReuseShuffleIndices.empty()) { | |||
6992 | VecCost += | |||
6993 | TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy); | |||
6994 | } else { | |||
6995 | SmallVector<int> Mask; | |||
6996 | buildShuffleEntryMask( | |||
6997 | E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, | |||
6998 | [E](Instruction *I) { | |||
6999 | assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode")(static_cast <bool> (E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode" ) ? void (0) : __assert_fail ("E->isOpcodeOrAlt(I) && \"Unexpected main/alternate opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 6999, __extension__ __PRETTY_FUNCTION__)); | |||
7000 | return I->getOpcode() == E->getAltOpcode(); | |||
7001 | }, | |||
7002 | Mask); | |||
7003 | VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, | |||
7004 | FinalVecTy, Mask); | |||
7005 | } | |||
7006 | return VecCost; | |||
7007 | }; | |||
7008 | return GetCostDiff(GetScalarCost, GetVectorCost); | |||
7009 | } | |||
7010 | default: | |||
7011 | llvm_unreachable("Unknown instruction")::llvm::llvm_unreachable_internal("Unknown instruction", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp" , 7011); | |||
7012 | } | |||
7013 | } | |||
7014 | ||||
7015 | bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { | |||
7016 | LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Check whether the tree with height " << VectorizableTree.size() << " is fully vectorizable .\n" ; } } while (false) | |||
7017 | << VectorizableTree.size() << " is fully vectorizable .\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Check whether the tree with height " << VectorizableTree.size() << " is fully vectorizable .\n" ; } } while (false); | |||
7018 | ||||
7019 | auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { | |||
7020 | SmallVector<int> Mask; | |||
7021 | return TE->State == TreeEntry::NeedToGather && | |||
7022 | !any_of(TE->Scalars, | |||
7023 | [this](Value *V) { return EphValues.contains(V); }) && | |||
7024 | (allConstant(TE->Scalars) || isSplat(TE->Scalars) || | |||
7025 | TE->Scalars.size() < Limit || | |||
7026 | ((TE->getOpcode() == Instruction::ExtractElement || | |||
7027 | all_of(TE->Scalars, | |||
7028 | [](Value *V) { | |||
7029 | return isa<ExtractElementInst, UndefValue>(V); | |||
7030 | })) && | |||
7031 | isFixedVectorShuffle(TE->Scalars, Mask)) || | |||
7032 | (TE->State == TreeEntry::NeedToGather && | |||
7033 | TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); | |||
7034 | }; | |||
7035 | ||||
7036 | // We only handle trees of heights 1 and 2. | |||
7037 | if (VectorizableTree.size() == 1 && | |||
7038 | (VectorizableTree[0]->State == TreeEntry::Vectorize || | |||
7039 | (ForReduction && | |||
7040 | AreVectorizableGathers(VectorizableTree[0].get(), | |||
7041 | VectorizableTree[0]->Scalars.size()) && | |||
7042 | VectorizableTree[0]->getVectorFactor() > 2))) | |||
7043 | return true; | |||
7044 | ||||
7045 | if (VectorizableTree.size() != 2) | |||
7046 | return false; | |||
7047 | ||||
7048 | // Handle splat and all-constants stores. Also try to vectorize tiny trees | |||
7049 | // with the second gather nodes if they have less scalar operands rather than | |||
7050 | // the initial tree element (may be profitable to shuffle the second gather) | |||
7051 | // or they are extractelements, which form shuffle. | |||
7052 | SmallVector<int> Mask; | |||
7053 | if (VectorizableTree[0]->State == TreeEntry::Vectorize && | |||
7054 | AreVectorizableGathers(VectorizableTree[1].get(), | |||
7055 | VectorizableTree[0]->Scalars.size())) | |||
7056 | return true; | |||
7057 | ||||
7058 | // Gathering cost would be too much for tiny trees. | |||
7059 | if (VectorizableTree[0]->State == TreeEntry::NeedToGather || | |||
7060 | (VectorizableTree[1]->State == TreeEntry::NeedToGather && | |||
7061 | VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) | |||
7062 | return false; | |||
7063 | ||||
7064 | return true; | |||
7065 | } | |||
7066 | ||||
7067 | static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, | |||
7068 | TargetTransformInfo *TTI, | |||
7069 | bool MustMatchOrInst) { | |||
7070 | // Look past the root to find a source value. Arbitrarily follow the | |||
7071 | // path through operand 0 of any 'or'. Also, peek through optional | |||
7072 | // shift-left-by-multiple-of-8-bits. | |||
7073 | Value *ZextLoad = Root; | |||
7074 | const APInt *ShAmtC; | |||
7075 | bool FoundOr = false; | |||
7076 | while (!isa<ConstantExpr>(ZextLoad) && | |||
7077 | (match(ZextLoad, m_Or(m_Value(), m_Value())) || | |||
7078 | (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && | |||
7079 | ShAmtC->urem(8) == 0))) { | |||
7080 | auto *BinOp = cast<BinaryOperator>(ZextLoad); | |||
7081 | ZextLoad = BinOp->getOperand(0); | |||
7082 | if (BinOp->getOpcode() == Instruction::Or) | |||
7083 | FoundOr = true; | |||
7084 | } | |||
7085 | // Check if the input is an extended load of the required or/shift expression. | |||
7086 | Value *Load; | |||
7087 | if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || | |||
7088 | !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) | |||
7089 | return false; | |||
7090 | ||||
7091 | // Require that the total load bit width is a legal integer type. | |||
7092 | // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. | |||
7093 | // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. | |||
7094 | Type *SrcTy = Load->getType(); | |||
7095 | unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; | |||
7096 | if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) | |||
7097 | return false; | |||
7098 | ||||
7099 | // Everything matched - assume that we can fold the whole sequence using | |||
7100 | // load combining. | |||
7101 | LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Assume load combining for tree starting at " << *(cast<Instruction>(Root)) << "\n"; } } while (false) | |||
7102 | << *(cast<Instruction>(Root)) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Assume load combining for tree starting at " << *(cast<Instruction>(Root)) << "\n"; } } while (false); | |||
7103 | ||||
7104 | return true; | |||
7105 | } | |||
7106 | ||||
7107 | bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { | |||
7108 | if (RdxKind != RecurKind::Or) | |||
7109 | return false; | |||
7110 | ||||
7111 | unsigned NumElts = VectorizableTree[0]->Scalars.size(); | |||
7112 | Value *FirstReduced = VectorizableTree[0]->Scalars[0]; | |||
7113 | return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, | |||
7114 | /* MatchOr */ false); | |||
7115 | } | |||
7116 | ||||
7117 | bool BoUpSLP::isLoadCombineCandidate() const { | |||
7118 | // Peek through a final sequence of stores and check if all operations are | |||
7119 | // likely to be load-combined. | |||
7120 | unsigned NumElts = VectorizableTree[0]->Scalars.size(); | |||
7121 | for (Value *Scalar : VectorizableTree[0]->Scalars) { | |||
7122 | Value *X; | |||
7123 | if (!match(Scalar, m_Store(m_Value(X), m_Value())) || | |||
7124 | !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) | |||
7125 | return false; | |||
7126 | } | |||
7127 | return true; | |||
7128 | } | |||
7129 | ||||
7130 | bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { | |||
7131 | // No need to vectorize inserts of gathered values. | |||
7132 | if (VectorizableTree.size() == 2 && | |||
7133 | isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && | |||
7134 | VectorizableTree[1]->State == TreeEntry::NeedToGather && | |||
7135 | (VectorizableTree[1]->getVectorFactor() <= 2 || | |||
7136 | !(isSplat(VectorizableTree[1]->Scalars) || | |||
7137 | allConstant(VectorizableTree[1]->Scalars)))) | |||
7138 | return true; | |||
7139 | ||||
7140 | // We can vectorize the tree if its size is greater than or equal to the | |||
7141 | // minimum size specified by the MinTreeSize command line option. | |||
7142 | if (VectorizableTree.size() >= MinTreeSize) | |||
7143 | return false; | |||
7144 | ||||
7145 | // If we have a tiny tree (a tree whose size is less than MinTreeSize), we | |||
7146 | // can vectorize it if we can prove it fully vectorizable. | |||
7147 | if (isFullyVectorizableTinyTree(ForReduction)) | |||
7148 | return false; | |||
7149 | ||||
7150 | assert(VectorizableTree.empty()(static_cast <bool> (VectorizableTree.empty() ? ExternalUses .empty() : true && "We shouldn't have any external users" ) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7152, __extension__ __PRETTY_FUNCTION__)) | |||
7151 | ? ExternalUses.empty()(static_cast <bool> (VectorizableTree.empty() ? ExternalUses .empty() : true && "We shouldn't have any external users" ) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7152, __extension__ __PRETTY_FUNCTION__)) | |||
7152 | : true && "We shouldn't have any external users")(static_cast <bool> (VectorizableTree.empty() ? ExternalUses .empty() : true && "We shouldn't have any external users" ) ? void (0) : __assert_fail ("VectorizableTree.empty() ? ExternalUses.empty() : true && \"We shouldn't have any external users\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7152, __extension__ __PRETTY_FUNCTION__)); | |||
7153 | ||||
7154 | // Otherwise, we can't vectorize the tree. It is both tiny and not fully | |||
7155 | // vectorizable. | |||
7156 | return true; | |||
7157 | } | |||
7158 | ||||
7159 | InstructionCost BoUpSLP::getSpillCost() const { | |||
7160 | // Walk from the bottom of the tree to the top, tracking which values are | |||
7161 | // live. When we see a call instruction that is not part of our tree, | |||
7162 | // query TTI to see if there is a cost to keeping values live over it | |||
7163 | // (for example, if spills and fills are required). | |||
7164 | unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); | |||
7165 | InstructionCost Cost = 0; | |||
7166 | ||||
7167 | SmallPtrSet<Instruction*, 4> LiveValues; | |||
7168 | Instruction *PrevInst = nullptr; | |||
7169 | ||||
7170 | // The entries in VectorizableTree are not necessarily ordered by their | |||
7171 | // position in basic blocks. Collect them and order them by dominance so later | |||
7172 | // instructions are guaranteed to be visited first. For instructions in | |||
7173 | // different basic blocks, we only scan to the beginning of the block, so | |||
7174 | // their order does not matter, as long as all instructions in a basic block | |||
7175 | // are grouped together. Using dominance ensures a deterministic order. | |||
7176 | SmallVector<Instruction *, 16> OrderedScalars; | |||
7177 | for (const auto &TEPtr : VectorizableTree) { | |||
7178 | Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); | |||
7179 | if (!Inst) | |||
7180 | continue; | |||
7181 | OrderedScalars.push_back(Inst); | |||
7182 | } | |||
7183 | llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { | |||
7184 | auto *NodeA = DT->getNode(A->getParent()); | |||
7185 | auto *NodeB = DT->getNode(B->getParent()); | |||
7186 | assert(NodeA && "Should only process reachable instructions")(static_cast <bool> (NodeA && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeA && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7186, __extension__ __PRETTY_FUNCTION__)); | |||
7187 | assert(NodeB && "Should only process reachable instructions")(static_cast <bool> (NodeB && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeB && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7187, __extension__ __PRETTY_FUNCTION__)); | |||
7188 | assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7189, __extension__ __PRETTY_FUNCTION__)) | |||
7189 | "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7189, __extension__ __PRETTY_FUNCTION__)); | |||
7190 | if (NodeA != NodeB) | |||
7191 | return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); | |||
7192 | return B->comesBefore(A); | |||
7193 | }); | |||
7194 | ||||
7195 | for (Instruction *Inst : OrderedScalars) { | |||
7196 | if (!PrevInst) { | |||
7197 | PrevInst = Inst; | |||
7198 | continue; | |||
7199 | } | |||
7200 | ||||
7201 | // Update LiveValues. | |||
7202 | LiveValues.erase(PrevInst); | |||
7203 | for (auto &J : PrevInst->operands()) { | |||
7204 | if (isa<Instruction>(&*J) && getTreeEntry(&*J)) | |||
7205 | LiveValues.insert(cast<Instruction>(&*J)); | |||
7206 | } | |||
7207 | ||||
7208 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues .size(); for (auto *X : LiveValues) dbgs() << " " << X->getName(); dbgs() << ", Looking at "; Inst->dump (); }; } } while (false) | |||
7209 | dbgs() << "SLP: #LV: " << LiveValues.size();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues .size(); for (auto *X : LiveValues) dbgs() << " " << X->getName(); dbgs() << ", Looking at "; Inst->dump (); }; } } while (false) | |||
7210 | for (auto *X : LiveValues)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues .size(); for (auto *X : LiveValues) dbgs() << " " << X->getName(); dbgs() << ", Looking at "; Inst->dump (); }; } } while (false) | |||
7211 | dbgs() << " " << X->getName();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues .size(); for (auto *X : LiveValues) dbgs() << " " << X->getName(); dbgs() << ", Looking at "; Inst->dump (); }; } } while (false) | |||
7212 | dbgs() << ", Looking at ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues .size(); for (auto *X : LiveValues) dbgs() << " " << X->getName(); dbgs() << ", Looking at "; Inst->dump (); }; } } while (false) | |||
7213 | Inst->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues .size(); for (auto *X : LiveValues) dbgs() << " " << X->getName(); dbgs() << ", Looking at "; Inst->dump (); }; } } while (false) | |||
7214 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { { dbgs() << "SLP: #LV: " << LiveValues .size(); for (auto *X : LiveValues) dbgs() << " " << X->getName(); dbgs() << ", Looking at "; Inst->dump (); }; } } while (false); | |||
7215 | ||||
7216 | // Now find the sequence of instructions between PrevInst and Inst. | |||
7217 | unsigned NumCalls = 0; | |||
7218 | BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), | |||
7219 | PrevInstIt = | |||
7220 | PrevInst->getIterator().getReverse(); | |||
7221 | while (InstIt != PrevInstIt) { | |||
7222 | if (PrevInstIt == PrevInst->getParent()->rend()) { | |||
7223 | PrevInstIt = Inst->getParent()->rbegin(); | |||
7224 | continue; | |||
7225 | } | |||
7226 | ||||
7227 | // Debug information does not impact spill cost. | |||
7228 | if ((isa<CallInst>(&*PrevInstIt) && | |||
7229 | !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && | |||
7230 | &*PrevInstIt != PrevInst) | |||
7231 | NumCalls++; | |||
7232 | ||||
7233 | ++PrevInstIt; | |||
7234 | } | |||
7235 | ||||
7236 | if (NumCalls) { | |||
7237 | SmallVector<Type*, 4> V; | |||
7238 | for (auto *II : LiveValues) { | |||
7239 | auto *ScalarTy = II->getType(); | |||
7240 | if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) | |||
7241 | ScalarTy = VectorTy->getElementType(); | |||
7242 | V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); | |||
7243 | } | |||
7244 | Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); | |||
7245 | } | |||
7246 | ||||
7247 | PrevInst = Inst; | |||
7248 | } | |||
7249 | ||||
7250 | return Cost; | |||
7251 | } | |||
7252 | ||||
7253 | /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the | |||
7254 | /// buildvector sequence. | |||
7255 | static bool isFirstInsertElement(const InsertElementInst *IE1, | |||
7256 | const InsertElementInst *IE2) { | |||
7257 | if (IE1 == IE2) | |||
7258 | return false; | |||
7259 | const auto *I1 = IE1; | |||
7260 | const auto *I2 = IE2; | |||
7261 | const InsertElementInst *PrevI1; | |||
7262 | const InsertElementInst *PrevI2; | |||
7263 | unsigned Idx1 = *getInsertIndex(IE1); | |||
7264 | unsigned Idx2 = *getInsertIndex(IE2); | |||
7265 | do { | |||
7266 | if (I2 == IE1) | |||
7267 | return true; | |||
7268 | if (I1 == IE2) | |||
7269 | return false; | |||
7270 | PrevI1 = I1; | |||
7271 | PrevI2 = I2; | |||
7272 | if (I1 && (I1 == IE1 || I1->hasOneUse()) && | |||
7273 | getInsertIndex(I1).value_or(Idx2) != Idx2) | |||
7274 | I1 = dyn_cast<InsertElementInst>(I1->getOperand(0)); | |||
7275 | if (I2 && ((I2 == IE2 || I2->hasOneUse())) && | |||
7276 | getInsertIndex(I2).value_or(Idx1) != Idx1) | |||
7277 | I2 = dyn_cast<InsertElementInst>(I2->getOperand(0)); | |||
7278 | } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2)); | |||
7279 | llvm_unreachable("Two different buildvectors not expected.")::llvm::llvm_unreachable_internal("Two different buildvectors not expected." , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7279); | |||
7280 | } | |||
7281 | ||||
7282 | namespace { | |||
7283 | /// Returns incoming Value *, if the requested type is Value * too, or a default | |||
7284 | /// value, otherwise. | |||
7285 | struct ValueSelect { | |||
7286 | template <typename U> | |||
7287 | static std::enable_if_t<std::is_same_v<Value *, U>, Value *> get(Value *V) { | |||
7288 | return V; | |||
7289 | } | |||
7290 | template <typename U> | |||
7291 | static std::enable_if_t<!std::is_same_v<Value *, U>, U> get(Value *) { | |||
7292 | return U(); | |||
7293 | } | |||
7294 | }; | |||
7295 | } // namespace | |||
7296 | ||||
7297 | /// Does the analysis of the provided shuffle masks and performs the requested | |||
7298 | /// actions on the vectors with the given shuffle masks. It tries to do it in | |||
7299 | /// several steps. | |||
7300 | /// 1. If the Base vector is not undef vector, resizing the very first mask to | |||
7301 | /// have common VF and perform action for 2 input vectors (including non-undef | |||
7302 | /// Base). Other shuffle masks are combined with the resulting after the 1 stage | |||
7303 | /// and processed as a shuffle of 2 elements. | |||
7304 | /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the | |||
7305 | /// action only for 1 vector with the given mask, if it is not the identity | |||
7306 | /// mask. | |||
7307 | /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2 | |||
7308 | /// vectors, combing the masks properly between the steps. | |||
7309 | template <typename T> | |||
7310 | static T *performExtractsShuffleAction( | |||
7311 | MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base, | |||
7312 | function_ref<unsigned(T *)> GetVF, | |||
7313 | function_ref<std::pair<T *, bool>(T *, ArrayRef<int>, bool)> ResizeAction, | |||
7314 | function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) { | |||
7315 | assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.")(static_cast <bool> (!ShuffleMask.empty() && "Empty list of shuffles for inserts." ) ? void (0) : __assert_fail ("!ShuffleMask.empty() && \"Empty list of shuffles for inserts.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7315, __extension__ __PRETTY_FUNCTION__)); | |||
7316 | SmallVector<int> Mask(ShuffleMask.begin()->second); | |||
7317 | auto VMIt = std::next(ShuffleMask.begin()); | |||
7318 | T *Prev = nullptr; | |||
7319 | SmallBitVector IsBaseUndef = isUndefVector(Base, Mask); | |||
7320 | if (!IsBaseUndef.all()) { | |||
7321 | // Base is not undef, need to combine it with the next subvectors. | |||
7322 | std::pair<T *, bool> Res = | |||
7323 | ResizeAction(ShuffleMask.begin()->first, Mask, /*ForSingleMask=*/false); | |||
7324 | SmallBitVector IsBasePoison = isUndefVector<true>(Base, Mask); | |||
7325 | for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) { | |||
7326 | if (Mask[Idx] == UndefMaskElem) | |||
7327 | Mask[Idx] = IsBasePoison.test(Idx) ? UndefMaskElem : Idx; | |||
7328 | else | |||
7329 | Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF; | |||
7330 | } | |||
7331 | auto *V = ValueSelect::get<T *>(Base); | |||
7332 | (void)V; | |||
7333 | assert((!V || GetVF(V) == Mask.size()) &&(static_cast <bool> ((!V || GetVF(V) == Mask.size()) && "Expected base vector of VF number of elements.") ? void (0) : __assert_fail ("(!V || GetVF(V) == Mask.size()) && \"Expected base vector of VF number of elements.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7334, __extension__ __PRETTY_FUNCTION__)) | |||
7334 | "Expected base vector of VF number of elements.")(static_cast <bool> ((!V || GetVF(V) == Mask.size()) && "Expected base vector of VF number of elements.") ? void (0) : __assert_fail ("(!V || GetVF(V) == Mask.size()) && \"Expected base vector of VF number of elements.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7334, __extension__ __PRETTY_FUNCTION__)); | |||
7335 | Prev = Action(Mask, {nullptr, Res.first}); | |||
7336 | } else if (ShuffleMask.size() == 1) { | |||
7337 | // Base is undef and only 1 vector is shuffled - perform the action only for | |||
7338 | // single vector, if the mask is not the identity mask. | |||
7339 | std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask, | |||
7340 | /*ForSingleMask=*/true); | |||
7341 | if (Res.second) | |||
7342 | // Identity mask is found. | |||
7343 | Prev = Res.first; | |||
7344 | else | |||
7345 | Prev = Action(Mask, {ShuffleMask.begin()->first}); | |||
7346 | } else { | |||
7347 | // Base is undef and at least 2 input vectors shuffled - perform 2 vectors | |||
7348 | // shuffles step by step, combining shuffle between the steps. | |||
7349 | unsigned Vec1VF = GetVF(ShuffleMask.begin()->first); | |||
7350 | unsigned Vec2VF = GetVF(VMIt->first); | |||
7351 | if (Vec1VF == Vec2VF) { | |||
7352 | // No need to resize the input vectors since they are of the same size, we | |||
7353 | // can shuffle them directly. | |||
7354 | ArrayRef<int> SecMask = VMIt->second; | |||
7355 | for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { | |||
7356 | if (SecMask[I] != UndefMaskElem) { | |||
7357 | assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.")(static_cast <bool> (Mask[I] == UndefMaskElem && "Multiple uses of scalars.") ? void (0) : __assert_fail ("Mask[I] == UndefMaskElem && \"Multiple uses of scalars.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7357, __extension__ __PRETTY_FUNCTION__)); | |||
7358 | Mask[I] = SecMask[I] + Vec1VF; | |||
7359 | } | |||
7360 | } | |||
7361 | Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first}); | |||
7362 | } else { | |||
7363 | // Vectors of different sizes - resize and reshuffle. | |||
7364 | std::pair<T *, bool> Res1 = ResizeAction(ShuffleMask.begin()->first, Mask, | |||
7365 | /*ForSingleMask=*/false); | |||
7366 | std::pair<T *, bool> Res2 = | |||
7367 | ResizeAction(VMIt->first, VMIt->second, /*ForSingleMask=*/false); | |||
7368 | ArrayRef<int> SecMask = VMIt->second; | |||
7369 | for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { | |||
7370 | if (Mask[I] != UndefMaskElem) { | |||
7371 | assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.")(static_cast <bool> (SecMask[I] == UndefMaskElem && "Multiple uses of scalars.") ? void (0) : __assert_fail ("SecMask[I] == UndefMaskElem && \"Multiple uses of scalars.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7371, __extension__ __PRETTY_FUNCTION__)); | |||
7372 | if (Res1.second) | |||
7373 | Mask[I] = I; | |||
7374 | } else if (SecMask[I] != UndefMaskElem) { | |||
7375 | assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.")(static_cast <bool> (Mask[I] == UndefMaskElem && "Multiple uses of scalars.") ? void (0) : __assert_fail ("Mask[I] == UndefMaskElem && \"Multiple uses of scalars.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7375, __extension__ __PRETTY_FUNCTION__)); | |||
7376 | Mask[I] = (Res2.second ? I : SecMask[I]) + VF; | |||
7377 | } | |||
7378 | } | |||
7379 | Prev = Action(Mask, {Res1.first, Res2.first}); | |||
7380 | } | |||
7381 | VMIt = std::next(VMIt); | |||
7382 | } | |||
7383 | bool IsBaseNotUndef = !IsBaseUndef.all(); | |||
7384 | (void)IsBaseNotUndef; | |||
7385 | // Perform requested actions for the remaining masks/vectors. | |||
7386 | for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) { | |||
7387 | // Shuffle other input vectors, if any. | |||
7388 | std::pair<T *, bool> Res = | |||
7389 | ResizeAction(VMIt->first, VMIt->second, /*ForSingleMask=*/false); | |||
7390 | ArrayRef<int> SecMask = VMIt->second; | |||
7391 | for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { | |||
7392 | if (SecMask[I] != UndefMaskElem) { | |||
7393 | assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&(static_cast <bool> ((Mask[I] == UndefMaskElem || IsBaseNotUndef ) && "Multiple uses of scalars.") ? void (0) : __assert_fail ("(Mask[I] == UndefMaskElem || IsBaseNotUndef) && \"Multiple uses of scalars.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7394, __extension__ __PRETTY_FUNCTION__)) | |||
7394 | "Multiple uses of scalars.")(static_cast <bool> ((Mask[I] == UndefMaskElem || IsBaseNotUndef ) && "Multiple uses of scalars.") ? void (0) : __assert_fail ("(Mask[I] == UndefMaskElem || IsBaseNotUndef) && \"Multiple uses of scalars.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7394, __extension__ __PRETTY_FUNCTION__)); | |||
7395 | Mask[I] = (Res.second ? I : SecMask[I]) + VF; | |||
7396 | } else if (Mask[I] != UndefMaskElem) { | |||
7397 | Mask[I] = I; | |||
7398 | } | |||
7399 | } | |||
7400 | Prev = Action(Mask, {Prev, Res.first}); | |||
7401 | } | |||
7402 | return Prev; | |||
7403 | } | |||
7404 | ||||
7405 | InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { | |||
7406 | InstructionCost Cost = 0; | |||
7407 | LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Calculating cost for tree of size " << VectorizableTree.size() << ".\n"; } } while ( false) | |||
7408 | << VectorizableTree.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Calculating cost for tree of size " << VectorizableTree.size() << ".\n"; } } while ( false); | |||
7409 | ||||
7410 | unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); | |||
7411 | ||||
7412 | for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { | |||
7413 | TreeEntry &TE = *VectorizableTree[I]; | |||
7414 | if (TE.State == TreeEntry::NeedToGather) { | |||
7415 | if (const TreeEntry *E = getTreeEntry(TE.getMainOp()); | |||
7416 | E && E->getVectorFactor() == TE.getVectorFactor() && | |||
7417 | E->isSame(TE.Scalars)) { | |||
7418 | // Some gather nodes might be absolutely the same as some vectorizable | |||
7419 | // nodes after reordering, need to handle it. | |||
7420 | LLVM_DEBUG(dbgs() << "SLP: Adding cost 0 for bundle that starts with "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost 0 for bundle that starts with " << *TE.Scalars[0] << ".\n" << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7421 | << *TE.Scalars[0] << ".\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost 0 for bundle that starts with " << *TE.Scalars[0] << ".\n" << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7422 | << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost 0 for bundle that starts with " << *TE.Scalars[0] << ".\n" << "SLP: Current total cost = " << Cost << "\n"; } } while (false); | |||
7423 | continue; | |||
7424 | } | |||
7425 | } | |||
7426 | ||||
7427 | InstructionCost C = getEntryCost(&TE, VectorizedVals); | |||
7428 | Cost += C; | |||
7429 | LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for bundle that starts with " << *TE.Scalars[0] << ".\n" << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7430 | << " for bundle that starts with " << *TE.Scalars[0]do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for bundle that starts with " << *TE.Scalars[0] << ".\n" << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7431 | << ".\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for bundle that starts with " << *TE.Scalars[0] << ".\n" << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7432 | << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for bundle that starts with " << *TE.Scalars[0] << ".\n" << "SLP: Current total cost = " << Cost << "\n"; } } while (false); | |||
7433 | } | |||
7434 | ||||
7435 | SmallPtrSet<Value *, 16> ExtractCostCalculated; | |||
7436 | InstructionCost ExtractCost = 0; | |||
7437 | SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks; | |||
7438 | SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers; | |||
7439 | SmallVector<APInt> DemandedElts; | |||
7440 | for (ExternalUser &EU : ExternalUses) { | |||
7441 | // We only add extract cost once for the same scalar. | |||
7442 | if (!isa_and_nonnull<InsertElementInst>(EU.User) && | |||
7443 | !ExtractCostCalculated.insert(EU.Scalar).second) | |||
7444 | continue; | |||
7445 | ||||
7446 | // Uses by ephemeral values are free (because the ephemeral value will be | |||
7447 | // removed prior to code generation, and so the extraction will be | |||
7448 | // removed as well). | |||
7449 | if (EphValues.count(EU.User)) | |||
7450 | continue; | |||
7451 | ||||
7452 | // No extract cost for vector "scalar" | |||
7453 | if (isa<FixedVectorType>(EU.Scalar->getType())) | |||
7454 | continue; | |||
7455 | ||||
7456 | // If found user is an insertelement, do not calculate extract cost but try | |||
7457 | // to detect it as a final shuffled/identity match. | |||
7458 | if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { | |||
7459 | if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { | |||
7460 | Optional<unsigned> InsertIdx = getInsertIndex(VU); | |||
7461 | if (InsertIdx) { | |||
7462 | const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar); | |||
7463 | auto *It = find_if( | |||
7464 | FirstUsers, | |||
7465 | [this, VU](const std::pair<Value *, const TreeEntry *> &Pair) { | |||
7466 | return areTwoInsertFromSameBuildVector( | |||
7467 | VU, cast<InsertElementInst>(Pair.first), | |||
7468 | [this](InsertElementInst *II) -> Value * { | |||
7469 | Value *Op0 = II->getOperand(0); | |||
7470 | if (getTreeEntry(II) && !getTreeEntry(Op0)) | |||
7471 | return nullptr; | |||
7472 | return Op0; | |||
7473 | }); | |||
7474 | }); | |||
7475 | int VecId = -1; | |||
7476 | if (It == FirstUsers.end()) { | |||
7477 | (void)ShuffleMasks.emplace_back(); | |||
7478 | SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE]; | |||
7479 | if (Mask.empty()) | |||
7480 | Mask.assign(FTy->getNumElements(), UndefMaskElem); | |||
7481 | // Find the insertvector, vectorized in tree, if any. | |||
7482 | Value *Base = VU; | |||
7483 | while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { | |||
7484 | if (IEBase != EU.User && | |||
7485 | (!IEBase->hasOneUse() || | |||
7486 | getInsertIndex(IEBase).value_or(*InsertIdx) == *InsertIdx)) | |||
7487 | break; | |||
7488 | // Build the mask for the vectorized insertelement instructions. | |||
7489 | if (const TreeEntry *E = getTreeEntry(IEBase)) { | |||
7490 | VU = IEBase; | |||
7491 | do { | |||
7492 | IEBase = cast<InsertElementInst>(Base); | |||
7493 | int Idx = *getInsertIndex(IEBase); | |||
7494 | assert(Mask[Idx] == UndefMaskElem &&(static_cast <bool> (Mask[Idx] == UndefMaskElem && "InsertElementInstruction used already.") ? void (0) : __assert_fail ("Mask[Idx] == UndefMaskElem && \"InsertElementInstruction used already.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7495, __extension__ __PRETTY_FUNCTION__)) | |||
7495 | "InsertElementInstruction used already.")(static_cast <bool> (Mask[Idx] == UndefMaskElem && "InsertElementInstruction used already.") ? void (0) : __assert_fail ("Mask[Idx] == UndefMaskElem && \"InsertElementInstruction used already.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7495, __extension__ __PRETTY_FUNCTION__)); | |||
7496 | Mask[Idx] = Idx; | |||
7497 | Base = IEBase->getOperand(0); | |||
7498 | } while (E == getTreeEntry(Base)); | |||
7499 | break; | |||
7500 | } | |||
7501 | Base = cast<InsertElementInst>(Base)->getOperand(0); | |||
7502 | } | |||
7503 | FirstUsers.emplace_back(VU, ScalarTE); | |||
7504 | DemandedElts.push_back(APInt::getZero(FTy->getNumElements())); | |||
7505 | VecId = FirstUsers.size() - 1; | |||
7506 | } else { | |||
7507 | if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first))) | |||
7508 | It->first = VU; | |||
7509 | VecId = std::distance(FirstUsers.begin(), It); | |||
7510 | } | |||
7511 | int InIdx = *InsertIdx; | |||
7512 | SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE]; | |||
7513 | if (Mask.empty()) | |||
7514 | Mask.assign(FTy->getNumElements(), UndefMaskElem); | |||
7515 | Mask[InIdx] = EU.Lane; | |||
7516 | DemandedElts[VecId].setBit(InIdx); | |||
7517 | continue; | |||
7518 | } | |||
7519 | } | |||
7520 | } | |||
7521 | ||||
7522 | // If we plan to rewrite the tree in a smaller type, we will need to sign | |||
7523 | // extend the extracted value back to the original type. Here, we account | |||
7524 | // for the extract and the added cost of the sign extend if needed. | |||
7525 | auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); | |||
7526 | auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; | |||
7527 | if (MinBWs.count(ScalarRoot)) { | |||
7528 | auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); | |||
7529 | auto Extend = | |||
7530 | MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; | |||
7531 | VecTy = FixedVectorType::get(MinTy, BundleWidth); | |||
7532 | ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), | |||
7533 | VecTy, EU.Lane); | |||
7534 | } else { | |||
7535 | ExtractCost += | |||
7536 | TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); | |||
7537 | } | |||
7538 | } | |||
7539 | ||||
7540 | InstructionCost SpillCost = getSpillCost(); | |||
7541 | Cost += SpillCost + ExtractCost; | |||
7542 | auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask, | |||
7543 | bool) { | |||
7544 | InstructionCost C = 0; | |||
7545 | unsigned VF = Mask.size(); | |||
7546 | unsigned VecVF = TE->getVectorFactor(); | |||
7547 | if (VF != VecVF && | |||
7548 | (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) || | |||
7549 | (all_of(Mask, | |||
7550 | [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) && | |||
7551 | !ShuffleVectorInst::isIdentityMask(Mask)))) { | |||
7552 | SmallVector<int> OrigMask(VecVF, UndefMaskElem); | |||
7553 | std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)), | |||
7554 | OrigMask.begin()); | |||
7555 | C = TTI->getShuffleCost( | |||
7556 | TTI::SK_PermuteSingleSrc, | |||
7557 | FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask); | |||
7558 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement external users.\n"; TE-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7559 | dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement external users.\n"; TE-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7560 | << " for final shuffle of insertelement external users.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement external users.\n"; TE-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7561 | TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement external users.\n"; TE-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false); | |||
7562 | Cost += C; | |||
7563 | return std::make_pair(TE, true); | |||
7564 | } | |||
7565 | return std::make_pair(TE, false); | |||
7566 | }; | |||
7567 | // Calculate the cost of the reshuffled vectors, if any. | |||
7568 | for (int I = 0, E = FirstUsers.size(); I < E; ++I) { | |||
7569 | Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0); | |||
7570 | unsigned VF = ShuffleMasks[I].begin()->second.size(); | |||
7571 | auto *FTy = FixedVectorType::get( | |||
7572 | cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF); | |||
7573 | auto Vector = ShuffleMasks[I].takeVector(); | |||
7574 | auto &&EstimateShufflesCost = [this, FTy, | |||
7575 | &Cost](ArrayRef<int> Mask, | |||
7576 | ArrayRef<const TreeEntry *> TEs) { | |||
7577 | assert((TEs.size() == 1 || TEs.size() == 2) &&(static_cast <bool> ((TEs.size() == 1 || TEs.size() == 2 ) && "Expected exactly 1 or 2 tree entries.") ? void ( 0) : __assert_fail ("(TEs.size() == 1 || TEs.size() == 2) && \"Expected exactly 1 or 2 tree entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7578, __extension__ __PRETTY_FUNCTION__)) | |||
7578 | "Expected exactly 1 or 2 tree entries.")(static_cast <bool> ((TEs.size() == 1 || TEs.size() == 2 ) && "Expected exactly 1 or 2 tree entries.") ? void ( 0) : __assert_fail ("(TEs.size() == 1 || TEs.size() == 2) && \"Expected exactly 1 or 2 tree entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7578, __extension__ __PRETTY_FUNCTION__)); | |||
7579 | if (TEs.size() == 1) { | |||
7580 | int Limit = 2 * Mask.size(); | |||
7581 | if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) || | |||
7582 | !ShuffleVectorInst::isIdentityMask(Mask)) { | |||
7583 | InstructionCost C = | |||
7584 | TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask); | |||
7585 | LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement " "external users.\n"; TEs .front()->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7586 | << " for final shuffle of insertelement "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement " "external users.\n"; TEs .front()->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7587 | "external users.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement " "external users.\n"; TEs .front()->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7588 | TEs.front()->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement " "external users.\n"; TEs .front()->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7589 | dbgs() << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of insertelement " "external users.\n"; TEs .front()->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false); | |||
7590 | Cost += C; | |||
7591 | } | |||
7592 | } else { | |||
7593 | InstructionCost C = | |||
7594 | TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask); | |||
7595 | LLVM_DEBUG(dbgs() << "SLP: Adding cost " << Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of vector node and external " "insertelement users.\n" ; if (TEs.front()) { TEs.front()->dump(); } TEs.back()-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7596 | << " for final shuffle of vector node and external "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of vector node and external " "insertelement users.\n" ; if (TEs.front()) { TEs.front()->dump(); } TEs.back()-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7597 | "insertelement users.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of vector node and external " "insertelement users.\n" ; if (TEs.front()) { TEs.front()->dump(); } TEs.back()-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7598 | if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of vector node and external " "insertelement users.\n" ; if (TEs.front()) { TEs.front()->dump(); } TEs.back()-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false) | |||
7599 | dbgs() << "SLP: Current total cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << C << " for final shuffle of vector node and external " "insertelement users.\n" ; if (TEs.front()) { TEs.front()->dump(); } TEs.back()-> dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"; } } while (false); | |||
7600 | Cost += C; | |||
7601 | } | |||
7602 | return TEs.back(); | |||
7603 | }; | |||
7604 | (void)performExtractsShuffleAction<const TreeEntry>( | |||
7605 | makeMutableArrayRef(Vector.data(), Vector.size()), Base, | |||
7606 | [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF, | |||
7607 | EstimateShufflesCost); | |||
7608 | InstructionCost InsertCost = TTI->getScalarizationOverhead( | |||
7609 | cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I], | |||
7610 | /*Insert*/ true, /*Extract*/ false); | |||
7611 | Cost -= InsertCost; | |||
7612 | } | |||
7613 | ||||
7614 | #ifndef NDEBUG | |||
7615 | SmallString<256> Str; | |||
7616 | { | |||
7617 | raw_svector_ostream OS(Str); | |||
7618 | OS << "SLP: Spill Cost = " << SpillCost << ".\n" | |||
7619 | << "SLP: Extract Cost = " << ExtractCost << ".\n" | |||
7620 | << "SLP: Total Cost = " << Cost << ".\n"; | |||
7621 | } | |||
7622 | LLVM_DEBUG(dbgs() << Str)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << Str; } } while (false); | |||
7623 | if (ViewSLPTree) | |||
7624 | ViewGraph(this, "SLP" + F->getName(), false, Str); | |||
7625 | #endif | |||
7626 | ||||
7627 | return Cost; | |||
7628 | } | |||
7629 | ||||
7630 | Optional<TargetTransformInfo::ShuffleKind> | |||
7631 | BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, | |||
7632 | SmallVectorImpl<const TreeEntry *> &Entries) { | |||
7633 | // TODO: currently checking only for Scalars in the tree entry, need to count | |||
7634 | // reused elements too for better cost estimation. | |||
7635 | Mask.assign(TE->Scalars.size(), UndefMaskElem); | |||
7636 | Entries.clear(); | |||
7637 | // Build a lists of values to tree entries. | |||
7638 | DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; | |||
7639 | for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { | |||
7640 | if (EntryPtr.get() == TE) | |||
7641 | break; | |||
7642 | if (EntryPtr->State != TreeEntry::NeedToGather) | |||
7643 | continue; | |||
7644 | for (Value *V : EntryPtr->Scalars) | |||
7645 | ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); | |||
7646 | } | |||
7647 | // Find all tree entries used by the gathered values. If no common entries | |||
7648 | // found - not a shuffle. | |||
7649 | // Here we build a set of tree nodes for each gathered value and trying to | |||
7650 | // find the intersection between these sets. If we have at least one common | |||
7651 | // tree node for each gathered value - we have just a permutation of the | |||
7652 | // single vector. If we have 2 different sets, we're in situation where we | |||
7653 | // have a permutation of 2 input vectors. | |||
7654 | SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; | |||
7655 | DenseMap<Value *, int> UsedValuesEntry; | |||
7656 | for (Value *V : TE->Scalars) { | |||
7657 | if (isa<UndefValue>(V)) | |||
7658 | continue; | |||
7659 | // Build a list of tree entries where V is used. | |||
7660 | SmallPtrSet<const TreeEntry *, 4> VToTEs; | |||
7661 | auto It = ValueToTEs.find(V); | |||
7662 | if (It != ValueToTEs.end()) | |||
7663 | VToTEs = It->second; | |||
7664 | if (const TreeEntry *VTE = getTreeEntry(V)) | |||
7665 | VToTEs.insert(VTE); | |||
7666 | if (VToTEs.empty()) | |||
7667 | return None; | |||
7668 | if (UsedTEs.empty()) { | |||
7669 | // The first iteration, just insert the list of nodes to vector. | |||
7670 | UsedTEs.push_back(VToTEs); | |||
7671 | } else { | |||
7672 | // Need to check if there are any previously used tree nodes which use V. | |||
7673 | // If there are no such nodes, consider that we have another one input | |||
7674 | // vector. | |||
7675 | SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); | |||
7676 | unsigned Idx = 0; | |||
7677 | for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { | |||
7678 | // Do we have a non-empty intersection of previously listed tree entries | |||
7679 | // and tree entries using current V? | |||
7680 | set_intersect(VToTEs, Set); | |||
7681 | if (!VToTEs.empty()) { | |||
7682 | // Yes, write the new subset and continue analysis for the next | |||
7683 | // scalar. | |||
7684 | Set.swap(VToTEs); | |||
7685 | break; | |||
7686 | } | |||
7687 | VToTEs = SavedVToTEs; | |||
7688 | ++Idx; | |||
7689 | } | |||
7690 | // No non-empty intersection found - need to add a second set of possible | |||
7691 | // source vectors. | |||
7692 | if (Idx == UsedTEs.size()) { | |||
7693 | // If the number of input vectors is greater than 2 - not a permutation, | |||
7694 | // fallback to the regular gather. | |||
7695 | if (UsedTEs.size() == 2) | |||
7696 | return None; | |||
7697 | UsedTEs.push_back(SavedVToTEs); | |||
7698 | Idx = UsedTEs.size() - 1; | |||
7699 | } | |||
7700 | UsedValuesEntry.try_emplace(V, Idx); | |||
7701 | } | |||
7702 | } | |||
7703 | ||||
7704 | if (UsedTEs.empty()) { | |||
7705 | assert(all_of(TE->Scalars, UndefValue::classof) &&(static_cast <bool> (all_of(TE->Scalars, UndefValue:: classof) && "Expected vector of undefs only.") ? void (0) : __assert_fail ("all_of(TE->Scalars, UndefValue::classof) && \"Expected vector of undefs only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7706, __extension__ __PRETTY_FUNCTION__)) | |||
7706 | "Expected vector of undefs only.")(static_cast <bool> (all_of(TE->Scalars, UndefValue:: classof) && "Expected vector of undefs only.") ? void (0) : __assert_fail ("all_of(TE->Scalars, UndefValue::classof) && \"Expected vector of undefs only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7706, __extension__ __PRETTY_FUNCTION__)); | |||
7707 | return None; | |||
7708 | } | |||
7709 | ||||
7710 | unsigned VF = 0; | |||
7711 | if (UsedTEs.size() == 1) { | |||
7712 | // Try to find the perfect match in another gather node at first. | |||
7713 | auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { | |||
7714 | return EntryPtr->isSame(TE->Scalars); | |||
7715 | }); | |||
7716 | if (It != UsedTEs.front().end()) { | |||
7717 | Entries.push_back(*It); | |||
7718 | std::iota(Mask.begin(), Mask.end(), 0); | |||
7719 | return TargetTransformInfo::SK_PermuteSingleSrc; | |||
7720 | } | |||
7721 | // No perfect match, just shuffle, so choose the first tree node. | |||
7722 | Entries.push_back(*UsedTEs.front().begin()); | |||
7723 | } else { | |||
7724 | // Try to find nodes with the same vector factor. | |||
7725 | assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.")(static_cast <bool> (UsedTEs.size() == 2 && "Expected at max 2 permuted entries." ) ? void (0) : __assert_fail ("UsedTEs.size() == 2 && \"Expected at max 2 permuted entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7725, __extension__ __PRETTY_FUNCTION__)); | |||
7726 | DenseMap<int, const TreeEntry *> VFToTE; | |||
7727 | for (const TreeEntry *TE : UsedTEs.front()) | |||
7728 | VFToTE.try_emplace(TE->getVectorFactor(), TE); | |||
7729 | for (const TreeEntry *TE : UsedTEs.back()) { | |||
7730 | auto It = VFToTE.find(TE->getVectorFactor()); | |||
7731 | if (It != VFToTE.end()) { | |||
7732 | VF = It->first; | |||
7733 | Entries.push_back(It->second); | |||
7734 | Entries.push_back(TE); | |||
7735 | break; | |||
7736 | } | |||
7737 | } | |||
7738 | // No 2 source vectors with the same vector factor - give up and do regular | |||
7739 | // gather. | |||
7740 | if (Entries.empty()) | |||
7741 | return None; | |||
7742 | } | |||
7743 | ||||
7744 | // Build a shuffle mask for better cost estimation and vector emission. | |||
7745 | for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { | |||
7746 | Value *V = TE->Scalars[I]; | |||
7747 | if (isa<UndefValue>(V)) | |||
7748 | continue; | |||
7749 | unsigned Idx = UsedValuesEntry.lookup(V); | |||
7750 | const TreeEntry *VTE = Entries[Idx]; | |||
7751 | int FoundLane = VTE->findLaneForValue(V); | |||
7752 | Mask[I] = Idx * VF + FoundLane; | |||
7753 | // Extra check required by isSingleSourceMaskImpl function (called by | |||
7754 | // ShuffleVectorInst::isSingleSourceMask). | |||
7755 | if (Mask[I] >= 2 * E) | |||
7756 | return None; | |||
7757 | } | |||
7758 | switch (Entries.size()) { | |||
7759 | case 1: | |||
7760 | return TargetTransformInfo::SK_PermuteSingleSrc; | |||
7761 | case 2: | |||
7762 | return TargetTransformInfo::SK_PermuteTwoSrc; | |||
7763 | default: | |||
7764 | break; | |||
7765 | } | |||
7766 | return None; | |||
7767 | } | |||
7768 | ||||
7769 | InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty, | |||
7770 | const APInt &ShuffledIndices, | |||
7771 | bool NeedToShuffle) const { | |||
7772 | InstructionCost Cost = | |||
7773 | TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true, | |||
7774 | /*Extract*/ false); | |||
7775 | if (NeedToShuffle) | |||
7776 | Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); | |||
7777 | return Cost; | |||
7778 | } | |||
7779 | ||||
7780 | InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { | |||
7781 | // Find the type of the operands in VL. | |||
7782 | Type *ScalarTy = VL[0]->getType(); | |||
7783 | if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) | |||
7784 | ScalarTy = SI->getValueOperand()->getType(); | |||
7785 | auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); | |||
7786 | bool DuplicateNonConst = false; | |||
7787 | // Find the cost of inserting/extracting values from the vector. | |||
7788 | // Check if the same elements are inserted several times and count them as | |||
7789 | // shuffle candidates. | |||
7790 | APInt ShuffledElements = APInt::getZero(VL.size()); | |||
7791 | DenseSet<Value *> UniqueElements; | |||
7792 | // Iterate in reverse order to consider insert elements with the high cost. | |||
7793 | for (unsigned I = VL.size(); I > 0; --I) { | |||
7794 | unsigned Idx = I - 1; | |||
7795 | // No need to shuffle duplicates for constants. | |||
7796 | if (isConstant(VL[Idx])) { | |||
7797 | ShuffledElements.setBit(Idx); | |||
7798 | continue; | |||
7799 | } | |||
7800 | if (!UniqueElements.insert(VL[Idx]).second) { | |||
7801 | DuplicateNonConst = true; | |||
7802 | ShuffledElements.setBit(Idx); | |||
7803 | } | |||
7804 | } | |||
7805 | return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); | |||
7806 | } | |||
7807 | ||||
7808 | // Perform operand reordering on the instructions in VL and return the reordered | |||
7809 | // operands in Left and Right. | |||
7810 | void BoUpSLP::reorderInputsAccordingToOpcode( | |||
7811 | ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left, | |||
7812 | SmallVectorImpl<Value *> &Right, const TargetLibraryInfo &TLI, | |||
7813 | const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R) { | |||
7814 | if (VL.empty()) | |||
7815 | return; | |||
7816 | VLOperands Ops(VL, TLI, DL, SE, R); | |||
7817 | // Reorder the operands in place. | |||
7818 | Ops.reorder(); | |||
7819 | Left = Ops.getVL(0); | |||
7820 | Right = Ops.getVL(1); | |||
7821 | } | |||
7822 | ||||
7823 | Instruction &BoUpSLP::getLastInstructionInBundle(const TreeEntry *E) { | |||
7824 | // Get the basic block this bundle is in. All instructions in the bundle | |||
7825 | // should be in this block (except for extractelement-like instructions with | |||
7826 | // constant indeces). | |||
7827 | auto *Front = E->getMainOp(); | |||
7828 | auto *BB = Front->getParent(); | |||
7829 | assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)) | |||
7830 | if (E->getOpcode() == Instruction::GetElementPtr &&(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)) | |||
7831 | !isa<GetElementPtrInst>(V))(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)) | |||
7832 | return true;(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)) | |||
7833 | auto *I = cast<Instruction>(V);(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)) | |||
7834 | return !E->isOpcodeOrAlt(I) || I->getParent() == BB ||(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)) | |||
7835 | isVectorLikeInstWithConstOps(I);(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)) | |||
7836 | }))(static_cast <bool> (llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt (I) || I->getParent() == BB || isVectorLikeInstWithConstOps (I); })) ? void (0) : __assert_fail ("llvm::all_of(E->Scalars, [=](Value *V) -> bool { if (E->getOpcode() == Instruction::GetElementPtr && !isa<GetElementPtrInst>(V)) return true; auto *I = cast<Instruction>(V); return !E->isOpcodeOrAlt(I) || I->getParent() == BB || isVectorLikeInstWithConstOps(I); })" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7836, __extension__ __PRETTY_FUNCTION__)); | |||
7837 | ||||
7838 | auto &&FindLastInst = [E, Front, this, &BB]() { | |||
7839 | Instruction *LastInst = Front; | |||
7840 | for (Value *V : E->Scalars) { | |||
7841 | auto *I = dyn_cast<Instruction>(V); | |||
7842 | if (!I) | |||
7843 | continue; | |||
7844 | if (LastInst->getParent() == I->getParent()) { | |||
7845 | if (LastInst->comesBefore(I)) | |||
7846 | LastInst = I; | |||
7847 | continue; | |||
7848 | } | |||
7849 | assert(isVectorLikeInstWithConstOps(LastInst) &&(static_cast <bool> (isVectorLikeInstWithConstOps(LastInst ) && isVectorLikeInstWithConstOps(I) && "Expected vector-like insts only." ) ? void (0) : __assert_fail ("isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I) && \"Expected vector-like insts only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7851, __extension__ __PRETTY_FUNCTION__)) | |||
7850 | isVectorLikeInstWithConstOps(I) &&(static_cast <bool> (isVectorLikeInstWithConstOps(LastInst ) && isVectorLikeInstWithConstOps(I) && "Expected vector-like insts only." ) ? void (0) : __assert_fail ("isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I) && \"Expected vector-like insts only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7851, __extension__ __PRETTY_FUNCTION__)) | |||
7851 | "Expected vector-like insts only.")(static_cast <bool> (isVectorLikeInstWithConstOps(LastInst ) && isVectorLikeInstWithConstOps(I) && "Expected vector-like insts only." ) ? void (0) : __assert_fail ("isVectorLikeInstWithConstOps(LastInst) && isVectorLikeInstWithConstOps(I) && \"Expected vector-like insts only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7851, __extension__ __PRETTY_FUNCTION__)); | |||
7852 | if (!DT->isReachableFromEntry(LastInst->getParent())) { | |||
7853 | LastInst = I; | |||
7854 | continue; | |||
7855 | } | |||
7856 | if (!DT->isReachableFromEntry(I->getParent())) | |||
7857 | continue; | |||
7858 | auto *NodeA = DT->getNode(LastInst->getParent()); | |||
7859 | auto *NodeB = DT->getNode(I->getParent()); | |||
7860 | assert(NodeA && "Should only process reachable instructions")(static_cast <bool> (NodeA && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeA && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7860, __extension__ __PRETTY_FUNCTION__)); | |||
7861 | assert(NodeB && "Should only process reachable instructions")(static_cast <bool> (NodeB && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeB && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7861, __extension__ __PRETTY_FUNCTION__)); | |||
7862 | assert((NodeA == NodeB) ==(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7864, __extension__ __PRETTY_FUNCTION__)) | |||
7863 | (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7864, __extension__ __PRETTY_FUNCTION__)) | |||
7864 | "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7864, __extension__ __PRETTY_FUNCTION__)); | |||
7865 | if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn()) | |||
7866 | LastInst = I; | |||
7867 | } | |||
7868 | BB = LastInst->getParent(); | |||
7869 | return LastInst; | |||
7870 | }; | |||
7871 | ||||
7872 | auto &&FindFirstInst = [E, Front, this]() { | |||
7873 | Instruction *FirstInst = Front; | |||
7874 | for (Value *V : E->Scalars) { | |||
7875 | auto *I = dyn_cast<Instruction>(V); | |||
7876 | if (!I) | |||
7877 | continue; | |||
7878 | if (FirstInst->getParent() == I->getParent()) { | |||
7879 | if (I->comesBefore(FirstInst)) | |||
7880 | FirstInst = I; | |||
7881 | continue; | |||
7882 | } | |||
7883 | assert(isVectorLikeInstWithConstOps(FirstInst) &&(static_cast <bool> (isVectorLikeInstWithConstOps(FirstInst ) && isVectorLikeInstWithConstOps(I) && "Expected vector-like insts only." ) ? void (0) : __assert_fail ("isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I) && \"Expected vector-like insts only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7885, __extension__ __PRETTY_FUNCTION__)) | |||
7884 | isVectorLikeInstWithConstOps(I) &&(static_cast <bool> (isVectorLikeInstWithConstOps(FirstInst ) && isVectorLikeInstWithConstOps(I) && "Expected vector-like insts only." ) ? void (0) : __assert_fail ("isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I) && \"Expected vector-like insts only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7885, __extension__ __PRETTY_FUNCTION__)) | |||
7885 | "Expected vector-like insts only.")(static_cast <bool> (isVectorLikeInstWithConstOps(FirstInst ) && isVectorLikeInstWithConstOps(I) && "Expected vector-like insts only." ) ? void (0) : __assert_fail ("isVectorLikeInstWithConstOps(FirstInst) && isVectorLikeInstWithConstOps(I) && \"Expected vector-like insts only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7885, __extension__ __PRETTY_FUNCTION__)); | |||
7886 | if (!DT->isReachableFromEntry(FirstInst->getParent())) { | |||
7887 | FirstInst = I; | |||
7888 | continue; | |||
7889 | } | |||
7890 | if (!DT->isReachableFromEntry(I->getParent())) | |||
7891 | continue; | |||
7892 | auto *NodeA = DT->getNode(FirstInst->getParent()); | |||
7893 | auto *NodeB = DT->getNode(I->getParent()); | |||
7894 | assert(NodeA && "Should only process reachable instructions")(static_cast <bool> (NodeA && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeA && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7894, __extension__ __PRETTY_FUNCTION__)); | |||
7895 | assert(NodeB && "Should only process reachable instructions")(static_cast <bool> (NodeB && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeB && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7895, __extension__ __PRETTY_FUNCTION__)); | |||
7896 | assert((NodeA == NodeB) ==(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7898, __extension__ __PRETTY_FUNCTION__)) | |||
7897 | (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7898, __extension__ __PRETTY_FUNCTION__)) | |||
7898 | "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeA == NodeB) == (NodeA->getDFSNumIn () == NodeB->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7898, __extension__ __PRETTY_FUNCTION__)); | |||
7899 | if (NodeA->getDFSNumIn() > NodeB->getDFSNumIn()) | |||
7900 | FirstInst = I; | |||
7901 | } | |||
7902 | return FirstInst; | |||
7903 | }; | |||
7904 | ||||
7905 | // Set the insert point to the beginning of the basic block if the entry | |||
7906 | // should not be scheduled. | |||
7907 | if (E->State != TreeEntry::NeedToGather && | |||
7908 | (doesNotNeedToSchedule(E->Scalars) || | |||
7909 | all_of(E->Scalars, isVectorLikeInstWithConstOps))) { | |||
7910 | Instruction *InsertInst; | |||
7911 | if (all_of(E->Scalars, [](Value *V) { | |||
7912 | return !isVectorLikeInstWithConstOps(V) && isUsedOutsideBlock(V); | |||
7913 | })) | |||
7914 | InsertInst = FindLastInst(); | |||
7915 | else | |||
7916 | InsertInst = FindFirstInst(); | |||
7917 | return *InsertInst; | |||
7918 | } | |||
7919 | ||||
7920 | // The last instruction in the bundle in program order. | |||
7921 | Instruction *LastInst = nullptr; | |||
7922 | ||||
7923 | // Find the last instruction. The common case should be that BB has been | |||
7924 | // scheduled, and the last instruction is VL.back(). So we start with | |||
7925 | // VL.back() and iterate over schedule data until we reach the end of the | |||
7926 | // bundle. The end of the bundle is marked by null ScheduleData. | |||
7927 | if (BlocksSchedules.count(BB)) { | |||
7928 | Value *V = E->isOneOf(E->Scalars.back()); | |||
7929 | if (doesNotNeedToBeScheduled(V)) | |||
7930 | V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled); | |||
7931 | auto *Bundle = BlocksSchedules[BB]->getScheduleData(V); | |||
7932 | if (Bundle && Bundle->isPartOfBundle()) | |||
7933 | for (; Bundle; Bundle = Bundle->NextInBundle) | |||
7934 | if (Bundle->OpValue == Bundle->Inst) | |||
7935 | LastInst = Bundle->Inst; | |||
7936 | } | |||
7937 | ||||
7938 | // LastInst can still be null at this point if there's either not an entry | |||
7939 | // for BB in BlocksSchedules or there's no ScheduleData available for | |||
7940 | // VL.back(). This can be the case if buildTree_rec aborts for various | |||
7941 | // reasons (e.g., the maximum recursion depth is reached, the maximum region | |||
7942 | // size is reached, etc.). ScheduleData is initialized in the scheduling | |||
7943 | // "dry-run". | |||
7944 | // | |||
7945 | // If this happens, we can still find the last instruction by brute force. We | |||
7946 | // iterate forwards from Front (inclusive) until we either see all | |||
7947 | // instructions in the bundle or reach the end of the block. If Front is the | |||
7948 | // last instruction in program order, LastInst will be set to Front, and we | |||
7949 | // will visit all the remaining instructions in the block. | |||
7950 | // | |||
7951 | // One of the reasons we exit early from buildTree_rec is to place an upper | |||
7952 | // bound on compile-time. Thus, taking an additional compile-time hit here is | |||
7953 | // not ideal. However, this should be exceedingly rare since it requires that | |||
7954 | // we both exit early from buildTree_rec and that the bundle be out-of-order | |||
7955 | // (causing us to iterate all the way to the end of the block). | |||
7956 | if (!LastInst) | |||
7957 | LastInst = FindLastInst(); | |||
7958 | assert(LastInst && "Failed to find last instruction in bundle")(static_cast <bool> (LastInst && "Failed to find last instruction in bundle" ) ? void (0) : __assert_fail ("LastInst && \"Failed to find last instruction in bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7958, __extension__ __PRETTY_FUNCTION__)); | |||
7959 | return *LastInst; | |||
7960 | } | |||
7961 | ||||
7962 | void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { | |||
7963 | auto *Front = E->getMainOp(); | |||
7964 | Instruction *LastInst = &getLastInstructionInBundle(E); | |||
7965 | assert(LastInst && "Failed to find last instruction in bundle")(static_cast <bool> (LastInst && "Failed to find last instruction in bundle" ) ? void (0) : __assert_fail ("LastInst && \"Failed to find last instruction in bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 7965, __extension__ __PRETTY_FUNCTION__)); | |||
7966 | // If the instruction is PHI, set the insert point after all the PHIs. | |||
7967 | bool IsPHI = isa<PHINode>(LastInst); | |||
7968 | if (IsPHI) | |||
7969 | LastInst = LastInst->getParent()->getFirstNonPHI(); | |||
7970 | if (IsPHI || (E->State != TreeEntry::NeedToGather && | |||
7971 | doesNotNeedToSchedule(E->Scalars))) { | |||
7972 | Builder.SetInsertPoint(LastInst); | |||
7973 | } else { | |||
7974 | // Set the insertion point after the last instruction in the bundle. Set the | |||
7975 | // debug location to Front. | |||
7976 | Builder.SetInsertPoint(LastInst->getParent(), | |||
7977 | std::next(LastInst->getIterator())); | |||
7978 | } | |||
7979 | Builder.SetCurrentDebugLocation(Front->getDebugLoc()); | |||
7980 | } | |||
7981 | ||||
7982 | Value *BoUpSLP::gather(ArrayRef<Value *> VL) { | |||
7983 | // List of instructions/lanes from current block and/or the blocks which are | |||
7984 | // part of the current loop. These instructions will be inserted at the end to | |||
7985 | // make it possible to optimize loops and hoist invariant instructions out of | |||
7986 | // the loops body with better chances for success. | |||
7987 | SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; | |||
7988 | SmallSet<int, 4> PostponedIndices; | |||
7989 | Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); | |||
7990 | auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { | |||
7991 | SmallPtrSet<BasicBlock *, 4> Visited; | |||
7992 | while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) | |||
7993 | InsertBB = InsertBB->getSinglePredecessor(); | |||
7994 | return InsertBB && InsertBB == InstBB; | |||
7995 | }; | |||
7996 | for (int I = 0, E = VL.size(); I < E; ++I) { | |||
7997 | if (auto *Inst = dyn_cast<Instruction>(VL[I])) | |||
7998 | if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || | |||
7999 | getTreeEntry(Inst) || (L && (L->contains(Inst)))) && | |||
8000 | PostponedIndices.insert(I).second) | |||
8001 | PostponedInsts.emplace_back(Inst, I); | |||
8002 | } | |||
8003 | ||||
8004 | auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { | |||
8005 | Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); | |||
8006 | auto *InsElt = dyn_cast<InsertElementInst>(Vec); | |||
8007 | if (!InsElt) | |||
8008 | return Vec; | |||
8009 | GatherShuffleExtractSeq.insert(InsElt); | |||
8010 | CSEBlocks.insert(InsElt->getParent()); | |||
8011 | // Add to our 'need-to-extract' list. | |||
8012 | if (TreeEntry *Entry = getTreeEntry(V)) { | |||
8013 | // Find which lane we need to extract. | |||
8014 | unsigned FoundLane = Entry->findLaneForValue(V); | |||
8015 | ExternalUses.emplace_back(V, InsElt, FoundLane); | |||
8016 | } | |||
8017 | return Vec; | |||
8018 | }; | |||
8019 | Value *Val0 = | |||
8020 | isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; | |||
8021 | FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); | |||
8022 | Value *Vec = PoisonValue::get(VecTy); | |||
8023 | SmallVector<int> NonConsts; | |||
8024 | // Insert constant values at first. | |||
8025 | for (int I = 0, E = VL.size(); I < E; ++I) { | |||
8026 | if (PostponedIndices.contains(I)) | |||
8027 | continue; | |||
8028 | if (!isConstant(VL[I])) { | |||
8029 | NonConsts.push_back(I); | |||
8030 | continue; | |||
8031 | } | |||
8032 | Vec = CreateInsertElement(Vec, VL[I], I); | |||
8033 | } | |||
8034 | // Insert non-constant values. | |||
8035 | for (int I : NonConsts) | |||
8036 | Vec = CreateInsertElement(Vec, VL[I], I); | |||
8037 | // Append instructions, which are/may be part of the loop, in the end to make | |||
8038 | // it possible to hoist non-loop-based instructions. | |||
8039 | for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) | |||
8040 | Vec = CreateInsertElement(Vec, Pair.first, Pair.second); | |||
8041 | ||||
8042 | return Vec; | |||
8043 | } | |||
8044 | ||||
8045 | namespace { | |||
8046 | /// Merges shuffle masks and emits final shuffle instruction, if required. | |||
8047 | class ShuffleInstructionBuilder { | |||
8048 | IRBuilderBase &Builder; | |||
8049 | const unsigned VF = 0; | |||
8050 | bool IsFinalized = false; | |||
8051 | SmallVector<int, 4> Mask; | |||
8052 | /// Holds all of the instructions that we gathered. | |||
8053 | SetVector<Instruction *> &GatherShuffleSeq; | |||
8054 | /// A list of blocks that we are going to CSE. | |||
8055 | SetVector<BasicBlock *> &CSEBlocks; | |||
8056 | ||||
8057 | public: | |||
8058 | ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, | |||
8059 | SetVector<Instruction *> &GatherShuffleSeq, | |||
8060 | SetVector<BasicBlock *> &CSEBlocks) | |||
8061 | : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), | |||
8062 | CSEBlocks(CSEBlocks) {} | |||
8063 | ||||
8064 | /// Adds a mask, inverting it before applying. | |||
8065 | void addInversedMask(ArrayRef<unsigned> SubMask) { | |||
8066 | if (SubMask.empty()) | |||
8067 | return; | |||
8068 | SmallVector<int, 4> NewMask; | |||
8069 | inversePermutation(SubMask, NewMask); | |||
8070 | addMask(NewMask); | |||
8071 | } | |||
8072 | ||||
8073 | /// Functions adds masks, merging them into single one. | |||
8074 | void addMask(ArrayRef<unsigned> SubMask) { | |||
8075 | SmallVector<int, 4> NewMask(SubMask); | |||
8076 | addMask(NewMask); | |||
8077 | } | |||
8078 | ||||
8079 | void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } | |||
8080 | ||||
8081 | Value *finalize(Value *V) { | |||
8082 | IsFinalized = true; | |||
8083 | unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); | |||
8084 | if (VF == ValueVF && Mask.empty()) | |||
8085 | return V; | |||
8086 | SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); | |||
8087 | std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); | |||
8088 | addMask(NormalizedMask); | |||
8089 | ||||
8090 | if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) | |||
8091 | return V; | |||
8092 | Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); | |||
8093 | if (auto *I = dyn_cast<Instruction>(Vec)) { | |||
8094 | GatherShuffleSeq.insert(I); | |||
8095 | CSEBlocks.insert(I->getParent()); | |||
8096 | } | |||
8097 | return Vec; | |||
8098 | } | |||
8099 | ||||
8100 | ~ShuffleInstructionBuilder() { | |||
8101 | assert((IsFinalized || Mask.empty()) &&(static_cast <bool> ((IsFinalized || Mask.empty()) && "Shuffle construction must be finalized.") ? void (0) : __assert_fail ("(IsFinalized || Mask.empty()) && \"Shuffle construction must be finalized.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8102, __extension__ __PRETTY_FUNCTION__)) | |||
8102 | "Shuffle construction must be finalized.")(static_cast <bool> ((IsFinalized || Mask.empty()) && "Shuffle construction must be finalized.") ? void (0) : __assert_fail ("(IsFinalized || Mask.empty()) && \"Shuffle construction must be finalized.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8102, __extension__ __PRETTY_FUNCTION__)); | |||
8103 | } | |||
8104 | }; | |||
8105 | } // namespace | |||
8106 | ||||
8107 | Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { | |||
8108 | const unsigned VF = VL.size(); | |||
8109 | InstructionsState S = getSameOpcode(VL, *TLI); | |||
8110 | // Special processing for GEPs bundle, which may include non-gep values. | |||
8111 | if (!S.getOpcode() && VL.front()->getType()->isPointerTy()) { | |||
8112 | const auto *It = | |||
8113 | find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }); | |||
8114 | if (It != VL.end()) | |||
8115 | S = getSameOpcode(*It, *TLI); | |||
8116 | } | |||
8117 | if (S.getOpcode()) { | |||
8118 | if (TreeEntry *E = getTreeEntry(S.OpValue)) | |||
8119 | if (E->isSame(VL)) { | |||
8120 | Value *V = vectorizeTree(E); | |||
8121 | if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { | |||
8122 | if (!E->ReuseShuffleIndices.empty()) { | |||
8123 | // Reshuffle to get only unique values. | |||
8124 | // If some of the scalars are duplicated in the vectorization tree | |||
8125 | // entry, we do not vectorize them but instead generate a mask for | |||
8126 | // the reuses. But if there are several users of the same entry, | |||
8127 | // they may have different vectorization factors. This is especially | |||
8128 | // important for PHI nodes. In this case, we need to adapt the | |||
8129 | // resulting instruction for the user vectorization factor and have | |||
8130 | // to reshuffle it again to take only unique elements of the vector. | |||
8131 | // Without this code the function incorrectly returns reduced vector | |||
8132 | // instruction with the same elements, not with the unique ones. | |||
8133 | ||||
8134 | // block: | |||
8135 | // %phi = phi <2 x > { .., %entry} {%shuffle, %block} | |||
8136 | // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> | |||
8137 | // ... (use %2) | |||
8138 | // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} | |||
8139 | // br %block | |||
8140 | SmallVector<int> UniqueIdxs(VF, UndefMaskElem); | |||
8141 | SmallSet<int, 4> UsedIdxs; | |||
8142 | int Pos = 0; | |||
8143 | int Sz = VL.size(); | |||
8144 | for (int Idx : E->ReuseShuffleIndices) { | |||
8145 | if (Idx != Sz && Idx != UndefMaskElem && | |||
8146 | UsedIdxs.insert(Idx).second) | |||
8147 | UniqueIdxs[Idx] = Pos; | |||
8148 | ++Pos; | |||
8149 | } | |||
8150 | assert(VF >= UsedIdxs.size() && "Expected vectorization factor "(static_cast <bool> (VF >= UsedIdxs.size() && "Expected vectorization factor " "less than original vector size." ) ? void (0) : __assert_fail ("VF >= UsedIdxs.size() && \"Expected vectorization factor \" \"less than original vector size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8151, __extension__ __PRETTY_FUNCTION__)) | |||
8151 | "less than original vector size.")(static_cast <bool> (VF >= UsedIdxs.size() && "Expected vectorization factor " "less than original vector size." ) ? void (0) : __assert_fail ("VF >= UsedIdxs.size() && \"Expected vectorization factor \" \"less than original vector size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8151, __extension__ __PRETTY_FUNCTION__)); | |||
8152 | UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); | |||
8153 | V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); | |||
8154 | } else { | |||
8155 | assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&(static_cast <bool> (VF < cast<FixedVectorType> (V->getType())->getNumElements() && "Expected vectorization factor less " "than original vector size.") ? void (0) : __assert_fail ("VF < cast<FixedVectorType>(V->getType())->getNumElements() && \"Expected vectorization factor less \" \"than original vector size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8157, __extension__ __PRETTY_FUNCTION__)) | |||
8156 | "Expected vectorization factor less "(static_cast <bool> (VF < cast<FixedVectorType> (V->getType())->getNumElements() && "Expected vectorization factor less " "than original vector size.") ? void (0) : __assert_fail ("VF < cast<FixedVectorType>(V->getType())->getNumElements() && \"Expected vectorization factor less \" \"than original vector size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8157, __extension__ __PRETTY_FUNCTION__)) | |||
8157 | "than original vector size.")(static_cast <bool> (VF < cast<FixedVectorType> (V->getType())->getNumElements() && "Expected vectorization factor less " "than original vector size.") ? void (0) : __assert_fail ("VF < cast<FixedVectorType>(V->getType())->getNumElements() && \"Expected vectorization factor less \" \"than original vector size.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8157, __extension__ __PRETTY_FUNCTION__)); | |||
8158 | SmallVector<int> UniformMask(VF, 0); | |||
8159 | std::iota(UniformMask.begin(), UniformMask.end(), 0); | |||
8160 | V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); | |||
8161 | } | |||
8162 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
8163 | GatherShuffleExtractSeq.insert(I); | |||
8164 | CSEBlocks.insert(I->getParent()); | |||
8165 | } | |||
8166 | } | |||
8167 | return V; | |||
8168 | } | |||
8169 | } | |||
8170 | ||||
8171 | // Can't vectorize this, so simply build a new vector with each lane | |||
8172 | // corresponding to the requested value. | |||
8173 | return createBuildVector(VL); | |||
8174 | } | |||
8175 | Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) { | |||
8176 | assert(any_of(VectorizableTree,(static_cast <bool> (any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && "Non-matching gather node.") ? void (0) : __assert_fail ("any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && \"Non-matching gather node.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8180, __extension__ __PRETTY_FUNCTION__)) | |||
8177 | [VL](const std::unique_ptr<TreeEntry> &TE) {(static_cast <bool> (any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && "Non-matching gather node.") ? void (0) : __assert_fail ("any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && \"Non-matching gather node.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8180, __extension__ __PRETTY_FUNCTION__)) | |||
8178 | return TE->State == TreeEntry::NeedToGather && TE->isSame(VL);(static_cast <bool> (any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && "Non-matching gather node.") ? void (0) : __assert_fail ("any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && \"Non-matching gather node.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8180, __extension__ __PRETTY_FUNCTION__)) | |||
8179 | }) &&(static_cast <bool> (any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && "Non-matching gather node.") ? void (0) : __assert_fail ("any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && \"Non-matching gather node.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8180, __extension__ __PRETTY_FUNCTION__)) | |||
8180 | "Non-matching gather node.")(static_cast <bool> (any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && "Non-matching gather node.") ? void (0) : __assert_fail ("any_of(VectorizableTree, [VL](const std::unique_ptr<TreeEntry> &TE) { return TE->State == TreeEntry::NeedToGather && TE->isSame(VL); }) && \"Non-matching gather node.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8180, __extension__ __PRETTY_FUNCTION__)); | |||
8181 | unsigned VF = VL.size(); | |||
8182 | // Exploit possible reuse of values across lanes. | |||
8183 | SmallVector<int> ReuseShuffleIndicies; | |||
8184 | SmallVector<Value *> UniqueValues; | |||
8185 | if (VL.size() > 2) { | |||
8186 | DenseMap<Value *, unsigned> UniquePositions; | |||
8187 | unsigned NumValues = | |||
8188 | std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { | |||
8189 | return !isa<UndefValue>(V); | |||
8190 | }).base()); | |||
8191 | VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); | |||
8192 | int UniqueVals = 0; | |||
8193 | for (Value *V : VL.drop_back(VL.size() - VF)) { | |||
8194 | if (isa<UndefValue>(V)) { | |||
8195 | ReuseShuffleIndicies.emplace_back(UndefMaskElem); | |||
8196 | continue; | |||
8197 | } | |||
8198 | if (isConstant(V)) { | |||
8199 | ReuseShuffleIndicies.emplace_back(UniqueValues.size()); | |||
8200 | UniqueValues.emplace_back(V); | |||
8201 | continue; | |||
8202 | } | |||
8203 | auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); | |||
8204 | ReuseShuffleIndicies.emplace_back(Res.first->second); | |||
8205 | if (Res.second) { | |||
8206 | UniqueValues.emplace_back(V); | |||
8207 | ++UniqueVals; | |||
8208 | } | |||
8209 | } | |||
8210 | if (UniqueVals == 1 && UniqueValues.size() == 1) { | |||
8211 | // Emit pure splat vector. | |||
8212 | ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), | |||
8213 | UndefMaskElem); | |||
8214 | } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { | |||
8215 | if (UniqueValues.empty()) { | |||
8216 | assert(all_of(VL, UndefValue::classof) && "Expected list of undefs.")(static_cast <bool> (all_of(VL, UndefValue::classof) && "Expected list of undefs.") ? void (0) : __assert_fail ("all_of(VL, UndefValue::classof) && \"Expected list of undefs.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8216, __extension__ __PRETTY_FUNCTION__)); | |||
8217 | NumValues = VF; | |||
8218 | } | |||
8219 | ReuseShuffleIndicies.clear(); | |||
8220 | UniqueValues.clear(); | |||
8221 | UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); | |||
8222 | } | |||
8223 | UniqueValues.append(VF - UniqueValues.size(), | |||
8224 | PoisonValue::get(VL[0]->getType())); | |||
8225 | VL = UniqueValues; | |||
8226 | } | |||
8227 | ||||
8228 | ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleExtractSeq, | |||
8229 | CSEBlocks); | |||
8230 | Value *Vec = gather(VL); | |||
8231 | if (!ReuseShuffleIndicies.empty()) { | |||
8232 | ShuffleBuilder.addMask(ReuseShuffleIndicies); | |||
8233 | Vec = ShuffleBuilder.finalize(Vec); | |||
8234 | } | |||
8235 | return Vec; | |||
8236 | } | |||
8237 | ||||
8238 | Value *BoUpSLP::vectorizeTree(TreeEntry *E) { | |||
8239 | IRBuilder<>::InsertPointGuard Guard(Builder); | |||
8240 | ||||
8241 | if (E->VectorizedValue) { | |||
8242 | LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"; } } while (false); | |||
8243 | return E->VectorizedValue; | |||
8244 | } | |||
8245 | ||||
8246 | bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); | |||
8247 | unsigned VF = E->getVectorFactor(); | |||
8248 | ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleExtractSeq, | |||
8249 | CSEBlocks); | |||
8250 | if (E->State == TreeEntry::NeedToGather) { | |||
8251 | if (E->getMainOp()) | |||
8252 | setInsertPointAfterBundle(E); | |||
8253 | Value *Vec; | |||
8254 | SmallVector<int> Mask; | |||
8255 | SmallVector<const TreeEntry *> Entries; | |||
8256 | Optional<TargetTransformInfo::ShuffleKind> Shuffle = | |||
8257 | isGatherShuffledEntry(E, Mask, Entries); | |||
8258 | if (Shuffle) { | |||
8259 | assert((Entries.size() == 1 || Entries.size() == 2) &&(static_cast <bool> ((Entries.size() == 1 || Entries.size () == 2) && "Expected shuffle of 1 or 2 entries.") ? void (0) : __assert_fail ("(Entries.size() == 1 || Entries.size() == 2) && \"Expected shuffle of 1 or 2 entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8260, __extension__ __PRETTY_FUNCTION__)) | |||
8260 | "Expected shuffle of 1 or 2 entries.")(static_cast <bool> ((Entries.size() == 1 || Entries.size () == 2) && "Expected shuffle of 1 or 2 entries.") ? void (0) : __assert_fail ("(Entries.size() == 1 || Entries.size() == 2) && \"Expected shuffle of 1 or 2 entries.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8260, __extension__ __PRETTY_FUNCTION__)); | |||
8261 | Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, | |||
8262 | Entries.back()->VectorizedValue, Mask); | |||
8263 | if (auto *I = dyn_cast<Instruction>(Vec)) { | |||
8264 | GatherShuffleExtractSeq.insert(I); | |||
8265 | CSEBlocks.insert(I->getParent()); | |||
8266 | } | |||
8267 | } else { | |||
8268 | Vec = gather(E->Scalars); | |||
8269 | } | |||
8270 | if (NeedToShuffleReuses) { | |||
8271 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8272 | Vec = ShuffleBuilder.finalize(Vec); | |||
8273 | } | |||
8274 | E->VectorizedValue = Vec; | |||
8275 | return Vec; | |||
8276 | } | |||
8277 | ||||
8278 | assert((E->State == TreeEntry::Vectorize ||(static_cast <bool> ((E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && "Unhandled state" ) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8280, __extension__ __PRETTY_FUNCTION__)) | |||
8279 | E->State == TreeEntry::ScatterVectorize) &&(static_cast <bool> ((E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && "Unhandled state" ) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8280, __extension__ __PRETTY_FUNCTION__)) | |||
8280 | "Unhandled state")(static_cast <bool> ((E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && "Unhandled state" ) ? void (0) : __assert_fail ("(E->State == TreeEntry::Vectorize || E->State == TreeEntry::ScatterVectorize) && \"Unhandled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8280, __extension__ __PRETTY_FUNCTION__)); | |||
8281 | unsigned ShuffleOrOp = | |||
8282 | E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); | |||
8283 | Instruction *VL0 = E->getMainOp(); | |||
8284 | Type *ScalarTy = VL0->getType(); | |||
8285 | if (auto *Store = dyn_cast<StoreInst>(VL0)) | |||
8286 | ScalarTy = Store->getValueOperand()->getType(); | |||
8287 | else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) | |||
8288 | ScalarTy = IE->getOperand(1)->getType(); | |||
8289 | auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); | |||
8290 | switch (ShuffleOrOp) { | |||
8291 | case Instruction::PHI: { | |||
8292 | assert((E->ReorderIndices.empty() ||(static_cast <bool> ((E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices. empty()) && "PHI reordering is free.") ? void (0) : __assert_fail ("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8295, __extension__ __PRETTY_FUNCTION__)) | |||
8293 | E != VectorizableTree.front().get() ||(static_cast <bool> ((E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices. empty()) && "PHI reordering is free.") ? void (0) : __assert_fail ("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8295, __extension__ __PRETTY_FUNCTION__)) | |||
8294 | !E->UserTreeIndices.empty()) &&(static_cast <bool> ((E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices. empty()) && "PHI reordering is free.") ? void (0) : __assert_fail ("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8295, __extension__ __PRETTY_FUNCTION__)) | |||
8295 | "PHI reordering is free.")(static_cast <bool> ((E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices. empty()) && "PHI reordering is free.") ? void (0) : __assert_fail ("(E->ReorderIndices.empty() || E != VectorizableTree.front().get() || !E->UserTreeIndices.empty()) && \"PHI reordering is free.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8295, __extension__ __PRETTY_FUNCTION__)); | |||
8296 | auto *PH = cast<PHINode>(VL0); | |||
8297 | Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); | |||
8298 | Builder.SetCurrentDebugLocation(PH->getDebugLoc()); | |||
8299 | PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); | |||
8300 | Value *V = NewPhi; | |||
8301 | ||||
8302 | // Adjust insertion point once all PHI's have been generated. | |||
8303 | Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt()); | |||
8304 | Builder.SetCurrentDebugLocation(PH->getDebugLoc()); | |||
8305 | ||||
8306 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8307 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8308 | V = ShuffleBuilder.finalize(V); | |||
8309 | ||||
8310 | E->VectorizedValue = V; | |||
8311 | ||||
8312 | // PHINodes may have multiple entries from the same block. We want to | |||
8313 | // visit every block once. | |||
8314 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; | |||
8315 | ||||
8316 | for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { | |||
8317 | ValueList Operands; | |||
8318 | BasicBlock *IBB = PH->getIncomingBlock(i); | |||
8319 | ||||
8320 | if (!VisitedBBs.insert(IBB).second) { | |||
8321 | NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); | |||
8322 | continue; | |||
8323 | } | |||
8324 | ||||
8325 | Builder.SetInsertPoint(IBB->getTerminator()); | |||
8326 | Builder.SetCurrentDebugLocation(PH->getDebugLoc()); | |||
8327 | Value *Vec = vectorizeTree(E->getOperand(i)); | |||
8328 | NewPhi->addIncoming(Vec, IBB); | |||
8329 | } | |||
8330 | ||||
8331 | assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&(static_cast <bool> (NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && "Invalid number of incoming values" ) ? void (0) : __assert_fail ("NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && \"Invalid number of incoming values\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8332, __extension__ __PRETTY_FUNCTION__)) | |||
8332 | "Invalid number of incoming values")(static_cast <bool> (NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && "Invalid number of incoming values" ) ? void (0) : __assert_fail ("NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && \"Invalid number of incoming values\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8332, __extension__ __PRETTY_FUNCTION__)); | |||
8333 | return V; | |||
8334 | } | |||
8335 | ||||
8336 | case Instruction::ExtractElement: { | |||
8337 | Value *V = E->getSingleOperand(0); | |||
8338 | setInsertPointAfterBundle(E); | |||
8339 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8340 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8341 | V = ShuffleBuilder.finalize(V); | |||
8342 | E->VectorizedValue = V; | |||
8343 | return V; | |||
8344 | } | |||
8345 | case Instruction::ExtractValue: { | |||
8346 | auto *LI = cast<LoadInst>(E->getSingleOperand(0)); | |||
8347 | Builder.SetInsertPoint(LI); | |||
8348 | auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); | |||
8349 | Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); | |||
8350 | LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); | |||
8351 | Value *NewV = propagateMetadata(V, E->Scalars); | |||
8352 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8353 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8354 | NewV = ShuffleBuilder.finalize(NewV); | |||
8355 | E->VectorizedValue = NewV; | |||
8356 | return NewV; | |||
8357 | } | |||
8358 | case Instruction::InsertElement: { | |||
8359 | assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique")(static_cast <bool> (E->ReuseShuffleIndices.empty() && "All inserts should be unique") ? void (0) : __assert_fail ( "E->ReuseShuffleIndices.empty() && \"All inserts should be unique\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8359, __extension__ __PRETTY_FUNCTION__)); | |||
8360 | Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); | |||
8361 | Value *V = vectorizeTree(E->getOperand(1)); | |||
8362 | ||||
8363 | // Create InsertVector shuffle if necessary | |||
8364 | auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { | |||
8365 | return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); | |||
8366 | })); | |||
8367 | const unsigned NumElts = | |||
8368 | cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); | |||
8369 | const unsigned NumScalars = E->Scalars.size(); | |||
8370 | ||||
8371 | unsigned Offset = *getInsertIndex(VL0); | |||
8372 | assert(Offset < NumElts && "Failed to find vector index offset")(static_cast <bool> (Offset < NumElts && "Failed to find vector index offset" ) ? void (0) : __assert_fail ("Offset < NumElts && \"Failed to find vector index offset\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8372, __extension__ __PRETTY_FUNCTION__)); | |||
8373 | ||||
8374 | // Create shuffle to resize vector | |||
8375 | SmallVector<int> Mask; | |||
8376 | if (!E->ReorderIndices.empty()) { | |||
8377 | inversePermutation(E->ReorderIndices, Mask); | |||
8378 | Mask.append(NumElts - NumScalars, UndefMaskElem); | |||
8379 | } else { | |||
8380 | Mask.assign(NumElts, UndefMaskElem); | |||
8381 | std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); | |||
8382 | } | |||
8383 | // Create InsertVector shuffle if necessary | |||
8384 | bool IsIdentity = true; | |||
8385 | SmallVector<int> PrevMask(NumElts, UndefMaskElem); | |||
8386 | Mask.swap(PrevMask); | |||
8387 | for (unsigned I = 0; I < NumScalars; ++I) { | |||
8388 | Value *Scalar = E->Scalars[PrevMask[I]]; | |||
8389 | unsigned InsertIdx = *getInsertIndex(Scalar); | |||
8390 | IsIdentity &= InsertIdx - Offset == I; | |||
8391 | Mask[InsertIdx - Offset] = I; | |||
8392 | } | |||
8393 | if (!IsIdentity || NumElts != NumScalars) { | |||
8394 | V = Builder.CreateShuffleVector(V, Mask); | |||
8395 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
8396 | GatherShuffleExtractSeq.insert(I); | |||
8397 | CSEBlocks.insert(I->getParent()); | |||
8398 | } | |||
8399 | } | |||
8400 | ||||
8401 | SmallVector<int> InsertMask(NumElts, UndefMaskElem); | |||
8402 | for (unsigned I = 0; I < NumElts; I++) { | |||
8403 | if (Mask[I] != UndefMaskElem) | |||
8404 | InsertMask[Offset + I] = I; | |||
8405 | } | |||
8406 | SmallBitVector IsFirstUndef = | |||
8407 | isUndefVector(FirstInsert->getOperand(0), InsertMask); | |||
8408 | if ((!IsIdentity || Offset != 0 || !IsFirstUndef.all()) && | |||
8409 | NumElts != NumScalars) { | |||
8410 | if (IsFirstUndef.all()) { | |||
8411 | if (!ShuffleVectorInst::isIdentityMask(InsertMask)) { | |||
8412 | SmallBitVector IsFirstPoison = | |||
8413 | isUndefVector<true>(FirstInsert->getOperand(0), InsertMask); | |||
8414 | if (!IsFirstPoison.all()) { | |||
8415 | for (unsigned I = 0; I < NumElts; I++) { | |||
8416 | if (InsertMask[I] == UndefMaskElem && !IsFirstPoison.test(I)) | |||
8417 | InsertMask[I] = I + NumElts; | |||
8418 | } | |||
8419 | } | |||
8420 | V = Builder.CreateShuffleVector( | |||
8421 | V, | |||
8422 | IsFirstPoison.all() ? PoisonValue::get(V->getType()) | |||
8423 | : FirstInsert->getOperand(0), | |||
8424 | InsertMask, cast<Instruction>(E->Scalars.back())->getName()); | |||
8425 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
8426 | GatherShuffleExtractSeq.insert(I); | |||
8427 | CSEBlocks.insert(I->getParent()); | |||
8428 | } | |||
8429 | } | |||
8430 | } else { | |||
8431 | SmallBitVector IsFirstPoison = | |||
8432 | isUndefVector<true>(FirstInsert->getOperand(0), InsertMask); | |||
8433 | for (unsigned I = 0; I < NumElts; I++) { | |||
8434 | if (InsertMask[I] == UndefMaskElem) | |||
8435 | InsertMask[I] = IsFirstPoison.test(I) ? UndefMaskElem : I; | |||
8436 | else | |||
8437 | InsertMask[I] += NumElts; | |||
8438 | } | |||
8439 | V = Builder.CreateShuffleVector( | |||
8440 | FirstInsert->getOperand(0), V, InsertMask, | |||
8441 | cast<Instruction>(E->Scalars.back())->getName()); | |||
8442 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
8443 | GatherShuffleExtractSeq.insert(I); | |||
8444 | CSEBlocks.insert(I->getParent()); | |||
8445 | } | |||
8446 | } | |||
8447 | } | |||
8448 | ||||
8449 | ++NumVectorInstructions; | |||
8450 | E->VectorizedValue = V; | |||
8451 | return V; | |||
8452 | } | |||
8453 | case Instruction::ZExt: | |||
8454 | case Instruction::SExt: | |||
8455 | case Instruction::FPToUI: | |||
8456 | case Instruction::FPToSI: | |||
8457 | case Instruction::FPExt: | |||
8458 | case Instruction::PtrToInt: | |||
8459 | case Instruction::IntToPtr: | |||
8460 | case Instruction::SIToFP: | |||
8461 | case Instruction::UIToFP: | |||
8462 | case Instruction::Trunc: | |||
8463 | case Instruction::FPTrunc: | |||
8464 | case Instruction::BitCast: { | |||
8465 | setInsertPointAfterBundle(E); | |||
8466 | ||||
8467 | Value *InVec = vectorizeTree(E->getOperand(0)); | |||
8468 | ||||
8469 | if (E->VectorizedValue) { | |||
8470 | LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"; } } while (false); | |||
8471 | return E->VectorizedValue; | |||
8472 | } | |||
8473 | ||||
8474 | auto *CI = cast<CastInst>(VL0); | |||
8475 | Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); | |||
8476 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8477 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8478 | V = ShuffleBuilder.finalize(V); | |||
8479 | ||||
8480 | E->VectorizedValue = V; | |||
8481 | ++NumVectorInstructions; | |||
8482 | return V; | |||
8483 | } | |||
8484 | case Instruction::FCmp: | |||
8485 | case Instruction::ICmp: { | |||
8486 | setInsertPointAfterBundle(E); | |||
8487 | ||||
8488 | Value *L = vectorizeTree(E->getOperand(0)); | |||
8489 | Value *R = vectorizeTree(E->getOperand(1)); | |||
8490 | ||||
8491 | if (E->VectorizedValue) { | |||
8492 | LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"; } } while (false); | |||
8493 | return E->VectorizedValue; | |||
8494 | } | |||
8495 | ||||
8496 | CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); | |||
8497 | Value *V = Builder.CreateCmp(P0, L, R); | |||
8498 | propagateIRFlags(V, E->Scalars, VL0); | |||
8499 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8500 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8501 | V = ShuffleBuilder.finalize(V); | |||
8502 | ||||
8503 | E->VectorizedValue = V; | |||
8504 | ++NumVectorInstructions; | |||
8505 | return V; | |||
8506 | } | |||
8507 | case Instruction::Select: { | |||
8508 | setInsertPointAfterBundle(E); | |||
8509 | ||||
8510 | Value *Cond = vectorizeTree(E->getOperand(0)); | |||
8511 | Value *True = vectorizeTree(E->getOperand(1)); | |||
8512 | Value *False = vectorizeTree(E->getOperand(2)); | |||
8513 | ||||
8514 | if (E->VectorizedValue) { | |||
8515 | LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"; } } while (false); | |||
8516 | return E->VectorizedValue; | |||
8517 | } | |||
8518 | ||||
8519 | Value *V = Builder.CreateSelect(Cond, True, False); | |||
8520 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8521 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8522 | V = ShuffleBuilder.finalize(V); | |||
8523 | ||||
8524 | E->VectorizedValue = V; | |||
8525 | ++NumVectorInstructions; | |||
8526 | return V; | |||
8527 | } | |||
8528 | case Instruction::FNeg: { | |||
8529 | setInsertPointAfterBundle(E); | |||
8530 | ||||
8531 | Value *Op = vectorizeTree(E->getOperand(0)); | |||
8532 | ||||
8533 | if (E->VectorizedValue) { | |||
8534 | LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"; } } while (false); | |||
8535 | return E->VectorizedValue; | |||
8536 | } | |||
8537 | ||||
8538 | Value *V = Builder.CreateUnOp( | |||
8539 | static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); | |||
8540 | propagateIRFlags(V, E->Scalars, VL0); | |||
8541 | if (auto *I = dyn_cast<Instruction>(V)) | |||
8542 | V = propagateMetadata(I, E->Scalars); | |||
8543 | ||||
8544 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8545 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8546 | V = ShuffleBuilder.finalize(V); | |||
8547 | ||||
8548 | E->VectorizedValue = V; | |||
8549 | ++NumVectorInstructions; | |||
8550 | ||||
8551 | return V; | |||
8552 | } | |||
8553 | case Instruction::Add: | |||
8554 | case Instruction::FAdd: | |||
8555 | case Instruction::Sub: | |||
8556 | case Instruction::FSub: | |||
8557 | case Instruction::Mul: | |||
8558 | case Instruction::FMul: | |||
8559 | case Instruction::UDiv: | |||
8560 | case Instruction::SDiv: | |||
8561 | case Instruction::FDiv: | |||
8562 | case Instruction::URem: | |||
8563 | case Instruction::SRem: | |||
8564 | case Instruction::FRem: | |||
8565 | case Instruction::Shl: | |||
8566 | case Instruction::LShr: | |||
8567 | case Instruction::AShr: | |||
8568 | case Instruction::And: | |||
8569 | case Instruction::Or: | |||
8570 | case Instruction::Xor: { | |||
8571 | setInsertPointAfterBundle(E); | |||
8572 | ||||
8573 | Value *LHS = vectorizeTree(E->getOperand(0)); | |||
8574 | Value *RHS = vectorizeTree(E->getOperand(1)); | |||
8575 | ||||
8576 | if (E->VectorizedValue) { | |||
8577 | LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"; } } while (false); | |||
8578 | return E->VectorizedValue; | |||
8579 | } | |||
8580 | ||||
8581 | Value *V = Builder.CreateBinOp( | |||
8582 | static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, | |||
8583 | RHS); | |||
8584 | propagateIRFlags(V, E->Scalars, VL0); | |||
8585 | if (auto *I = dyn_cast<Instruction>(V)) | |||
8586 | V = propagateMetadata(I, E->Scalars); | |||
8587 | ||||
8588 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8589 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8590 | V = ShuffleBuilder.finalize(V); | |||
8591 | ||||
8592 | E->VectorizedValue = V; | |||
8593 | ++NumVectorInstructions; | |||
8594 | ||||
8595 | return V; | |||
8596 | } | |||
8597 | case Instruction::Load: { | |||
8598 | // Loads are inserted at the head of the tree because we don't want to | |||
8599 | // sink them all the way down past store instructions. | |||
8600 | setInsertPointAfterBundle(E); | |||
8601 | ||||
8602 | LoadInst *LI = cast<LoadInst>(VL0); | |||
8603 | Instruction *NewLI; | |||
8604 | unsigned AS = LI->getPointerAddressSpace(); | |||
8605 | Value *PO = LI->getPointerOperand(); | |||
8606 | if (E->State == TreeEntry::Vectorize) { | |||
8607 | Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); | |||
8608 | NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); | |||
8609 | ||||
8610 | // The pointer operand uses an in-tree scalar so we add the new BitCast | |||
8611 | // or LoadInst to ExternalUses list to make sure that an extract will | |||
8612 | // be generated in the future. | |||
8613 | if (TreeEntry *Entry = getTreeEntry(PO)) { | |||
8614 | // Find which lane we need to extract. | |||
8615 | unsigned FoundLane = Entry->findLaneForValue(PO); | |||
8616 | ExternalUses.emplace_back( | |||
8617 | PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane); | |||
8618 | } | |||
8619 | } else { | |||
8620 | assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state")(static_cast <bool> (E->State == TreeEntry::ScatterVectorize && "Unhandled state") ? void (0) : __assert_fail ("E->State == TreeEntry::ScatterVectorize && \"Unhandled state\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8620, __extension__ __PRETTY_FUNCTION__)); | |||
8621 | Value *VecPtr = vectorizeTree(E->getOperand(0)); | |||
8622 | // Use the minimum alignment of the gathered loads. | |||
8623 | Align CommonAlignment = LI->getAlign(); | |||
8624 | for (Value *V : E->Scalars) | |||
8625 | CommonAlignment = | |||
8626 | std::min(CommonAlignment, cast<LoadInst>(V)->getAlign()); | |||
8627 | NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); | |||
8628 | } | |||
8629 | Value *V = propagateMetadata(NewLI, E->Scalars); | |||
8630 | ||||
8631 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8632 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8633 | V = ShuffleBuilder.finalize(V); | |||
8634 | E->VectorizedValue = V; | |||
8635 | ++NumVectorInstructions; | |||
8636 | return V; | |||
8637 | } | |||
8638 | case Instruction::Store: { | |||
8639 | auto *SI = cast<StoreInst>(VL0); | |||
8640 | unsigned AS = SI->getPointerAddressSpace(); | |||
8641 | ||||
8642 | setInsertPointAfterBundle(E); | |||
8643 | ||||
8644 | Value *VecValue = vectorizeTree(E->getOperand(0)); | |||
8645 | ShuffleBuilder.addMask(E->ReorderIndices); | |||
8646 | VecValue = ShuffleBuilder.finalize(VecValue); | |||
8647 | ||||
8648 | Value *ScalarPtr = SI->getPointerOperand(); | |||
8649 | Value *VecPtr = Builder.CreateBitCast( | |||
8650 | ScalarPtr, VecValue->getType()->getPointerTo(AS)); | |||
8651 | StoreInst *ST = | |||
8652 | Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign()); | |||
8653 | ||||
8654 | // The pointer operand uses an in-tree scalar, so add the new BitCast or | |||
8655 | // StoreInst to ExternalUses to make sure that an extract will be | |||
8656 | // generated in the future. | |||
8657 | if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { | |||
8658 | // Find which lane we need to extract. | |||
8659 | unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); | |||
8660 | ExternalUses.push_back(ExternalUser( | |||
8661 | ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST, | |||
8662 | FoundLane)); | |||
8663 | } | |||
8664 | ||||
8665 | Value *V = propagateMetadata(ST, E->Scalars); | |||
8666 | ||||
8667 | E->VectorizedValue = V; | |||
8668 | ++NumVectorInstructions; | |||
8669 | return V; | |||
8670 | } | |||
8671 | case Instruction::GetElementPtr: { | |||
8672 | auto *GEP0 = cast<GetElementPtrInst>(VL0); | |||
8673 | setInsertPointAfterBundle(E); | |||
8674 | ||||
8675 | Value *Op0 = vectorizeTree(E->getOperand(0)); | |||
8676 | ||||
8677 | SmallVector<Value *> OpVecs; | |||
8678 | for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { | |||
8679 | Value *OpVec = vectorizeTree(E->getOperand(J)); | |||
8680 | OpVecs.push_back(OpVec); | |||
8681 | } | |||
8682 | ||||
8683 | Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); | |||
8684 | if (Instruction *I = dyn_cast<GetElementPtrInst>(V)) { | |||
8685 | SmallVector<Value *> GEPs; | |||
8686 | for (Value *V : E->Scalars) { | |||
8687 | if (isa<GetElementPtrInst>(V)) | |||
8688 | GEPs.push_back(V); | |||
8689 | } | |||
8690 | V = propagateMetadata(I, GEPs); | |||
8691 | } | |||
8692 | ||||
8693 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8694 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8695 | V = ShuffleBuilder.finalize(V); | |||
8696 | ||||
8697 | E->VectorizedValue = V; | |||
8698 | ++NumVectorInstructions; | |||
8699 | ||||
8700 | return V; | |||
8701 | } | |||
8702 | case Instruction::Call: { | |||
8703 | CallInst *CI = cast<CallInst>(VL0); | |||
8704 | setInsertPointAfterBundle(E); | |||
8705 | ||||
8706 | Intrinsic::ID IID = Intrinsic::not_intrinsic; | |||
8707 | if (Function *FI = CI->getCalledFunction()) | |||
8708 | IID = FI->getIntrinsicID(); | |||
8709 | ||||
8710 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
8711 | ||||
8712 | auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); | |||
8713 | bool UseIntrinsic = ID != Intrinsic::not_intrinsic && | |||
8714 | VecCallCosts.first <= VecCallCosts.second; | |||
8715 | ||||
8716 | Value *ScalarArg = nullptr; | |||
8717 | std::vector<Value *> OpVecs; | |||
8718 | SmallVector<Type *, 2> TysForDecl = | |||
8719 | {FixedVectorType::get(CI->getType(), E->Scalars.size())}; | |||
8720 | for (int j = 0, e = CI->arg_size(); j < e; ++j) { | |||
8721 | ValueList OpVL; | |||
8722 | // Some intrinsics have scalar arguments. This argument should not be | |||
8723 | // vectorized. | |||
8724 | if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) { | |||
8725 | CallInst *CEI = cast<CallInst>(VL0); | |||
8726 | ScalarArg = CEI->getArgOperand(j); | |||
8727 | OpVecs.push_back(CEI->getArgOperand(j)); | |||
8728 | if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) | |||
8729 | TysForDecl.push_back(ScalarArg->getType()); | |||
8730 | continue; | |||
8731 | } | |||
8732 | ||||
8733 | Value *OpVec = vectorizeTree(E->getOperand(j)); | |||
8734 | LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"; } } while (false); | |||
8735 | OpVecs.push_back(OpVec); | |||
8736 | if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) | |||
8737 | TysForDecl.push_back(OpVec->getType()); | |||
8738 | } | |||
8739 | ||||
8740 | Function *CF; | |||
8741 | if (!UseIntrinsic) { | |||
8742 | VFShape Shape = | |||
8743 | VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( | |||
8744 | VecTy->getNumElements())), | |||
8745 | false /*HasGlobalPred*/); | |||
8746 | CF = VFDatabase(*CI).getVectorizedFunction(Shape); | |||
8747 | } else { | |||
8748 | CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); | |||
8749 | } | |||
8750 | ||||
8751 | SmallVector<OperandBundleDef, 1> OpBundles; | |||
8752 | CI->getOperandBundlesAsDefs(OpBundles); | |||
8753 | Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); | |||
8754 | ||||
8755 | // The scalar argument uses an in-tree scalar so we add the new vectorized | |||
8756 | // call to ExternalUses list to make sure that an extract will be | |||
8757 | // generated in the future. | |||
8758 | if (ScalarArg) { | |||
8759 | if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { | |||
8760 | // Find which lane we need to extract. | |||
8761 | unsigned FoundLane = Entry->findLaneForValue(ScalarArg); | |||
8762 | ExternalUses.push_back( | |||
8763 | ExternalUser(ScalarArg, cast<User>(V), FoundLane)); | |||
8764 | } | |||
8765 | } | |||
8766 | ||||
8767 | propagateIRFlags(V, E->Scalars, VL0); | |||
8768 | ShuffleBuilder.addInversedMask(E->ReorderIndices); | |||
8769 | ShuffleBuilder.addMask(E->ReuseShuffleIndices); | |||
8770 | V = ShuffleBuilder.finalize(V); | |||
8771 | ||||
8772 | E->VectorizedValue = V; | |||
8773 | ++NumVectorInstructions; | |||
8774 | return V; | |||
8775 | } | |||
8776 | case Instruction::ShuffleVector: { | |||
8777 | assert(E->isAltShuffle() &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8783, __extension__ __PRETTY_FUNCTION__)) | |||
8778 | ((Instruction::isBinaryOp(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8783, __extension__ __PRETTY_FUNCTION__)) | |||
8779 | Instruction::isBinaryOp(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8783, __extension__ __PRETTY_FUNCTION__)) | |||
8780 | (Instruction::isCast(E->getOpcode()) &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8783, __extension__ __PRETTY_FUNCTION__)) | |||
8781 | Instruction::isCast(E->getAltOpcode())) ||(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8783, __extension__ __PRETTY_FUNCTION__)) | |||
8782 | (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8783, __extension__ __PRETTY_FUNCTION__)) | |||
8783 | "Invalid Shuffle Vector Operand")(static_cast <bool> (E->isAltShuffle() && (( Instruction::isBinaryOp(E->getOpcode()) && Instruction ::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E ->getOpcode()) && Instruction::isCast(E->getAltOpcode ())) || (isa<CmpInst>(VL0) && isa<CmpInst> (E->getAltOp()))) && "Invalid Shuffle Vector Operand" ) ? void (0) : __assert_fail ("E->isAltShuffle() && ((Instruction::isBinaryOp(E->getOpcode()) && Instruction::isBinaryOp(E->getAltOpcode())) || (Instruction::isCast(E->getOpcode()) && Instruction::isCast(E->getAltOpcode())) || (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && \"Invalid Shuffle Vector Operand\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8783, __extension__ __PRETTY_FUNCTION__)); | |||
8784 | ||||
8785 | Value *LHS = nullptr, *RHS = nullptr; | |||
8786 | if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { | |||
8787 | setInsertPointAfterBundle(E); | |||
8788 | LHS = vectorizeTree(E->getOperand(0)); | |||
8789 | RHS = vectorizeTree(E->getOperand(1)); | |||
8790 | } else { | |||
8791 | setInsertPointAfterBundle(E); | |||
8792 | LHS = vectorizeTree(E->getOperand(0)); | |||
8793 | } | |||
8794 | ||||
8795 | if (E->VectorizedValue) { | |||
8796 | LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"; } } while (false); | |||
8797 | return E->VectorizedValue; | |||
8798 | } | |||
8799 | ||||
8800 | Value *V0, *V1; | |||
8801 | if (Instruction::isBinaryOp(E->getOpcode())) { | |||
8802 | V0 = Builder.CreateBinOp( | |||
8803 | static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); | |||
8804 | V1 = Builder.CreateBinOp( | |||
8805 | static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); | |||
8806 | } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { | |||
8807 | V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); | |||
8808 | auto *AltCI = cast<CmpInst>(E->getAltOp()); | |||
8809 | CmpInst::Predicate AltPred = AltCI->getPredicate(); | |||
8810 | V1 = Builder.CreateCmp(AltPred, LHS, RHS); | |||
8811 | } else { | |||
8812 | V0 = Builder.CreateCast( | |||
8813 | static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); | |||
8814 | V1 = Builder.CreateCast( | |||
8815 | static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); | |||
8816 | } | |||
8817 | // Add V0 and V1 to later analysis to try to find and remove matching | |||
8818 | // instruction, if any. | |||
8819 | for (Value *V : {V0, V1}) { | |||
8820 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
8821 | GatherShuffleExtractSeq.insert(I); | |||
8822 | CSEBlocks.insert(I->getParent()); | |||
8823 | } | |||
8824 | } | |||
8825 | ||||
8826 | // Create shuffle to take alternate operations from the vector. | |||
8827 | // Also, gather up main and alt scalar ops to propagate IR flags to | |||
8828 | // each vector operation. | |||
8829 | ValueList OpScalars, AltScalars; | |||
8830 | SmallVector<int> Mask; | |||
8831 | buildShuffleEntryMask( | |||
8832 | E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, | |||
8833 | [E, this](Instruction *I) { | |||
8834 | assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode")(static_cast <bool> (E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode" ) ? void (0) : __assert_fail ("E->isOpcodeOrAlt(I) && \"Unexpected main/alternate opcode\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8834, __extension__ __PRETTY_FUNCTION__)); | |||
8835 | return isAlternateInstruction(I, E->getMainOp(), E->getAltOp(), | |||
8836 | *TLI); | |||
8837 | }, | |||
8838 | Mask, &OpScalars, &AltScalars); | |||
8839 | ||||
8840 | propagateIRFlags(V0, OpScalars); | |||
8841 | propagateIRFlags(V1, AltScalars); | |||
8842 | ||||
8843 | Value *V = Builder.CreateShuffleVector(V0, V1, Mask); | |||
8844 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
8845 | V = propagateMetadata(I, E->Scalars); | |||
8846 | GatherShuffleExtractSeq.insert(I); | |||
8847 | CSEBlocks.insert(I->getParent()); | |||
8848 | } | |||
8849 | V = ShuffleBuilder.finalize(V); | |||
8850 | ||||
8851 | E->VectorizedValue = V; | |||
8852 | ++NumVectorInstructions; | |||
8853 | ||||
8854 | return V; | |||
8855 | } | |||
8856 | default: | |||
8857 | llvm_unreachable("unknown inst")::llvm::llvm_unreachable_internal("unknown inst", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp" , 8857); | |||
8858 | } | |||
8859 | return nullptr; | |||
8860 | } | |||
8861 | ||||
8862 | Value *BoUpSLP::vectorizeTree() { | |||
8863 | ExtraValueToDebugLocsMap ExternallyUsedValues; | |||
8864 | return vectorizeTree(ExternallyUsedValues); | |||
8865 | } | |||
8866 | ||||
8867 | namespace { | |||
8868 | /// Data type for handling buildvector sequences with the reused scalars from | |||
8869 | /// other tree entries. | |||
8870 | struct ShuffledInsertData { | |||
8871 | /// List of insertelements to be replaced by shuffles. | |||
8872 | SmallVector<InsertElementInst *> InsertElements; | |||
8873 | /// The parent vectors and shuffle mask for the given list of inserts. | |||
8874 | MapVector<Value *, SmallVector<int>> ValueMasks; | |||
8875 | }; | |||
8876 | } // namespace | |||
8877 | ||||
8878 | Value * | |||
8879 | BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { | |||
8880 | // All blocks must be scheduled before any instructions are inserted. | |||
8881 | for (auto &BSIter : BlocksSchedules) { | |||
8882 | scheduleBlock(BSIter.second.get()); | |||
8883 | } | |||
8884 | ||||
8885 | Builder.SetInsertPoint(&F->getEntryBlock().front()); | |||
8886 | auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); | |||
8887 | ||||
8888 | // If the vectorized tree can be rewritten in a smaller type, we truncate the | |||
8889 | // vectorized root. InstCombine will then rewrite the entire expression. We | |||
8890 | // sign extend the extracted values below. | |||
8891 | auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; | |||
8892 | if (MinBWs.count(ScalarRoot)) { | |||
8893 | if (auto *I = dyn_cast<Instruction>(VectorRoot)) { | |||
8894 | // If current instr is a phi and not the last phi, insert it after the | |||
8895 | // last phi node. | |||
8896 | if (isa<PHINode>(I)) | |||
8897 | Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); | |||
8898 | else | |||
8899 | Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); | |||
8900 | } | |||
8901 | auto BundleWidth = VectorizableTree[0]->Scalars.size(); | |||
8902 | auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); | |||
8903 | auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); | |||
8904 | auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); | |||
8905 | VectorizableTree[0]->VectorizedValue = Trunc; | |||
8906 | } | |||
8907 | ||||
8908 | LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Extracting " << ExternalUses .size() << " values .\n"; } } while (false) | |||
8909 | << " values .\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Extracting " << ExternalUses .size() << " values .\n"; } } while (false); | |||
8910 | ||||
8911 | SmallVector<ShuffledInsertData> ShuffledInserts; | |||
8912 | // Maps vector instruction to original insertelement instruction | |||
8913 | DenseMap<Value *, InsertElementInst *> VectorToInsertElement; | |||
8914 | // Extract all of the elements with the external uses. | |||
8915 | for (const auto &ExternalUse : ExternalUses) { | |||
8916 | Value *Scalar = ExternalUse.Scalar; | |||
8917 | llvm::User *User = ExternalUse.User; | |||
8918 | ||||
8919 | // Skip users that we already RAUW. This happens when one instruction | |||
8920 | // has multiple uses of the same value. | |||
8921 | if (User && !is_contained(Scalar->users(), User)) | |||
8922 | continue; | |||
8923 | TreeEntry *E = getTreeEntry(Scalar); | |||
8924 | assert(E && "Invalid scalar")(static_cast <bool> (E && "Invalid scalar") ? void (0) : __assert_fail ("E && \"Invalid scalar\"", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp" , 8924, __extension__ __PRETTY_FUNCTION__)); | |||
8925 | assert(E->State != TreeEntry::NeedToGather &&(static_cast <bool> (E->State != TreeEntry::NeedToGather && "Extracting from a gather list") ? void (0) : __assert_fail ("E->State != TreeEntry::NeedToGather && \"Extracting from a gather list\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8926, __extension__ __PRETTY_FUNCTION__)) | |||
8926 | "Extracting from a gather list")(static_cast <bool> (E->State != TreeEntry::NeedToGather && "Extracting from a gather list") ? void (0) : __assert_fail ("E->State != TreeEntry::NeedToGather && \"Extracting from a gather list\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8926, __extension__ __PRETTY_FUNCTION__)); | |||
8927 | // Non-instruction pointers are not deleted, just skip them. | |||
8928 | if (E->getOpcode() == Instruction::GetElementPtr && | |||
8929 | !isa<GetElementPtrInst>(Scalar)) | |||
8930 | continue; | |||
8931 | ||||
8932 | Value *Vec = E->VectorizedValue; | |||
8933 | assert(Vec && "Can't find vectorizable value")(static_cast <bool> (Vec && "Can't find vectorizable value" ) ? void (0) : __assert_fail ("Vec && \"Can't find vectorizable value\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8933, __extension__ __PRETTY_FUNCTION__)); | |||
8934 | ||||
8935 | Value *Lane = Builder.getInt32(ExternalUse.Lane); | |||
8936 | auto ExtractAndExtendIfNeeded = [&](Value *Vec) { | |||
8937 | if (Scalar->getType() != Vec->getType()) { | |||
8938 | Value *Ex; | |||
8939 | // "Reuse" the existing extract to improve final codegen. | |||
8940 | if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { | |||
8941 | Ex = Builder.CreateExtractElement(ES->getOperand(0), | |||
8942 | ES->getOperand(1)); | |||
8943 | } else { | |||
8944 | Ex = Builder.CreateExtractElement(Vec, Lane); | |||
8945 | } | |||
8946 | // The then branch of the previous if may produce constants, since 0 | |||
8947 | // operand might be a constant. | |||
8948 | if (auto *ExI = dyn_cast<Instruction>(Ex)) { | |||
8949 | GatherShuffleExtractSeq.insert(ExI); | |||
8950 | CSEBlocks.insert(ExI->getParent()); | |||
8951 | } | |||
8952 | // If necessary, sign-extend or zero-extend ScalarRoot | |||
8953 | // to the larger type. | |||
8954 | if (!MinBWs.count(ScalarRoot)) | |||
8955 | return Ex; | |||
8956 | if (MinBWs[ScalarRoot].second) | |||
8957 | return Builder.CreateSExt(Ex, Scalar->getType()); | |||
8958 | return Builder.CreateZExt(Ex, Scalar->getType()); | |||
8959 | } | |||
8960 | assert(isa<FixedVectorType>(Scalar->getType()) &&(static_cast <bool> (isa<FixedVectorType>(Scalar-> getType()) && isa<InsertElementInst>(Scalar) && "In-tree scalar of vector type is not insertelement?") ? void (0) : __assert_fail ("isa<FixedVectorType>(Scalar->getType()) && isa<InsertElementInst>(Scalar) && \"In-tree scalar of vector type is not insertelement?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8962, __extension__ __PRETTY_FUNCTION__)) | |||
8961 | isa<InsertElementInst>(Scalar) &&(static_cast <bool> (isa<FixedVectorType>(Scalar-> getType()) && isa<InsertElementInst>(Scalar) && "In-tree scalar of vector type is not insertelement?") ? void (0) : __assert_fail ("isa<FixedVectorType>(Scalar->getType()) && isa<InsertElementInst>(Scalar) && \"In-tree scalar of vector type is not insertelement?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8962, __extension__ __PRETTY_FUNCTION__)) | |||
8962 | "In-tree scalar of vector type is not insertelement?")(static_cast <bool> (isa<FixedVectorType>(Scalar-> getType()) && isa<InsertElementInst>(Scalar) && "In-tree scalar of vector type is not insertelement?") ? void (0) : __assert_fail ("isa<FixedVectorType>(Scalar->getType()) && isa<InsertElementInst>(Scalar) && \"In-tree scalar of vector type is not insertelement?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8962, __extension__ __PRETTY_FUNCTION__)); | |||
8963 | auto *IE = cast<InsertElementInst>(Scalar); | |||
8964 | VectorToInsertElement.try_emplace(Vec, IE); | |||
8965 | return Vec; | |||
8966 | }; | |||
8967 | // If User == nullptr, the Scalar is used as extra arg. Generate | |||
8968 | // ExtractElement instruction and update the record for this scalar in | |||
8969 | // ExternallyUsedValues. | |||
8970 | if (!User) { | |||
8971 | assert(ExternallyUsedValues.count(Scalar) &&(static_cast <bool> (ExternallyUsedValues.count(Scalar) && "Scalar with nullptr as an external user must be registered in " "ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8973, __extension__ __PRETTY_FUNCTION__)) | |||
8972 | "Scalar with nullptr as an external user must be registered in "(static_cast <bool> (ExternallyUsedValues.count(Scalar) && "Scalar with nullptr as an external user must be registered in " "ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8973, __extension__ __PRETTY_FUNCTION__)) | |||
8973 | "ExternallyUsedValues map")(static_cast <bool> (ExternallyUsedValues.count(Scalar) && "Scalar with nullptr as an external user must be registered in " "ExternallyUsedValues map") ? void (0) : __assert_fail ("ExternallyUsedValues.count(Scalar) && \"Scalar with nullptr as an external user must be registered in \" \"ExternallyUsedValues map\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8973, __extension__ __PRETTY_FUNCTION__)); | |||
8974 | if (auto *VecI = dyn_cast<Instruction>(Vec)) { | |||
8975 | Builder.SetInsertPoint(VecI->getParent(), | |||
8976 | std::next(VecI->getIterator())); | |||
8977 | } else { | |||
8978 | Builder.SetInsertPoint(&F->getEntryBlock().front()); | |||
8979 | } | |||
8980 | Value *NewInst = ExtractAndExtendIfNeeded(Vec); | |||
8981 | auto &NewInstLocs = ExternallyUsedValues[NewInst]; | |||
8982 | auto It = ExternallyUsedValues.find(Scalar); | |||
8983 | assert(It != ExternallyUsedValues.end() &&(static_cast <bool> (It != ExternallyUsedValues.end() && "Externally used scalar is not found in ExternallyUsedValues" ) ? void (0) : __assert_fail ("It != ExternallyUsedValues.end() && \"Externally used scalar is not found in ExternallyUsedValues\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8984, __extension__ __PRETTY_FUNCTION__)) | |||
8984 | "Externally used scalar is not found in ExternallyUsedValues")(static_cast <bool> (It != ExternallyUsedValues.end() && "Externally used scalar is not found in ExternallyUsedValues" ) ? void (0) : __assert_fail ("It != ExternallyUsedValues.end() && \"Externally used scalar is not found in ExternallyUsedValues\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 8984, __extension__ __PRETTY_FUNCTION__)); | |||
8985 | NewInstLocs.append(It->second); | |||
8986 | ExternallyUsedValues.erase(Scalar); | |||
8987 | // Required to update internally referenced instructions. | |||
8988 | Scalar->replaceAllUsesWith(NewInst); | |||
8989 | continue; | |||
8990 | } | |||
8991 | ||||
8992 | if (auto *VU = dyn_cast<InsertElementInst>(User)) { | |||
8993 | // Skip if the scalar is another vector op or Vec is not an instruction. | |||
8994 | if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) { | |||
8995 | if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) { | |||
8996 | Optional<unsigned> InsertIdx = getInsertIndex(VU); | |||
8997 | if (InsertIdx) { | |||
8998 | // Need to use original vector, if the root is truncated. | |||
8999 | if (MinBWs.count(Scalar) && | |||
9000 | VectorizableTree[0]->VectorizedValue == Vec) | |||
9001 | Vec = VectorRoot; | |||
9002 | auto *It = | |||
9003 | find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) { | |||
9004 | // Checks if 2 insertelements are from the same buildvector. | |||
9005 | InsertElementInst *VecInsert = Data.InsertElements.front(); | |||
9006 | return areTwoInsertFromSameBuildVector( | |||
9007 | VU, VecInsert, | |||
9008 | [](InsertElementInst *II) { return II->getOperand(0); }); | |||
9009 | }); | |||
9010 | unsigned Idx = *InsertIdx; | |||
9011 | if (It == ShuffledInserts.end()) { | |||
9012 | (void)ShuffledInserts.emplace_back(); | |||
9013 | It = std::next(ShuffledInserts.begin(), | |||
9014 | ShuffledInserts.size() - 1); | |||
9015 | SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; | |||
9016 | if (Mask.empty()) | |||
9017 | Mask.assign(FTy->getNumElements(), UndefMaskElem); | |||
9018 | // Find the insertvector, vectorized in tree, if any. | |||
9019 | Value *Base = VU; | |||
9020 | while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { | |||
9021 | if (IEBase != User && | |||
9022 | (!IEBase->hasOneUse() || | |||
9023 | getInsertIndex(IEBase).value_or(Idx) == Idx)) | |||
9024 | break; | |||
9025 | // Build the mask for the vectorized insertelement instructions. | |||
9026 | if (const TreeEntry *E = getTreeEntry(IEBase)) { | |||
9027 | do { | |||
9028 | IEBase = cast<InsertElementInst>(Base); | |||
9029 | int IEIdx = *getInsertIndex(IEBase); | |||
9030 | assert(Mask[Idx] == UndefMaskElem &&(static_cast <bool> (Mask[Idx] == UndefMaskElem && "InsertElementInstruction used already.") ? void (0) : __assert_fail ("Mask[Idx] == UndefMaskElem && \"InsertElementInstruction used already.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9031, __extension__ __PRETTY_FUNCTION__)) | |||
9031 | "InsertElementInstruction used already.")(static_cast <bool> (Mask[Idx] == UndefMaskElem && "InsertElementInstruction used already.") ? void (0) : __assert_fail ("Mask[Idx] == UndefMaskElem && \"InsertElementInstruction used already.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9031, __extension__ __PRETTY_FUNCTION__)); | |||
9032 | Mask[IEIdx] = IEIdx; | |||
9033 | Base = IEBase->getOperand(0); | |||
9034 | } while (E == getTreeEntry(Base)); | |||
9035 | break; | |||
9036 | } | |||
9037 | Base = cast<InsertElementInst>(Base)->getOperand(0); | |||
9038 | // After the vectorization the def-use chain has changed, need | |||
9039 | // to look through original insertelement instructions, if they | |||
9040 | // get replaced by vector instructions. | |||
9041 | auto It = VectorToInsertElement.find(Base); | |||
9042 | if (It != VectorToInsertElement.end()) | |||
9043 | Base = It->second; | |||
9044 | } | |||
9045 | } | |||
9046 | SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; | |||
9047 | if (Mask.empty()) | |||
9048 | Mask.assign(FTy->getNumElements(), UndefMaskElem); | |||
9049 | Mask[Idx] = ExternalUse.Lane; | |||
9050 | It->InsertElements.push_back(cast<InsertElementInst>(User)); | |||
9051 | continue; | |||
9052 | } | |||
9053 | } | |||
9054 | } | |||
9055 | } | |||
9056 | ||||
9057 | // Generate extracts for out-of-tree users. | |||
9058 | // Find the insertion point for the extractelement lane. | |||
9059 | if (auto *VecI = dyn_cast<Instruction>(Vec)) { | |||
9060 | if (PHINode *PH = dyn_cast<PHINode>(User)) { | |||
9061 | for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { | |||
9062 | if (PH->getIncomingValue(i) == Scalar) { | |||
9063 | Instruction *IncomingTerminator = | |||
9064 | PH->getIncomingBlock(i)->getTerminator(); | |||
9065 | if (isa<CatchSwitchInst>(IncomingTerminator)) { | |||
9066 | Builder.SetInsertPoint(VecI->getParent(), | |||
9067 | std::next(VecI->getIterator())); | |||
9068 | } else { | |||
9069 | Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); | |||
9070 | } | |||
9071 | Value *NewInst = ExtractAndExtendIfNeeded(Vec); | |||
9072 | PH->setOperand(i, NewInst); | |||
9073 | } | |||
9074 | } | |||
9075 | } else { | |||
9076 | Builder.SetInsertPoint(cast<Instruction>(User)); | |||
9077 | Value *NewInst = ExtractAndExtendIfNeeded(Vec); | |||
9078 | User->replaceUsesOfWith(Scalar, NewInst); | |||
9079 | } | |||
9080 | } else { | |||
9081 | Builder.SetInsertPoint(&F->getEntryBlock().front()); | |||
9082 | Value *NewInst = ExtractAndExtendIfNeeded(Vec); | |||
9083 | User->replaceUsesOfWith(Scalar, NewInst); | |||
9084 | } | |||
9085 | ||||
9086 | LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Replaced:" << *User << ".\n"; } } while (false); | |||
9087 | } | |||
9088 | ||||
9089 | // Checks if the mask is an identity mask. | |||
9090 | auto &&IsIdentityMask = [](ArrayRef<int> Mask, FixedVectorType *VecTy) { | |||
9091 | int Limit = Mask.size(); | |||
9092 | return VecTy->getNumElements() == Mask.size() && | |||
9093 | all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) && | |||
9094 | ShuffleVectorInst::isIdentityMask(Mask); | |||
9095 | }; | |||
9096 | // Tries to combine 2 different masks into single one. | |||
9097 | auto &&CombineMasks = [](SmallVectorImpl<int> &Mask, ArrayRef<int> ExtMask) { | |||
9098 | SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem); | |||
9099 | for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) { | |||
9100 | if (ExtMask[I] == UndefMaskElem) | |||
9101 | continue; | |||
9102 | NewMask[I] = Mask[ExtMask[I]]; | |||
9103 | } | |||
9104 | Mask.swap(NewMask); | |||
9105 | }; | |||
9106 | // Peek through shuffles, trying to simplify the final shuffle code. | |||
9107 | auto &&PeekThroughShuffles = | |||
9108 | [&IsIdentityMask, &CombineMasks](Value *&V, SmallVectorImpl<int> &Mask, | |||
9109 | bool CheckForLengthChange = false) { | |||
9110 | while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) { | |||
9111 | // Exit if not a fixed vector type or changing size shuffle. | |||
9112 | if (!isa<FixedVectorType>(SV->getType()) || | |||
9113 | (CheckForLengthChange && SV->changesLength())) | |||
9114 | break; | |||
9115 | // Exit if the identity or broadcast mask is found. | |||
9116 | if (IsIdentityMask(Mask, cast<FixedVectorType>(SV->getType())) || | |||
9117 | SV->isZeroEltSplat()) | |||
9118 | break; | |||
9119 | bool IsOp1Undef = isUndefVector(SV->getOperand(0), Mask).all(); | |||
9120 | bool IsOp2Undef = isUndefVector(SV->getOperand(1), Mask).all(); | |||
9121 | if (!IsOp1Undef && !IsOp2Undef) | |||
9122 | break; | |||
9123 | SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(), | |||
9124 | SV->getShuffleMask().end()); | |||
9125 | CombineMasks(ShuffleMask, Mask); | |||
9126 | Mask.swap(ShuffleMask); | |||
9127 | if (IsOp2Undef) | |||
9128 | V = SV->getOperand(0); | |||
9129 | else | |||
9130 | V = SV->getOperand(1); | |||
9131 | } | |||
9132 | }; | |||
9133 | // Smart shuffle instruction emission, walks through shuffles trees and | |||
9134 | // tries to find the best matching vector for the actual shuffle | |||
9135 | // instruction. | |||
9136 | auto &&CreateShuffle = [this, &IsIdentityMask, &PeekThroughShuffles, | |||
9137 | &CombineMasks](Value *V1, Value *V2, | |||
9138 | ArrayRef<int> Mask) -> Value * { | |||
9139 | assert(V1 && "Expected at least one vector value.")(static_cast <bool> (V1 && "Expected at least one vector value." ) ? void (0) : __assert_fail ("V1 && \"Expected at least one vector value.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9139, __extension__ __PRETTY_FUNCTION__)); | |||
9140 | if (V2 && !isUndefVector(V2, Mask).all()) { | |||
9141 | // Peek through shuffles. | |||
9142 | Value *Op1 = V1; | |||
9143 | Value *Op2 = V2; | |||
9144 | int VF = | |||
9145 | cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue(); | |||
9146 | SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem); | |||
9147 | SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem); | |||
9148 | for (int I = 0, E = Mask.size(); I < E; ++I) { | |||
9149 | if (Mask[I] < VF) | |||
9150 | CombinedMask1[I] = Mask[I]; | |||
9151 | else | |||
9152 | CombinedMask2[I] = Mask[I] - VF; | |||
9153 | } | |||
9154 | Value *PrevOp1; | |||
9155 | Value *PrevOp2; | |||
9156 | do { | |||
9157 | PrevOp1 = Op1; | |||
9158 | PrevOp2 = Op2; | |||
9159 | PeekThroughShuffles(Op1, CombinedMask1, /*CheckForLengthChange=*/true); | |||
9160 | PeekThroughShuffles(Op2, CombinedMask2, /*CheckForLengthChange=*/true); | |||
9161 | // Check if we have 2 resizing shuffles - need to peek through operands | |||
9162 | // again. | |||
9163 | if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1)) | |||
9164 | if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2)) | |||
9165 | if (SV1->getOperand(0)->getType() == | |||
9166 | SV2->getOperand(0)->getType() && | |||
9167 | SV1->getOperand(0)->getType() != SV1->getType() && | |||
9168 | isUndefVector(SV1->getOperand(1), CombinedMask1).all() && | |||
9169 | isUndefVector(SV2->getOperand(1), CombinedMask2).all()) { | |||
9170 | Op1 = SV1->getOperand(0); | |||
9171 | Op2 = SV2->getOperand(0); | |||
9172 | SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(), | |||
9173 | SV1->getShuffleMask().end()); | |||
9174 | CombineMasks(ShuffleMask1, CombinedMask1); | |||
9175 | CombinedMask1.swap(ShuffleMask1); | |||
9176 | SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(), | |||
9177 | SV2->getShuffleMask().end()); | |||
9178 | CombineMasks(ShuffleMask2, CombinedMask2); | |||
9179 | CombinedMask2.swap(ShuffleMask2); | |||
9180 | } | |||
9181 | } while (PrevOp1 != Op1 || PrevOp2 != Op2); | |||
9182 | VF = cast<VectorType>(Op1->getType()) | |||
9183 | ->getElementCount() | |||
9184 | .getKnownMinValue(); | |||
9185 | for (int I = 0, E = Mask.size(); I < E; ++I) { | |||
9186 | if (CombinedMask2[I] != UndefMaskElem) { | |||
9187 | assert(CombinedMask1[I] == UndefMaskElem &&(static_cast <bool> (CombinedMask1[I] == UndefMaskElem && "Expected undefined mask element") ? void (0) : __assert_fail ("CombinedMask1[I] == UndefMaskElem && \"Expected undefined mask element\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9188, __extension__ __PRETTY_FUNCTION__)) | |||
9188 | "Expected undefined mask element")(static_cast <bool> (CombinedMask1[I] == UndefMaskElem && "Expected undefined mask element") ? void (0) : __assert_fail ("CombinedMask1[I] == UndefMaskElem && \"Expected undefined mask element\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9188, __extension__ __PRETTY_FUNCTION__)); | |||
9189 | CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF); | |||
9190 | } | |||
9191 | } | |||
9192 | Value *Vec = Builder.CreateShuffleVector( | |||
9193 | Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2, | |||
9194 | CombinedMask1); | |||
9195 | if (auto *I = dyn_cast<Instruction>(Vec)) { | |||
9196 | GatherShuffleExtractSeq.insert(I); | |||
9197 | CSEBlocks.insert(I->getParent()); | |||
9198 | } | |||
9199 | return Vec; | |||
9200 | } | |||
9201 | if (isa<PoisonValue>(V1)) | |||
9202 | return PoisonValue::get(FixedVectorType::get( | |||
9203 | cast<VectorType>(V1->getType())->getElementType(), Mask.size())); | |||
9204 | Value *Op = V1; | |||
9205 | SmallVector<int> CombinedMask(Mask); | |||
9206 | PeekThroughShuffles(Op, CombinedMask); | |||
9207 | if (!isa<FixedVectorType>(Op->getType()) || | |||
9208 | !IsIdentityMask(CombinedMask, cast<FixedVectorType>(Op->getType()))) { | |||
9209 | Value *Vec = Builder.CreateShuffleVector(Op, CombinedMask); | |||
9210 | if (auto *I = dyn_cast<Instruction>(Vec)) { | |||
9211 | GatherShuffleExtractSeq.insert(I); | |||
9212 | CSEBlocks.insert(I->getParent()); | |||
9213 | } | |||
9214 | return Vec; | |||
9215 | } | |||
9216 | return Op; | |||
9217 | }; | |||
9218 | ||||
9219 | auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask, | |||
9220 | bool ForSingleMask) { | |||
9221 | unsigned VF = Mask.size(); | |||
9222 | unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements(); | |||
9223 | if (VF != VecVF) { | |||
9224 | if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) { | |||
9225 | Vec = CreateShuffle(Vec, nullptr, Mask); | |||
9226 | return std::make_pair(Vec, true); | |||
9227 | } | |||
9228 | if (!ForSingleMask) { | |||
9229 | SmallVector<int> ResizeMask(VF, UndefMaskElem); | |||
9230 | for (unsigned I = 0; I < VF; ++I) { | |||
9231 | if (Mask[I] != UndefMaskElem) | |||
9232 | ResizeMask[Mask[I]] = Mask[I]; | |||
9233 | } | |||
9234 | Vec = CreateShuffle(Vec, nullptr, ResizeMask); | |||
9235 | } | |||
9236 | } | |||
9237 | ||||
9238 | return std::make_pair(Vec, false); | |||
9239 | }; | |||
9240 | // Perform shuffling of the vectorize tree entries for better handling of | |||
9241 | // external extracts. | |||
9242 | for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) { | |||
9243 | // Find the first and the last instruction in the list of insertelements. | |||
9244 | sort(ShuffledInserts[I].InsertElements, isFirstInsertElement); | |||
9245 | InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front(); | |||
9246 | InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back(); | |||
9247 | Builder.SetInsertPoint(LastInsert); | |||
9248 | auto Vector = ShuffledInserts[I].ValueMasks.takeVector(); | |||
9249 | Value *NewInst = performExtractsShuffleAction<Value>( | |||
9250 | makeMutableArrayRef(Vector.data(), Vector.size()), | |||
9251 | FirstInsert->getOperand(0), | |||
9252 | [](Value *Vec) { | |||
9253 | return cast<VectorType>(Vec->getType()) | |||
9254 | ->getElementCount() | |||
9255 | .getKnownMinValue(); | |||
9256 | }, | |||
9257 | ResizeToVF, | |||
9258 | [FirstInsert, &CreateShuffle](ArrayRef<int> Mask, | |||
9259 | ArrayRef<Value *> Vals) { | |||
9260 | assert((Vals.size() == 1 || Vals.size() == 2) &&(static_cast <bool> ((Vals.size() == 1 || Vals.size() == 2) && "Expected exactly 1 or 2 input values.") ? void (0) : __assert_fail ("(Vals.size() == 1 || Vals.size() == 2) && \"Expected exactly 1 or 2 input values.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9261, __extension__ __PRETTY_FUNCTION__)) | |||
9261 | "Expected exactly 1 or 2 input values.")(static_cast <bool> ((Vals.size() == 1 || Vals.size() == 2) && "Expected exactly 1 or 2 input values.") ? void (0) : __assert_fail ("(Vals.size() == 1 || Vals.size() == 2) && \"Expected exactly 1 or 2 input values.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9261, __extension__ __PRETTY_FUNCTION__)); | |||
9262 | if (Vals.size() == 1) { | |||
9263 | // Do not create shuffle if the mask is a simple identity | |||
9264 | // non-resizing mask. | |||
9265 | if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType()) | |||
9266 | ->getNumElements() || | |||
9267 | !ShuffleVectorInst::isIdentityMask(Mask)) | |||
9268 | return CreateShuffle(Vals.front(), nullptr, Mask); | |||
9269 | return Vals.front(); | |||
9270 | } | |||
9271 | return CreateShuffle(Vals.front() ? Vals.front() | |||
9272 | : FirstInsert->getOperand(0), | |||
9273 | Vals.back(), Mask); | |||
9274 | }); | |||
9275 | auto It = ShuffledInserts[I].InsertElements.rbegin(); | |||
9276 | // Rebuild buildvector chain. | |||
9277 | InsertElementInst *II = nullptr; | |||
9278 | if (It != ShuffledInserts[I].InsertElements.rend()) | |||
9279 | II = *It; | |||
9280 | SmallVector<Instruction *> Inserts; | |||
9281 | while (It != ShuffledInserts[I].InsertElements.rend()) { | |||
9282 | assert(II && "Must be an insertelement instruction.")(static_cast <bool> (II && "Must be an insertelement instruction." ) ? void (0) : __assert_fail ("II && \"Must be an insertelement instruction.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9282, __extension__ __PRETTY_FUNCTION__)); | |||
9283 | if (*It == II) | |||
9284 | ++It; | |||
9285 | else | |||
9286 | Inserts.push_back(cast<Instruction>(II)); | |||
9287 | II = dyn_cast<InsertElementInst>(II->getOperand(0)); | |||
9288 | } | |||
9289 | for (Instruction *II : reverse(Inserts)) { | |||
9290 | II->replaceUsesOfWith(II->getOperand(0), NewInst); | |||
9291 | if (auto *NewI = dyn_cast<Instruction>(NewInst)) | |||
9292 | if (II->getParent() == NewI->getParent() && II->comesBefore(NewI)) | |||
9293 | II->moveAfter(NewI); | |||
9294 | NewInst = II; | |||
9295 | } | |||
9296 | LastInsert->replaceAllUsesWith(NewInst); | |||
9297 | for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) { | |||
9298 | IE->replaceUsesOfWith(IE->getOperand(0), | |||
9299 | PoisonValue::get(IE->getOperand(0)->getType())); | |||
9300 | IE->replaceUsesOfWith(IE->getOperand(1), | |||
9301 | PoisonValue::get(IE->getOperand(1)->getType())); | |||
9302 | eraseInstruction(IE); | |||
9303 | } | |||
9304 | CSEBlocks.insert(LastInsert->getParent()); | |||
9305 | } | |||
9306 | ||||
9307 | // For each vectorized value: | |||
9308 | for (auto &TEPtr : VectorizableTree) { | |||
9309 | TreeEntry *Entry = TEPtr.get(); | |||
9310 | ||||
9311 | // No need to handle users of gathered values. | |||
9312 | if (Entry->State == TreeEntry::NeedToGather) | |||
9313 | continue; | |||
9314 | ||||
9315 | assert(Entry->VectorizedValue && "Can't find vectorizable value")(static_cast <bool> (Entry->VectorizedValue && "Can't find vectorizable value") ? void (0) : __assert_fail ( "Entry->VectorizedValue && \"Can't find vectorizable value\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9315, __extension__ __PRETTY_FUNCTION__)); | |||
9316 | ||||
9317 | // For each lane: | |||
9318 | for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { | |||
9319 | Value *Scalar = Entry->Scalars[Lane]; | |||
9320 | ||||
9321 | if (Entry->getOpcode() == Instruction::GetElementPtr && | |||
9322 | !isa<GetElementPtrInst>(Scalar)) | |||
9323 | continue; | |||
9324 | #ifndef NDEBUG | |||
9325 | Type *Ty = Scalar->getType(); | |||
9326 | if (!Ty->isVoidTy()) { | |||
9327 | for (User *U : Scalar->users()) { | |||
9328 | LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: \tvalidating user:" << *U << ".\n"; } } while (false); | |||
9329 | ||||
9330 | // It is legal to delete users in the ignorelist. | |||
9331 | assert((getTreeEntry(U) ||(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull <Instruction>(U) && isDeleted(cast<Instruction >(U)))) && "Deleting out-of-tree value") ? void (0 ) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9335, __extension__ __PRETTY_FUNCTION__)) | |||
9332 | (UserIgnoreList && UserIgnoreList->contains(U)) ||(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull <Instruction>(U) && isDeleted(cast<Instruction >(U)))) && "Deleting out-of-tree value") ? void (0 ) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9335, __extension__ __PRETTY_FUNCTION__)) | |||
9333 | (isa_and_nonnull<Instruction>(U) &&(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull <Instruction>(U) && isDeleted(cast<Instruction >(U)))) && "Deleting out-of-tree value") ? void (0 ) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9335, __extension__ __PRETTY_FUNCTION__)) | |||
9334 | isDeleted(cast<Instruction>(U)))) &&(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull <Instruction>(U) && isDeleted(cast<Instruction >(U)))) && "Deleting out-of-tree value") ? void (0 ) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9335, __extension__ __PRETTY_FUNCTION__)) | |||
9335 | "Deleting out-of-tree value")(static_cast <bool> ((getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull <Instruction>(U) && isDeleted(cast<Instruction >(U)))) && "Deleting out-of-tree value") ? void (0 ) : __assert_fail ("(getTreeEntry(U) || (UserIgnoreList && UserIgnoreList->contains(U)) || (isa_and_nonnull<Instruction>(U) && isDeleted(cast<Instruction>(U)))) && \"Deleting out-of-tree value\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9335, __extension__ __PRETTY_FUNCTION__)); | |||
9336 | } | |||
9337 | } | |||
9338 | #endif | |||
9339 | LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: \tErasing scalar:" << * Scalar << ".\n"; } } while (false); | |||
9340 | eraseInstruction(cast<Instruction>(Scalar)); | |||
9341 | } | |||
9342 | } | |||
9343 | ||||
9344 | Builder.ClearInsertionPoint(); | |||
9345 | InstrElementSize.clear(); | |||
9346 | ||||
9347 | return VectorizableTree[0]->VectorizedValue; | |||
9348 | } | |||
9349 | ||||
9350 | void BoUpSLP::optimizeGatherSequence() { | |||
9351 | LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleExtractSeq.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Optimizing " << GatherShuffleExtractSeq .size() << " gather sequences instructions.\n"; } } while (false) | |||
9352 | << " gather sequences instructions.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Optimizing " << GatherShuffleExtractSeq .size() << " gather sequences instructions.\n"; } } while (false); | |||
9353 | // LICM InsertElementInst sequences. | |||
9354 | for (Instruction *I : GatherShuffleExtractSeq) { | |||
9355 | if (isDeleted(I)) | |||
9356 | continue; | |||
9357 | ||||
9358 | // Check if this block is inside a loop. | |||
9359 | Loop *L = LI->getLoopFor(I->getParent()); | |||
9360 | if (!L) | |||
9361 | continue; | |||
9362 | ||||
9363 | // Check if it has a preheader. | |||
9364 | BasicBlock *PreHeader = L->getLoopPreheader(); | |||
9365 | if (!PreHeader) | |||
9366 | continue; | |||
9367 | ||||
9368 | // If the vector or the element that we insert into it are | |||
9369 | // instructions that are defined in this basic block then we can't | |||
9370 | // hoist this instruction. | |||
9371 | if (any_of(I->operands(), [L](Value *V) { | |||
9372 | auto *OpI = dyn_cast<Instruction>(V); | |||
9373 | return OpI && L->contains(OpI); | |||
9374 | })) | |||
9375 | continue; | |||
9376 | ||||
9377 | // We can hoist this instruction. Move it to the pre-header. | |||
9378 | I->moveBefore(PreHeader->getTerminator()); | |||
9379 | CSEBlocks.insert(PreHeader); | |||
9380 | } | |||
9381 | ||||
9382 | // Make a list of all reachable blocks in our CSE queue. | |||
9383 | SmallVector<const DomTreeNode *, 8> CSEWorkList; | |||
9384 | CSEWorkList.reserve(CSEBlocks.size()); | |||
9385 | for (BasicBlock *BB : CSEBlocks) | |||
9386 | if (DomTreeNode *N = DT->getNode(BB)) { | |||
9387 | assert(DT->isReachableFromEntry(N))(static_cast <bool> (DT->isReachableFromEntry(N)) ? void (0) : __assert_fail ("DT->isReachableFromEntry(N)", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp" , 9387, __extension__ __PRETTY_FUNCTION__)); | |||
9388 | CSEWorkList.push_back(N); | |||
9389 | } | |||
9390 | ||||
9391 | // Sort blocks by domination. This ensures we visit a block after all blocks | |||
9392 | // dominating it are visited. | |||
9393 | llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { | |||
9394 | assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&(static_cast <bool> ((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9395, __extension__ __PRETTY_FUNCTION__)) | |||
9395 | "Different nodes should have different DFS numbers")(static_cast <bool> ((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9395, __extension__ __PRETTY_FUNCTION__)); | |||
9396 | return A->getDFSNumIn() < B->getDFSNumIn(); | |||
9397 | }); | |||
9398 | ||||
9399 | // Less defined shuffles can be replaced by the more defined copies. | |||
9400 | // Between two shuffles one is less defined if it has the same vector operands | |||
9401 | // and its mask indeces are the same as in the first one or undefs. E.g. | |||
9402 | // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, | |||
9403 | // poison, <0, 0, 0, 0>. | |||
9404 | auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, | |||
9405 | SmallVectorImpl<int> &NewMask) { | |||
9406 | if (I1->getType() != I2->getType()) | |||
9407 | return false; | |||
9408 | auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); | |||
9409 | auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); | |||
9410 | if (!SI1 || !SI2) | |||
9411 | return I1->isIdenticalTo(I2); | |||
9412 | if (SI1->isIdenticalTo(SI2)) | |||
9413 | return true; | |||
9414 | for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) | |||
9415 | if (SI1->getOperand(I) != SI2->getOperand(I)) | |||
9416 | return false; | |||
9417 | // Check if the second instruction is more defined than the first one. | |||
9418 | NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); | |||
9419 | ArrayRef<int> SM1 = SI1->getShuffleMask(); | |||
9420 | // Count trailing undefs in the mask to check the final number of used | |||
9421 | // registers. | |||
9422 | unsigned LastUndefsCnt = 0; | |||
9423 | for (int I = 0, E = NewMask.size(); I < E; ++I) { | |||
9424 | if (SM1[I] == UndefMaskElem) | |||
9425 | ++LastUndefsCnt; | |||
9426 | else | |||
9427 | LastUndefsCnt = 0; | |||
9428 | if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && | |||
9429 | NewMask[I] != SM1[I]) | |||
9430 | return false; | |||
9431 | if (NewMask[I] == UndefMaskElem) | |||
9432 | NewMask[I] = SM1[I]; | |||
9433 | } | |||
9434 | // Check if the last undefs actually change the final number of used vector | |||
9435 | // registers. | |||
9436 | return SM1.size() - LastUndefsCnt > 1 && | |||
9437 | TTI->getNumberOfParts(SI1->getType()) == | |||
9438 | TTI->getNumberOfParts( | |||
9439 | FixedVectorType::get(SI1->getType()->getElementType(), | |||
9440 | SM1.size() - LastUndefsCnt)); | |||
9441 | }; | |||
9442 | // Perform O(N^2) search over the gather/shuffle sequences and merge identical | |||
9443 | // instructions. TODO: We can further optimize this scan if we split the | |||
9444 | // instructions into different buckets based on the insert lane. | |||
9445 | SmallVector<Instruction *, 16> Visited; | |||
9446 | for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { | |||
9447 | assert(*I &&(static_cast <bool> (*I && (I == CSEWorkList.begin () || !DT->dominates(*I, *std::prev(I))) && "Worklist not sorted properly!" ) ? void (0) : __assert_fail ("*I && (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9449, __extension__ __PRETTY_FUNCTION__)) | |||
9448 | (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&(static_cast <bool> (*I && (I == CSEWorkList.begin () || !DT->dominates(*I, *std::prev(I))) && "Worklist not sorted properly!" ) ? void (0) : __assert_fail ("*I && (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9449, __extension__ __PRETTY_FUNCTION__)) | |||
9449 | "Worklist not sorted properly!")(static_cast <bool> (*I && (I == CSEWorkList.begin () || !DT->dominates(*I, *std::prev(I))) && "Worklist not sorted properly!" ) ? void (0) : __assert_fail ("*I && (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && \"Worklist not sorted properly!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9449, __extension__ __PRETTY_FUNCTION__)); | |||
9450 | BasicBlock *BB = (*I)->getBlock(); | |||
9451 | // For all instructions in blocks containing gather sequences: | |||
9452 | for (Instruction &In : llvm::make_early_inc_range(*BB)) { | |||
9453 | if (isDeleted(&In)) | |||
9454 | continue; | |||
9455 | if (!isa<InsertElementInst, ExtractElementInst, ShuffleVectorInst>(&In) && | |||
9456 | !GatherShuffleExtractSeq.contains(&In)) | |||
9457 | continue; | |||
9458 | ||||
9459 | // Check if we can replace this instruction with any of the | |||
9460 | // visited instructions. | |||
9461 | bool Replaced = false; | |||
9462 | for (Instruction *&V : Visited) { | |||
9463 | SmallVector<int> NewMask; | |||
9464 | if (IsIdenticalOrLessDefined(&In, V, NewMask) && | |||
9465 | DT->dominates(V->getParent(), In.getParent())) { | |||
9466 | In.replaceAllUsesWith(V); | |||
9467 | eraseInstruction(&In); | |||
9468 | if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) | |||
9469 | if (!NewMask.empty()) | |||
9470 | SI->setShuffleMask(NewMask); | |||
9471 | Replaced = true; | |||
9472 | break; | |||
9473 | } | |||
9474 | if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && | |||
9475 | GatherShuffleExtractSeq.contains(V) && | |||
9476 | IsIdenticalOrLessDefined(V, &In, NewMask) && | |||
9477 | DT->dominates(In.getParent(), V->getParent())) { | |||
9478 | In.moveAfter(V); | |||
9479 | V->replaceAllUsesWith(&In); | |||
9480 | eraseInstruction(V); | |||
9481 | if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) | |||
9482 | if (!NewMask.empty()) | |||
9483 | SI->setShuffleMask(NewMask); | |||
9484 | V = &In; | |||
9485 | Replaced = true; | |||
9486 | break; | |||
9487 | } | |||
9488 | } | |||
9489 | if (!Replaced) { | |||
9490 | assert(!is_contained(Visited, &In))(static_cast <bool> (!is_contained(Visited, &In)) ? void (0) : __assert_fail ("!is_contained(Visited, &In)", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9490, __extension__ __PRETTY_FUNCTION__)); | |||
9491 | Visited.push_back(&In); | |||
9492 | } | |||
9493 | } | |||
9494 | } | |||
9495 | CSEBlocks.clear(); | |||
9496 | GatherShuffleExtractSeq.clear(); | |||
9497 | } | |||
9498 | ||||
9499 | BoUpSLP::ScheduleData * | |||
9500 | BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { | |||
9501 | ScheduleData *Bundle = nullptr; | |||
9502 | ScheduleData *PrevInBundle = nullptr; | |||
9503 | for (Value *V : VL) { | |||
9504 | if (doesNotNeedToBeScheduled(V)) | |||
9505 | continue; | |||
9506 | ScheduleData *BundleMember = getScheduleData(V); | |||
9507 | assert(BundleMember &&(static_cast <bool> (BundleMember && "no ScheduleData for bundle member " "(maybe not in same basic block)") ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member \" \"(maybe not in same basic block)\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9509, __extension__ __PRETTY_FUNCTION__)) | |||
9508 | "no ScheduleData for bundle member "(static_cast <bool> (BundleMember && "no ScheduleData for bundle member " "(maybe not in same basic block)") ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member \" \"(maybe not in same basic block)\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9509, __extension__ __PRETTY_FUNCTION__)) | |||
9509 | "(maybe not in same basic block)")(static_cast <bool> (BundleMember && "no ScheduleData for bundle member " "(maybe not in same basic block)") ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member \" \"(maybe not in same basic block)\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9509, __extension__ __PRETTY_FUNCTION__)); | |||
9510 | assert(BundleMember->isSchedulingEntity() &&(static_cast <bool> (BundleMember->isSchedulingEntity () && "bundle member already part of other bundle") ? void (0) : __assert_fail ("BundleMember->isSchedulingEntity() && \"bundle member already part of other bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9511, __extension__ __PRETTY_FUNCTION__)) | |||
9511 | "bundle member already part of other bundle")(static_cast <bool> (BundleMember->isSchedulingEntity () && "bundle member already part of other bundle") ? void (0) : __assert_fail ("BundleMember->isSchedulingEntity() && \"bundle member already part of other bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9511, __extension__ __PRETTY_FUNCTION__)); | |||
9512 | if (PrevInBundle) { | |||
9513 | PrevInBundle->NextInBundle = BundleMember; | |||
9514 | } else { | |||
9515 | Bundle = BundleMember; | |||
9516 | } | |||
9517 | ||||
9518 | // Group the instructions to a bundle. | |||
9519 | BundleMember->FirstInBundle = Bundle; | |||
9520 | PrevInBundle = BundleMember; | |||
9521 | } | |||
9522 | assert(Bundle && "Failed to find schedule bundle")(static_cast <bool> (Bundle && "Failed to find schedule bundle" ) ? void (0) : __assert_fail ("Bundle && \"Failed to find schedule bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9522, __extension__ __PRETTY_FUNCTION__)); | |||
9523 | return Bundle; | |||
9524 | } | |||
9525 | ||||
9526 | // Groups the instructions to a bundle (which is then a single scheduling entity) | |||
9527 | // and schedules instructions until the bundle gets ready. | |||
9528 | Optional<BoUpSLP::ScheduleData *> | |||
9529 | BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, | |||
9530 | const InstructionsState &S) { | |||
9531 | // No need to schedule PHIs, insertelement, extractelement and extractvalue | |||
9532 | // instructions. | |||
9533 | if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) || | |||
| ||||
9534 | doesNotNeedToSchedule(VL)) | |||
9535 | return nullptr; | |||
9536 | ||||
9537 | // Initialize the instruction bundle. | |||
9538 | Instruction *OldScheduleEnd = ScheduleEnd; | |||
9539 | LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: bundle: " << *S.OpValue << "\n"; } } while (false); | |||
9540 | ||||
9541 | auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, | |||
9542 | ScheduleData *Bundle) { | |||
9543 | // The scheduling region got new instructions at the lower end (or it is a | |||
9544 | // new region for the first bundle). This makes it necessary to | |||
9545 | // recalculate all dependencies. | |||
9546 | // It is seldom that this needs to be done a second time after adding the | |||
9547 | // initial bundle to the region. | |||
9548 | if (ScheduleEnd != OldScheduleEnd
| |||
9549 | for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) | |||
9550 | doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); | |||
9551 | ReSchedule = true; | |||
9552 | } | |||
9553 | if (Bundle
| |||
9554 | LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundledo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: try schedule bundle " << *Bundle << " in block " << BB->getName() << "\n"; } } while (false) | |||
9555 | << " in block " << BB->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: try schedule bundle " << *Bundle << " in block " << BB->getName() << "\n"; } } while (false); | |||
9556 | calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); | |||
9557 | } | |||
9558 | ||||
9559 | if (ReSchedule) { | |||
9560 | resetSchedule(); | |||
9561 | initialFillReadyList(ReadyInsts); | |||
9562 | } | |||
9563 | ||||
9564 | // Now try to schedule the new bundle or (if no bundle) just calculate | |||
9565 | // dependencies. As soon as the bundle is "ready" it means that there are no | |||
9566 | // cyclic dependencies and we can schedule it. Note that's important that we | |||
9567 | // don't "schedule" the bundle yet (see cancelScheduling). | |||
9568 | while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && | |||
9569 | !ReadyInsts.empty()) { | |||
9570 | ScheduleData *Picked = ReadyInsts.pop_back_val(); | |||
9571 | assert(Picked->isSchedulingEntity() && Picked->isReady() &&(static_cast <bool> (Picked->isSchedulingEntity() && Picked->isReady() && "must be ready to schedule") ? void (0) : __assert_fail ("Picked->isSchedulingEntity() && Picked->isReady() && \"must be ready to schedule\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9572, __extension__ __PRETTY_FUNCTION__)) | |||
9572 | "must be ready to schedule")(static_cast <bool> (Picked->isSchedulingEntity() && Picked->isReady() && "must be ready to schedule") ? void (0) : __assert_fail ("Picked->isSchedulingEntity() && Picked->isReady() && \"must be ready to schedule\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9572, __extension__ __PRETTY_FUNCTION__)); | |||
9573 | schedule(Picked, ReadyInsts); | |||
9574 | } | |||
9575 | }; | |||
9576 | ||||
9577 | // Make sure that the scheduling region contains all | |||
9578 | // instructions of the bundle. | |||
9579 | for (Value *V : VL) { | |||
9580 | if (doesNotNeedToBeScheduled(V)) | |||
9581 | continue; | |||
9582 | if (!extendSchedulingRegion(V, S)) { | |||
9583 | // If the scheduling region got new instructions at the lower end (or it | |||
9584 | // is a new region for the first bundle). This makes it necessary to | |||
9585 | // recalculate all dependencies. | |||
9586 | // Otherwise the compiler may crash trying to incorrectly calculate | |||
9587 | // dependencies and emit instruction in the wrong order at the actual | |||
9588 | // scheduling. | |||
9589 | TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); | |||
9590 | return None; | |||
9591 | } | |||
9592 | } | |||
9593 | ||||
9594 | bool ReSchedule = false; | |||
9595 | for (Value *V : VL) { | |||
9596 | if (doesNotNeedToBeScheduled(V)) | |||
9597 | continue; | |||
9598 | ScheduleData *BundleMember = getScheduleData(V); | |||
9599 | assert(BundleMember &&(static_cast <bool> (BundleMember && "no ScheduleData for bundle member (maybe not in same basic block)" ) ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member (maybe not in same basic block)\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9600, __extension__ __PRETTY_FUNCTION__)) | |||
9600 | "no ScheduleData for bundle member (maybe not in same basic block)")(static_cast <bool> (BundleMember && "no ScheduleData for bundle member (maybe not in same basic block)" ) ? void (0) : __assert_fail ("BundleMember && \"no ScheduleData for bundle member (maybe not in same basic block)\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9600, __extension__ __PRETTY_FUNCTION__)); | |||
9601 | ||||
9602 | // Make sure we don't leave the pieces of the bundle in the ready list when | |||
9603 | // whole bundle might not be ready. | |||
9604 | ReadyInsts.remove(BundleMember); | |||
9605 | ||||
9606 | if (!BundleMember->IsScheduled) | |||
9607 | continue; | |||
9608 | // A bundle member was scheduled as single instruction before and now | |||
9609 | // needs to be scheduled as part of the bundle. We just get rid of the | |||
9610 | // existing schedule. | |||
9611 | LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMemberdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: reset schedule because " << *BundleMember << " was already scheduled\n"; } } while (false) | |||
9612 | << " was already scheduled\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: reset schedule because " << *BundleMember << " was already scheduled\n"; } } while (false); | |||
9613 | ReSchedule = true; | |||
9614 | } | |||
9615 | ||||
9616 | auto *Bundle = buildBundle(VL); | |||
9617 | TryScheduleBundleImpl(ReSchedule, Bundle); | |||
9618 | if (!Bundle->isReady()) { | |||
9619 | cancelScheduling(VL, S.OpValue); | |||
9620 | return None; | |||
9621 | } | |||
9622 | return Bundle; | |||
9623 | } | |||
9624 | ||||
9625 | void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, | |||
9626 | Value *OpValue) { | |||
9627 | if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) || | |||
9628 | doesNotNeedToSchedule(VL)) | |||
9629 | return; | |||
9630 | ||||
9631 | if (doesNotNeedToBeScheduled(OpValue)) | |||
9632 | OpValue = *find_if_not(VL, doesNotNeedToBeScheduled); | |||
9633 | ScheduleData *Bundle = getScheduleData(OpValue); | |||
9634 | LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"; } } while (false); | |||
9635 | assert(!Bundle->IsScheduled &&(static_cast <bool> (!Bundle->IsScheduled && "Can't cancel bundle which is already scheduled") ? void (0) : __assert_fail ("!Bundle->IsScheduled && \"Can't cancel bundle which is already scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9636, __extension__ __PRETTY_FUNCTION__)) | |||
9636 | "Can't cancel bundle which is already scheduled")(static_cast <bool> (!Bundle->IsScheduled && "Can't cancel bundle which is already scheduled") ? void (0) : __assert_fail ("!Bundle->IsScheduled && \"Can't cancel bundle which is already scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9636, __extension__ __PRETTY_FUNCTION__)); | |||
9637 | assert(Bundle->isSchedulingEntity() &&(static_cast <bool> (Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction (VL)) && "tried to unbundle something which is not a bundle" ) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && \"tried to unbundle something which is not a bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9639, __extension__ __PRETTY_FUNCTION__)) | |||
9638 | (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&(static_cast <bool> (Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction (VL)) && "tried to unbundle something which is not a bundle" ) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && \"tried to unbundle something which is not a bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9639, __extension__ __PRETTY_FUNCTION__)) | |||
9639 | "tried to unbundle something which is not a bundle")(static_cast <bool> (Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction (VL)) && "tried to unbundle something which is not a bundle" ) ? void (0) : __assert_fail ("Bundle->isSchedulingEntity() && (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && \"tried to unbundle something which is not a bundle\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9639, __extension__ __PRETTY_FUNCTION__)); | |||
9640 | ||||
9641 | // Remove the bundle from the ready list. | |||
9642 | if (Bundle->isReady()) | |||
9643 | ReadyInsts.remove(Bundle); | |||
9644 | ||||
9645 | // Un-bundle: make single instructions out of the bundle. | |||
9646 | ScheduleData *BundleMember = Bundle; | |||
9647 | while (BundleMember) { | |||
9648 | assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links")(static_cast <bool> (BundleMember->FirstInBundle == Bundle && "corrupt bundle links") ? void (0) : __assert_fail ("BundleMember->FirstInBundle == Bundle && \"corrupt bundle links\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9648, __extension__ __PRETTY_FUNCTION__)); | |||
9649 | BundleMember->FirstInBundle = BundleMember; | |||
9650 | ScheduleData *Next = BundleMember->NextInBundle; | |||
9651 | BundleMember->NextInBundle = nullptr; | |||
9652 | BundleMember->TE = nullptr; | |||
9653 | if (BundleMember->unscheduledDepsInBundle() == 0) { | |||
9654 | ReadyInsts.insert(BundleMember); | |||
9655 | } | |||
9656 | BundleMember = Next; | |||
9657 | } | |||
9658 | } | |||
9659 | ||||
9660 | BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { | |||
9661 | // Allocate a new ScheduleData for the instruction. | |||
9662 | if (ChunkPos >= ChunkSize) { | |||
9663 | ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); | |||
9664 | ChunkPos = 0; | |||
9665 | } | |||
9666 | return &(ScheduleDataChunks.back()[ChunkPos++]); | |||
9667 | } | |||
9668 | ||||
9669 | bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, | |||
9670 | const InstructionsState &S) { | |||
9671 | if (getScheduleData(V, isOneOf(S, V))) | |||
9672 | return true; | |||
9673 | Instruction *I = dyn_cast<Instruction>(V); | |||
9674 | assert(I && "bundle member must be an instruction")(static_cast <bool> (I && "bundle member must be an instruction" ) ? void (0) : __assert_fail ("I && \"bundle member must be an instruction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9674, __extension__ __PRETTY_FUNCTION__)); | |||
9675 | assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&(static_cast <bool> (!isa<PHINode>(I) && ! isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled (I) && "phi nodes/insertelements/extractelements/extractvalues don't need to " "be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9678, __extension__ __PRETTY_FUNCTION__)) | |||
9676 | !doesNotNeedToBeScheduled(I) &&(static_cast <bool> (!isa<PHINode>(I) && ! isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled (I) && "phi nodes/insertelements/extractelements/extractvalues don't need to " "be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9678, __extension__ __PRETTY_FUNCTION__)) | |||
9677 | "phi nodes/insertelements/extractelements/extractvalues don't need to "(static_cast <bool> (!isa<PHINode>(I) && ! isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled (I) && "phi nodes/insertelements/extractelements/extractvalues don't need to " "be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9678, __extension__ __PRETTY_FUNCTION__)) | |||
9678 | "be scheduled")(static_cast <bool> (!isa<PHINode>(I) && ! isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled (I) && "phi nodes/insertelements/extractelements/extractvalues don't need to " "be scheduled") ? void (0) : __assert_fail ("!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && !doesNotNeedToBeScheduled(I) && \"phi nodes/insertelements/extractelements/extractvalues don't need to \" \"be scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9678, __extension__ __PRETTY_FUNCTION__)); | |||
9679 | auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool { | |||
9680 | ScheduleData *ISD = getScheduleData(I); | |||
9681 | if (!ISD) | |||
9682 | return false; | |||
9683 | assert(isInSchedulingRegion(ISD) &&(static_cast <bool> (isInSchedulingRegion(ISD) && "ScheduleData not in scheduling region") ? void (0) : __assert_fail ("isInSchedulingRegion(ISD) && \"ScheduleData not in scheduling region\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9684, __extension__ __PRETTY_FUNCTION__)) | |||
9684 | "ScheduleData not in scheduling region")(static_cast <bool> (isInSchedulingRegion(ISD) && "ScheduleData not in scheduling region") ? void (0) : __assert_fail ("isInSchedulingRegion(ISD) && \"ScheduleData not in scheduling region\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9684, __extension__ __PRETTY_FUNCTION__)); | |||
9685 | ScheduleData *SD = allocateScheduleDataChunks(); | |||
9686 | SD->Inst = I; | |||
9687 | SD->init(SchedulingRegionID, S.OpValue); | |||
9688 | ExtraScheduleDataMap[I][S.OpValue] = SD; | |||
9689 | return true; | |||
9690 | }; | |||
9691 | if (CheckScheduleForI(I)) | |||
9692 | return true; | |||
9693 | if (!ScheduleStart) { | |||
9694 | // It's the first instruction in the new region. | |||
9695 | initScheduleData(I, I->getNextNode(), nullptr, nullptr); | |||
9696 | ScheduleStart = I; | |||
9697 | ScheduleEnd = I->getNextNode(); | |||
9698 | if (isOneOf(S, I) != I) | |||
9699 | CheckScheduleForI(I); | |||
9700 | assert(ScheduleEnd && "tried to vectorize a terminator?")(static_cast <bool> (ScheduleEnd && "tried to vectorize a terminator?" ) ? void (0) : __assert_fail ("ScheduleEnd && \"tried to vectorize a terminator?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9700, __extension__ __PRETTY_FUNCTION__)); | |||
9701 | LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: initialize schedule region to " << *I << "\n"; } } while (false); | |||
9702 | return true; | |||
9703 | } | |||
9704 | // Search up and down at the same time, because we don't know if the new | |||
9705 | // instruction is above or below the existing scheduling region. | |||
9706 | BasicBlock::reverse_iterator UpIter = | |||
9707 | ++ScheduleStart->getIterator().getReverse(); | |||
9708 | BasicBlock::reverse_iterator UpperEnd = BB->rend(); | |||
9709 | BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); | |||
9710 | BasicBlock::iterator LowerEnd = BB->end(); | |||
9711 | while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && | |||
9712 | &*DownIter != I) { | |||
9713 | if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { | |||
9714 | LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: exceeded schedule region size limit\n" ; } } while (false); | |||
9715 | return false; | |||
9716 | } | |||
9717 | ||||
9718 | ++UpIter; | |||
9719 | ++DownIter; | |||
9720 | } | |||
9721 | if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { | |||
9722 | assert(I->getParent() == ScheduleStart->getParent() &&(static_cast <bool> (I->getParent() == ScheduleStart ->getParent() && "Instruction is in wrong basic block." ) ? void (0) : __assert_fail ("I->getParent() == ScheduleStart->getParent() && \"Instruction is in wrong basic block.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9723, __extension__ __PRETTY_FUNCTION__)) | |||
9723 | "Instruction is in wrong basic block.")(static_cast <bool> (I->getParent() == ScheduleStart ->getParent() && "Instruction is in wrong basic block." ) ? void (0) : __assert_fail ("I->getParent() == ScheduleStart->getParent() && \"Instruction is in wrong basic block.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9723, __extension__ __PRETTY_FUNCTION__)); | |||
9724 | initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); | |||
9725 | ScheduleStart = I; | |||
9726 | if (isOneOf(S, I) != I) | |||
9727 | CheckScheduleForI(I); | |||
9728 | LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *Ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: extend schedule region start to " << *I << "\n"; } } while (false) | |||
9729 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: extend schedule region start to " << *I << "\n"; } } while (false); | |||
9730 | return true; | |||
9731 | } | |||
9732 | assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&(static_cast <bool> ((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && "Expected to reach top of the basic block or instruction down the " "lower end.") ? void (0) : __assert_fail ("(UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && \"Expected to reach top of the basic block or instruction down the \" \"lower end.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9734, __extension__ __PRETTY_FUNCTION__)) | |||
9733 | "Expected to reach top of the basic block or instruction down the "(static_cast <bool> ((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && "Expected to reach top of the basic block or instruction down the " "lower end.") ? void (0) : __assert_fail ("(UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && \"Expected to reach top of the basic block or instruction down the \" \"lower end.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9734, __extension__ __PRETTY_FUNCTION__)) | |||
9734 | "lower end.")(static_cast <bool> ((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && "Expected to reach top of the basic block or instruction down the " "lower end.") ? void (0) : __assert_fail ("(UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && \"Expected to reach top of the basic block or instruction down the \" \"lower end.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9734, __extension__ __PRETTY_FUNCTION__)); | |||
9735 | assert(I->getParent() == ScheduleEnd->getParent() &&(static_cast <bool> (I->getParent() == ScheduleEnd-> getParent() && "Instruction is in wrong basic block." ) ? void (0) : __assert_fail ("I->getParent() == ScheduleEnd->getParent() && \"Instruction is in wrong basic block.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9736, __extension__ __PRETTY_FUNCTION__)) | |||
9736 | "Instruction is in wrong basic block.")(static_cast <bool> (I->getParent() == ScheduleEnd-> getParent() && "Instruction is in wrong basic block." ) ? void (0) : __assert_fail ("I->getParent() == ScheduleEnd->getParent() && \"Instruction is in wrong basic block.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9736, __extension__ __PRETTY_FUNCTION__)); | |||
9737 | initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, | |||
9738 | nullptr); | |||
9739 | ScheduleEnd = I->getNextNode(); | |||
9740 | if (isOneOf(S, I) != I) | |||
9741 | CheckScheduleForI(I); | |||
9742 | assert(ScheduleEnd && "tried to vectorize a terminator?")(static_cast <bool> (ScheduleEnd && "tried to vectorize a terminator?" ) ? void (0) : __assert_fail ("ScheduleEnd && \"tried to vectorize a terminator?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9742, __extension__ __PRETTY_FUNCTION__)); | |||
9743 | LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: extend schedule region end to " << *I << "\n"; } } while (false); | |||
9744 | return true; | |||
9745 | } | |||
9746 | ||||
9747 | void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, | |||
9748 | Instruction *ToI, | |||
9749 | ScheduleData *PrevLoadStore, | |||
9750 | ScheduleData *NextLoadStore) { | |||
9751 | ScheduleData *CurrentLoadStore = PrevLoadStore; | |||
9752 | for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { | |||
9753 | // No need to allocate data for non-schedulable instructions. | |||
9754 | if (doesNotNeedToBeScheduled(I)) | |||
9755 | continue; | |||
9756 | ScheduleData *SD = ScheduleDataMap.lookup(I); | |||
9757 | if (!SD) { | |||
9758 | SD = allocateScheduleDataChunks(); | |||
9759 | ScheduleDataMap[I] = SD; | |||
9760 | SD->Inst = I; | |||
9761 | } | |||
9762 | assert(!isInSchedulingRegion(SD) &&(static_cast <bool> (!isInSchedulingRegion(SD) && "new ScheduleData already in scheduling region") ? void (0) : __assert_fail ("!isInSchedulingRegion(SD) && \"new ScheduleData already in scheduling region\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9763, __extension__ __PRETTY_FUNCTION__)) | |||
9763 | "new ScheduleData already in scheduling region")(static_cast <bool> (!isInSchedulingRegion(SD) && "new ScheduleData already in scheduling region") ? void (0) : __assert_fail ("!isInSchedulingRegion(SD) && \"new ScheduleData already in scheduling region\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9763, __extension__ __PRETTY_FUNCTION__)); | |||
9764 | SD->init(SchedulingRegionID, I); | |||
9765 | ||||
9766 | if (I->mayReadOrWriteMemory() && | |||
9767 | (!isa<IntrinsicInst>(I) || | |||
9768 | (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && | |||
9769 | cast<IntrinsicInst>(I)->getIntrinsicID() != | |||
9770 | Intrinsic::pseudoprobe))) { | |||
9771 | // Update the linked list of memory accessing instructions. | |||
9772 | if (CurrentLoadStore) { | |||
9773 | CurrentLoadStore->NextLoadStore = SD; | |||
9774 | } else { | |||
9775 | FirstLoadStoreInRegion = SD; | |||
9776 | } | |||
9777 | CurrentLoadStore = SD; | |||
9778 | } | |||
9779 | ||||
9780 | if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || | |||
9781 | match(I, m_Intrinsic<Intrinsic::stackrestore>())) | |||
9782 | RegionHasStackSave = true; | |||
9783 | } | |||
9784 | if (NextLoadStore) { | |||
9785 | if (CurrentLoadStore) | |||
9786 | CurrentLoadStore->NextLoadStore = NextLoadStore; | |||
9787 | } else { | |||
9788 | LastLoadStoreInRegion = CurrentLoadStore; | |||
9789 | } | |||
9790 | } | |||
9791 | ||||
9792 | void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, | |||
9793 | bool InsertInReadyList, | |||
9794 | BoUpSLP *SLP) { | |||
9795 | assert(SD->isSchedulingEntity())(static_cast <bool> (SD->isSchedulingEntity()) ? void (0) : __assert_fail ("SD->isSchedulingEntity()", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp" , 9795, __extension__ __PRETTY_FUNCTION__)); | |||
9796 | ||||
9797 | SmallVector<ScheduleData *, 10> WorkList; | |||
9798 | WorkList.push_back(SD); | |||
9799 | ||||
9800 | while (!WorkList.empty()) { | |||
9801 | ScheduleData *SD = WorkList.pop_back_val(); | |||
9802 | for (ScheduleData *BundleMember = SD; BundleMember; | |||
9803 | BundleMember = BundleMember->NextInBundle) { | |||
9804 | assert(isInSchedulingRegion(BundleMember))(static_cast <bool> (isInSchedulingRegion(BundleMember) ) ? void (0) : __assert_fail ("isInSchedulingRegion(BundleMember)" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9804, __extension__ __PRETTY_FUNCTION__)); | |||
9805 | if (BundleMember->hasValidDependencies()) | |||
9806 | continue; | |||
9807 | ||||
9808 | LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMemberdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: update deps of " << *BundleMember << "\n"; } } while (false) | |||
9809 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: update deps of " << *BundleMember << "\n"; } } while (false); | |||
9810 | BundleMember->Dependencies = 0; | |||
9811 | BundleMember->resetUnscheduledDeps(); | |||
9812 | ||||
9813 | // Handle def-use chain dependencies. | |||
9814 | if (BundleMember->OpValue != BundleMember->Inst) { | |||
9815 | if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) { | |||
9816 | BundleMember->Dependencies++; | |||
9817 | ScheduleData *DestBundle = UseSD->FirstInBundle; | |||
9818 | if (!DestBundle->IsScheduled) | |||
9819 | BundleMember->incrementUnscheduledDeps(1); | |||
9820 | if (!DestBundle->hasValidDependencies()) | |||
9821 | WorkList.push_back(DestBundle); | |||
9822 | } | |||
9823 | } else { | |||
9824 | for (User *U : BundleMember->Inst->users()) { | |||
9825 | if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) { | |||
9826 | BundleMember->Dependencies++; | |||
9827 | ScheduleData *DestBundle = UseSD->FirstInBundle; | |||
9828 | if (!DestBundle->IsScheduled) | |||
9829 | BundleMember->incrementUnscheduledDeps(1); | |||
9830 | if (!DestBundle->hasValidDependencies()) | |||
9831 | WorkList.push_back(DestBundle); | |||
9832 | } | |||
9833 | } | |||
9834 | } | |||
9835 | ||||
9836 | auto makeControlDependent = [&](Instruction *I) { | |||
9837 | auto *DepDest = getScheduleData(I); | |||
9838 | assert(DepDest && "must be in schedule window")(static_cast <bool> (DepDest && "must be in schedule window" ) ? void (0) : __assert_fail ("DepDest && \"must be in schedule window\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9838, __extension__ __PRETTY_FUNCTION__)); | |||
9839 | DepDest->ControlDependencies.push_back(BundleMember); | |||
9840 | BundleMember->Dependencies++; | |||
9841 | ScheduleData *DestBundle = DepDest->FirstInBundle; | |||
9842 | if (!DestBundle->IsScheduled) | |||
9843 | BundleMember->incrementUnscheduledDeps(1); | |||
9844 | if (!DestBundle->hasValidDependencies()) | |||
9845 | WorkList.push_back(DestBundle); | |||
9846 | }; | |||
9847 | ||||
9848 | // Any instruction which isn't safe to speculate at the beginning of the | |||
9849 | // block is control dependend on any early exit or non-willreturn call | |||
9850 | // which proceeds it. | |||
9851 | if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) { | |||
9852 | for (Instruction *I = BundleMember->Inst->getNextNode(); | |||
9853 | I != ScheduleEnd; I = I->getNextNode()) { | |||
9854 | if (isSafeToSpeculativelyExecute(I, &*BB->begin(), SLP->AC)) | |||
9855 | continue; | |||
9856 | ||||
9857 | // Add the dependency | |||
9858 | makeControlDependent(I); | |||
9859 | ||||
9860 | if (!isGuaranteedToTransferExecutionToSuccessor(I)) | |||
9861 | // Everything past here must be control dependent on I. | |||
9862 | break; | |||
9863 | } | |||
9864 | } | |||
9865 | ||||
9866 | if (RegionHasStackSave) { | |||
9867 | // If we have an inalloc alloca instruction, it needs to be scheduled | |||
9868 | // after any preceeding stacksave. We also need to prevent any alloca | |||
9869 | // from reordering above a preceeding stackrestore. | |||
9870 | if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) || | |||
9871 | match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) { | |||
9872 | for (Instruction *I = BundleMember->Inst->getNextNode(); | |||
9873 | I != ScheduleEnd; I = I->getNextNode()) { | |||
9874 | if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || | |||
9875 | match(I, m_Intrinsic<Intrinsic::stackrestore>())) | |||
9876 | // Any allocas past here must be control dependent on I, and I | |||
9877 | // must be memory dependend on BundleMember->Inst. | |||
9878 | break; | |||
9879 | ||||
9880 | if (!isa<AllocaInst>(I)) | |||
9881 | continue; | |||
9882 | ||||
9883 | // Add the dependency | |||
9884 | makeControlDependent(I); | |||
9885 | } | |||
9886 | } | |||
9887 | ||||
9888 | // In addition to the cases handle just above, we need to prevent | |||
9889 | // allocas from moving below a stacksave. The stackrestore case | |||
9890 | // is currently thought to be conservatism. | |||
9891 | if (isa<AllocaInst>(BundleMember->Inst)) { | |||
9892 | for (Instruction *I = BundleMember->Inst->getNextNode(); | |||
9893 | I != ScheduleEnd; I = I->getNextNode()) { | |||
9894 | if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) && | |||
9895 | !match(I, m_Intrinsic<Intrinsic::stackrestore>())) | |||
9896 | continue; | |||
9897 | ||||
9898 | // Add the dependency | |||
9899 | makeControlDependent(I); | |||
9900 | break; | |||
9901 | } | |||
9902 | } | |||
9903 | } | |||
9904 | ||||
9905 | // Handle the memory dependencies (if any). | |||
9906 | ScheduleData *DepDest = BundleMember->NextLoadStore; | |||
9907 | if (!DepDest) | |||
9908 | continue; | |||
9909 | Instruction *SrcInst = BundleMember->Inst; | |||
9910 | assert(SrcInst->mayReadOrWriteMemory() &&(static_cast <bool> (SrcInst->mayReadOrWriteMemory() && "NextLoadStore list for non memory effecting bundle?" ) ? void (0) : __assert_fail ("SrcInst->mayReadOrWriteMemory() && \"NextLoadStore list for non memory effecting bundle?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9911, __extension__ __PRETTY_FUNCTION__)) | |||
9911 | "NextLoadStore list for non memory effecting bundle?")(static_cast <bool> (SrcInst->mayReadOrWriteMemory() && "NextLoadStore list for non memory effecting bundle?" ) ? void (0) : __assert_fail ("SrcInst->mayReadOrWriteMemory() && \"NextLoadStore list for non memory effecting bundle?\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9911, __extension__ __PRETTY_FUNCTION__)); | |||
9912 | MemoryLocation SrcLoc = getLocation(SrcInst); | |||
9913 | bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); | |||
9914 | unsigned numAliased = 0; | |||
9915 | unsigned DistToSrc = 1; | |||
9916 | ||||
9917 | for ( ; DepDest; DepDest = DepDest->NextLoadStore) { | |||
9918 | assert(isInSchedulingRegion(DepDest))(static_cast <bool> (isInSchedulingRegion(DepDest)) ? void (0) : __assert_fail ("isInSchedulingRegion(DepDest)", "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp" , 9918, __extension__ __PRETTY_FUNCTION__)); | |||
9919 | ||||
9920 | // We have two limits to reduce the complexity: | |||
9921 | // 1) AliasedCheckLimit: It's a small limit to reduce calls to | |||
9922 | // SLP->isAliased (which is the expensive part in this loop). | |||
9923 | // 2) MaxMemDepDistance: It's for very large blocks and it aborts | |||
9924 | // the whole loop (even if the loop is fast, it's quadratic). | |||
9925 | // It's important for the loop break condition (see below) to | |||
9926 | // check this limit even between two read-only instructions. | |||
9927 | if (DistToSrc >= MaxMemDepDistance || | |||
9928 | ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && | |||
9929 | (numAliased >= AliasedCheckLimit || | |||
9930 | SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { | |||
9931 | ||||
9932 | // We increment the counter only if the locations are aliased | |||
9933 | // (instead of counting all alias checks). This gives a better | |||
9934 | // balance between reduced runtime and accurate dependencies. | |||
9935 | numAliased++; | |||
9936 | ||||
9937 | DepDest->MemoryDependencies.push_back(BundleMember); | |||
9938 | BundleMember->Dependencies++; | |||
9939 | ScheduleData *DestBundle = DepDest->FirstInBundle; | |||
9940 | if (!DestBundle->IsScheduled) { | |||
9941 | BundleMember->incrementUnscheduledDeps(1); | |||
9942 | } | |||
9943 | if (!DestBundle->hasValidDependencies()) { | |||
9944 | WorkList.push_back(DestBundle); | |||
9945 | } | |||
9946 | } | |||
9947 | ||||
9948 | // Example, explaining the loop break condition: Let's assume our | |||
9949 | // starting instruction is i0 and MaxMemDepDistance = 3. | |||
9950 | // | |||
9951 | // +--------v--v--v | |||
9952 | // i0,i1,i2,i3,i4,i5,i6,i7,i8 | |||
9953 | // +--------^--^--^ | |||
9954 | // | |||
9955 | // MaxMemDepDistance let us stop alias-checking at i3 and we add | |||
9956 | // dependencies from i0 to i3,i4,.. (even if they are not aliased). | |||
9957 | // Previously we already added dependencies from i3 to i6,i7,i8 | |||
9958 | // (because of MaxMemDepDistance). As we added a dependency from | |||
9959 | // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 | |||
9960 | // and we can abort this loop at i6. | |||
9961 | if (DistToSrc >= 2 * MaxMemDepDistance) | |||
9962 | break; | |||
9963 | DistToSrc++; | |||
9964 | } | |||
9965 | } | |||
9966 | if (InsertInReadyList
| |||
| ||||
9967 | ReadyInsts.insert(SD); | |||
9968 | LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Instdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n"; } } while (false) | |||
9969 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: gets ready on update: " << *SD->Inst << "\n"; } } while (false); | |||
9970 | } | |||
9971 | } | |||
9972 | } | |||
9973 | ||||
9974 | void BoUpSLP::BlockScheduling::resetSchedule() { | |||
9975 | assert(ScheduleStart &&(static_cast <bool> (ScheduleStart && "tried to reset schedule on block which has not been scheduled" ) ? void (0) : __assert_fail ("ScheduleStart && \"tried to reset schedule on block which has not been scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9976, __extension__ __PRETTY_FUNCTION__)) | |||
9976 | "tried to reset schedule on block which has not been scheduled")(static_cast <bool> (ScheduleStart && "tried to reset schedule on block which has not been scheduled" ) ? void (0) : __assert_fail ("ScheduleStart && \"tried to reset schedule on block which has not been scheduled\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9976, __extension__ __PRETTY_FUNCTION__)); | |||
9977 | for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { | |||
9978 | doForAllOpcodes(I, [&](ScheduleData *SD) { | |||
9979 | assert(isInSchedulingRegion(SD) &&(static_cast <bool> (isInSchedulingRegion(SD) && "ScheduleData not in scheduling region") ? void (0) : __assert_fail ("isInSchedulingRegion(SD) && \"ScheduleData not in scheduling region\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9980, __extension__ __PRETTY_FUNCTION__)) | |||
9980 | "ScheduleData not in scheduling region")(static_cast <bool> (isInSchedulingRegion(SD) && "ScheduleData not in scheduling region") ? void (0) : __assert_fail ("isInSchedulingRegion(SD) && \"ScheduleData not in scheduling region\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 9980, __extension__ __PRETTY_FUNCTION__)); | |||
9981 | SD->IsScheduled = false; | |||
9982 | SD->resetUnscheduledDeps(); | |||
9983 | }); | |||
9984 | } | |||
9985 | ReadyInsts.clear(); | |||
9986 | } | |||
9987 | ||||
9988 | void BoUpSLP::scheduleBlock(BlockScheduling *BS) { | |||
9989 | if (!BS->ScheduleStart) | |||
9990 | return; | |||
9991 | ||||
9992 | LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: schedule block " << BS ->BB->getName() << "\n"; } } while (false); | |||
9993 | ||||
9994 | // A key point - if we got here, pre-scheduling was able to find a valid | |||
9995 | // scheduling of the sub-graph of the scheduling window which consists | |||
9996 | // of all vector bundles and their transitive users. As such, we do not | |||
9997 | // need to reschedule anything *outside of* that subgraph. | |||
9998 | ||||
9999 | BS->resetSchedule(); | |||
10000 | ||||
10001 | // For the real scheduling we use a more sophisticated ready-list: it is | |||
10002 | // sorted by the original instruction location. This lets the final schedule | |||
10003 | // be as close as possible to the original instruction order. | |||
10004 | // WARNING: If changing this order causes a correctness issue, that means | |||
10005 | // there is some missing dependence edge in the schedule data graph. | |||
10006 | struct ScheduleDataCompare { | |||
10007 | bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { | |||
10008 | return SD2->SchedulingPriority < SD1->SchedulingPriority; | |||
10009 | } | |||
10010 | }; | |||
10011 | std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; | |||
10012 | ||||
10013 | // Ensure that all dependency data is updated (for nodes in the sub-graph) | |||
10014 | // and fill the ready-list with initial instructions. | |||
10015 | int Idx = 0; | |||
10016 | for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; | |||
10017 | I = I->getNextNode()) { | |||
10018 | BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) { | |||
10019 | TreeEntry *SDTE = getTreeEntry(SD->Inst); | |||
10020 | (void)SDTE; | |||
10021 | assert((isVectorLikeInstWithConstOps(SD->Inst) ||(static_cast <bool> ((isVectorLikeInstWithConstOps(SD-> Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule (SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch" ) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10024, __extension__ __PRETTY_FUNCTION__)) | |||
10022 | SD->isPartOfBundle() ==(static_cast <bool> ((isVectorLikeInstWithConstOps(SD-> Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule (SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch" ) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10024, __extension__ __PRETTY_FUNCTION__)) | |||
10023 | (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&(static_cast <bool> ((isVectorLikeInstWithConstOps(SD-> Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule (SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch" ) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10024, __extension__ __PRETTY_FUNCTION__)) | |||
10024 | "scheduler and vectorizer bundle mismatch")(static_cast <bool> ((isVectorLikeInstWithConstOps(SD-> Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule (SDTE->Scalars))) && "scheduler and vectorizer bundle mismatch" ) ? void (0) : __assert_fail ("(isVectorLikeInstWithConstOps(SD->Inst) || SD->isPartOfBundle() == (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && \"scheduler and vectorizer bundle mismatch\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10024, __extension__ __PRETTY_FUNCTION__)); | |||
10025 | SD->FirstInBundle->SchedulingPriority = Idx++; | |||
10026 | ||||
10027 | if (SD->isSchedulingEntity() && SD->isPartOfBundle()) | |||
10028 | BS->calculateDependencies(SD, false, this); | |||
10029 | }); | |||
10030 | } | |||
10031 | BS->initialFillReadyList(ReadyInsts); | |||
10032 | ||||
10033 | Instruction *LastScheduledInst = BS->ScheduleEnd; | |||
10034 | ||||
10035 | // Do the "real" scheduling. | |||
10036 | while (!ReadyInsts.empty()) { | |||
10037 | ScheduleData *picked = *ReadyInsts.begin(); | |||
10038 | ReadyInsts.erase(ReadyInsts.begin()); | |||
10039 | ||||
10040 | // Move the scheduled instruction(s) to their dedicated places, if not | |||
10041 | // there yet. | |||
10042 | for (ScheduleData *BundleMember = picked; BundleMember; | |||
10043 | BundleMember = BundleMember->NextInBundle) { | |||
10044 | Instruction *pickedInst = BundleMember->Inst; | |||
10045 | if (pickedInst->getNextNode() != LastScheduledInst) | |||
10046 | pickedInst->moveBefore(LastScheduledInst); | |||
10047 | LastScheduledInst = pickedInst; | |||
10048 | } | |||
10049 | ||||
10050 | BS->schedule(picked, ReadyInsts); | |||
10051 | } | |||
10052 | ||||
10053 | // Check that we didn't break any of our invariants. | |||
10054 | #ifdef EXPENSIVE_CHECKS | |||
10055 | BS->verify(); | |||
10056 | #endif | |||
10057 | ||||
10058 | #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) | |||
10059 | // Check that all schedulable entities got scheduled | |||
10060 | for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) { | |||
10061 | BS->doForAllOpcodes(I, [&](ScheduleData *SD) { | |||
10062 | if (SD->isSchedulingEntity() && SD->hasValidDependencies()) { | |||
10063 | assert(SD->IsScheduled && "must be scheduled at this point")(static_cast <bool> (SD->IsScheduled && "must be scheduled at this point" ) ? void (0) : __assert_fail ("SD->IsScheduled && \"must be scheduled at this point\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10063, __extension__ __PRETTY_FUNCTION__)); | |||
10064 | } | |||
10065 | }); | |||
10066 | } | |||
10067 | #endif | |||
10068 | ||||
10069 | // Avoid duplicate scheduling of the block. | |||
10070 | BS->ScheduleStart = nullptr; | |||
10071 | } | |||
10072 | ||||
10073 | unsigned BoUpSLP::getVectorElementSize(Value *V) { | |||
10074 | // If V is a store, just return the width of the stored value (or value | |||
10075 | // truncated just before storing) without traversing the expression tree. | |||
10076 | // This is the common case. | |||
10077 | if (auto *Store = dyn_cast<StoreInst>(V)) | |||
10078 | return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); | |||
10079 | ||||
10080 | if (auto *IEI = dyn_cast<InsertElementInst>(V)) | |||
10081 | return getVectorElementSize(IEI->getOperand(1)); | |||
10082 | ||||
10083 | auto E = InstrElementSize.find(V); | |||
10084 | if (E != InstrElementSize.end()) | |||
10085 | return E->second; | |||
10086 | ||||
10087 | // If V is not a store, we can traverse the expression tree to find loads | |||
10088 | // that feed it. The type of the loaded value may indicate a more suitable | |||
10089 | // width than V's type. We want to base the vector element size on the width | |||
10090 | // of memory operations where possible. | |||
10091 | SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; | |||
10092 | SmallPtrSet<Instruction *, 16> Visited; | |||
10093 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
10094 | Worklist.emplace_back(I, I->getParent()); | |||
10095 | Visited.insert(I); | |||
10096 | } | |||
10097 | ||||
10098 | // Traverse the expression tree in bottom-up order looking for loads. If we | |||
10099 | // encounter an instruction we don't yet handle, we give up. | |||
10100 | auto Width = 0u; | |||
10101 | while (!Worklist.empty()) { | |||
10102 | Instruction *I; | |||
10103 | BasicBlock *Parent; | |||
10104 | std::tie(I, Parent) = Worklist.pop_back_val(); | |||
10105 | ||||
10106 | // We should only be looking at scalar instructions here. If the current | |||
10107 | // instruction has a vector type, skip. | |||
10108 | auto *Ty = I->getType(); | |||
10109 | if (isa<VectorType>(Ty)) | |||
10110 | continue; | |||
10111 | ||||
10112 | // If the current instruction is a load, update MaxWidth to reflect the | |||
10113 | // width of the loaded value. | |||
10114 | if (isa<LoadInst, ExtractElementInst, ExtractValueInst>(I)) | |||
10115 | Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); | |||
10116 | ||||
10117 | // Otherwise, we need to visit the operands of the instruction. We only | |||
10118 | // handle the interesting cases from buildTree here. If an operand is an | |||
10119 | // instruction we haven't yet visited and from the same basic block as the | |||
10120 | // user or the use is a PHI node, we add it to the worklist. | |||
10121 | else if (isa<PHINode, CastInst, GetElementPtrInst, CmpInst, SelectInst, | |||
10122 | BinaryOperator, UnaryOperator>(I)) { | |||
10123 | for (Use &U : I->operands()) | |||
10124 | if (auto *J = dyn_cast<Instruction>(U.get())) | |||
10125 | if (Visited.insert(J).second && | |||
10126 | (isa<PHINode>(I) || J->getParent() == Parent)) | |||
10127 | Worklist.emplace_back(J, J->getParent()); | |||
10128 | } else { | |||
10129 | break; | |||
10130 | } | |||
10131 | } | |||
10132 | ||||
10133 | // If we didn't encounter a memory access in the expression tree, or if we | |||
10134 | // gave up for some reason, just return the width of V. Otherwise, return the | |||
10135 | // maximum width we found. | |||
10136 | if (!Width) { | |||
10137 | if (auto *CI = dyn_cast<CmpInst>(V)) | |||
10138 | V = CI->getOperand(0); | |||
10139 | Width = DL->getTypeSizeInBits(V->getType()); | |||
10140 | } | |||
10141 | ||||
10142 | for (Instruction *I : Visited) | |||
10143 | InstrElementSize[I] = Width; | |||
10144 | ||||
10145 | return Width; | |||
10146 | } | |||
10147 | ||||
10148 | // Determine if a value V in a vectorizable expression Expr can be demoted to a | |||
10149 | // smaller type with a truncation. We collect the values that will be demoted | |||
10150 | // in ToDemote and additional roots that require investigating in Roots. | |||
10151 | static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, | |||
10152 | SmallVectorImpl<Value *> &ToDemote, | |||
10153 | SmallVectorImpl<Value *> &Roots) { | |||
10154 | // We can always demote constants. | |||
10155 | if (isa<Constant>(V)) { | |||
10156 | ToDemote.push_back(V); | |||
10157 | return true; | |||
10158 | } | |||
10159 | ||||
10160 | // If the value is not an instruction in the expression with only one use, it | |||
10161 | // cannot be demoted. | |||
10162 | auto *I = dyn_cast<Instruction>(V); | |||
10163 | if (!I || !I->hasOneUse() || !Expr.count(I)) | |||
10164 | return false; | |||
10165 | ||||
10166 | switch (I->getOpcode()) { | |||
10167 | ||||
10168 | // We can always demote truncations and extensions. Since truncations can | |||
10169 | // seed additional demotion, we save the truncated value. | |||
10170 | case Instruction::Trunc: | |||
10171 | Roots.push_back(I->getOperand(0)); | |||
10172 | break; | |||
10173 | case Instruction::ZExt: | |||
10174 | case Instruction::SExt: | |||
10175 | if (isa<ExtractElementInst, InsertElementInst>(I->getOperand(0))) | |||
10176 | return false; | |||
10177 | break; | |||
10178 | ||||
10179 | // We can demote certain binary operations if we can demote both of their | |||
10180 | // operands. | |||
10181 | case Instruction::Add: | |||
10182 | case Instruction::Sub: | |||
10183 | case Instruction::Mul: | |||
10184 | case Instruction::And: | |||
10185 | case Instruction::Or: | |||
10186 | case Instruction::Xor: | |||
10187 | if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || | |||
10188 | !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) | |||
10189 | return false; | |||
10190 | break; | |||
10191 | ||||
10192 | // We can demote selects if we can demote their true and false values. | |||
10193 | case Instruction::Select: { | |||
10194 | SelectInst *SI = cast<SelectInst>(I); | |||
10195 | if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || | |||
10196 | !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) | |||
10197 | return false; | |||
10198 | break; | |||
10199 | } | |||
10200 | ||||
10201 | // We can demote phis if we can demote all their incoming operands. Note that | |||
10202 | // we don't need to worry about cycles since we ensure single use above. | |||
10203 | case Instruction::PHI: { | |||
10204 | PHINode *PN = cast<PHINode>(I); | |||
10205 | for (Value *IncValue : PN->incoming_values()) | |||
10206 | if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) | |||
10207 | return false; | |||
10208 | break; | |||
10209 | } | |||
10210 | ||||
10211 | // Otherwise, conservatively give up. | |||
10212 | default: | |||
10213 | return false; | |||
10214 | } | |||
10215 | ||||
10216 | // Record the value that we can demote. | |||
10217 | ToDemote.push_back(V); | |||
10218 | return true; | |||
10219 | } | |||
10220 | ||||
10221 | void BoUpSLP::computeMinimumValueSizes() { | |||
10222 | // If there are no external uses, the expression tree must be rooted by a | |||
10223 | // store. We can't demote in-memory values, so there is nothing to do here. | |||
10224 | if (ExternalUses.empty()) | |||
10225 | return; | |||
10226 | ||||
10227 | // We only attempt to truncate integer expressions. | |||
10228 | auto &TreeRoot = VectorizableTree[0]->Scalars; | |||
10229 | auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); | |||
10230 | if (!TreeRootIT) | |||
10231 | return; | |||
10232 | ||||
10233 | // If the expression is not rooted by a store, these roots should have | |||
10234 | // external uses. We will rely on InstCombine to rewrite the expression in | |||
10235 | // the narrower type. However, InstCombine only rewrites single-use values. | |||
10236 | // This means that if a tree entry other than a root is used externally, it | |||
10237 | // must have multiple uses and InstCombine will not rewrite it. The code | |||
10238 | // below ensures that only the roots are used externally. | |||
10239 | SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); | |||
10240 | for (auto &EU : ExternalUses) | |||
10241 | if (!Expr.erase(EU.Scalar)) | |||
10242 | return; | |||
10243 | if (!Expr.empty()) | |||
10244 | return; | |||
10245 | ||||
10246 | // Collect the scalar values of the vectorizable expression. We will use this | |||
10247 | // context to determine which values can be demoted. If we see a truncation, | |||
10248 | // we mark it as seeding another demotion. | |||
10249 | for (auto &EntryPtr : VectorizableTree) | |||
10250 | Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); | |||
10251 | ||||
10252 | // Ensure the roots of the vectorizable tree don't form a cycle. They must | |||
10253 | // have a single external user that is not in the vectorizable tree. | |||
10254 | for (auto *Root : TreeRoot) | |||
10255 | if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) | |||
10256 | return; | |||
10257 | ||||
10258 | // Conservatively determine if we can actually truncate the roots of the | |||
10259 | // expression. Collect the values that can be demoted in ToDemote and | |||
10260 | // additional roots that require investigating in Roots. | |||
10261 | SmallVector<Value *, 32> ToDemote; | |||
10262 | SmallVector<Value *, 4> Roots; | |||
10263 | for (auto *Root : TreeRoot) | |||
10264 | if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) | |||
10265 | return; | |||
10266 | ||||
10267 | // The maximum bit width required to represent all the values that can be | |||
10268 | // demoted without loss of precision. It would be safe to truncate the roots | |||
10269 | // of the expression to this width. | |||
10270 | auto MaxBitWidth = 8u; | |||
10271 | ||||
10272 | // We first check if all the bits of the roots are demanded. If they're not, | |||
10273 | // we can truncate the roots to this narrower type. | |||
10274 | for (auto *Root : TreeRoot) { | |||
10275 | auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); | |||
10276 | MaxBitWidth = std::max<unsigned>( | |||
10277 | Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); | |||
10278 | } | |||
10279 | ||||
10280 | // True if the roots can be zero-extended back to their original type, rather | |||
10281 | // than sign-extended. We know that if the leading bits are not demanded, we | |||
10282 | // can safely zero-extend. So we initialize IsKnownPositive to True. | |||
10283 | bool IsKnownPositive = true; | |||
10284 | ||||
10285 | // If all the bits of the roots are demanded, we can try a little harder to | |||
10286 | // compute a narrower type. This can happen, for example, if the roots are | |||
10287 | // getelementptr indices. InstCombine promotes these indices to the pointer | |||
10288 | // width. Thus, all their bits are technically demanded even though the | |||
10289 | // address computation might be vectorized in a smaller type. | |||
10290 | // | |||
10291 | // We start by looking at each entry that can be demoted. We compute the | |||
10292 | // maximum bit width required to store the scalar by using ValueTracking to | |||
10293 | // compute the number of high-order bits we can truncate. | |||
10294 | if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && | |||
10295 | llvm::all_of(TreeRoot, [](Value *R) { | |||
10296 | assert(R->hasOneUse() && "Root should have only one use!")(static_cast <bool> (R->hasOneUse() && "Root should have only one use!" ) ? void (0) : __assert_fail ("R->hasOneUse() && \"Root should have only one use!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10296, __extension__ __PRETTY_FUNCTION__)); | |||
10297 | return isa<GetElementPtrInst>(R->user_back()); | |||
10298 | })) { | |||
10299 | MaxBitWidth = 8u; | |||
10300 | ||||
10301 | // Determine if the sign bit of all the roots is known to be zero. If not, | |||
10302 | // IsKnownPositive is set to False. | |||
10303 | IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { | |||
10304 | KnownBits Known = computeKnownBits(R, *DL); | |||
10305 | return Known.isNonNegative(); | |||
10306 | }); | |||
10307 | ||||
10308 | // Determine the maximum number of bits required to store the scalar | |||
10309 | // values. | |||
10310 | for (auto *Scalar : ToDemote) { | |||
10311 | auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); | |||
10312 | auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); | |||
10313 | MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); | |||
10314 | } | |||
10315 | ||||
10316 | // If we can't prove that the sign bit is zero, we must add one to the | |||
10317 | // maximum bit width to account for the unknown sign bit. This preserves | |||
10318 | // the existing sign bit so we can safely sign-extend the root back to the | |||
10319 | // original type. Otherwise, if we know the sign bit is zero, we will | |||
10320 | // zero-extend the root instead. | |||
10321 | // | |||
10322 | // FIXME: This is somewhat suboptimal, as there will be cases where adding | |||
10323 | // one to the maximum bit width will yield a larger-than-necessary | |||
10324 | // type. In general, we need to add an extra bit only if we can't | |||
10325 | // prove that the upper bit of the original type is equal to the | |||
10326 | // upper bit of the proposed smaller type. If these two bits are the | |||
10327 | // same (either zero or one) we know that sign-extending from the | |||
10328 | // smaller type will result in the same value. Here, since we can't | |||
10329 | // yet prove this, we are just making the proposed smaller type | |||
10330 | // larger to ensure correctness. | |||
10331 | if (!IsKnownPositive) | |||
10332 | ++MaxBitWidth; | |||
10333 | } | |||
10334 | ||||
10335 | // Round MaxBitWidth up to the next power-of-two. | |||
10336 | if (!isPowerOf2_64(MaxBitWidth)) | |||
10337 | MaxBitWidth = NextPowerOf2(MaxBitWidth); | |||
10338 | ||||
10339 | // If the maximum bit width we compute is less than the with of the roots' | |||
10340 | // type, we can proceed with the narrowing. Otherwise, do nothing. | |||
10341 | if (MaxBitWidth >= TreeRootIT->getBitWidth()) | |||
10342 | return; | |||
10343 | ||||
10344 | // If we can truncate the root, we must collect additional values that might | |||
10345 | // be demoted as a result. That is, those seeded by truncations we will | |||
10346 | // modify. | |||
10347 | while (!Roots.empty()) | |||
10348 | collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); | |||
10349 | ||||
10350 | // Finally, map the values we can demote to the maximum bit with we computed. | |||
10351 | for (auto *Scalar : ToDemote) | |||
10352 | MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); | |||
10353 | } | |||
10354 | ||||
10355 | namespace { | |||
10356 | ||||
10357 | /// The SLPVectorizer Pass. | |||
10358 | struct SLPVectorizer : public FunctionPass { | |||
10359 | SLPVectorizerPass Impl; | |||
10360 | ||||
10361 | /// Pass identification, replacement for typeid | |||
10362 | static char ID; | |||
10363 | ||||
10364 | explicit SLPVectorizer() : FunctionPass(ID) { | |||
10365 | initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); | |||
10366 | } | |||
10367 | ||||
10368 | bool doInitialization(Module &M) override { return false; } | |||
10369 | ||||
10370 | bool runOnFunction(Function &F) override { | |||
10371 | if (skipFunction(F)) | |||
10372 | return false; | |||
10373 | ||||
10374 | auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); | |||
10375 | auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); | |||
10376 | auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); | |||
10377 | auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; | |||
10378 | auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); | |||
10379 | auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); | |||
10380 | auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); | |||
10381 | auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); | |||
10382 | auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); | |||
10383 | auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); | |||
10384 | ||||
10385 | return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); | |||
10386 | } | |||
10387 | ||||
10388 | void getAnalysisUsage(AnalysisUsage &AU) const override { | |||
10389 | FunctionPass::getAnalysisUsage(AU); | |||
10390 | AU.addRequired<AssumptionCacheTracker>(); | |||
10391 | AU.addRequired<ScalarEvolutionWrapperPass>(); | |||
10392 | AU.addRequired<AAResultsWrapperPass>(); | |||
10393 | AU.addRequired<TargetTransformInfoWrapperPass>(); | |||
10394 | AU.addRequired<LoopInfoWrapperPass>(); | |||
10395 | AU.addRequired<DominatorTreeWrapperPass>(); | |||
10396 | AU.addRequired<DemandedBitsWrapperPass>(); | |||
10397 | AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); | |||
10398 | AU.addRequired<InjectTLIMappingsLegacy>(); | |||
10399 | AU.addPreserved<LoopInfoWrapperPass>(); | |||
10400 | AU.addPreserved<DominatorTreeWrapperPass>(); | |||
10401 | AU.addPreserved<AAResultsWrapperPass>(); | |||
10402 | AU.addPreserved<GlobalsAAWrapperPass>(); | |||
10403 | AU.setPreservesCFG(); | |||
10404 | } | |||
10405 | }; | |||
10406 | ||||
10407 | } // end anonymous namespace | |||
10408 | ||||
10409 | PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { | |||
10410 | auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); | |||
10411 | auto *TTI = &AM.getResult<TargetIRAnalysis>(F); | |||
10412 | auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); | |||
10413 | auto *AA = &AM.getResult<AAManager>(F); | |||
10414 | auto *LI = &AM.getResult<LoopAnalysis>(F); | |||
10415 | auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); | |||
10416 | auto *AC = &AM.getResult<AssumptionAnalysis>(F); | |||
10417 | auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); | |||
10418 | auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); | |||
10419 | ||||
10420 | bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); | |||
10421 | if (!Changed) | |||
10422 | return PreservedAnalyses::all(); | |||
10423 | ||||
10424 | PreservedAnalyses PA; | |||
10425 | PA.preserveSet<CFGAnalyses>(); | |||
10426 | return PA; | |||
10427 | } | |||
10428 | ||||
10429 | bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, | |||
10430 | TargetTransformInfo *TTI_, | |||
10431 | TargetLibraryInfo *TLI_, AAResults *AA_, | |||
10432 | LoopInfo *LI_, DominatorTree *DT_, | |||
10433 | AssumptionCache *AC_, DemandedBits *DB_, | |||
10434 | OptimizationRemarkEmitter *ORE_) { | |||
10435 | if (!RunSLPVectorization) | |||
10436 | return false; | |||
10437 | SE = SE_; | |||
10438 | TTI = TTI_; | |||
10439 | TLI = TLI_; | |||
10440 | AA = AA_; | |||
10441 | LI = LI_; | |||
10442 | DT = DT_; | |||
10443 | AC = AC_; | |||
10444 | DB = DB_; | |||
10445 | DL = &F.getParent()->getDataLayout(); | |||
10446 | ||||
10447 | Stores.clear(); | |||
10448 | GEPs.clear(); | |||
10449 | bool Changed = false; | |||
10450 | ||||
10451 | // If the target claims to have no vector registers don't attempt | |||
10452 | // vectorization. | |||
10453 | if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { | |||
10454 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Didn't find any vector registers for target, abort.\n" ; } } while (false) | |||
10455 | dbgs() << "SLP: Didn't find any vector registers for target, abort.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Didn't find any vector registers for target, abort.\n" ; } } while (false); | |||
10456 | return false; | |||
10457 | } | |||
10458 | ||||
10459 | // Don't vectorize when the attribute NoImplicitFloat is used. | |||
10460 | if (F.hasFnAttribute(Attribute::NoImplicitFloat)) | |||
10461 | return false; | |||
10462 | ||||
10463 | LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"; } } while (false); | |||
10464 | ||||
10465 | // Use the bottom up slp vectorizer to construct chains that start with | |||
10466 | // store instructions. | |||
10467 | BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); | |||
10468 | ||||
10469 | // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to | |||
10470 | // delete instructions. | |||
10471 | ||||
10472 | // Update DFS numbers now so that we can use them for ordering. | |||
10473 | DT->updateDFSNumbers(); | |||
10474 | ||||
10475 | // Scan the blocks in the function in post order. | |||
10476 | for (auto *BB : post_order(&F.getEntryBlock())) { | |||
10477 | // Start new block - clear the list of reduction roots. | |||
10478 | R.clearReductionData(); | |||
10479 | collectSeedInstructions(BB); | |||
10480 | ||||
10481 | // Vectorize trees that end at stores. | |||
10482 | if (!Stores.empty()) { | |||
10483 | LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Found stores for " << Stores .size() << " underlying objects.\n"; } } while (false) | |||
10484 | << " underlying objects.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Found stores for " << Stores .size() << " underlying objects.\n"; } } while (false); | |||
10485 | Changed |= vectorizeStoreChains(R); | |||
10486 | } | |||
10487 | ||||
10488 | // Vectorize trees that end at reductions. | |||
10489 | Changed |= vectorizeChainsInBlock(BB, R); | |||
10490 | ||||
10491 | // Vectorize the index computations of getelementptr instructions. This | |||
10492 | // is primarily intended to catch gather-like idioms ending at | |||
10493 | // non-consecutive loads. | |||
10494 | if (!GEPs.empty()) { | |||
10495 | LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Found GEPs for " << GEPs .size() << " underlying objects.\n"; } } while (false) | |||
10496 | << " underlying objects.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Found GEPs for " << GEPs .size() << " underlying objects.\n"; } } while (false); | |||
10497 | Changed |= vectorizeGEPIndices(BB, R); | |||
10498 | } | |||
10499 | } | |||
10500 | ||||
10501 | if (Changed) { | |||
10502 | R.optimizeGatherSequence(); | |||
10503 | LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: vectorized \"" << F.getName () << "\"\n"; } } while (false); | |||
10504 | } | |||
10505 | return Changed; | |||
10506 | } | |||
10507 | ||||
10508 | bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, | |||
10509 | unsigned Idx, unsigned MinVF) { | |||
10510 | LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() << "\n"; } } while (false) | |||
10511 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() << "\n"; } } while (false); | |||
10512 | const unsigned Sz = R.getVectorElementSize(Chain[0]); | |||
10513 | unsigned VF = Chain.size(); | |||
10514 | ||||
10515 | if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) | |||
10516 | return false; | |||
10517 | ||||
10518 | LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idxdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx << "\n"; } } while ( false) | |||
10519 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx << "\n"; } } while ( false); | |||
10520 | ||||
10521 | R.buildTree(Chain); | |||
10522 | if (R.isTreeTinyAndNotFullyVectorizable()) | |||
10523 | return false; | |||
10524 | if (R.isLoadCombineCandidate()) | |||
10525 | return false; | |||
10526 | R.reorderTopToBottom(); | |||
10527 | R.reorderBottomToTop(); | |||
10528 | R.buildExternalUses(); | |||
10529 | ||||
10530 | R.computeMinimumValueSizes(); | |||
10531 | ||||
10532 | InstructionCost Cost = R.getTreeCost(); | |||
10533 | ||||
10534 | LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF=" << VF << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Found cost = " << Cost << " for VF=" << VF << "\n"; } } while (false ); | |||
10535 | if (Cost < -SLPCostThreshold) { | |||
10536 | LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"; } } while (false); | |||
10537 | ||||
10538 | using namespace ore; | |||
10539 | ||||
10540 | R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "StoresVectorized", | |||
10541 | cast<StoreInst>(Chain[0])) | |||
10542 | << "Stores SLP vectorized with cost " << NV("Cost", Cost) | |||
10543 | << " and with tree size " | |||
10544 | << NV("TreeSize", R.getTreeSize())); | |||
10545 | ||||
10546 | R.vectorizeTree(); | |||
10547 | return true; | |||
10548 | } | |||
10549 | ||||
10550 | return false; | |||
10551 | } | |||
10552 | ||||
10553 | bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, | |||
10554 | BoUpSLP &R) { | |||
10555 | // We may run into multiple chains that merge into a single chain. We mark the | |||
10556 | // stores that we vectorized so that we don't visit the same store twice. | |||
10557 | BoUpSLP::ValueSet VectorizedStores; | |||
10558 | bool Changed = false; | |||
10559 | ||||
10560 | int E = Stores.size(); | |||
10561 | SmallBitVector Tails(E, false); | |||
10562 | int MaxIter = MaxStoreLookup.getValue(); | |||
10563 | SmallVector<std::pair<int, int>, 16> ConsecutiveChain( | |||
10564 | E, std::make_pair(E, INT_MAX2147483647)); | |||
10565 | SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); | |||
10566 | int IterCnt; | |||
10567 | auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, | |||
10568 | &CheckedPairs, | |||
10569 | &ConsecutiveChain](int K, int Idx) { | |||
10570 | if (IterCnt >= MaxIter) | |||
10571 | return true; | |||
10572 | if (CheckedPairs[Idx].test(K)) | |||
10573 | return ConsecutiveChain[K].second == 1 && | |||
10574 | ConsecutiveChain[K].first == Idx; | |||
10575 | ++IterCnt; | |||
10576 | CheckedPairs[Idx].set(K); | |||
10577 | CheckedPairs[K].set(Idx); | |||
10578 | Optional<int> Diff = getPointersDiff( | |||
10579 | Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), | |||
10580 | Stores[Idx]->getValueOperand()->getType(), | |||
10581 | Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); | |||
10582 | if (!Diff || *Diff == 0) | |||
10583 | return false; | |||
10584 | int Val = *Diff; | |||
10585 | if (Val < 0) { | |||
10586 | if (ConsecutiveChain[Idx].second > -Val) { | |||
10587 | Tails.set(K); | |||
10588 | ConsecutiveChain[Idx] = std::make_pair(K, -Val); | |||
10589 | } | |||
10590 | return false; | |||
10591 | } | |||
10592 | if (ConsecutiveChain[K].second <= Val) | |||
10593 | return false; | |||
10594 | ||||
10595 | Tails.set(Idx); | |||
10596 | ConsecutiveChain[K] = std::make_pair(Idx, Val); | |||
10597 | return Val == 1; | |||
10598 | }; | |||
10599 | // Do a quadratic search on all of the given stores in reverse order and find | |||
10600 | // all of the pairs of stores that follow each other. | |||
10601 | for (int Idx = E - 1; Idx >= 0; --Idx) { | |||
10602 | // If a store has multiple consecutive store candidates, search according | |||
10603 | // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... | |||
10604 | // This is because usually pairing with immediate succeeding or preceding | |||
10605 | // candidate create the best chance to find slp vectorization opportunity. | |||
10606 | const int MaxLookDepth = std::max(E - Idx, Idx + 1); | |||
10607 | IterCnt = 0; | |||
10608 | for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) | |||
10609 | if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || | |||
10610 | (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) | |||
10611 | break; | |||
10612 | } | |||
10613 | ||||
10614 | // Tracks if we tried to vectorize stores starting from the given tail | |||
10615 | // already. | |||
10616 | SmallBitVector TriedTails(E, false); | |||
10617 | // For stores that start but don't end a link in the chain: | |||
10618 | for (int Cnt = E; Cnt > 0; --Cnt) { | |||
10619 | int I = Cnt - 1; | |||
10620 | if (ConsecutiveChain[I].first == E || Tails.test(I)) | |||
10621 | continue; | |||
10622 | // We found a store instr that starts a chain. Now follow the chain and try | |||
10623 | // to vectorize it. | |||
10624 | BoUpSLP::ValueList Operands; | |||
10625 | // Collect the chain into a list. | |||
10626 | while (I != E && !VectorizedStores.count(Stores[I])) { | |||
10627 | Operands.push_back(Stores[I]); | |||
10628 | Tails.set(I); | |||
10629 | if (ConsecutiveChain[I].second != 1) { | |||
10630 | // Mark the new end in the chain and go back, if required. It might be | |||
10631 | // required if the original stores come in reversed order, for example. | |||
10632 | if (ConsecutiveChain[I].first != E && | |||
10633 | Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && | |||
10634 | !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { | |||
10635 | TriedTails.set(I); | |||
10636 | Tails.reset(ConsecutiveChain[I].first); | |||
10637 | if (Cnt < ConsecutiveChain[I].first + 2) | |||
10638 | Cnt = ConsecutiveChain[I].first + 2; | |||
10639 | } | |||
10640 | break; | |||
10641 | } | |||
10642 | // Move to the next value in the chain. | |||
10643 | I = ConsecutiveChain[I].first; | |||
10644 | } | |||
10645 | assert(!Operands.empty() && "Expected non-empty list of stores.")(static_cast <bool> (!Operands.empty() && "Expected non-empty list of stores." ) ? void (0) : __assert_fail ("!Operands.empty() && \"Expected non-empty list of stores.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 10645, __extension__ __PRETTY_FUNCTION__)); | |||
10646 | ||||
10647 | unsigned MaxVecRegSize = R.getMaxVecRegSize(); | |||
10648 | unsigned EltSize = R.getVectorElementSize(Operands[0]); | |||
10649 | unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); | |||
10650 | ||||
10651 | unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), | |||
10652 | MaxElts); | |||
10653 | auto *Store = cast<StoreInst>(Operands[0]); | |||
10654 | Type *StoreTy = Store->getValueOperand()->getType(); | |||
10655 | Type *ValueTy = StoreTy; | |||
10656 | if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) | |||
10657 | ValueTy = Trunc->getSrcTy(); | |||
10658 | unsigned MinVF = TTI->getStoreMinimumVF( | |||
10659 | R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy); | |||
10660 | ||||
10661 | if (MaxVF <= MinVF) { | |||
10662 | LLVM_DEBUG(dbgs() << "SLP: Vectorization infeasible as MaxVF (" << MaxVF << ") <= "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Vectorization infeasible as MaxVF (" << MaxVF << ") <= " << "MinVF (" << MinVF << ")\n"; } } while (false) | |||
10663 | << "MinVF (" << MinVF << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Vectorization infeasible as MaxVF (" << MaxVF << ") <= " << "MinVF (" << MinVF << ")\n"; } } while (false); | |||
10664 | } | |||
10665 | ||||
10666 | // FIXME: Is division-by-2 the correct step? Should we assert that the | |||
10667 | // register size is a power-of-2? | |||
10668 | unsigned StartIdx = 0; | |||
10669 | for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { | |||
10670 | for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { | |||
10671 | ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); | |||
10672 | if (!VectorizedStores.count(Slice.front()) && | |||
10673 | !VectorizedStores.count(Slice.back()) && | |||
10674 | vectorizeStoreChain(Slice, R, Cnt, MinVF)) { | |||
10675 | // Mark the vectorized stores so that we don't vectorize them again. | |||
10676 | VectorizedStores.insert(Slice.begin(), Slice.end()); | |||
10677 | Changed = true; | |||
10678 | // If we vectorized initial block, no need to try to vectorize it | |||
10679 | // again. | |||
10680 | if (Cnt == StartIdx) | |||
10681 | StartIdx += Size; | |||
10682 | Cnt += Size; | |||
10683 | continue; | |||
10684 | } | |||
10685 | ++Cnt; | |||
10686 | } | |||
10687 | // Check if the whole array was vectorized already - exit. | |||
10688 | if (StartIdx >= Operands.size()) | |||
10689 | break; | |||
10690 | } | |||
10691 | } | |||
10692 | ||||
10693 | return Changed; | |||
10694 | } | |||
10695 | ||||
10696 | void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { | |||
10697 | // Initialize the collections. We will make a single pass over the block. | |||
10698 | Stores.clear(); | |||
10699 | GEPs.clear(); | |||
10700 | ||||
10701 | // Visit the store and getelementptr instructions in BB and organize them in | |||
10702 | // Stores and GEPs according to the underlying objects of their pointer | |||
10703 | // operands. | |||
10704 | for (Instruction &I : *BB) { | |||
10705 | // Ignore store instructions that are volatile or have a pointer operand | |||
10706 | // that doesn't point to a scalar type. | |||
10707 | if (auto *SI = dyn_cast<StoreInst>(&I)) { | |||
10708 | if (!SI->isSimple()) | |||
10709 | continue; | |||
10710 | if (!isValidElementType(SI->getValueOperand()->getType())) | |||
10711 | continue; | |||
10712 | Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); | |||
10713 | } | |||
10714 | ||||
10715 | // Ignore getelementptr instructions that have more than one index, a | |||
10716 | // constant index, or a pointer operand that doesn't point to a scalar | |||
10717 | // type. | |||
10718 | else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { | |||
10719 | auto Idx = GEP->idx_begin()->get(); | |||
10720 | if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) | |||
10721 | continue; | |||
10722 | if (!isValidElementType(Idx->getType())) | |||
10723 | continue; | |||
10724 | if (GEP->getType()->isVectorTy()) | |||
10725 | continue; | |||
10726 | GEPs[GEP->getPointerOperand()].push_back(GEP); | |||
10727 | } | |||
10728 | } | |||
10729 | } | |||
10730 | ||||
10731 | bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { | |||
10732 | if (!A || !B) | |||
10733 | return false; | |||
10734 | if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B)) | |||
10735 | return false; | |||
10736 | Value *VL[] = {A, B}; | |||
10737 | return tryToVectorizeList(VL, R); | |||
10738 | } | |||
10739 | ||||
10740 | bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, | |||
10741 | bool LimitForRegisterSize) { | |||
10742 | if (VL.size() < 2) | |||
10743 | return false; | |||
10744 | ||||
10745 | LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size() << ".\n"; } } while (false) | |||
10746 | << VL.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size() << ".\n"; } } while (false); | |||
10747 | ||||
10748 | // Check that all of the parts are instructions of the same type, | |||
10749 | // we permit an alternate opcode via InstructionsState. | |||
10750 | InstructionsState S = getSameOpcode(VL, *TLI); | |||
10751 | if (!S.getOpcode()) | |||
10752 | return false; | |||
10753 | ||||
10754 | Instruction *I0 = cast<Instruction>(S.OpValue); | |||
10755 | // Make sure invalid types (including vector type) are rejected before | |||
10756 | // determining vectorization factor for scalar instructions. | |||
10757 | for (Value *V : VL) { | |||
10758 | Type *Ty = V->getType(); | |||
10759 | if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { | |||
10760 | // NOTE: the following will give user internal llvm type name, which may | |||
10761 | // not be useful. | |||
10762 | R.getORE()->emit([&]() { | |||
10763 | std::string type_str; | |||
10764 | llvm::raw_string_ostream rso(type_str); | |||
10765 | Ty->print(rso); | |||
10766 | return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "UnsupportedType", I0) | |||
10767 | << "Cannot SLP vectorize list: type " | |||
10768 | << rso.str() + " is unsupported by vectorizer"; | |||
10769 | }); | |||
10770 | return false; | |||
10771 | } | |||
10772 | } | |||
10773 | ||||
10774 | unsigned Sz = R.getVectorElementSize(I0); | |||
10775 | unsigned MinVF = R.getMinVF(Sz); | |||
10776 | unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); | |||
10777 | MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); | |||
10778 | if (MaxVF < 2) { | |||
10779 | R.getORE()->emit([&]() { | |||
10780 | return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "SmallVF", I0) | |||
10781 | << "Cannot SLP vectorize list: vectorization factor " | |||
10782 | << "less than 2 is not supported"; | |||
10783 | }); | |||
10784 | return false; | |||
10785 | } | |||
10786 | ||||
10787 | bool Changed = false; | |||
10788 | bool CandidateFound = false; | |||
10789 | InstructionCost MinCost = SLPCostThreshold.getValue(); | |||
10790 | Type *ScalarTy = VL[0]->getType(); | |||
10791 | if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) | |||
10792 | ScalarTy = IE->getOperand(1)->getType(); | |||
10793 | ||||
10794 | unsigned NextInst = 0, MaxInst = VL.size(); | |||
10795 | for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { | |||
10796 | // No actual vectorization should happen, if number of parts is the same as | |||
10797 | // provided vectorization factor (i.e. the scalar type is used for vector | |||
10798 | // code during codegen). | |||
10799 | auto *VecTy = FixedVectorType::get(ScalarTy, VF); | |||
10800 | if (TTI->getNumberOfParts(VecTy) == VF) | |||
10801 | continue; | |||
10802 | for (unsigned I = NextInst; I < MaxInst; ++I) { | |||
10803 | unsigned OpsWidth = 0; | |||
10804 | ||||
10805 | if (I + VF > MaxInst) | |||
10806 | OpsWidth = MaxInst - I; | |||
10807 | else | |||
10808 | OpsWidth = VF; | |||
10809 | ||||
10810 | if (!isPowerOf2_32(OpsWidth)) | |||
10811 | continue; | |||
10812 | ||||
10813 | if ((LimitForRegisterSize && OpsWidth < MaxVF) || | |||
10814 | (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) | |||
10815 | break; | |||
10816 | ||||
10817 | ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); | |||
10818 | // Check that a previous iteration of this loop did not delete the Value. | |||
10819 | if (llvm::any_of(Ops, [&R](Value *V) { | |||
10820 | auto *I = dyn_cast<Instruction>(V); | |||
10821 | return I && R.isDeleted(I); | |||
10822 | })) | |||
10823 | continue; | |||
10824 | ||||
10825 | LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n"; } } while (false) | |||
10826 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing " << OpsWidth << " operations " << "\n"; } } while (false); | |||
10827 | ||||
10828 | R.buildTree(Ops); | |||
10829 | if (R.isTreeTinyAndNotFullyVectorizable()) | |||
10830 | continue; | |||
10831 | R.reorderTopToBottom(); | |||
10832 | R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); | |||
10833 | R.buildExternalUses(); | |||
10834 | ||||
10835 | R.computeMinimumValueSizes(); | |||
10836 | InstructionCost Cost = R.getTreeCost(); | |||
10837 | CandidateFound = true; | |||
10838 | MinCost = std::min(MinCost, Cost); | |||
10839 | ||||
10840 | LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF=" << VF << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Found cost = " << Cost << " for VF=" << VF << "\n"; } } while (false ); | |||
10841 | if (Cost < -SLPCostThreshold) { | |||
10842 | LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"; } } while (false); | |||
10843 | R.getORE()->emit(OptimizationRemark(SV_NAME"slp-vectorizer", "VectorizedList", | |||
10844 | cast<Instruction>(Ops[0])) | |||
10845 | << "SLP vectorized with cost " << ore::NV("Cost", Cost) | |||
10846 | << " and with tree size " | |||
10847 | << ore::NV("TreeSize", R.getTreeSize())); | |||
10848 | ||||
10849 | R.vectorizeTree(); | |||
10850 | // Move to the next bundle. | |||
10851 | I += VF - 1; | |||
10852 | NextInst = I + 1; | |||
10853 | Changed = true; | |||
10854 | } | |||
10855 | } | |||
10856 | } | |||
10857 | ||||
10858 | if (!Changed && CandidateFound) { | |||
10859 | R.getORE()->emit([&]() { | |||
10860 | return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "NotBeneficial", I0) | |||
10861 | << "List vectorization was possible but not beneficial with cost " | |||
10862 | << ore::NV("Cost", MinCost) << " >= " | |||
10863 | << ore::NV("Treshold", -SLPCostThreshold); | |||
10864 | }); | |||
10865 | } else if (!Changed) { | |||
10866 | R.getORE()->emit([&]() { | |||
10867 | return OptimizationRemarkMissed(SV_NAME"slp-vectorizer", "NotPossible", I0) | |||
10868 | << "Cannot SLP vectorize list: vectorization was impossible" | |||
10869 | << " with available vectorization factors"; | |||
10870 | }); | |||
10871 | } | |||
10872 | return Changed; | |||
10873 | } | |||
10874 | ||||
10875 | bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { | |||
10876 | if (!I) | |||
10877 | return false; | |||
10878 | ||||
10879 | if (!isa<BinaryOperator, CmpInst>(I) || isa<VectorType>(I->getType())) | |||
10880 | return false; | |||
10881 | ||||
10882 | Value *P = I->getParent(); | |||
10883 | ||||
10884 | // Vectorize in current basic block only. | |||
10885 | auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); | |||
10886 | auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); | |||
10887 | if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) | |||
10888 | return false; | |||
10889 | ||||
10890 | // First collect all possible candidates | |||
10891 | SmallVector<std::pair<Value *, Value *>, 4> Candidates; | |||
10892 | Candidates.emplace_back(Op0, Op1); | |||
10893 | ||||
10894 | auto *A = dyn_cast<BinaryOperator>(Op0); | |||
10895 | auto *B = dyn_cast<BinaryOperator>(Op1); | |||
10896 | // Try to skip B. | |||
10897 | if (A && B && B->hasOneUse()) { | |||
10898 | auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); | |||
10899 | auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); | |||
10900 | if (B0 && B0->getParent() == P) | |||
10901 | Candidates.emplace_back(A, B0); | |||
10902 | if (B1 && B1->getParent() == P) | |||
10903 | Candidates.emplace_back(A, B1); | |||
10904 | } | |||
10905 | // Try to skip A. | |||
10906 | if (B && A && A->hasOneUse()) { | |||
10907 | auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); | |||
10908 | auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); | |||
10909 | if (A0 && A0->getParent() == P) | |||
10910 | Candidates.emplace_back(A0, B); | |||
10911 | if (A1 && A1->getParent() == P) | |||
10912 | Candidates.emplace_back(A1, B); | |||
10913 | } | |||
10914 | ||||
10915 | if (Candidates.size() == 1) | |||
10916 | return tryToVectorizePair(Op0, Op1, R); | |||
10917 | ||||
10918 | // We have multiple options. Try to pick the single best. | |||
10919 | Optional<int> BestCandidate = R.findBestRootPair(Candidates); | |||
10920 | if (!BestCandidate) | |||
10921 | return false; | |||
10922 | return tryToVectorizePair(Candidates[*BestCandidate].first, | |||
10923 | Candidates[*BestCandidate].second, R); | |||
10924 | } | |||
10925 | ||||
10926 | namespace { | |||
10927 | ||||
10928 | /// Model horizontal reductions. | |||
10929 | /// | |||
10930 | /// A horizontal reduction is a tree of reduction instructions that has values | |||
10931 | /// that can be put into a vector as its leaves. For example: | |||
10932 | /// | |||
10933 | /// mul mul mul mul | |||
10934 | /// \ / \ / | |||
10935 | /// + + | |||
10936 | /// \ / | |||
10937 | /// + | |||
10938 | /// This tree has "mul" as its leaf values and "+" as its reduction | |||
10939 | /// instructions. A reduction can feed into a store or a binary operation | |||
10940 | /// feeding a phi. | |||
10941 | /// ... | |||
10942 | /// \ / | |||
10943 | /// + | |||
10944 | /// | | |||
10945 | /// phi += | |||
10946 | /// | |||
10947 | /// Or: | |||
10948 | /// ... | |||
10949 | /// \ / | |||
10950 | /// + | |||
10951 | /// | | |||
10952 | /// *p = | |||
10953 | /// | |||
10954 | class HorizontalReduction { | |||
10955 | using ReductionOpsType = SmallVector<Value *, 16>; | |||
10956 | using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; | |||
10957 | ReductionOpsListType ReductionOps; | |||
10958 | /// List of possibly reduced values. | |||
10959 | SmallVector<SmallVector<Value *>> ReducedVals; | |||
10960 | /// Maps reduced value to the corresponding reduction operation. | |||
10961 | DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps; | |||
10962 | // Use map vector to make stable output. | |||
10963 | MapVector<Instruction *, Value *> ExtraArgs; | |||
10964 | WeakTrackingVH ReductionRoot; | |||
10965 | /// The type of reduction operation. | |||
10966 | RecurKind RdxKind; | |||
10967 | ||||
10968 | static bool isCmpSelMinMax(Instruction *I) { | |||
10969 | return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && | |||
10970 | RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); | |||
10971 | } | |||
10972 | ||||
10973 | // And/or are potentially poison-safe logical patterns like: | |||
10974 | // select x, y, false | |||
10975 | // select x, true, y | |||
10976 | static bool isBoolLogicOp(Instruction *I) { | |||
10977 | return isa<SelectInst>(I) && | |||
10978 | (match(I, m_LogicalAnd()) || match(I, m_LogicalOr())); | |||
10979 | } | |||
10980 | ||||
10981 | /// Checks if instruction is associative and can be vectorized. | |||
10982 | static bool isVectorizable(RecurKind Kind, Instruction *I) { | |||
10983 | if (Kind == RecurKind::None) | |||
10984 | return false; | |||
10985 | ||||
10986 | // Integer ops that map to select instructions or intrinsics are fine. | |||
10987 | if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || | |||
10988 | isBoolLogicOp(I)) | |||
10989 | return true; | |||
10990 | ||||
10991 | if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { | |||
10992 | // FP min/max are associative except for NaN and -0.0. We do not | |||
10993 | // have to rule out -0.0 here because the intrinsic semantics do not | |||
10994 | // specify a fixed result for it. | |||
10995 | return I->getFastMathFlags().noNaNs(); | |||
10996 | } | |||
10997 | ||||
10998 | return I->isAssociative(); | |||
10999 | } | |||
11000 | ||||
11001 | static Value *getRdxOperand(Instruction *I, unsigned Index) { | |||
11002 | // Poison-safe 'or' takes the form: select X, true, Y | |||
11003 | // To make that work with the normal operand processing, we skip the | |||
11004 | // true value operand. | |||
11005 | // TODO: Change the code and data structures to handle this without a hack. | |||
11006 | if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) | |||
11007 | return I->getOperand(2); | |||
11008 | return I->getOperand(Index); | |||
11009 | } | |||
11010 | ||||
11011 | /// Creates reduction operation with the current opcode. | |||
11012 | static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, | |||
11013 | Value *RHS, const Twine &Name, bool UseSelect) { | |||
11014 | unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); | |||
11015 | switch (Kind) { | |||
11016 | case RecurKind::Or: | |||
11017 | if (UseSelect && | |||
11018 | LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) | |||
11019 | return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); | |||
11020 | return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, | |||
11021 | Name); | |||
11022 | case RecurKind::And: | |||
11023 | if (UseSelect && | |||
11024 | LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) | |||
11025 | return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); | |||
11026 | return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, | |||
11027 | Name); | |||
11028 | case RecurKind::Add: | |||
11029 | case RecurKind::Mul: | |||
11030 | case RecurKind::Xor: | |||
11031 | case RecurKind::FAdd: | |||
11032 | case RecurKind::FMul: | |||
11033 | return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, | |||
11034 | Name); | |||
11035 | case RecurKind::FMax: | |||
11036 | return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); | |||
11037 | case RecurKind::FMin: | |||
11038 | return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); | |||
11039 | case RecurKind::SMax: | |||
11040 | if (UseSelect) { | |||
11041 | Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); | |||
11042 | return Builder.CreateSelect(Cmp, LHS, RHS, Name); | |||
11043 | } | |||
11044 | return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); | |||
11045 | case RecurKind::SMin: | |||
11046 | if (UseSelect) { | |||
11047 | Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); | |||
11048 | return Builder.CreateSelect(Cmp, LHS, RHS, Name); | |||
11049 | } | |||
11050 | return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); | |||
11051 | case RecurKind::UMax: | |||
11052 | if (UseSelect) { | |||
11053 | Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); | |||
11054 | return Builder.CreateSelect(Cmp, LHS, RHS, Name); | |||
11055 | } | |||
11056 | return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); | |||
11057 | case RecurKind::UMin: | |||
11058 | if (UseSelect) { | |||
11059 | Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); | |||
11060 | return Builder.CreateSelect(Cmp, LHS, RHS, Name); | |||
11061 | } | |||
11062 | return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); | |||
11063 | default: | |||
11064 | llvm_unreachable("Unknown reduction operation.")::llvm::llvm_unreachable_internal("Unknown reduction operation." , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11064); | |||
11065 | } | |||
11066 | } | |||
11067 | ||||
11068 | /// Creates reduction operation with the current opcode with the IR flags | |||
11069 | /// from \p ReductionOps, dropping nuw/nsw flags. | |||
11070 | static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, | |||
11071 | Value *RHS, const Twine &Name, | |||
11072 | const ReductionOpsListType &ReductionOps) { | |||
11073 | bool UseSelect = ReductionOps.size() == 2 || | |||
11074 | // Logical or/and. | |||
11075 | (ReductionOps.size() == 1 && | |||
11076 | isa<SelectInst>(ReductionOps.front().front())); | |||
11077 | assert((!UseSelect || ReductionOps.size() != 2 ||(static_cast <bool> ((!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && "Expected cmp + select pairs for reduction") ? void (0) : __assert_fail ("(!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && \"Expected cmp + select pairs for reduction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11079, __extension__ __PRETTY_FUNCTION__)) | |||
11078 | isa<SelectInst>(ReductionOps[1][0])) &&(static_cast <bool> ((!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && "Expected cmp + select pairs for reduction") ? void (0) : __assert_fail ("(!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && \"Expected cmp + select pairs for reduction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11079, __extension__ __PRETTY_FUNCTION__)) | |||
11079 | "Expected cmp + select pairs for reduction")(static_cast <bool> ((!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && "Expected cmp + select pairs for reduction") ? void (0) : __assert_fail ("(!UseSelect || ReductionOps.size() != 2 || isa<SelectInst>(ReductionOps[1][0])) && \"Expected cmp + select pairs for reduction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11079, __extension__ __PRETTY_FUNCTION__)); | |||
11080 | Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); | |||
11081 | if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { | |||
11082 | if (auto *Sel = dyn_cast<SelectInst>(Op)) { | |||
11083 | propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr, | |||
11084 | /*IncludeWrapFlags=*/false); | |||
11085 | propagateIRFlags(Op, ReductionOps[1], nullptr, | |||
11086 | /*IncludeWrapFlags=*/false); | |||
11087 | return Op; | |||
11088 | } | |||
11089 | } | |||
11090 | propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false); | |||
11091 | return Op; | |||
11092 | } | |||
11093 | ||||
11094 | static RecurKind getRdxKind(Value *V) { | |||
11095 | auto *I = dyn_cast<Instruction>(V); | |||
11096 | if (!I) | |||
11097 | return RecurKind::None; | |||
11098 | if (match(I, m_Add(m_Value(), m_Value()))) | |||
11099 | return RecurKind::Add; | |||
11100 | if (match(I, m_Mul(m_Value(), m_Value()))) | |||
11101 | return RecurKind::Mul; | |||
11102 | if (match(I, m_And(m_Value(), m_Value())) || | |||
11103 | match(I, m_LogicalAnd(m_Value(), m_Value()))) | |||
11104 | return RecurKind::And; | |||
11105 | if (match(I, m_Or(m_Value(), m_Value())) || | |||
11106 | match(I, m_LogicalOr(m_Value(), m_Value()))) | |||
11107 | return RecurKind::Or; | |||
11108 | if (match(I, m_Xor(m_Value(), m_Value()))) | |||
11109 | return RecurKind::Xor; | |||
11110 | if (match(I, m_FAdd(m_Value(), m_Value()))) | |||
11111 | return RecurKind::FAdd; | |||
11112 | if (match(I, m_FMul(m_Value(), m_Value()))) | |||
11113 | return RecurKind::FMul; | |||
11114 | ||||
11115 | if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) | |||
11116 | return RecurKind::FMax; | |||
11117 | if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) | |||
11118 | return RecurKind::FMin; | |||
11119 | ||||
11120 | // This matches either cmp+select or intrinsics. SLP is expected to handle | |||
11121 | // either form. | |||
11122 | // TODO: If we are canonicalizing to intrinsics, we can remove several | |||
11123 | // special-case paths that deal with selects. | |||
11124 | if (match(I, m_SMax(m_Value(), m_Value()))) | |||
11125 | return RecurKind::SMax; | |||
11126 | if (match(I, m_SMin(m_Value(), m_Value()))) | |||
11127 | return RecurKind::SMin; | |||
11128 | if (match(I, m_UMax(m_Value(), m_Value()))) | |||
11129 | return RecurKind::UMax; | |||
11130 | if (match(I, m_UMin(m_Value(), m_Value()))) | |||
11131 | return RecurKind::UMin; | |||
11132 | ||||
11133 | if (auto *Select = dyn_cast<SelectInst>(I)) { | |||
11134 | // Try harder: look for min/max pattern based on instructions producing | |||
11135 | // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). | |||
11136 | // During the intermediate stages of SLP, it's very common to have | |||
11137 | // pattern like this (since optimizeGatherSequence is run only once | |||
11138 | // at the end): | |||
11139 | // %1 = extractelement <2 x i32> %a, i32 0 | |||
11140 | // %2 = extractelement <2 x i32> %a, i32 1 | |||
11141 | // %cond = icmp sgt i32 %1, %2 | |||
11142 | // %3 = extractelement <2 x i32> %a, i32 0 | |||
11143 | // %4 = extractelement <2 x i32> %a, i32 1 | |||
11144 | // %select = select i1 %cond, i32 %3, i32 %4 | |||
11145 | CmpInst::Predicate Pred; | |||
11146 | Instruction *L1; | |||
11147 | Instruction *L2; | |||
11148 | ||||
11149 | Value *LHS = Select->getTrueValue(); | |||
11150 | Value *RHS = Select->getFalseValue(); | |||
11151 | Value *Cond = Select->getCondition(); | |||
11152 | ||||
11153 | // TODO: Support inverse predicates. | |||
11154 | if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { | |||
11155 | if (!isa<ExtractElementInst>(RHS) || | |||
11156 | !L2->isIdenticalTo(cast<Instruction>(RHS))) | |||
11157 | return RecurKind::None; | |||
11158 | } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { | |||
11159 | if (!isa<ExtractElementInst>(LHS) || | |||
11160 | !L1->isIdenticalTo(cast<Instruction>(LHS))) | |||
11161 | return RecurKind::None; | |||
11162 | } else { | |||
11163 | if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) | |||
11164 | return RecurKind::None; | |||
11165 | if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || | |||
11166 | !L1->isIdenticalTo(cast<Instruction>(LHS)) || | |||
11167 | !L2->isIdenticalTo(cast<Instruction>(RHS))) | |||
11168 | return RecurKind::None; | |||
11169 | } | |||
11170 | ||||
11171 | switch (Pred) { | |||
11172 | default: | |||
11173 | return RecurKind::None; | |||
11174 | case CmpInst::ICMP_SGT: | |||
11175 | case CmpInst::ICMP_SGE: | |||
11176 | return RecurKind::SMax; | |||
11177 | case CmpInst::ICMP_SLT: | |||
11178 | case CmpInst::ICMP_SLE: | |||
11179 | return RecurKind::SMin; | |||
11180 | case CmpInst::ICMP_UGT: | |||
11181 | case CmpInst::ICMP_UGE: | |||
11182 | return RecurKind::UMax; | |||
11183 | case CmpInst::ICMP_ULT: | |||
11184 | case CmpInst::ICMP_ULE: | |||
11185 | return RecurKind::UMin; | |||
11186 | } | |||
11187 | } | |||
11188 | return RecurKind::None; | |||
11189 | } | |||
11190 | ||||
11191 | /// Get the index of the first operand. | |||
11192 | static unsigned getFirstOperandIndex(Instruction *I) { | |||
11193 | return isCmpSelMinMax(I) ? 1 : 0; | |||
11194 | } | |||
11195 | ||||
11196 | /// Total number of operands in the reduction operation. | |||
11197 | static unsigned getNumberOfOperands(Instruction *I) { | |||
11198 | return isCmpSelMinMax(I) ? 3 : 2; | |||
11199 | } | |||
11200 | ||||
11201 | /// Checks if the instruction is in basic block \p BB. | |||
11202 | /// For a cmp+sel min/max reduction check that both ops are in \p BB. | |||
11203 | static bool hasSameParent(Instruction *I, BasicBlock *BB) { | |||
11204 | if (isCmpSelMinMax(I) || isBoolLogicOp(I)) { | |||
11205 | auto *Sel = cast<SelectInst>(I); | |||
11206 | auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); | |||
11207 | return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; | |||
11208 | } | |||
11209 | return I->getParent() == BB; | |||
11210 | } | |||
11211 | ||||
11212 | /// Expected number of uses for reduction operations/reduced values. | |||
11213 | static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { | |||
11214 | if (IsCmpSelMinMax) { | |||
11215 | // SelectInst must be used twice while the condition op must have single | |||
11216 | // use only. | |||
11217 | if (auto *Sel = dyn_cast<SelectInst>(I)) | |||
11218 | return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); | |||
11219 | return I->hasNUses(2); | |||
11220 | } | |||
11221 | ||||
11222 | // Arithmetic reduction operation must be used once only. | |||
11223 | return I->hasOneUse(); | |||
11224 | } | |||
11225 | ||||
11226 | /// Initializes the list of reduction operations. | |||
11227 | void initReductionOps(Instruction *I) { | |||
11228 | if (isCmpSelMinMax(I)) | |||
11229 | ReductionOps.assign(2, ReductionOpsType()); | |||
11230 | else | |||
11231 | ReductionOps.assign(1, ReductionOpsType()); | |||
11232 | } | |||
11233 | ||||
11234 | /// Add all reduction operations for the reduction instruction \p I. | |||
11235 | void addReductionOps(Instruction *I) { | |||
11236 | if (isCmpSelMinMax(I)) { | |||
11237 | ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); | |||
11238 | ReductionOps[1].emplace_back(I); | |||
11239 | } else { | |||
11240 | ReductionOps[0].emplace_back(I); | |||
11241 | } | |||
11242 | } | |||
11243 | ||||
11244 | static Value *getLHS(RecurKind Kind, Instruction *I) { | |||
11245 | if (Kind == RecurKind::None) | |||
11246 | return nullptr; | |||
11247 | return I->getOperand(getFirstOperandIndex(I)); | |||
11248 | } | |||
11249 | static Value *getRHS(RecurKind Kind, Instruction *I) { | |||
11250 | if (Kind == RecurKind::None) | |||
11251 | return nullptr; | |||
11252 | return I->getOperand(getFirstOperandIndex(I) + 1); | |||
11253 | } | |||
11254 | ||||
11255 | static bool isGoodForReduction(ArrayRef<Value *> Data) { | |||
11256 | int Sz = Data.size(); | |||
11257 | auto *I = dyn_cast<Instruction>(Data.front()); | |||
11258 | return Sz > 1 || isConstant(Data.front()) || | |||
11259 | (I && !isa<LoadInst>(I) && isValidForAlternation(I->getOpcode())); | |||
11260 | } | |||
11261 | ||||
11262 | public: | |||
11263 | HorizontalReduction() = default; | |||
11264 | ||||
11265 | /// Try to find a reduction tree. | |||
11266 | bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst, | |||
11267 | ScalarEvolution &SE, const DataLayout &DL, | |||
11268 | const TargetLibraryInfo &TLI) { | |||
11269 | assert((!Phi || is_contained(Phi->operands(), Inst)) &&(static_cast <bool> ((!Phi || is_contained(Phi->operands (), Inst)) && "Phi needs to use the binary operator") ? void (0) : __assert_fail ("(!Phi || is_contained(Phi->operands(), Inst)) && \"Phi needs to use the binary operator\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11270, __extension__ __PRETTY_FUNCTION__)) | |||
11270 | "Phi needs to use the binary operator")(static_cast <bool> ((!Phi || is_contained(Phi->operands (), Inst)) && "Phi needs to use the binary operator") ? void (0) : __assert_fail ("(!Phi || is_contained(Phi->operands(), Inst)) && \"Phi needs to use the binary operator\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11270, __extension__ __PRETTY_FUNCTION__)); | |||
11271 | assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||(static_cast <bool> ((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || isa<IntrinsicInst>(Inst )) && "Expected binop, select, or intrinsic for reduction matching" ) ? void (0) : __assert_fail ("(isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || isa<IntrinsicInst>(Inst)) && \"Expected binop, select, or intrinsic for reduction matching\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11273, __extension__ __PRETTY_FUNCTION__)) | |||
11272 | isa<IntrinsicInst>(Inst)) &&(static_cast <bool> ((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || isa<IntrinsicInst>(Inst )) && "Expected binop, select, or intrinsic for reduction matching" ) ? void (0) : __assert_fail ("(isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || isa<IntrinsicInst>(Inst)) && \"Expected binop, select, or intrinsic for reduction matching\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11273, __extension__ __PRETTY_FUNCTION__)) | |||
11273 | "Expected binop, select, or intrinsic for reduction matching")(static_cast <bool> ((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || isa<IntrinsicInst>(Inst )) && "Expected binop, select, or intrinsic for reduction matching" ) ? void (0) : __assert_fail ("(isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || isa<IntrinsicInst>(Inst)) && \"Expected binop, select, or intrinsic for reduction matching\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11273, __extension__ __PRETTY_FUNCTION__)); | |||
11274 | RdxKind = getRdxKind(Inst); | |||
11275 | ||||
11276 | // We could have a initial reductions that is not an add. | |||
11277 | // r *= v1 + v2 + v3 + v4 | |||
11278 | // In such a case start looking for a tree rooted in the first '+'. | |||
11279 | if (Phi) { | |||
11280 | if (getLHS(RdxKind, Inst) == Phi) { | |||
11281 | Phi = nullptr; | |||
11282 | Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); | |||
11283 | if (!Inst) | |||
11284 | return false; | |||
11285 | RdxKind = getRdxKind(Inst); | |||
11286 | } else if (getRHS(RdxKind, Inst) == Phi) { | |||
11287 | Phi = nullptr; | |||
11288 | Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); | |||
11289 | if (!Inst) | |||
11290 | return false; | |||
11291 | RdxKind = getRdxKind(Inst); | |||
11292 | } | |||
11293 | } | |||
11294 | ||||
11295 | if (!isVectorizable(RdxKind, Inst)) | |||
11296 | return false; | |||
11297 | ||||
11298 | // Analyze "regular" integer/FP types for reductions - no target-specific | |||
11299 | // types or pointers. | |||
11300 | Type *Ty = Inst->getType(); | |||
11301 | if (!isValidElementType(Ty) || Ty->isPointerTy()) | |||
11302 | return false; | |||
11303 | ||||
11304 | // Though the ultimate reduction may have multiple uses, its condition must | |||
11305 | // have only single use. | |||
11306 | if (auto *Sel = dyn_cast<SelectInst>(Inst)) | |||
11307 | if (!Sel->getCondition()->hasOneUse()) | |||
11308 | return false; | |||
11309 | ||||
11310 | ReductionRoot = Inst; | |||
11311 | ||||
11312 | // Iterate through all the operands of the possible reduction tree and | |||
11313 | // gather all the reduced values, sorting them by their value id. | |||
11314 | BasicBlock *BB = Inst->getParent(); | |||
11315 | bool IsCmpSelMinMax = isCmpSelMinMax(Inst); | |||
11316 | SmallVector<Instruction *> Worklist(1, Inst); | |||
11317 | // Checks if the operands of the \p TreeN instruction are also reduction | |||
11318 | // operations or should be treated as reduced values or an extra argument, | |||
11319 | // which is not part of the reduction. | |||
11320 | auto &&CheckOperands = [this, IsCmpSelMinMax, | |||
11321 | BB](Instruction *TreeN, | |||
11322 | SmallVectorImpl<Value *> &ExtraArgs, | |||
11323 | SmallVectorImpl<Value *> &PossibleReducedVals, | |||
11324 | SmallVectorImpl<Instruction *> &ReductionOps) { | |||
11325 | for (int I = getFirstOperandIndex(TreeN), | |||
11326 | End = getNumberOfOperands(TreeN); | |||
11327 | I < End; ++I) { | |||
11328 | Value *EdgeVal = getRdxOperand(TreeN, I); | |||
11329 | ReducedValsToOps[EdgeVal].push_back(TreeN); | |||
11330 | auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); | |||
11331 | // Edge has wrong parent - mark as an extra argument. | |||
11332 | if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) && | |||
11333 | !hasSameParent(EdgeInst, BB)) { | |||
11334 | ExtraArgs.push_back(EdgeVal); | |||
11335 | continue; | |||
11336 | } | |||
11337 | // If the edge is not an instruction, or it is different from the main | |||
11338 | // reduction opcode or has too many uses - possible reduced value. | |||
11339 | if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind || | |||
11340 | IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) || | |||
11341 | !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) || | |||
11342 | !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) { | |||
11343 | PossibleReducedVals.push_back(EdgeVal); | |||
11344 | continue; | |||
11345 | } | |||
11346 | ReductionOps.push_back(EdgeInst); | |||
11347 | } | |||
11348 | }; | |||
11349 | // Try to regroup reduced values so that it gets more profitable to try to | |||
11350 | // reduce them. Values are grouped by their value ids, instructions - by | |||
11351 | // instruction op id and/or alternate op id, plus do extra analysis for | |||
11352 | // loads (grouping them by the distabce between pointers) and cmp | |||
11353 | // instructions (grouping them by the predicate). | |||
11354 | MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>> | |||
11355 | PossibleReducedVals; | |||
11356 | initReductionOps(Inst); | |||
11357 | DenseMap<Value *, SmallVector<LoadInst *>> LoadsMap; | |||
11358 | SmallSet<size_t, 2> LoadKeyUsed; | |||
11359 | SmallPtrSet<Value *, 4> DoNotReverseVals; | |||
11360 | while (!Worklist.empty()) { | |||
11361 | Instruction *TreeN = Worklist.pop_back_val(); | |||
11362 | SmallVector<Value *> Args; | |||
11363 | SmallVector<Value *> PossibleRedVals; | |||
11364 | SmallVector<Instruction *> PossibleReductionOps; | |||
11365 | CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps); | |||
11366 | // If too many extra args - mark the instruction itself as a reduction | |||
11367 | // value, not a reduction operation. | |||
11368 | if (Args.size() < 2) { | |||
11369 | addReductionOps(TreeN); | |||
11370 | // Add extra args. | |||
11371 | if (!Args.empty()) { | |||
11372 | assert(Args.size() == 1 && "Expected only single argument.")(static_cast <bool> (Args.size() == 1 && "Expected only single argument." ) ? void (0) : __assert_fail ("Args.size() == 1 && \"Expected only single argument.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11372, __extension__ __PRETTY_FUNCTION__)); | |||
11373 | ExtraArgs[TreeN] = Args.front(); | |||
11374 | } | |||
11375 | // Add reduction values. The values are sorted for better vectorization | |||
11376 | // results. | |||
11377 | for (Value *V : PossibleRedVals) { | |||
11378 | size_t Key, Idx; | |||
11379 | std::tie(Key, Idx) = generateKeySubkey( | |||
11380 | V, &TLI, | |||
11381 | [&](size_t Key, LoadInst *LI) { | |||
11382 | Value *Ptr = getUnderlyingObject(LI->getPointerOperand()); | |||
11383 | if (LoadKeyUsed.contains(Key)) { | |||
11384 | auto LIt = LoadsMap.find(Ptr); | |||
11385 | if (LIt != LoadsMap.end()) { | |||
11386 | for (LoadInst *RLI: LIt->second) { | |||
11387 | if (getPointersDiff( | |||
11388 | RLI->getType(), RLI->getPointerOperand(), | |||
11389 | LI->getType(), LI->getPointerOperand(), DL, SE, | |||
11390 | /*StrictCheck=*/true)) | |||
11391 | return hash_value(RLI->getPointerOperand()); | |||
11392 | } | |||
11393 | for (LoadInst *RLI : LIt->second) { | |||
11394 | if (arePointersCompatible(RLI->getPointerOperand(), | |||
11395 | LI->getPointerOperand(), TLI)) { | |||
11396 | hash_code SubKey = hash_value(RLI->getPointerOperand()); | |||
11397 | DoNotReverseVals.insert(RLI); | |||
11398 | return SubKey; | |||
11399 | } | |||
11400 | } | |||
11401 | if (LIt->second.size() > 2) { | |||
11402 | hash_code SubKey = | |||
11403 | hash_value(LIt->second.back()->getPointerOperand()); | |||
11404 | DoNotReverseVals.insert(LIt->second.back()); | |||
11405 | return SubKey; | |||
11406 | } | |||
11407 | } | |||
11408 | } | |||
11409 | LoadKeyUsed.insert(Key); | |||
11410 | LoadsMap.try_emplace(Ptr).first->second.push_back(LI); | |||
11411 | return hash_value(LI->getPointerOperand()); | |||
11412 | }, | |||
11413 | /*AllowAlternate=*/false); | |||
11414 | ++PossibleReducedVals[Key][Idx] | |||
11415 | .insert(std::make_pair(V, 0)) | |||
11416 | .first->second; | |||
11417 | } | |||
11418 | Worklist.append(PossibleReductionOps.rbegin(), | |||
11419 | PossibleReductionOps.rend()); | |||
11420 | } else { | |||
11421 | size_t Key, Idx; | |||
11422 | std::tie(Key, Idx) = generateKeySubkey( | |||
11423 | TreeN, &TLI, | |||
11424 | [&](size_t Key, LoadInst *LI) { | |||
11425 | Value *Ptr = getUnderlyingObject(LI->getPointerOperand()); | |||
11426 | if (LoadKeyUsed.contains(Key)) { | |||
11427 | auto LIt = LoadsMap.find(Ptr); | |||
11428 | if (LIt != LoadsMap.end()) { | |||
11429 | for (LoadInst *RLI: LIt->second) { | |||
11430 | if (getPointersDiff(RLI->getType(), | |||
11431 | RLI->getPointerOperand(), LI->getType(), | |||
11432 | LI->getPointerOperand(), DL, SE, | |||
11433 | /*StrictCheck=*/true)) | |||
11434 | return hash_value(RLI->getPointerOperand()); | |||
11435 | } | |||
11436 | for (LoadInst *RLI : LIt->second) { | |||
11437 | if (arePointersCompatible(RLI->getPointerOperand(), | |||
11438 | LI->getPointerOperand(), TLI)) { | |||
11439 | hash_code SubKey = hash_value(RLI->getPointerOperand()); | |||
11440 | DoNotReverseVals.insert(RLI); | |||
11441 | return SubKey; | |||
11442 | } | |||
11443 | } | |||
11444 | if (LIt->second.size() > 2) { | |||
11445 | hash_code SubKey = hash_value(LIt->second.back()->getPointerOperand()); | |||
11446 | DoNotReverseVals.insert(LIt->second.back()); | |||
11447 | return SubKey; | |||
11448 | } | |||
11449 | } | |||
11450 | } | |||
11451 | LoadKeyUsed.insert(Key); | |||
11452 | LoadsMap.try_emplace(Ptr).first->second.push_back(LI); | |||
11453 | return hash_value(LI->getPointerOperand()); | |||
11454 | }, | |||
11455 | /*AllowAlternate=*/false); | |||
11456 | ++PossibleReducedVals[Key][Idx] | |||
11457 | .insert(std::make_pair(TreeN, 0)) | |||
11458 | .first->second; | |||
11459 | } | |||
11460 | } | |||
11461 | auto PossibleReducedValsVect = PossibleReducedVals.takeVector(); | |||
11462 | // Sort values by the total number of values kinds to start the reduction | |||
11463 | // from the longest possible reduced values sequences. | |||
11464 | for (auto &PossibleReducedVals : PossibleReducedValsVect) { | |||
11465 | auto PossibleRedVals = PossibleReducedVals.second.takeVector(); | |||
11466 | SmallVector<SmallVector<Value *>> PossibleRedValsVect; | |||
11467 | for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end(); | |||
11468 | It != E; ++It) { | |||
11469 | PossibleRedValsVect.emplace_back(); | |||
11470 | auto RedValsVect = It->second.takeVector(); | |||
11471 | stable_sort(RedValsVect, llvm::less_second()); | |||
11472 | for (const std::pair<Value *, unsigned> &Data : RedValsVect) | |||
11473 | PossibleRedValsVect.back().append(Data.second, Data.first); | |||
11474 | } | |||
11475 | stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) { | |||
11476 | return P1.size() > P2.size(); | |||
11477 | }); | |||
11478 | int NewIdx = -1; | |||
11479 | for (ArrayRef<Value *> Data : PossibleRedValsVect) { | |||
11480 | if (isGoodForReduction(Data) || | |||
11481 | (isa<LoadInst>(Data.front()) && NewIdx >= 0 && | |||
11482 | isa<LoadInst>(ReducedVals[NewIdx].front()) && | |||
11483 | getUnderlyingObject( | |||
11484 | cast<LoadInst>(Data.front())->getPointerOperand()) == | |||
11485 | getUnderlyingObject(cast<LoadInst>(ReducedVals[NewIdx].front()) | |||
11486 | ->getPointerOperand()))) { | |||
11487 | if (NewIdx < 0) { | |||
11488 | NewIdx = ReducedVals.size(); | |||
11489 | ReducedVals.emplace_back(); | |||
11490 | } | |||
11491 | if (DoNotReverseVals.contains(Data.front())) | |||
11492 | ReducedVals[NewIdx].append(Data.begin(), Data.end()); | |||
11493 | else | |||
11494 | ReducedVals[NewIdx].append(Data.rbegin(), Data.rend()); | |||
11495 | } else { | |||
11496 | ReducedVals.emplace_back().append(Data.rbegin(), Data.rend()); | |||
11497 | } | |||
11498 | } | |||
11499 | } | |||
11500 | // Sort the reduced values by number of same/alternate opcode and/or pointer | |||
11501 | // operand. | |||
11502 | stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) { | |||
11503 | return P1.size() > P2.size(); | |||
11504 | }); | |||
11505 | return true; | |||
11506 | } | |||
11507 | ||||
11508 | /// Attempt to vectorize the tree found by matchAssociativeReduction. | |||
11509 | Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI, | |||
11510 | const TargetLibraryInfo &TLI) { | |||
11511 | constexpr int ReductionLimit = 4; | |||
11512 | constexpr unsigned RegMaxNumber = 4; | |||
11513 | constexpr unsigned RedValsMaxNumber = 128; | |||
11514 | // If there are a sufficient number of reduction values, reduce | |||
11515 | // to a nearby power-of-2. We can safely generate oversized | |||
11516 | // vectors and rely on the backend to split them to legal sizes. | |||
11517 | size_t NumReducedVals = | |||
11518 | std::accumulate(ReducedVals.begin(), ReducedVals.end(), 0, | |||
11519 | [](size_t Num, ArrayRef<Value *> Vals) { | |||
11520 | if (!isGoodForReduction(Vals)) | |||
11521 | return Num; | |||
11522 | return Num + Vals.size(); | |||
11523 | }); | |||
11524 | if (NumReducedVals < ReductionLimit) { | |||
11525 | for (ReductionOpsType &RdxOps : ReductionOps) | |||
11526 | for (Value *RdxOp : RdxOps) | |||
11527 | V.analyzedReductionRoot(cast<Instruction>(RdxOp)); | |||
11528 | return nullptr; | |||
11529 | } | |||
11530 | ||||
11531 | IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); | |||
11532 | ||||
11533 | // Track the reduced values in case if they are replaced by extractelement | |||
11534 | // because of the vectorization. | |||
11535 | DenseMap<Value *, WeakTrackingVH> TrackedVals( | |||
11536 | ReducedVals.size() * ReducedVals.front().size() + ExtraArgs.size()); | |||
11537 | BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; | |||
11538 | ExternallyUsedValues.reserve(ExtraArgs.size() + 1); | |||
11539 | // The same extra argument may be used several times, so log each attempt | |||
11540 | // to use it. | |||
11541 | for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { | |||
11542 | assert(Pair.first && "DebugLoc must be set.")(static_cast <bool> (Pair.first && "DebugLoc must be set." ) ? void (0) : __assert_fail ("Pair.first && \"DebugLoc must be set.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11542, __extension__ __PRETTY_FUNCTION__)); | |||
11543 | ExternallyUsedValues[Pair.second].push_back(Pair.first); | |||
11544 | TrackedVals.try_emplace(Pair.second, Pair.second); | |||
11545 | } | |||
11546 | ||||
11547 | // The compare instruction of a min/max is the insertion point for new | |||
11548 | // instructions and may be replaced with a new compare instruction. | |||
11549 | auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) { | |||
11550 | assert(isa<SelectInst>(RdxRootInst) &&(static_cast <bool> (isa<SelectInst>(RdxRootInst) && "Expected min/max reduction to have select root instruction" ) ? void (0) : __assert_fail ("isa<SelectInst>(RdxRootInst) && \"Expected min/max reduction to have select root instruction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11551, __extension__ __PRETTY_FUNCTION__)) | |||
11551 | "Expected min/max reduction to have select root instruction")(static_cast <bool> (isa<SelectInst>(RdxRootInst) && "Expected min/max reduction to have select root instruction" ) ? void (0) : __assert_fail ("isa<SelectInst>(RdxRootInst) && \"Expected min/max reduction to have select root instruction\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11551, __extension__ __PRETTY_FUNCTION__)); | |||
11552 | Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); | |||
11553 | assert(isa<Instruction>(ScalarCond) &&(static_cast <bool> (isa<Instruction>(ScalarCond) && "Expected min/max reduction to have compare condition" ) ? void (0) : __assert_fail ("isa<Instruction>(ScalarCond) && \"Expected min/max reduction to have compare condition\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11554, __extension__ __PRETTY_FUNCTION__)) | |||
11554 | "Expected min/max reduction to have compare condition")(static_cast <bool> (isa<Instruction>(ScalarCond) && "Expected min/max reduction to have compare condition" ) ? void (0) : __assert_fail ("isa<Instruction>(ScalarCond) && \"Expected min/max reduction to have compare condition\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11554, __extension__ __PRETTY_FUNCTION__)); | |||
11555 | return cast<Instruction>(ScalarCond); | |||
11556 | }; | |||
11557 | ||||
11558 | // The reduction root is used as the insertion point for new instructions, | |||
11559 | // so set it as externally used to prevent it from being deleted. | |||
11560 | ExternallyUsedValues[ReductionRoot]; | |||
11561 | SmallDenseSet<Value *> IgnoreList(ReductionOps.size() * | |||
11562 | ReductionOps.front().size()); | |||
11563 | for (ReductionOpsType &RdxOps : ReductionOps) | |||
11564 | for (Value *RdxOp : RdxOps) { | |||
11565 | if (!RdxOp) | |||
11566 | continue; | |||
11567 | IgnoreList.insert(RdxOp); | |||
11568 | } | |||
11569 | bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot)); | |||
11570 | ||||
11571 | // Need to track reduced vals, they may be changed during vectorization of | |||
11572 | // subvectors. | |||
11573 | for (ArrayRef<Value *> Candidates : ReducedVals) | |||
11574 | for (Value *V : Candidates) | |||
11575 | TrackedVals.try_emplace(V, V); | |||
11576 | ||||
11577 | DenseMap<Value *, unsigned> VectorizedVals(ReducedVals.size()); | |||
11578 | Value *VectorizedTree = nullptr; | |||
11579 | bool CheckForReusedReductionOps = false; | |||
11580 | // Try to vectorize elements based on their type. | |||
11581 | for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) { | |||
11582 | ArrayRef<Value *> OrigReducedVals = ReducedVals[I]; | |||
11583 | InstructionsState S = getSameOpcode(OrigReducedVals, TLI); | |||
11584 | SmallVector<Value *> Candidates; | |||
11585 | Candidates.reserve(2 * OrigReducedVals.size()); | |||
11586 | DenseMap<Value *, Value *> TrackedToOrig(2 * OrigReducedVals.size()); | |||
11587 | for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) { | |||
11588 | Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second; | |||
11589 | // Check if the reduction value was not overriden by the extractelement | |||
11590 | // instruction because of the vectorization and exclude it, if it is not | |||
11591 | // compatible with other values. | |||
11592 | if (auto *Inst = dyn_cast<Instruction>(RdxVal)) | |||
11593 | if (isVectorLikeInstWithConstOps(Inst) && | |||
11594 | (!S.getOpcode() || !S.isOpcodeOrAlt(Inst))) | |||
11595 | continue; | |||
11596 | Candidates.push_back(RdxVal); | |||
11597 | TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]); | |||
11598 | } | |||
11599 | bool ShuffledExtracts = false; | |||
11600 | // Try to handle shuffled extractelements. | |||
11601 | if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() && | |||
11602 | I + 1 < E) { | |||
11603 | InstructionsState NextS = getSameOpcode(ReducedVals[I + 1], TLI); | |||
11604 | if (NextS.getOpcode() == Instruction::ExtractElement && | |||
11605 | !NextS.isAltShuffle()) { | |||
11606 | SmallVector<Value *> CommonCandidates(Candidates); | |||
11607 | for (Value *RV : ReducedVals[I + 1]) { | |||
11608 | Value *RdxVal = TrackedVals.find(RV)->second; | |||
11609 | // Check if the reduction value was not overriden by the | |||
11610 | // extractelement instruction because of the vectorization and | |||
11611 | // exclude it, if it is not compatible with other values. | |||
11612 | if (auto *Inst = dyn_cast<Instruction>(RdxVal)) | |||
11613 | if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst)) | |||
11614 | continue; | |||
11615 | CommonCandidates.push_back(RdxVal); | |||
11616 | TrackedToOrig.try_emplace(RdxVal, RV); | |||
11617 | } | |||
11618 | SmallVector<int> Mask; | |||
11619 | if (isFixedVectorShuffle(CommonCandidates, Mask)) { | |||
11620 | ++I; | |||
11621 | Candidates.swap(CommonCandidates); | |||
11622 | ShuffledExtracts = true; | |||
11623 | } | |||
11624 | } | |||
11625 | } | |||
11626 | unsigned NumReducedVals = Candidates.size(); | |||
11627 | if (NumReducedVals < ReductionLimit) | |||
11628 | continue; | |||
11629 | ||||
11630 | unsigned MaxVecRegSize = V.getMaxVecRegSize(); | |||
11631 | unsigned EltSize = V.getVectorElementSize(Candidates[0]); | |||
11632 | unsigned MaxElts = RegMaxNumber * PowerOf2Floor(MaxVecRegSize / EltSize); | |||
11633 | ||||
11634 | unsigned ReduxWidth = std::min<unsigned>( | |||
11635 | PowerOf2Floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts)); | |||
11636 | unsigned Start = 0; | |||
11637 | unsigned Pos = Start; | |||
11638 | // Restarts vectorization attempt with lower vector factor. | |||
11639 | unsigned PrevReduxWidth = ReduxWidth; | |||
11640 | bool CheckForReusedReductionOpsLocal = false; | |||
11641 | auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals, | |||
11642 | &CheckForReusedReductionOpsLocal, | |||
11643 | &PrevReduxWidth, &V, | |||
11644 | &IgnoreList](bool IgnoreVL = false) { | |||
11645 | bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList); | |||
11646 | if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) { | |||
11647 | // Check if any of the reduction ops are gathered. If so, worth | |||
11648 | // trying again with less number of reduction ops. | |||
11649 | CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered; | |||
11650 | } | |||
11651 | ++Pos; | |||
11652 | if (Pos < NumReducedVals - ReduxWidth + 1) | |||
11653 | return IsAnyRedOpGathered; | |||
11654 | Pos = Start; | |||
11655 | ReduxWidth /= 2; | |||
11656 | return IsAnyRedOpGathered; | |||
11657 | }; | |||
11658 | while (Pos < NumReducedVals - ReduxWidth + 1 && | |||
11659 | ReduxWidth >= ReductionLimit) { | |||
11660 | // Dependency in tree of the reduction ops - drop this attempt, try | |||
11661 | // later. | |||
11662 | if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth && | |||
11663 | Start == 0) { | |||
11664 | CheckForReusedReductionOps = true; | |||
11665 | break; | |||
11666 | } | |||
11667 | PrevReduxWidth = ReduxWidth; | |||
11668 | ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth); | |||
11669 | // Beeing analyzed already - skip. | |||
11670 | if (V.areAnalyzedReductionVals(VL)) { | |||
11671 | (void)AdjustReducedVals(/*IgnoreVL=*/true); | |||
11672 | continue; | |||
11673 | } | |||
11674 | // Early exit if any of the reduction values were deleted during | |||
11675 | // previous vectorization attempts. | |||
11676 | if (any_of(VL, [&V](Value *RedVal) { | |||
11677 | auto *RedValI = dyn_cast<Instruction>(RedVal); | |||
11678 | if (!RedValI) | |||
11679 | return false; | |||
11680 | return V.isDeleted(RedValI); | |||
11681 | })) | |||
11682 | break; | |||
11683 | V.buildTree(VL, IgnoreList); | |||
11684 | if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) { | |||
11685 | if (!AdjustReducedVals()) | |||
11686 | V.analyzedReductionVals(VL); | |||
11687 | continue; | |||
11688 | } | |||
11689 | if (V.isLoadCombineReductionCandidate(RdxKind)) { | |||
11690 | if (!AdjustReducedVals()) | |||
11691 | V.analyzedReductionVals(VL); | |||
11692 | continue; | |||
11693 | } | |||
11694 | V.reorderTopToBottom(); | |||
11695 | // No need to reorder the root node at all. | |||
11696 | V.reorderBottomToTop(/*IgnoreReorder=*/true); | |||
11697 | // Keep extracted other reduction values, if they are used in the | |||
11698 | // vectorization trees. | |||
11699 | BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues( | |||
11700 | ExternallyUsedValues); | |||
11701 | for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) { | |||
11702 | if (Cnt == I || (ShuffledExtracts && Cnt == I - 1)) | |||
11703 | continue; | |||
11704 | for_each(ReducedVals[Cnt], | |||
11705 | [&LocalExternallyUsedValues, &TrackedVals](Value *V) { | |||
11706 | if (isa<Instruction>(V)) | |||
11707 | LocalExternallyUsedValues[TrackedVals[V]]; | |||
11708 | }); | |||
11709 | } | |||
11710 | // Number of uses of the candidates in the vector of values. | |||
11711 | SmallDenseMap<Value *, unsigned> NumUses(Candidates.size()); | |||
11712 | for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { | |||
11713 | Value *V = Candidates[Cnt]; | |||
11714 | ++NumUses.try_emplace(V, 0).first->getSecond(); | |||
11715 | } | |||
11716 | for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { | |||
11717 | Value *V = Candidates[Cnt]; | |||
11718 | ++NumUses.try_emplace(V, 0).first->getSecond(); | |||
11719 | } | |||
11720 | // Gather externally used values. | |||
11721 | SmallPtrSet<Value *, 4> Visited; | |||
11722 | for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { | |||
11723 | Value *V = Candidates[Cnt]; | |||
11724 | if (!Visited.insert(V).second) | |||
11725 | continue; | |||
11726 | unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; | |||
11727 | if (NumOps != ReducedValsToOps.find(V)->second.size()) | |||
11728 | LocalExternallyUsedValues[V]; | |||
11729 | } | |||
11730 | for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { | |||
11731 | Value *V = Candidates[Cnt]; | |||
11732 | if (!Visited.insert(V).second) | |||
11733 | continue; | |||
11734 | unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; | |||
11735 | if (NumOps != ReducedValsToOps.find(V)->second.size()) | |||
11736 | LocalExternallyUsedValues[V]; | |||
11737 | } | |||
11738 | V.buildExternalUses(LocalExternallyUsedValues); | |||
11739 | ||||
11740 | V.computeMinimumValueSizes(); | |||
11741 | ||||
11742 | // Intersect the fast-math-flags from all reduction operations. | |||
11743 | FastMathFlags RdxFMF; | |||
11744 | RdxFMF.set(); | |||
11745 | for (Value *U : IgnoreList) | |||
11746 | if (auto *FPMO = dyn_cast<FPMathOperator>(U)) | |||
11747 | RdxFMF &= FPMO->getFastMathFlags(); | |||
11748 | // Estimate cost. | |||
11749 | InstructionCost TreeCost = V.getTreeCost(VL); | |||
11750 | InstructionCost ReductionCost = | |||
11751 | getReductionCost(TTI, VL, ReduxWidth, RdxFMF); | |||
11752 | if (V.isVectorizedFirstNode() && isa<LoadInst>(VL.front())) { | |||
11753 | Instruction *MainOp = V.getFirstNodeMainOp(); | |||
11754 | for (Value *V : VL) { | |||
11755 | auto *VI = dyn_cast<LoadInst>(V); | |||
11756 | // Add the costs of scalar GEP pointers, to be removed from the | |||
11757 | // code. | |||
11758 | if (!VI || VI == MainOp) | |||
11759 | continue; | |||
11760 | auto *Ptr = dyn_cast<GetElementPtrInst>(VI->getPointerOperand()); | |||
11761 | if (!Ptr || !Ptr->hasOneUse() || Ptr->hasAllConstantIndices()) | |||
11762 | continue; | |||
11763 | TreeCost -= TTI->getArithmeticInstrCost( | |||
11764 | Instruction::Add, Ptr->getType(), TTI::TCK_RecipThroughput); | |||
11765 | } | |||
11766 | } | |||
11767 | InstructionCost Cost = TreeCost + ReductionCost; | |||
11768 | LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for reduction\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Found cost = " << Cost << " for reduction\n"; } } while (false); | |||
11769 | if (!Cost.isValid()) | |||
11770 | return nullptr; | |||
11771 | if (Cost >= -SLPCostThreshold) { | |||
11772 | V.getORE()->emit([&]() { | |||
11773 | return OptimizationRemarkMissed( | |||
11774 | SV_NAME"slp-vectorizer", "HorSLPNotBeneficial", | |||
11775 | ReducedValsToOps.find(VL[0])->second.front()) | |||
11776 | << "Vectorizing horizontal reduction is possible " | |||
11777 | << "but not beneficial with cost " << ore::NV("Cost", Cost) | |||
11778 | << " and threshold " | |||
11779 | << ore::NV("Threshold", -SLPCostThreshold); | |||
11780 | }); | |||
11781 | if (!AdjustReducedVals()) | |||
11782 | V.analyzedReductionVals(VL); | |||
11783 | continue; | |||
11784 | } | |||
11785 | ||||
11786 | LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost << ". (HorRdx)\n"; } } while (false) | |||
11787 | << Cost << ". (HorRdx)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost << ". (HorRdx)\n"; } } while (false); | |||
11788 | V.getORE()->emit([&]() { | |||
11789 | return OptimizationRemark( | |||
11790 | SV_NAME"slp-vectorizer", "VectorizedHorizontalReduction", | |||
11791 | ReducedValsToOps.find(VL[0])->second.front()) | |||
11792 | << "Vectorized horizontal reduction with cost " | |||
11793 | << ore::NV("Cost", Cost) << " and with tree size " | |||
11794 | << ore::NV("TreeSize", V.getTreeSize()); | |||
11795 | }); | |||
11796 | ||||
11797 | Builder.setFastMathFlags(RdxFMF); | |||
11798 | ||||
11799 | // Vectorize a tree. | |||
11800 | Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues); | |||
11801 | ||||
11802 | // Emit a reduction. If the root is a select (min/max idiom), the insert | |||
11803 | // point is the compare condition of that select. | |||
11804 | Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); | |||
11805 | if (IsCmpSelMinMax) | |||
11806 | Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst)); | |||
11807 | else | |||
11808 | Builder.SetInsertPoint(RdxRootInst); | |||
11809 | ||||
11810 | // To prevent poison from leaking across what used to be sequential, | |||
11811 | // safe, scalar boolean logic operations, the reduction operand must be | |||
11812 | // frozen. | |||
11813 | if (isBoolLogicOp(RdxRootInst)) | |||
11814 | VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); | |||
11815 | ||||
11816 | Value *ReducedSubTree = | |||
11817 | emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); | |||
11818 | ||||
11819 | if (!VectorizedTree) { | |||
11820 | // Initialize the final value in the reduction. | |||
11821 | VectorizedTree = ReducedSubTree; | |||
11822 | } else { | |||
11823 | // Update the final value in the reduction. | |||
11824 | Builder.SetCurrentDebugLocation( | |||
11825 | cast<Instruction>(ReductionOps.front().front())->getDebugLoc()); | |||
11826 | VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, | |||
11827 | ReducedSubTree, "op.rdx", ReductionOps); | |||
11828 | } | |||
11829 | // Count vectorized reduced values to exclude them from final reduction. | |||
11830 | for (Value *V : VL) | |||
11831 | ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0) | |||
11832 | .first->getSecond(); | |||
11833 | Pos += ReduxWidth; | |||
11834 | Start = Pos; | |||
11835 | ReduxWidth = PowerOf2Floor(NumReducedVals - Pos); | |||
11836 | } | |||
11837 | } | |||
11838 | if (VectorizedTree) { | |||
11839 | // Reorder operands of bool logical op in the natural order to avoid | |||
11840 | // possible problem with poison propagation. If not possible to reorder | |||
11841 | // (both operands are originally RHS), emit an extra freeze instruction | |||
11842 | // for the LHS operand. | |||
11843 | //I.e., if we have original code like this: | |||
11844 | // RedOp1 = select i1 ?, i1 LHS, i1 false | |||
11845 | // RedOp2 = select i1 RHS, i1 ?, i1 false | |||
11846 | ||||
11847 | // Then, we swap LHS/RHS to create a new op that matches the poison | |||
11848 | // semantics of the original code. | |||
11849 | ||||
11850 | // If we have original code like this and both values could be poison: | |||
11851 | // RedOp1 = select i1 ?, i1 LHS, i1 false | |||
11852 | // RedOp2 = select i1 ?, i1 RHS, i1 false | |||
11853 | ||||
11854 | // Then, we must freeze LHS in the new op. | |||
11855 | auto &&FixBoolLogicalOps = | |||
11856 | [&Builder, VectorizedTree](Value *&LHS, Value *&RHS, | |||
11857 | Instruction *RedOp1, Instruction *RedOp2) { | |||
11858 | if (!isBoolLogicOp(RedOp1)) | |||
11859 | return; | |||
11860 | if (LHS == VectorizedTree || getRdxOperand(RedOp1, 0) == LHS || | |||
11861 | isGuaranteedNotToBePoison(LHS)) | |||
11862 | return; | |||
11863 | if (!isBoolLogicOp(RedOp2)) | |||
11864 | return; | |||
11865 | if (RHS == VectorizedTree || getRdxOperand(RedOp2, 0) == RHS || | |||
11866 | isGuaranteedNotToBePoison(RHS)) { | |||
11867 | std::swap(LHS, RHS); | |||
11868 | return; | |||
11869 | } | |||
11870 | LHS = Builder.CreateFreeze(LHS); | |||
11871 | }; | |||
11872 | // Finish the reduction. | |||
11873 | // Need to add extra arguments and not vectorized possible reduction | |||
11874 | // values. | |||
11875 | // Try to avoid dependencies between the scalar remainders after | |||
11876 | // reductions. | |||
11877 | auto &&FinalGen = | |||
11878 | [this, &Builder, &TrackedVals, &FixBoolLogicalOps]( | |||
11879 | ArrayRef<std::pair<Instruction *, Value *>> InstVals) { | |||
11880 | unsigned Sz = InstVals.size(); | |||
11881 | SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 + | |||
11882 | Sz % 2); | |||
11883 | for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) { | |||
11884 | Instruction *RedOp = InstVals[I + 1].first; | |||
11885 | Builder.SetCurrentDebugLocation(RedOp->getDebugLoc()); | |||
11886 | Value *RdxVal1 = InstVals[I].second; | |||
11887 | Value *StableRdxVal1 = RdxVal1; | |||
11888 | auto It1 = TrackedVals.find(RdxVal1); | |||
11889 | if (It1 != TrackedVals.end()) | |||
11890 | StableRdxVal1 = It1->second; | |||
11891 | Value *RdxVal2 = InstVals[I + 1].second; | |||
11892 | Value *StableRdxVal2 = RdxVal2; | |||
11893 | auto It2 = TrackedVals.find(RdxVal2); | |||
11894 | if (It2 != TrackedVals.end()) | |||
11895 | StableRdxVal2 = It2->second; | |||
11896 | // To prevent poison from leaking across what used to be | |||
11897 | // sequential, safe, scalar boolean logic operations, the | |||
11898 | // reduction operand must be frozen. | |||
11899 | FixBoolLogicalOps(StableRdxVal1, StableRdxVal2, InstVals[I].first, | |||
11900 | RedOp); | |||
11901 | Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1, | |||
11902 | StableRdxVal2, "op.rdx", ReductionOps); | |||
11903 | ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed); | |||
11904 | } | |||
11905 | if (Sz % 2 == 1) | |||
11906 | ExtraReds[Sz / 2] = InstVals.back(); | |||
11907 | return ExtraReds; | |||
11908 | }; | |||
11909 | SmallVector<std::pair<Instruction *, Value *>> ExtraReductions; | |||
11910 | ExtraReductions.emplace_back(cast<Instruction>(ReductionRoot), | |||
11911 | VectorizedTree); | |||
11912 | SmallPtrSet<Value *, 8> Visited; | |||
11913 | for (ArrayRef<Value *> Candidates : ReducedVals) { | |||
11914 | for (Value *RdxVal : Candidates) { | |||
11915 | if (!Visited.insert(RdxVal).second) | |||
11916 | continue; | |||
11917 | unsigned NumOps = VectorizedVals.lookup(RdxVal); | |||
11918 | for (Instruction *RedOp : | |||
11919 | makeArrayRef(ReducedValsToOps.find(RdxVal)->second) | |||
11920 | .drop_back(NumOps)) | |||
11921 | ExtraReductions.emplace_back(RedOp, RdxVal); | |||
11922 | } | |||
11923 | } | |||
11924 | for (auto &Pair : ExternallyUsedValues) { | |||
11925 | // Add each externally used value to the final reduction. | |||
11926 | for (auto *I : Pair.second) | |||
11927 | ExtraReductions.emplace_back(I, Pair.first); | |||
11928 | } | |||
11929 | // Iterate through all not-vectorized reduction values/extra arguments. | |||
11930 | while (ExtraReductions.size() > 1) { | |||
11931 | VectorizedTree = ExtraReductions.front().second; | |||
11932 | SmallVector<std::pair<Instruction *, Value *>> NewReds = | |||
11933 | FinalGen(ExtraReductions); | |||
11934 | ExtraReductions.swap(NewReds); | |||
11935 | } | |||
11936 | VectorizedTree = ExtraReductions.front().second; | |||
11937 | ||||
11938 | ReductionRoot->replaceAllUsesWith(VectorizedTree); | |||
11939 | ||||
11940 | // The original scalar reduction is expected to have no remaining | |||
11941 | // uses outside the reduction tree itself. Assert that we got this | |||
11942 | // correct, replace internal uses with undef, and mark for eventual | |||
11943 | // deletion. | |||
11944 | #ifndef NDEBUG | |||
11945 | SmallSet<Value *, 4> IgnoreSet; | |||
11946 | for (ArrayRef<Value *> RdxOps : ReductionOps) | |||
11947 | IgnoreSet.insert(RdxOps.begin(), RdxOps.end()); | |||
11948 | #endif | |||
11949 | for (ArrayRef<Value *> RdxOps : ReductionOps) { | |||
11950 | for (Value *Ignore : RdxOps) { | |||
11951 | if (!Ignore) | |||
11952 | continue; | |||
11953 | #ifndef NDEBUG | |||
11954 | for (auto *U : Ignore->users()) { | |||
11955 | assert(IgnoreSet.count(U) &&(static_cast <bool> (IgnoreSet.count(U) && "All users must be either in the reduction ops list." ) ? void (0) : __assert_fail ("IgnoreSet.count(U) && \"All users must be either in the reduction ops list.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11956, __extension__ __PRETTY_FUNCTION__)) | |||
11956 | "All users must be either in the reduction ops list.")(static_cast <bool> (IgnoreSet.count(U) && "All users must be either in the reduction ops list." ) ? void (0) : __assert_fail ("IgnoreSet.count(U) && \"All users must be either in the reduction ops list.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 11956, __extension__ __PRETTY_FUNCTION__)); | |||
11957 | } | |||
11958 | #endif | |||
11959 | if (!Ignore->use_empty()) { | |||
11960 | Value *Undef = UndefValue::get(Ignore->getType()); | |||
11961 | Ignore->replaceAllUsesWith(Undef); | |||
11962 | } | |||
11963 | V.eraseInstruction(cast<Instruction>(Ignore)); | |||
11964 | } | |||
11965 | } | |||
11966 | } else if (!CheckForReusedReductionOps) { | |||
11967 | for (ReductionOpsType &RdxOps : ReductionOps) | |||
11968 | for (Value *RdxOp : RdxOps) | |||
11969 | V.analyzedReductionRoot(cast<Instruction>(RdxOp)); | |||
11970 | } | |||
11971 | return VectorizedTree; | |||
11972 | } | |||
11973 | ||||
11974 | private: | |||
11975 | /// Calculate the cost of a reduction. | |||
11976 | InstructionCost getReductionCost(TargetTransformInfo *TTI, | |||
11977 | ArrayRef<Value *> ReducedVals, | |||
11978 | unsigned ReduxWidth, FastMathFlags FMF) { | |||
11979 | TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; | |||
11980 | Value *FirstReducedVal = ReducedVals.front(); | |||
11981 | Type *ScalarTy = FirstReducedVal->getType(); | |||
11982 | FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); | |||
11983 | InstructionCost VectorCost = 0, ScalarCost; | |||
11984 | // If all of the reduced values are constant, the vector cost is 0, since | |||
11985 | // the reduction value can be calculated at the compile time. | |||
11986 | bool AllConsts = all_of(ReducedVals, isConstant); | |||
11987 | switch (RdxKind) { | |||
11988 | case RecurKind::Add: | |||
11989 | case RecurKind::Mul: | |||
11990 | case RecurKind::Or: | |||
11991 | case RecurKind::And: | |||
11992 | case RecurKind::Xor: | |||
11993 | case RecurKind::FAdd: | |||
11994 | case RecurKind::FMul: { | |||
11995 | unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); | |||
11996 | if (!AllConsts) | |||
11997 | VectorCost = | |||
11998 | TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); | |||
11999 | ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); | |||
12000 | break; | |||
12001 | } | |||
12002 | case RecurKind::FMax: | |||
12003 | case RecurKind::FMin: { | |||
12004 | auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); | |||
12005 | if (!AllConsts) { | |||
12006 | auto *VecCondTy = | |||
12007 | cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); | |||
12008 | VectorCost = | |||
12009 | TTI->getMinMaxReductionCost(VectorTy, VecCondTy, | |||
12010 | /*IsUnsigned=*/false, CostKind); | |||
12011 | } | |||
12012 | CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); | |||
12013 | ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, | |||
12014 | SclCondTy, RdxPred, CostKind) + | |||
12015 | TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, | |||
12016 | SclCondTy, RdxPred, CostKind); | |||
12017 | break; | |||
12018 | } | |||
12019 | case RecurKind::SMax: | |||
12020 | case RecurKind::SMin: | |||
12021 | case RecurKind::UMax: | |||
12022 | case RecurKind::UMin: { | |||
12023 | auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); | |||
12024 | if (!AllConsts) { | |||
12025 | auto *VecCondTy = | |||
12026 | cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); | |||
12027 | bool IsUnsigned = | |||
12028 | RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; | |||
12029 | VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, | |||
12030 | IsUnsigned, CostKind); | |||
12031 | } | |||
12032 | CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); | |||
12033 | ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, | |||
12034 | SclCondTy, RdxPred, CostKind) + | |||
12035 | TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, | |||
12036 | SclCondTy, RdxPred, CostKind); | |||
12037 | break; | |||
12038 | } | |||
12039 | default: | |||
12040 | llvm_unreachable("Expected arithmetic or min/max reduction operation")::llvm::llvm_unreachable_internal("Expected arithmetic or min/max reduction operation" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12040); | |||
12041 | } | |||
12042 | ||||
12043 | // Scalar cost is repeated for N-1 elements. | |||
12044 | ScalarCost *= (ReduxWidth - 1); | |||
12045 | LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost << " for reduction that starts with " << *FirstReducedVal << " (It is a splitting reduction)\n" ; } } while (false) | |||
12046 | << " for reduction that starts with " << *FirstReducedValdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost << " for reduction that starts with " << *FirstReducedVal << " (It is a splitting reduction)\n" ; } } while (false) | |||
12047 | << " (It is a splitting reduction)\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost << " for reduction that starts with " << *FirstReducedVal << " (It is a splitting reduction)\n" ; } } while (false); | |||
12048 | return VectorCost - ScalarCost; | |||
12049 | } | |||
12050 | ||||
12051 | /// Emit a horizontal reduction of the vectorized value. | |||
12052 | Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, | |||
12053 | unsigned ReduxWidth, const TargetTransformInfo *TTI) { | |||
12054 | assert(VectorizedValue && "Need to have a vectorized tree node")(static_cast <bool> (VectorizedValue && "Need to have a vectorized tree node" ) ? void (0) : __assert_fail ("VectorizedValue && \"Need to have a vectorized tree node\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12054, __extension__ __PRETTY_FUNCTION__)); | |||
12055 | assert(isPowerOf2_32(ReduxWidth) &&(static_cast <bool> (isPowerOf2_32(ReduxWidth) && "We only handle power-of-two reductions for now") ? void (0) : __assert_fail ("isPowerOf2_32(ReduxWidth) && \"We only handle power-of-two reductions for now\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12056, __extension__ __PRETTY_FUNCTION__)) | |||
12056 | "We only handle power-of-two reductions for now")(static_cast <bool> (isPowerOf2_32(ReduxWidth) && "We only handle power-of-two reductions for now") ? void (0) : __assert_fail ("isPowerOf2_32(ReduxWidth) && \"We only handle power-of-two reductions for now\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12056, __extension__ __PRETTY_FUNCTION__)); | |||
12057 | assert(RdxKind != RecurKind::FMulAdd &&(static_cast <bool> (RdxKind != RecurKind::FMulAdd && "A call to the llvm.fmuladd intrinsic is not handled yet") ? void (0) : __assert_fail ("RdxKind != RecurKind::FMulAdd && \"A call to the llvm.fmuladd intrinsic is not handled yet\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12058, __extension__ __PRETTY_FUNCTION__)) | |||
12058 | "A call to the llvm.fmuladd intrinsic is not handled yet")(static_cast <bool> (RdxKind != RecurKind::FMulAdd && "A call to the llvm.fmuladd intrinsic is not handled yet") ? void (0) : __assert_fail ("RdxKind != RecurKind::FMulAdd && \"A call to the llvm.fmuladd intrinsic is not handled yet\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12058, __extension__ __PRETTY_FUNCTION__)); | |||
12059 | ||||
12060 | ++NumVectorInstructions; | |||
12061 | return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); | |||
12062 | } | |||
12063 | }; | |||
12064 | ||||
12065 | } // end anonymous namespace | |||
12066 | ||||
12067 | static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { | |||
12068 | if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) | |||
12069 | return cast<FixedVectorType>(IE->getType())->getNumElements(); | |||
12070 | ||||
12071 | unsigned AggregateSize = 1; | |||
12072 | auto *IV = cast<InsertValueInst>(InsertInst); | |||
12073 | Type *CurrentType = IV->getType(); | |||
12074 | do { | |||
12075 | if (auto *ST = dyn_cast<StructType>(CurrentType)) { | |||
12076 | for (auto *Elt : ST->elements()) | |||
12077 | if (Elt != ST->getElementType(0)) // check homogeneity | |||
12078 | return None; | |||
12079 | AggregateSize *= ST->getNumElements(); | |||
12080 | CurrentType = ST->getElementType(0); | |||
12081 | } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { | |||
12082 | AggregateSize *= AT->getNumElements(); | |||
12083 | CurrentType = AT->getElementType(); | |||
12084 | } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { | |||
12085 | AggregateSize *= VT->getNumElements(); | |||
12086 | return AggregateSize; | |||
12087 | } else if (CurrentType->isSingleValueType()) { | |||
12088 | return AggregateSize; | |||
12089 | } else { | |||
12090 | return None; | |||
12091 | } | |||
12092 | } while (true); | |||
12093 | } | |||
12094 | ||||
12095 | static void findBuildAggregate_rec(Instruction *LastInsertInst, | |||
12096 | TargetTransformInfo *TTI, | |||
12097 | SmallVectorImpl<Value *> &BuildVectorOpds, | |||
12098 | SmallVectorImpl<Value *> &InsertElts, | |||
12099 | unsigned OperandOffset) { | |||
12100 | do { | |||
12101 | Value *InsertedOperand = LastInsertInst->getOperand(1); | |||
12102 | Optional<unsigned> OperandIndex = | |||
12103 | getInsertIndex(LastInsertInst, OperandOffset); | |||
12104 | if (!OperandIndex) | |||
12105 | return; | |||
12106 | if (isa<InsertElementInst, InsertValueInst>(InsertedOperand)) { | |||
12107 | findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, | |||
12108 | BuildVectorOpds, InsertElts, *OperandIndex); | |||
12109 | ||||
12110 | } else { | |||
12111 | BuildVectorOpds[*OperandIndex] = InsertedOperand; | |||
12112 | InsertElts[*OperandIndex] = LastInsertInst; | |||
12113 | } | |||
12114 | LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); | |||
12115 | } while (LastInsertInst != nullptr && | |||
12116 | isa<InsertValueInst, InsertElementInst>(LastInsertInst) && | |||
12117 | LastInsertInst->hasOneUse()); | |||
12118 | } | |||
12119 | ||||
12120 | /// Recognize construction of vectors like | |||
12121 | /// %ra = insertelement <4 x float> poison, float %s0, i32 0 | |||
12122 | /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 | |||
12123 | /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 | |||
12124 | /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 | |||
12125 | /// starting from the last insertelement or insertvalue instruction. | |||
12126 | /// | |||
12127 | /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, | |||
12128 | /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. | |||
12129 | /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. | |||
12130 | /// | |||
12131 | /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. | |||
12132 | /// | |||
12133 | /// \return true if it matches. | |||
12134 | static bool findBuildAggregate(Instruction *LastInsertInst, | |||
12135 | TargetTransformInfo *TTI, | |||
12136 | SmallVectorImpl<Value *> &BuildVectorOpds, | |||
12137 | SmallVectorImpl<Value *> &InsertElts) { | |||
12138 | ||||
12139 | assert((isa<InsertElementInst>(LastInsertInst) ||(static_cast <bool> ((isa<InsertElementInst>(LastInsertInst ) || isa<InsertValueInst>(LastInsertInst)) && "Expected insertelement or insertvalue instruction!" ) ? void (0) : __assert_fail ("(isa<InsertElementInst>(LastInsertInst) || isa<InsertValueInst>(LastInsertInst)) && \"Expected insertelement or insertvalue instruction!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12141, __extension__ __PRETTY_FUNCTION__)) | |||
12140 | isa<InsertValueInst>(LastInsertInst)) &&(static_cast <bool> ((isa<InsertElementInst>(LastInsertInst ) || isa<InsertValueInst>(LastInsertInst)) && "Expected insertelement or insertvalue instruction!" ) ? void (0) : __assert_fail ("(isa<InsertElementInst>(LastInsertInst) || isa<InsertValueInst>(LastInsertInst)) && \"Expected insertelement or insertvalue instruction!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12141, __extension__ __PRETTY_FUNCTION__)) | |||
12141 | "Expected insertelement or insertvalue instruction!")(static_cast <bool> ((isa<InsertElementInst>(LastInsertInst ) || isa<InsertValueInst>(LastInsertInst)) && "Expected insertelement or insertvalue instruction!" ) ? void (0) : __assert_fail ("(isa<InsertElementInst>(LastInsertInst) || isa<InsertValueInst>(LastInsertInst)) && \"Expected insertelement or insertvalue instruction!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12141, __extension__ __PRETTY_FUNCTION__)); | |||
12142 | ||||
12143 | assert((BuildVectorOpds.empty() && InsertElts.empty()) &&(static_cast <bool> ((BuildVectorOpds.empty() && InsertElts.empty()) && "Expected empty result vectors!" ) ? void (0) : __assert_fail ("(BuildVectorOpds.empty() && InsertElts.empty()) && \"Expected empty result vectors!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12144, __extension__ __PRETTY_FUNCTION__)) | |||
12144 | "Expected empty result vectors!")(static_cast <bool> ((BuildVectorOpds.empty() && InsertElts.empty()) && "Expected empty result vectors!" ) ? void (0) : __assert_fail ("(BuildVectorOpds.empty() && InsertElts.empty()) && \"Expected empty result vectors!\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12144, __extension__ __PRETTY_FUNCTION__)); | |||
12145 | ||||
12146 | Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); | |||
12147 | if (!AggregateSize) | |||
12148 | return false; | |||
12149 | BuildVectorOpds.resize(*AggregateSize); | |||
12150 | InsertElts.resize(*AggregateSize); | |||
12151 | ||||
12152 | findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0); | |||
12153 | llvm::erase_value(BuildVectorOpds, nullptr); | |||
12154 | llvm::erase_value(InsertElts, nullptr); | |||
12155 | if (BuildVectorOpds.size() >= 2) | |||
12156 | return true; | |||
12157 | ||||
12158 | return false; | |||
12159 | } | |||
12160 | ||||
12161 | /// Try and get a reduction value from a phi node. | |||
12162 | /// | |||
12163 | /// Given a phi node \p P in a block \p ParentBB, consider possible reductions | |||
12164 | /// if they come from either \p ParentBB or a containing loop latch. | |||
12165 | /// | |||
12166 | /// \returns A candidate reduction value if possible, or \code nullptr \endcode | |||
12167 | /// if not possible. | |||
12168 | static Value *getReductionValue(const DominatorTree *DT, PHINode *P, | |||
12169 | BasicBlock *ParentBB, LoopInfo *LI) { | |||
12170 | // There are situations where the reduction value is not dominated by the | |||
12171 | // reduction phi. Vectorizing such cases has been reported to cause | |||
12172 | // miscompiles. See PR25787. | |||
12173 | auto DominatedReduxValue = [&](Value *R) { | |||
12174 | return isa<Instruction>(R) && | |||
12175 | DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); | |||
12176 | }; | |||
12177 | ||||
12178 | Value *Rdx = nullptr; | |||
12179 | ||||
12180 | // Return the incoming value if it comes from the same BB as the phi node. | |||
12181 | if (P->getIncomingBlock(0) == ParentBB) { | |||
12182 | Rdx = P->getIncomingValue(0); | |||
12183 | } else if (P->getIncomingBlock(1) == ParentBB) { | |||
12184 | Rdx = P->getIncomingValue(1); | |||
12185 | } | |||
12186 | ||||
12187 | if (Rdx && DominatedReduxValue(Rdx)) | |||
12188 | return Rdx; | |||
12189 | ||||
12190 | // Otherwise, check whether we have a loop latch to look at. | |||
12191 | Loop *BBL = LI->getLoopFor(ParentBB); | |||
12192 | if (!BBL) | |||
12193 | return nullptr; | |||
12194 | BasicBlock *BBLatch = BBL->getLoopLatch(); | |||
12195 | if (!BBLatch) | |||
12196 | return nullptr; | |||
12197 | ||||
12198 | // There is a loop latch, return the incoming value if it comes from | |||
12199 | // that. This reduction pattern occasionally turns up. | |||
12200 | if (P->getIncomingBlock(0) == BBLatch) { | |||
12201 | Rdx = P->getIncomingValue(0); | |||
12202 | } else if (P->getIncomingBlock(1) == BBLatch) { | |||
12203 | Rdx = P->getIncomingValue(1); | |||
12204 | } | |||
12205 | ||||
12206 | if (Rdx && DominatedReduxValue(Rdx)) | |||
12207 | return Rdx; | |||
12208 | ||||
12209 | return nullptr; | |||
12210 | } | |||
12211 | ||||
12212 | static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { | |||
12213 | if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) | |||
12214 | return true; | |||
12215 | if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) | |||
12216 | return true; | |||
12217 | if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) | |||
12218 | return true; | |||
12219 | if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) | |||
12220 | return true; | |||
12221 | if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) | |||
12222 | return true; | |||
12223 | if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) | |||
12224 | return true; | |||
12225 | if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) | |||
12226 | return true; | |||
12227 | return false; | |||
12228 | } | |||
12229 | ||||
12230 | bool SLPVectorizerPass::vectorizeHorReduction( | |||
12231 | PHINode *P, Value *V, BasicBlock *BB, BoUpSLP &R, TargetTransformInfo *TTI, | |||
12232 | SmallVectorImpl<WeakTrackingVH> &PostponedInsts) { | |||
12233 | if (!ShouldVectorizeHor) | |||
12234 | return false; | |||
12235 | ||||
12236 | auto *Root = dyn_cast_or_null<Instruction>(V); | |||
12237 | if (!Root) | |||
12238 | return false; | |||
12239 | ||||
12240 | if (!isa<BinaryOperator>(Root)) | |||
12241 | P = nullptr; | |||
12242 | ||||
12243 | if (Root->getParent() != BB || isa<PHINode>(Root)) | |||
12244 | return false; | |||
12245 | // Start analysis starting from Root instruction. If horizontal reduction is | |||
12246 | // found, try to vectorize it. If it is not a horizontal reduction or | |||
12247 | // vectorization is not possible or not effective, and currently analyzed | |||
12248 | // instruction is a binary operation, try to vectorize the operands, using | |||
12249 | // pre-order DFS traversal order. If the operands were not vectorized, repeat | |||
12250 | // the same procedure considering each operand as a possible root of the | |||
12251 | // horizontal reduction. | |||
12252 | // Interrupt the process if the Root instruction itself was vectorized or all | |||
12253 | // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. | |||
12254 | // If a horizintal reduction was not matched or vectorized we collect | |||
12255 | // instructions for possible later attempts for vectorization. | |||
12256 | std::queue<std::pair<Instruction *, unsigned>> Stack; | |||
12257 | Stack.emplace(Root, 0); | |||
12258 | SmallPtrSet<Value *, 8> VisitedInstrs; | |||
12259 | bool Res = false; | |||
12260 | auto &&TryToReduce = [this, TTI, &P, &R](Instruction *Inst, Value *&B0, | |||
12261 | Value *&B1) -> Value * { | |||
12262 | if (R.isAnalyzedReductionRoot(Inst)) | |||
12263 | return nullptr; | |||
12264 | bool IsBinop = matchRdxBop(Inst, B0, B1); | |||
12265 | bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); | |||
12266 | if (IsBinop || IsSelect) { | |||
12267 | HorizontalReduction HorRdx; | |||
12268 | if (HorRdx.matchAssociativeReduction(P, Inst, *SE, *DL, *TLI)) | |||
12269 | return HorRdx.tryToReduce(R, TTI, *TLI); | |||
12270 | } | |||
12271 | return nullptr; | |||
12272 | }; | |||
12273 | while (!Stack.empty()) { | |||
12274 | Instruction *Inst; | |||
12275 | unsigned Level; | |||
12276 | std::tie(Inst, Level) = Stack.front(); | |||
12277 | Stack.pop(); | |||
12278 | // Do not try to analyze instruction that has already been vectorized. | |||
12279 | // This may happen when we vectorize instruction operands on a previous | |||
12280 | // iteration while stack was populated before that happened. | |||
12281 | if (R.isDeleted(Inst)) | |||
12282 | continue; | |||
12283 | Value *B0 = nullptr, *B1 = nullptr; | |||
12284 | if (Value *V = TryToReduce(Inst, B0, B1)) { | |||
12285 | Res = true; | |||
12286 | // Set P to nullptr to avoid re-analysis of phi node in | |||
12287 | // matchAssociativeReduction function unless this is the root node. | |||
12288 | P = nullptr; | |||
12289 | if (auto *I = dyn_cast<Instruction>(V)) { | |||
12290 | // Try to find another reduction. | |||
12291 | Stack.emplace(I, Level); | |||
12292 | continue; | |||
12293 | } | |||
12294 | } else { | |||
12295 | bool IsBinop = B0 && B1; | |||
12296 | if (P && IsBinop) { | |||
12297 | Inst = dyn_cast<Instruction>(B0); | |||
12298 | if (Inst == P) | |||
12299 | Inst = dyn_cast<Instruction>(B1); | |||
12300 | if (!Inst) { | |||
12301 | // Set P to nullptr to avoid re-analysis of phi node in | |||
12302 | // matchAssociativeReduction function unless this is the root node. | |||
12303 | P = nullptr; | |||
12304 | continue; | |||
12305 | } | |||
12306 | } | |||
12307 | // Set P to nullptr to avoid re-analysis of phi node in | |||
12308 | // matchAssociativeReduction function unless this is the root node. | |||
12309 | P = nullptr; | |||
12310 | // Do not collect CmpInst or InsertElementInst/InsertValueInst as their | |||
12311 | // analysis is done separately. | |||
12312 | if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst)) | |||
12313 | PostponedInsts.push_back(Inst); | |||
12314 | } | |||
12315 | ||||
12316 | // Try to vectorize operands. | |||
12317 | // Continue analysis for the instruction from the same basic block only to | |||
12318 | // save compile time. | |||
12319 | if (++Level < RecursionMaxDepth) | |||
12320 | for (auto *Op : Inst->operand_values()) | |||
12321 | if (VisitedInstrs.insert(Op).second) | |||
12322 | if (auto *I = dyn_cast<Instruction>(Op)) | |||
12323 | // Do not try to vectorize CmpInst operands, this is done | |||
12324 | // separately. | |||
12325 | if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) && | |||
12326 | !R.isDeleted(I) && I->getParent() == BB) | |||
12327 | Stack.emplace(I, Level); | |||
12328 | } | |||
12329 | return Res; | |||
12330 | } | |||
12331 | ||||
12332 | bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, | |||
12333 | BasicBlock *BB, BoUpSLP &R, | |||
12334 | TargetTransformInfo *TTI) { | |||
12335 | SmallVector<WeakTrackingVH> PostponedInsts; | |||
12336 | bool Res = vectorizeHorReduction(P, V, BB, R, TTI, PostponedInsts); | |||
12337 | Res |= tryToVectorize(PostponedInsts, R); | |||
12338 | return Res; | |||
12339 | } | |||
12340 | ||||
12341 | bool SLPVectorizerPass::tryToVectorize(ArrayRef<WeakTrackingVH> Insts, | |||
12342 | BoUpSLP &R) { | |||
12343 | bool Res = false; | |||
12344 | for (Value *V : Insts) | |||
12345 | if (auto *Inst = dyn_cast<Instruction>(V); Inst && !R.isDeleted(Inst)) | |||
12346 | Res |= tryToVectorize(Inst, R); | |||
12347 | return Res; | |||
12348 | } | |||
12349 | ||||
12350 | bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, | |||
12351 | BasicBlock *BB, BoUpSLP &R) { | |||
12352 | const DataLayout &DL = BB->getModule()->getDataLayout(); | |||
12353 | if (!R.canMapToVector(IVI->getType(), DL)) | |||
12354 | return false; | |||
12355 | ||||
12356 | SmallVector<Value *, 16> BuildVectorOpds; | |||
12357 | SmallVector<Value *, 16> BuildVectorInsts; | |||
12358 | if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) | |||
12359 | return false; | |||
12360 | ||||
12361 | LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"; } } while (false); | |||
12362 | // Aggregate value is unlikely to be processed in vector register. | |||
12363 | return tryToVectorizeList(BuildVectorOpds, R); | |||
12364 | } | |||
12365 | ||||
12366 | bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, | |||
12367 | BasicBlock *BB, BoUpSLP &R) { | |||
12368 | SmallVector<Value *, 16> BuildVectorInsts; | |||
12369 | SmallVector<Value *, 16> BuildVectorOpds; | |||
12370 | SmallVector<int> Mask; | |||
12371 | if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || | |||
12372 | (llvm::all_of( | |||
12373 | BuildVectorOpds, | |||
12374 | [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && | |||
12375 | isFixedVectorShuffle(BuildVectorOpds, Mask))) | |||
12376 | return false; | |||
12377 | ||||
12378 | LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"; } } while (false); | |||
12379 | return tryToVectorizeList(BuildVectorInsts, R); | |||
12380 | } | |||
12381 | ||||
12382 | template <typename T> | |||
12383 | static bool | |||
12384 | tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, | |||
12385 | function_ref<unsigned(T *)> Limit, | |||
12386 | function_ref<bool(T *, T *)> Comparator, | |||
12387 | function_ref<bool(T *, T *)> AreCompatible, | |||
12388 | function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, | |||
12389 | bool LimitForRegisterSize) { | |||
12390 | bool Changed = false; | |||
12391 | // Sort by type, parent, operands. | |||
12392 | stable_sort(Incoming, Comparator); | |||
12393 | ||||
12394 | // Try to vectorize elements base on their type. | |||
12395 | SmallVector<T *> Candidates; | |||
12396 | for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { | |||
12397 | // Look for the next elements with the same type, parent and operand | |||
12398 | // kinds. | |||
12399 | auto *SameTypeIt = IncIt; | |||
12400 | while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) | |||
12401 | ++SameTypeIt; | |||
12402 | ||||
12403 | // Try to vectorize them. | |||
12404 | unsigned NumElts = (SameTypeIt - IncIt); | |||
12405 | LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Trying to vectorize starting at nodes (" << NumElts << ")\n"; } } while (false) | |||
12406 | << NumElts << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Trying to vectorize starting at nodes (" << NumElts << ")\n"; } } while (false); | |||
12407 | // The vectorization is a 3-state attempt: | |||
12408 | // 1. Try to vectorize instructions with the same/alternate opcodes with the | |||
12409 | // size of maximal register at first. | |||
12410 | // 2. Try to vectorize remaining instructions with the same type, if | |||
12411 | // possible. This may result in the better vectorization results rather than | |||
12412 | // if we try just to vectorize instructions with the same/alternate opcodes. | |||
12413 | // 3. Final attempt to try to vectorize all instructions with the | |||
12414 | // same/alternate ops only, this may result in some extra final | |||
12415 | // vectorization. | |||
12416 | if (NumElts > 1 && | |||
12417 | TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { | |||
12418 | // Success start over because instructions might have been changed. | |||
12419 | Changed = true; | |||
12420 | } else if (NumElts < Limit(*IncIt) && | |||
12421 | (Candidates.empty() || | |||
12422 | Candidates.front()->getType() == (*IncIt)->getType())) { | |||
12423 | Candidates.append(IncIt, std::next(IncIt, NumElts)); | |||
12424 | } | |||
12425 | // Final attempt to vectorize instructions with the same types. | |||
12426 | if (Candidates.size() > 1 && | |||
12427 | (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { | |||
12428 | if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { | |||
12429 | // Success start over because instructions might have been changed. | |||
12430 | Changed = true; | |||
12431 | } else if (LimitForRegisterSize) { | |||
12432 | // Try to vectorize using small vectors. | |||
12433 | for (auto *It = Candidates.begin(), *End = Candidates.end(); | |||
12434 | It != End;) { | |||
12435 | auto *SameTypeIt = It; | |||
12436 | while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) | |||
12437 | ++SameTypeIt; | |||
12438 | unsigned NumElts = (SameTypeIt - It); | |||
12439 | if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), | |||
12440 | /*LimitForRegisterSize=*/false)) | |||
12441 | Changed = true; | |||
12442 | It = SameTypeIt; | |||
12443 | } | |||
12444 | } | |||
12445 | Candidates.clear(); | |||
12446 | } | |||
12447 | ||||
12448 | // Start over at the next instruction of a different type (or the end). | |||
12449 | IncIt = SameTypeIt; | |||
12450 | } | |||
12451 | return Changed; | |||
12452 | } | |||
12453 | ||||
12454 | /// Compare two cmp instructions. If IsCompatibility is true, function returns | |||
12455 | /// true if 2 cmps have same/swapped predicates and mos compatible corresponding | |||
12456 | /// operands. If IsCompatibility is false, function implements strict weak | |||
12457 | /// ordering relation between two cmp instructions, returning true if the first | |||
12458 | /// instruction is "less" than the second, i.e. its predicate is less than the | |||
12459 | /// predicate of the second or the operands IDs are less than the operands IDs | |||
12460 | /// of the second cmp instruction. | |||
12461 | template <bool IsCompatibility> | |||
12462 | static bool compareCmp(Value *V, Value *V2, TargetLibraryInfo &TLI, | |||
12463 | function_ref<bool(Instruction *)> IsDeleted) { | |||
12464 | auto *CI1 = cast<CmpInst>(V); | |||
12465 | auto *CI2 = cast<CmpInst>(V2); | |||
12466 | if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) | |||
12467 | return false; | |||
12468 | if (CI1->getOperand(0)->getType()->getTypeID() < | |||
12469 | CI2->getOperand(0)->getType()->getTypeID()) | |||
12470 | return !IsCompatibility; | |||
12471 | if (CI1->getOperand(0)->getType()->getTypeID() > | |||
12472 | CI2->getOperand(0)->getType()->getTypeID()) | |||
12473 | return false; | |||
12474 | CmpInst::Predicate Pred1 = CI1->getPredicate(); | |||
12475 | CmpInst::Predicate Pred2 = CI2->getPredicate(); | |||
12476 | CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); | |||
12477 | CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); | |||
12478 | CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); | |||
12479 | CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); | |||
12480 | if (BasePred1 < BasePred2) | |||
12481 | return !IsCompatibility; | |||
12482 | if (BasePred1 > BasePred2) | |||
12483 | return false; | |||
12484 | // Compare operands. | |||
12485 | bool LEPreds = Pred1 <= Pred2; | |||
12486 | bool GEPreds = Pred1 >= Pred2; | |||
12487 | for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { | |||
12488 | auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); | |||
12489 | auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); | |||
12490 | if (Op1->getValueID() < Op2->getValueID()) | |||
12491 | return !IsCompatibility; | |||
12492 | if (Op1->getValueID() > Op2->getValueID()) | |||
12493 | return false; | |||
12494 | if (auto *I1 = dyn_cast<Instruction>(Op1)) | |||
12495 | if (auto *I2 = dyn_cast<Instruction>(Op2)) { | |||
12496 | if (I1->getParent() != I2->getParent()) | |||
12497 | return false; | |||
12498 | InstructionsState S = getSameOpcode({I1, I2}, TLI); | |||
12499 | if (S.getOpcode()) | |||
12500 | continue; | |||
12501 | return false; | |||
12502 | } | |||
12503 | } | |||
12504 | return IsCompatibility; | |||
12505 | } | |||
12506 | ||||
12507 | bool SLPVectorizerPass::vectorizeSimpleInstructions(InstSetVector &Instructions, | |||
12508 | BasicBlock *BB, BoUpSLP &R, | |||
12509 | bool AtTerminator) { | |||
12510 | bool OpsChanged = false; | |||
12511 | SmallVector<Instruction *, 4> PostponedCmps; | |||
12512 | SmallVector<WeakTrackingVH> PostponedInsts; | |||
12513 | // pass1 - try to vectorize reductions only | |||
12514 | for (auto *I : reverse(Instructions)) { | |||
12515 | if (R.isDeleted(I)) | |||
12516 | continue; | |||
12517 | if (isa<CmpInst>(I)) { | |||
12518 | PostponedCmps.push_back(I); | |||
12519 | continue; | |||
12520 | } | |||
12521 | OpsChanged |= vectorizeHorReduction(nullptr, I, BB, R, TTI, PostponedInsts); | |||
12522 | } | |||
12523 | // pass2 - try to match and vectorize a buildvector sequence. | |||
12524 | for (auto *I : reverse(Instructions)) { | |||
12525 | if (R.isDeleted(I) || isa<CmpInst>(I)) | |||
12526 | continue; | |||
12527 | if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) { | |||
12528 | OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); | |||
12529 | } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) { | |||
12530 | OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); | |||
12531 | } | |||
12532 | } | |||
12533 | // Now try to vectorize postponed instructions. | |||
12534 | OpsChanged |= tryToVectorize(PostponedInsts, R); | |||
12535 | ||||
12536 | if (AtTerminator) { | |||
12537 | // Try to find reductions first. | |||
12538 | for (Instruction *I : PostponedCmps) { | |||
12539 | if (R.isDeleted(I)) | |||
12540 | continue; | |||
12541 | for (Value *Op : I->operands()) | |||
12542 | OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); | |||
12543 | } | |||
12544 | // Try to vectorize operands as vector bundles. | |||
12545 | for (Instruction *I : PostponedCmps) { | |||
12546 | if (R.isDeleted(I)) | |||
12547 | continue; | |||
12548 | OpsChanged |= tryToVectorize(I, R); | |||
12549 | } | |||
12550 | // Try to vectorize list of compares. | |||
12551 | // Sort by type, compare predicate, etc. | |||
12552 | auto CompareSorter = [&](Value *V, Value *V2) { | |||
12553 | return compareCmp<false>(V, V2, *TLI, | |||
12554 | [&R](Instruction *I) { return R.isDeleted(I); }); | |||
12555 | }; | |||
12556 | ||||
12557 | auto AreCompatibleCompares = [&](Value *V1, Value *V2) { | |||
12558 | if (V1 == V2) | |||
12559 | return true; | |||
12560 | return compareCmp<true>(V1, V2, *TLI, | |||
12561 | [&R](Instruction *I) { return R.isDeleted(I); }); | |||
12562 | }; | |||
12563 | auto Limit = [&R](Value *V) { | |||
12564 | unsigned EltSize = R.getVectorElementSize(V); | |||
12565 | return std::max(2U, R.getMaxVecRegSize() / EltSize); | |||
12566 | }; | |||
12567 | ||||
12568 | SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); | |||
12569 | OpsChanged |= tryToVectorizeSequence<Value>( | |||
12570 | Vals, Limit, CompareSorter, AreCompatibleCompares, | |||
12571 | [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { | |||
12572 | // Exclude possible reductions from other blocks. | |||
12573 | bool ArePossiblyReducedInOtherBlock = | |||
12574 | any_of(Candidates, [](Value *V) { | |||
12575 | return any_of(V->users(), [V](User *U) { | |||
12576 | return isa<SelectInst>(U) && | |||
12577 | cast<SelectInst>(U)->getParent() != | |||
12578 | cast<Instruction>(V)->getParent(); | |||
12579 | }); | |||
12580 | }); | |||
12581 | if (ArePossiblyReducedInOtherBlock) | |||
12582 | return false; | |||
12583 | return tryToVectorizeList(Candidates, R, LimitForRegisterSize); | |||
12584 | }, | |||
12585 | /*LimitForRegisterSize=*/true); | |||
12586 | Instructions.clear(); | |||
12587 | } else { | |||
12588 | Instructions.clear(); | |||
12589 | // Insert in reverse order since the PostponedCmps vector was filled in | |||
12590 | // reverse order. | |||
12591 | Instructions.insert(PostponedCmps.rbegin(), PostponedCmps.rend()); | |||
12592 | } | |||
12593 | return OpsChanged; | |||
12594 | } | |||
12595 | ||||
12596 | bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { | |||
12597 | bool Changed = false; | |||
12598 | SmallVector<Value *, 4> Incoming; | |||
12599 | SmallPtrSet<Value *, 16> VisitedInstrs; | |||
12600 | // Maps phi nodes to the non-phi nodes found in the use tree for each phi | |||
12601 | // node. Allows better to identify the chains that can be vectorized in the | |||
12602 | // better way. | |||
12603 | DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; | |||
12604 | auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { | |||
12605 | assert(isValidElementType(V1->getType()) &&(static_cast <bool> (isValidElementType(V1->getType( )) && isValidElementType(V2->getType()) && "Expected vectorizable types only.") ? void (0) : __assert_fail ("isValidElementType(V1->getType()) && isValidElementType(V2->getType()) && \"Expected vectorizable types only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12607, __extension__ __PRETTY_FUNCTION__)) | |||
12606 | isValidElementType(V2->getType()) &&(static_cast <bool> (isValidElementType(V1->getType( )) && isValidElementType(V2->getType()) && "Expected vectorizable types only.") ? void (0) : __assert_fail ("isValidElementType(V1->getType()) && isValidElementType(V2->getType()) && \"Expected vectorizable types only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12607, __extension__ __PRETTY_FUNCTION__)) | |||
12607 | "Expected vectorizable types only.")(static_cast <bool> (isValidElementType(V1->getType( )) && isValidElementType(V2->getType()) && "Expected vectorizable types only.") ? void (0) : __assert_fail ("isValidElementType(V1->getType()) && isValidElementType(V2->getType()) && \"Expected vectorizable types only.\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12607, __extension__ __PRETTY_FUNCTION__)); | |||
12608 | // It is fine to compare type IDs here, since we expect only vectorizable | |||
12609 | // types, like ints, floats and pointers, we don't care about other type. | |||
12610 | if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) | |||
12611 | return true; | |||
12612 | if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) | |||
12613 | return false; | |||
12614 | ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; | |||
12615 | ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; | |||
12616 | if (Opcodes1.size() < Opcodes2.size()) | |||
12617 | return true; | |||
12618 | if (Opcodes1.size() > Opcodes2.size()) | |||
12619 | return false; | |||
12620 | Optional<bool> ConstOrder; | |||
12621 | for (int I = 0, E = Opcodes1.size(); I < E; ++I) { | |||
12622 | // Undefs are compatible with any other value. | |||
12623 | if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { | |||
12624 | if (!ConstOrder) | |||
12625 | ConstOrder = | |||
12626 | !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); | |||
12627 | continue; | |||
12628 | } | |||
12629 | if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) | |||
12630 | if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { | |||
12631 | DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); | |||
12632 | DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); | |||
12633 | if (!NodeI1) | |||
12634 | return NodeI2 != nullptr; | |||
12635 | if (!NodeI2) | |||
12636 | return false; | |||
12637 | assert((NodeI1 == NodeI2) ==(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1-> getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12639, __extension__ __PRETTY_FUNCTION__)) | |||
12638 | (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1-> getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12639, __extension__ __PRETTY_FUNCTION__)) | |||
12639 | "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1-> getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12639, __extension__ __PRETTY_FUNCTION__)); | |||
12640 | if (NodeI1 != NodeI2) | |||
12641 | return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); | |||
12642 | InstructionsState S = getSameOpcode({I1, I2}, *TLI); | |||
12643 | if (S.getOpcode()) | |||
12644 | continue; | |||
12645 | return I1->getOpcode() < I2->getOpcode(); | |||
12646 | } | |||
12647 | if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { | |||
12648 | if (!ConstOrder) | |||
12649 | ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); | |||
12650 | continue; | |||
12651 | } | |||
12652 | if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) | |||
12653 | return true; | |||
12654 | if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) | |||
12655 | return false; | |||
12656 | } | |||
12657 | return ConstOrder && *ConstOrder; | |||
12658 | }; | |||
12659 | auto AreCompatiblePHIs = [&PHIToOpcodes, this](Value *V1, Value *V2) { | |||
12660 | if (V1 == V2) | |||
12661 | return true; | |||
12662 | if (V1->getType() != V2->getType()) | |||
12663 | return false; | |||
12664 | ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; | |||
12665 | ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; | |||
12666 | if (Opcodes1.size() != Opcodes2.size()) | |||
12667 | return false; | |||
12668 | for (int I = 0, E = Opcodes1.size(); I < E; ++I) { | |||
12669 | // Undefs are compatible with any other value. | |||
12670 | if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) | |||
12671 | continue; | |||
12672 | if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) | |||
12673 | if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { | |||
12674 | if (I1->getParent() != I2->getParent()) | |||
12675 | return false; | |||
12676 | InstructionsState S = getSameOpcode({I1, I2}, *TLI); | |||
12677 | if (S.getOpcode()) | |||
12678 | continue; | |||
12679 | return false; | |||
12680 | } | |||
12681 | if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) | |||
12682 | continue; | |||
12683 | if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) | |||
12684 | return false; | |||
12685 | } | |||
12686 | return true; | |||
12687 | }; | |||
12688 | auto Limit = [&R](Value *V) { | |||
12689 | unsigned EltSize = R.getVectorElementSize(V); | |||
12690 | return std::max(2U, R.getMaxVecRegSize() / EltSize); | |||
12691 | }; | |||
12692 | ||||
12693 | bool HaveVectorizedPhiNodes = false; | |||
12694 | do { | |||
12695 | // Collect the incoming values from the PHIs. | |||
12696 | Incoming.clear(); | |||
12697 | for (Instruction &I : *BB) { | |||
12698 | PHINode *P = dyn_cast<PHINode>(&I); | |||
12699 | if (!P) | |||
12700 | break; | |||
12701 | ||||
12702 | // No need to analyze deleted, vectorized and non-vectorizable | |||
12703 | // instructions. | |||
12704 | if (!VisitedInstrs.count(P) && !R.isDeleted(P) && | |||
12705 | isValidElementType(P->getType())) | |||
12706 | Incoming.push_back(P); | |||
12707 | } | |||
12708 | ||||
12709 | // Find the corresponding non-phi nodes for better matching when trying to | |||
12710 | // build the tree. | |||
12711 | for (Value *V : Incoming) { | |||
12712 | SmallVectorImpl<Value *> &Opcodes = | |||
12713 | PHIToOpcodes.try_emplace(V).first->getSecond(); | |||
12714 | if (!Opcodes.empty()) | |||
12715 | continue; | |||
12716 | SmallVector<Value *, 4> Nodes(1, V); | |||
12717 | SmallPtrSet<Value *, 4> Visited; | |||
12718 | while (!Nodes.empty()) { | |||
12719 | auto *PHI = cast<PHINode>(Nodes.pop_back_val()); | |||
12720 | if (!Visited.insert(PHI).second) | |||
12721 | continue; | |||
12722 | for (Value *V : PHI->incoming_values()) { | |||
12723 | if (auto *PHI1 = dyn_cast<PHINode>((V))) { | |||
12724 | Nodes.push_back(PHI1); | |||
12725 | continue; | |||
12726 | } | |||
12727 | Opcodes.emplace_back(V); | |||
12728 | } | |||
12729 | } | |||
12730 | } | |||
12731 | ||||
12732 | HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( | |||
12733 | Incoming, Limit, PHICompare, AreCompatiblePHIs, | |||
12734 | [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { | |||
12735 | return tryToVectorizeList(Candidates, R, LimitForRegisterSize); | |||
12736 | }, | |||
12737 | /*LimitForRegisterSize=*/true); | |||
12738 | Changed |= HaveVectorizedPhiNodes; | |||
12739 | VisitedInstrs.insert(Incoming.begin(), Incoming.end()); | |||
12740 | } while (HaveVectorizedPhiNodes); | |||
12741 | ||||
12742 | VisitedInstrs.clear(); | |||
12743 | ||||
12744 | InstSetVector PostProcessInstructions; | |||
12745 | SmallDenseSet<Instruction *, 4> KeyNodes; | |||
12746 | for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { | |||
12747 | // Skip instructions with scalable type. The num of elements is unknown at | |||
12748 | // compile-time for scalable type. | |||
12749 | if (isa<ScalableVectorType>(it->getType())) | |||
12750 | continue; | |||
12751 | ||||
12752 | // Skip instructions marked for the deletion. | |||
12753 | if (R.isDeleted(&*it)) | |||
12754 | continue; | |||
12755 | // We may go through BB multiple times so skip the one we have checked. | |||
12756 | if (!VisitedInstrs.insert(&*it).second) { | |||
12757 | if (it->use_empty() && KeyNodes.contains(&*it) && | |||
12758 | vectorizeSimpleInstructions(PostProcessInstructions, BB, R, | |||
12759 | it->isTerminator())) { | |||
12760 | // We would like to start over since some instructions are deleted | |||
12761 | // and the iterator may become invalid value. | |||
12762 | Changed = true; | |||
12763 | it = BB->begin(); | |||
12764 | e = BB->end(); | |||
12765 | } | |||
12766 | continue; | |||
12767 | } | |||
12768 | ||||
12769 | if (isa<DbgInfoIntrinsic>(it)) | |||
12770 | continue; | |||
12771 | ||||
12772 | // Try to vectorize reductions that use PHINodes. | |||
12773 | if (PHINode *P = dyn_cast<PHINode>(it)) { | |||
12774 | // Check that the PHI is a reduction PHI. | |||
12775 | if (P->getNumIncomingValues() == 2) { | |||
12776 | // Try to match and vectorize a horizontal reduction. | |||
12777 | if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, | |||
12778 | TTI)) { | |||
12779 | Changed = true; | |||
12780 | it = BB->begin(); | |||
12781 | e = BB->end(); | |||
12782 | continue; | |||
12783 | } | |||
12784 | } | |||
12785 | // Try to vectorize the incoming values of the PHI, to catch reductions | |||
12786 | // that feed into PHIs. | |||
12787 | for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { | |||
12788 | // Skip if the incoming block is the current BB for now. Also, bypass | |||
12789 | // unreachable IR for efficiency and to avoid crashing. | |||
12790 | // TODO: Collect the skipped incoming values and try to vectorize them | |||
12791 | // after processing BB. | |||
12792 | if (BB == P->getIncomingBlock(I) || | |||
12793 | !DT->isReachableFromEntry(P->getIncomingBlock(I))) | |||
12794 | continue; | |||
12795 | ||||
12796 | // Postponed instructions should not be vectorized here, delay their | |||
12797 | // vectorization. | |||
12798 | if (auto *PI = dyn_cast<Instruction>(P->getIncomingValue(I)); | |||
12799 | PI && !PostProcessInstructions.contains(PI)) | |||
12800 | Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), | |||
12801 | P->getIncomingBlock(I), R, TTI); | |||
12802 | } | |||
12803 | continue; | |||
12804 | } | |||
12805 | ||||
12806 | // Ran into an instruction without users, like terminator, or function call | |||
12807 | // with ignored return value, store. Ignore unused instructions (basing on | |||
12808 | // instruction type, except for CallInst and InvokeInst). | |||
12809 | if (it->use_empty() && | |||
12810 | (it->getType()->isVoidTy() || isa<CallInst, InvokeInst>(it))) { | |||
12811 | KeyNodes.insert(&*it); | |||
12812 | bool OpsChanged = false; | |||
12813 | auto *SI = dyn_cast<StoreInst>(it); | |||
12814 | bool TryToVectorizeRoot = ShouldStartVectorizeHorAtStore || !SI; | |||
12815 | if (SI) { | |||
12816 | auto I = Stores.find(getUnderlyingObject(SI->getPointerOperand())); | |||
12817 | // Try to vectorize chain in store, if this is the only store to the | |||
12818 | // address in the block. | |||
12819 | // TODO: This is just a temporarily solution to save compile time. Need | |||
12820 | // to investigate if we can safely turn on slp-vectorize-hor-store | |||
12821 | // instead to allow lookup for reduction chains in all non-vectorized | |||
12822 | // stores (need to check side effects and compile time). | |||
12823 | TryToVectorizeRoot = (I == Stores.end() || I->second.size() == 1) && | |||
12824 | SI->getValueOperand()->hasOneUse(); | |||
12825 | } | |||
12826 | if (TryToVectorizeRoot) { | |||
12827 | for (auto *V : it->operand_values()) { | |||
12828 | // Postponed instructions should not be vectorized here, delay their | |||
12829 | // vectorization. | |||
12830 | if (auto *VI = dyn_cast<Instruction>(V); | |||
12831 | VI && !PostProcessInstructions.contains(VI)) | |||
12832 | // Try to match and vectorize a horizontal reduction. | |||
12833 | OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); | |||
12834 | } | |||
12835 | } | |||
12836 | // Start vectorization of post-process list of instructions from the | |||
12837 | // top-tree instructions to try to vectorize as many instructions as | |||
12838 | // possible. | |||
12839 | OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, | |||
12840 | it->isTerminator()); | |||
12841 | if (OpsChanged) { | |||
12842 | // We would like to start over since some instructions are deleted | |||
12843 | // and the iterator may become invalid value. | |||
12844 | Changed = true; | |||
12845 | it = BB->begin(); | |||
12846 | e = BB->end(); | |||
12847 | continue; | |||
12848 | } | |||
12849 | } | |||
12850 | ||||
12851 | if (isa<CmpInst, InsertElementInst, InsertValueInst>(it)) | |||
12852 | PostProcessInstructions.insert(&*it); | |||
12853 | } | |||
12854 | ||||
12855 | return Changed; | |||
12856 | } | |||
12857 | ||||
12858 | bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { | |||
12859 | auto Changed = false; | |||
12860 | for (auto &Entry : GEPs) { | |||
12861 | // If the getelementptr list has fewer than two elements, there's nothing | |||
12862 | // to do. | |||
12863 | if (Entry.second.size() < 2) | |||
12864 | continue; | |||
12865 | ||||
12866 | LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing a getelementptr list of length " << Entry.second.size() << ".\n"; } } while (false ) | |||
12867 | << Entry.second.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing a getelementptr list of length " << Entry.second.size() << ".\n"; } } while (false ); | |||
12868 | ||||
12869 | // Process the GEP list in chunks suitable for the target's supported | |||
12870 | // vector size. If a vector register can't hold 1 element, we are done. We | |||
12871 | // are trying to vectorize the index computations, so the maximum number of | |||
12872 | // elements is based on the size of the index expression, rather than the | |||
12873 | // size of the GEP itself (the target's pointer size). | |||
12874 | unsigned MaxVecRegSize = R.getMaxVecRegSize(); | |||
12875 | unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); | |||
12876 | if (MaxVecRegSize < EltSize) | |||
12877 | continue; | |||
12878 | ||||
12879 | unsigned MaxElts = MaxVecRegSize / EltSize; | |||
12880 | for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { | |||
12881 | auto Len = std::min<unsigned>(BE - BI, MaxElts); | |||
12882 | ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); | |||
12883 | ||||
12884 | // Initialize a set a candidate getelementptrs. Note that we use a | |||
12885 | // SetVector here to preserve program order. If the index computations | |||
12886 | // are vectorizable and begin with loads, we want to minimize the chance | |||
12887 | // of having to reorder them later. | |||
12888 | SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); | |||
12889 | ||||
12890 | // Some of the candidates may have already been vectorized after we | |||
12891 | // initially collected them. If so, they are marked as deleted, so remove | |||
12892 | // them from the set of candidates. | |||
12893 | Candidates.remove_if( | |||
12894 | [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); | |||
12895 | ||||
12896 | // Remove from the set of candidates all pairs of getelementptrs with | |||
12897 | // constant differences. Such getelementptrs are likely not good | |||
12898 | // candidates for vectorization in a bottom-up phase since one can be | |||
12899 | // computed from the other. We also ensure all candidate getelementptr | |||
12900 | // indices are unique. | |||
12901 | for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { | |||
12902 | auto *GEPI = GEPList[I]; | |||
12903 | if (!Candidates.count(GEPI)) | |||
12904 | continue; | |||
12905 | auto *SCEVI = SE->getSCEV(GEPList[I]); | |||
12906 | for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { | |||
12907 | auto *GEPJ = GEPList[J]; | |||
12908 | auto *SCEVJ = SE->getSCEV(GEPList[J]); | |||
12909 | if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { | |||
12910 | Candidates.remove(GEPI); | |||
12911 | Candidates.remove(GEPJ); | |||
12912 | } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { | |||
12913 | Candidates.remove(GEPJ); | |||
12914 | } | |||
12915 | } | |||
12916 | } | |||
12917 | ||||
12918 | // We break out of the above computation as soon as we know there are | |||
12919 | // fewer than two candidates remaining. | |||
12920 | if (Candidates.size() < 2) | |||
12921 | continue; | |||
12922 | ||||
12923 | // Add the single, non-constant index of each candidate to the bundle. We | |||
12924 | // ensured the indices met these constraints when we originally collected | |||
12925 | // the getelementptrs. | |||
12926 | SmallVector<Value *, 16> Bundle(Candidates.size()); | |||
12927 | auto BundleIndex = 0u; | |||
12928 | for (auto *V : Candidates) { | |||
12929 | auto *GEP = cast<GetElementPtrInst>(V); | |||
12930 | auto *GEPIdx = GEP->idx_begin()->get(); | |||
12931 | assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx))(static_cast <bool> (GEP->getNumIndices() == 1 || !isa <Constant>(GEPIdx)) ? void (0) : __assert_fail ("GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12931, __extension__ __PRETTY_FUNCTION__)); | |||
12932 | Bundle[BundleIndex++] = GEPIdx; | |||
12933 | } | |||
12934 | ||||
12935 | // Try and vectorize the indices. We are currently only interested in | |||
12936 | // gather-like cases of the form: | |||
12937 | // | |||
12938 | // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... | |||
12939 | // | |||
12940 | // where the loads of "a", the loads of "b", and the subtractions can be | |||
12941 | // performed in parallel. It's likely that detecting this pattern in a | |||
12942 | // bottom-up phase will be simpler and less costly than building a | |||
12943 | // full-blown top-down phase beginning at the consecutive loads. | |||
12944 | Changed |= tryToVectorizeList(Bundle, R); | |||
12945 | } | |||
12946 | } | |||
12947 | return Changed; | |||
12948 | } | |||
12949 | ||||
12950 | bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { | |||
12951 | bool Changed = false; | |||
12952 | // Sort by type, base pointers and values operand. Value operands must be | |||
12953 | // compatible (have the same opcode, same parent), otherwise it is | |||
12954 | // definitely not profitable to try to vectorize them. | |||
12955 | auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { | |||
12956 | if (V->getPointerOperandType()->getTypeID() < | |||
12957 | V2->getPointerOperandType()->getTypeID()) | |||
12958 | return true; | |||
12959 | if (V->getPointerOperandType()->getTypeID() > | |||
12960 | V2->getPointerOperandType()->getTypeID()) | |||
12961 | return false; | |||
12962 | // UndefValues are compatible with all other values. | |||
12963 | if (isa<UndefValue>(V->getValueOperand()) || | |||
12964 | isa<UndefValue>(V2->getValueOperand())) | |||
12965 | return false; | |||
12966 | if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) | |||
12967 | if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { | |||
12968 | DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = | |||
12969 | DT->getNode(I1->getParent()); | |||
12970 | DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = | |||
12971 | DT->getNode(I2->getParent()); | |||
12972 | assert(NodeI1 && "Should only process reachable instructions")(static_cast <bool> (NodeI1 && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeI1 && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12972, __extension__ __PRETTY_FUNCTION__)); | |||
12973 | assert(NodeI2 && "Should only process reachable instructions")(static_cast <bool> (NodeI2 && "Should only process reachable instructions" ) ? void (0) : __assert_fail ("NodeI2 && \"Should only process reachable instructions\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12973, __extension__ __PRETTY_FUNCTION__)); | |||
12974 | assert((NodeI1 == NodeI2) ==(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1-> getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12976, __extension__ __PRETTY_FUNCTION__)) | |||
12975 | (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1-> getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12976, __extension__ __PRETTY_FUNCTION__)) | |||
12976 | "Different nodes should have different DFS numbers")(static_cast <bool> ((NodeI1 == NodeI2) == (NodeI1-> getDFSNumIn() == NodeI2->getDFSNumIn()) && "Different nodes should have different DFS numbers" ) ? void (0) : __assert_fail ("(NodeI1 == NodeI2) == (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && \"Different nodes should have different DFS numbers\"" , "llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp", 12976, __extension__ __PRETTY_FUNCTION__)); | |||
12977 | if (NodeI1 != NodeI2) | |||
12978 | return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); | |||
12979 | InstructionsState S = getSameOpcode({I1, I2}, *TLI); | |||
12980 | if (S.getOpcode()) | |||
12981 | return false; | |||
12982 | return I1->getOpcode() < I2->getOpcode(); | |||
12983 | } | |||
12984 | if (isa<Constant>(V->getValueOperand()) && | |||
12985 | isa<Constant>(V2->getValueOperand())) | |||
12986 | return false; | |||
12987 | return V->getValueOperand()->getValueID() < | |||
12988 | V2->getValueOperand()->getValueID(); | |||
12989 | }; | |||
12990 | ||||
12991 | auto &&AreCompatibleStores = [this](StoreInst *V1, StoreInst *V2) { | |||
12992 | if (V1 == V2) | |||
12993 | return true; | |||
12994 | if (V1->getPointerOperandType() != V2->getPointerOperandType()) | |||
12995 | return false; | |||
12996 | // Undefs are compatible with any other value. | |||
12997 | if (isa<UndefValue>(V1->getValueOperand()) || | |||
12998 | isa<UndefValue>(V2->getValueOperand())) | |||
12999 | return true; | |||
13000 | if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) | |||
13001 | if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { | |||
13002 | if (I1->getParent() != I2->getParent()) | |||
13003 | return false; | |||
13004 | InstructionsState S = getSameOpcode({I1, I2}, *TLI); | |||
13005 | return S.getOpcode() > 0; | |||
13006 | } | |||
13007 | if (isa<Constant>(V1->getValueOperand()) && | |||
13008 | isa<Constant>(V2->getValueOperand())) | |||
13009 | return true; | |||
13010 | return V1->getValueOperand()->getValueID() == | |||
13011 | V2->getValueOperand()->getValueID(); | |||
13012 | }; | |||
13013 | auto Limit = [&R, this](StoreInst *SI) { | |||
13014 | unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); | |||
13015 | return R.getMinVF(EltSize); | |||
13016 | }; | |||
13017 | ||||
13018 | // Attempt to sort and vectorize each of the store-groups. | |||
13019 | for (auto &Pair : Stores) { | |||
13020 | if (Pair.second.size() < 2) | |||
13021 | continue; | |||
13022 | ||||
13023 | LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing a store chain of length " << Pair.second.size() << ".\n"; } } while (false ) | |||
13024 | << Pair.second.size() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("SLP")) { dbgs() << "SLP: Analyzing a store chain of length " << Pair.second.size() << ".\n"; } } while (false ); | |||
13025 | ||||
13026 | if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) | |||
13027 | continue; | |||
13028 | ||||
13029 | Changed |= tryToVectorizeSequence<StoreInst>( | |||
13030 | Pair.second, Limit, StoreSorter, AreCompatibleStores, | |||
13031 | [this, &R](ArrayRef<StoreInst *> Candidates, bool) { | |||
13032 | return vectorizeStores(Candidates, R); | |||
13033 | }, | |||
13034 | /*LimitForRegisterSize=*/false); | |||
13035 | } | |||
13036 | return Changed; | |||
13037 | } | |||
13038 | ||||
13039 | char SLPVectorizer::ID = 0; | |||
13040 | ||||
13041 | static const char lv_name[] = "SLP Vectorizer"; | |||
13042 | ||||
13043 | INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)static void *initializeSLPVectorizerPassOnce(PassRegistry & Registry) { | |||
13044 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry); | |||
13045 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry); | |||
13046 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry); | |||
13047 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)initializeScalarEvolutionWrapperPassPass(Registry); | |||
13048 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify)initializeLoopSimplifyPass(Registry); | |||
13049 | INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)initializeDemandedBitsWrapperPassPass(Registry); | |||
13050 | INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)initializeOptimizationRemarkEmitterWrapperPassPass(Registry); | |||
13051 | INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)initializeInjectTLIMappingsLegacyPass(Registry); | |||
13052 | INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)PassInfo *PI = new PassInfo( lv_name, "slp-vectorizer", & SLPVectorizer::ID, PassInfo::NormalCtor_t(callDefaultCtor< SLPVectorizer>), false, false); Registry.registerPass(*PI, true); return PI; } static llvm::once_flag InitializeSLPVectorizerPassFlag ; void llvm::initializeSLPVectorizerPass(PassRegistry &Registry ) { llvm::call_once(InitializeSLPVectorizerPassFlag, initializeSLPVectorizerPassOnce , std::ref(Registry)); } | |||
13053 | ||||
13054 | Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } |