File: | lib/Transforms/Vectorize/LoopVectorize.cpp |
Warning: | line 6562, column 35 Potential leak of memory pointed to by 'BlockMask' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops | |||
11 | // and generates target-independent LLVM-IR. | |||
12 | // The vectorizer uses the TargetTransformInfo analysis to estimate the costs | |||
13 | // of instructions in order to estimate the profitability of vectorization. | |||
14 | // | |||
15 | // The loop vectorizer combines consecutive loop iterations into a single | |||
16 | // 'wide' iteration. After this transformation the index is incremented | |||
17 | // by the SIMD vector width, and not by one. | |||
18 | // | |||
19 | // This pass has three parts: | |||
20 | // 1. The main loop pass that drives the different parts. | |||
21 | // 2. LoopVectorizationLegality - A unit that checks for the legality | |||
22 | // of the vectorization. | |||
23 | // 3. InnerLoopVectorizer - A unit that performs the actual | |||
24 | // widening of instructions. | |||
25 | // 4. LoopVectorizationCostModel - A unit that checks for the profitability | |||
26 | // of vectorization. It decides on the optimal vector width, which | |||
27 | // can be one, if vectorization is not profitable. | |||
28 | // | |||
29 | // There is a development effort going on to migrate loop vectorizer to the | |||
30 | // VPlan infrastructure and to introduce outer loop vectorization support (see | |||
31 | // docs/Proposal/VectorizationPlan.rst and | |||
32 | // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this | |||
33 | // purpose, we temporarily introduced the VPlan-native vectorization path: an | |||
34 | // alternative vectorization path that is natively implemented on top of the | |||
35 | // VPlan infrastructure. See EnableVPlanNativePath for enabling. | |||
36 | // | |||
37 | //===----------------------------------------------------------------------===// | |||
38 | // | |||
39 | // The reduction-variable vectorization is based on the paper: | |||
40 | // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization. | |||
41 | // | |||
42 | // Variable uniformity checks are inspired by: | |||
43 | // Karrenberg, R. and Hack, S. Whole Function Vectorization. | |||
44 | // | |||
45 | // The interleaved access vectorization is based on the paper: | |||
46 | // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved | |||
47 | // Data for SIMD | |||
48 | // | |||
49 | // Other ideas/concepts are from: | |||
50 | // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later. | |||
51 | // | |||
52 | // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of | |||
53 | // Vectorizing Compilers. | |||
54 | // | |||
55 | //===----------------------------------------------------------------------===// | |||
56 | ||||
57 | #include "llvm/Transforms/Vectorize/LoopVectorize.h" | |||
58 | #include "LoopVectorizationPlanner.h" | |||
59 | #include "VPRecipeBuilder.h" | |||
60 | #include "VPlanHCFGBuilder.h" | |||
61 | #include "llvm/ADT/APInt.h" | |||
62 | #include "llvm/ADT/ArrayRef.h" | |||
63 | #include "llvm/ADT/DenseMap.h" | |||
64 | #include "llvm/ADT/DenseMapInfo.h" | |||
65 | #include "llvm/ADT/Hashing.h" | |||
66 | #include "llvm/ADT/MapVector.h" | |||
67 | #include "llvm/ADT/None.h" | |||
68 | #include "llvm/ADT/Optional.h" | |||
69 | #include "llvm/ADT/STLExtras.h" | |||
70 | #include "llvm/ADT/SetVector.h" | |||
71 | #include "llvm/ADT/SmallPtrSet.h" | |||
72 | #include "llvm/ADT/SmallVector.h" | |||
73 | #include "llvm/ADT/Statistic.h" | |||
74 | #include "llvm/ADT/StringRef.h" | |||
75 | #include "llvm/ADT/Twine.h" | |||
76 | #include "llvm/ADT/iterator_range.h" | |||
77 | #include "llvm/Analysis/AssumptionCache.h" | |||
78 | #include "llvm/Analysis/BasicAliasAnalysis.h" | |||
79 | #include "llvm/Analysis/BlockFrequencyInfo.h" | |||
80 | #include "llvm/Analysis/CFG.h" | |||
81 | #include "llvm/Analysis/CodeMetrics.h" | |||
82 | #include "llvm/Analysis/DemandedBits.h" | |||
83 | #include "llvm/Analysis/GlobalsModRef.h" | |||
84 | #include "llvm/Analysis/LoopAccessAnalysis.h" | |||
85 | #include "llvm/Analysis/LoopAnalysisManager.h" | |||
86 | #include "llvm/Analysis/LoopInfo.h" | |||
87 | #include "llvm/Analysis/LoopIterator.h" | |||
88 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" | |||
89 | #include "llvm/Analysis/ScalarEvolution.h" | |||
90 | #include "llvm/Analysis/ScalarEvolutionExpander.h" | |||
91 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" | |||
92 | #include "llvm/Analysis/TargetLibraryInfo.h" | |||
93 | #include "llvm/Analysis/TargetTransformInfo.h" | |||
94 | #include "llvm/Analysis/VectorUtils.h" | |||
95 | #include "llvm/IR/Attributes.h" | |||
96 | #include "llvm/IR/BasicBlock.h" | |||
97 | #include "llvm/IR/CFG.h" | |||
98 | #include "llvm/IR/Constant.h" | |||
99 | #include "llvm/IR/Constants.h" | |||
100 | #include "llvm/IR/DataLayout.h" | |||
101 | #include "llvm/IR/DebugInfoMetadata.h" | |||
102 | #include "llvm/IR/DebugLoc.h" | |||
103 | #include "llvm/IR/DerivedTypes.h" | |||
104 | #include "llvm/IR/DiagnosticInfo.h" | |||
105 | #include "llvm/IR/Dominators.h" | |||
106 | #include "llvm/IR/Function.h" | |||
107 | #include "llvm/IR/IRBuilder.h" | |||
108 | #include "llvm/IR/InstrTypes.h" | |||
109 | #include "llvm/IR/Instruction.h" | |||
110 | #include "llvm/IR/Instructions.h" | |||
111 | #include "llvm/IR/IntrinsicInst.h" | |||
112 | #include "llvm/IR/Intrinsics.h" | |||
113 | #include "llvm/IR/LLVMContext.h" | |||
114 | #include "llvm/IR/Metadata.h" | |||
115 | #include "llvm/IR/Module.h" | |||
116 | #include "llvm/IR/Operator.h" | |||
117 | #include "llvm/IR/Type.h" | |||
118 | #include "llvm/IR/Use.h" | |||
119 | #include "llvm/IR/User.h" | |||
120 | #include "llvm/IR/Value.h" | |||
121 | #include "llvm/IR/ValueHandle.h" | |||
122 | #include "llvm/IR/Verifier.h" | |||
123 | #include "llvm/Pass.h" | |||
124 | #include "llvm/Support/Casting.h" | |||
125 | #include "llvm/Support/CommandLine.h" | |||
126 | #include "llvm/Support/Compiler.h" | |||
127 | #include "llvm/Support/Debug.h" | |||
128 | #include "llvm/Support/ErrorHandling.h" | |||
129 | #include "llvm/Support/MathExtras.h" | |||
130 | #include "llvm/Support/raw_ostream.h" | |||
131 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" | |||
132 | #include "llvm/Transforms/Utils/LoopSimplify.h" | |||
133 | #include "llvm/Transforms/Utils/LoopUtils.h" | |||
134 | #include "llvm/Transforms/Utils/LoopVersioning.h" | |||
135 | #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h" | |||
136 | #include <algorithm> | |||
137 | #include <cassert> | |||
138 | #include <cstdint> | |||
139 | #include <cstdlib> | |||
140 | #include <functional> | |||
141 | #include <iterator> | |||
142 | #include <limits> | |||
143 | #include <memory> | |||
144 | #include <string> | |||
145 | #include <tuple> | |||
146 | #include <utility> | |||
147 | #include <vector> | |||
148 | ||||
149 | using namespace llvm; | |||
150 | ||||
151 | #define LV_NAME"loop-vectorize" "loop-vectorize" | |||
152 | #define DEBUG_TYPE"loop-vectorize" LV_NAME"loop-vectorize" | |||
153 | ||||
154 | STATISTIC(LoopsVectorized, "Number of loops vectorized")static llvm::Statistic LoopsVectorized = {"loop-vectorize", "LoopsVectorized" , "Number of loops vectorized", {0}, {false}}; | |||
155 | STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization")static llvm::Statistic LoopsAnalyzed = {"loop-vectorize", "LoopsAnalyzed" , "Number of loops analyzed for vectorization", {0}, {false}}; | |||
156 | ||||
157 | /// Loops with a known constant trip count below this number are vectorized only | |||
158 | /// if no scalar iteration overheads are incurred. | |||
159 | static cl::opt<unsigned> TinyTripCountVectorThreshold( | |||
160 | "vectorizer-min-trip-count", cl::init(16), cl::Hidden, | |||
161 | cl::desc("Loops with a constant trip count that is smaller than this " | |||
162 | "value are vectorized only if no scalar iteration overheads " | |||
163 | "are incurred.")); | |||
164 | ||||
165 | static cl::opt<bool> MaximizeBandwidth( | |||
166 | "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, | |||
167 | cl::desc("Maximize bandwidth when selecting vectorization factor which " | |||
168 | "will be determined by the smallest type in loop.")); | |||
169 | ||||
170 | static cl::opt<bool> EnableInterleavedMemAccesses( | |||
171 | "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, | |||
172 | cl::desc("Enable vectorization on interleaved memory accesses in a loop")); | |||
173 | ||||
174 | /// Maximum factor for an interleaved memory access. | |||
175 | static cl::opt<unsigned> MaxInterleaveGroupFactor( | |||
176 | "max-interleave-group-factor", cl::Hidden, | |||
177 | cl::desc("Maximum factor for an interleaved access group (default = 8)"), | |||
178 | cl::init(8)); | |||
179 | ||||
180 | /// We don't interleave loops with a known constant trip count below this | |||
181 | /// number. | |||
182 | static const unsigned TinyTripCountInterleaveThreshold = 128; | |||
183 | ||||
184 | static cl::opt<unsigned> ForceTargetNumScalarRegs( | |||
185 | "force-target-num-scalar-regs", cl::init(0), cl::Hidden, | |||
186 | cl::desc("A flag that overrides the target's number of scalar registers.")); | |||
187 | ||||
188 | static cl::opt<unsigned> ForceTargetNumVectorRegs( | |||
189 | "force-target-num-vector-regs", cl::init(0), cl::Hidden, | |||
190 | cl::desc("A flag that overrides the target's number of vector registers.")); | |||
191 | ||||
192 | static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor( | |||
193 | "force-target-max-scalar-interleave", cl::init(0), cl::Hidden, | |||
194 | cl::desc("A flag that overrides the target's max interleave factor for " | |||
195 | "scalar loops.")); | |||
196 | ||||
197 | static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor( | |||
198 | "force-target-max-vector-interleave", cl::init(0), cl::Hidden, | |||
199 | cl::desc("A flag that overrides the target's max interleave factor for " | |||
200 | "vectorized loops.")); | |||
201 | ||||
202 | static cl::opt<unsigned> ForceTargetInstructionCost( | |||
203 | "force-target-instruction-cost", cl::init(0), cl::Hidden, | |||
204 | cl::desc("A flag that overrides the target's expected cost for " | |||
205 | "an instruction to a single constant value. Mostly " | |||
206 | "useful for getting consistent testing.")); | |||
207 | ||||
208 | static cl::opt<unsigned> SmallLoopCost( | |||
209 | "small-loop-cost", cl::init(20), cl::Hidden, | |||
210 | cl::desc( | |||
211 | "The cost of a loop that is considered 'small' by the interleaver.")); | |||
212 | ||||
213 | static cl::opt<bool> LoopVectorizeWithBlockFrequency( | |||
214 | "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden, | |||
215 | cl::desc("Enable the use of the block frequency analysis to access PGO " | |||
216 | "heuristics minimizing code growth in cold regions and being more " | |||
217 | "aggressive in hot regions.")); | |||
218 | ||||
219 | // Runtime interleave loops for load/store throughput. | |||
220 | static cl::opt<bool> EnableLoadStoreRuntimeInterleave( | |||
221 | "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, | |||
222 | cl::desc( | |||
223 | "Enable runtime interleaving until load/store ports are saturated")); | |||
224 | ||||
225 | /// The number of stores in a loop that are allowed to need predication. | |||
226 | static cl::opt<unsigned> NumberOfStoresToPredicate( | |||
227 | "vectorize-num-stores-pred", cl::init(1), cl::Hidden, | |||
228 | cl::desc("Max number of stores to be predicated behind an if.")); | |||
229 | ||||
230 | static cl::opt<bool> EnableIndVarRegisterHeur( | |||
231 | "enable-ind-var-reg-heur", cl::init(true), cl::Hidden, | |||
232 | cl::desc("Count the induction variable only once when interleaving")); | |||
233 | ||||
234 | static cl::opt<bool> EnableCondStoresVectorization( | |||
235 | "enable-cond-stores-vec", cl::init(true), cl::Hidden, | |||
236 | cl::desc("Enable if predication of stores during vectorization.")); | |||
237 | ||||
238 | static cl::opt<unsigned> MaxNestedScalarReductionIC( | |||
239 | "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, | |||
240 | cl::desc("The maximum interleave count to use when interleaving a scalar " | |||
241 | "reduction in a nested loop.")); | |||
242 | ||||
243 | static cl::opt<bool> EnableVPlanNativePath( | |||
244 | "enable-vplan-native-path", cl::init(false), cl::Hidden, | |||
245 | cl::desc("Enable VPlan-native vectorization path with " | |||
246 | "support for outer loop vectorization.")); | |||
247 | ||||
248 | // This flag enables the stress testing of the VPlan H-CFG construction in the | |||
249 | // VPlan-native vectorization path. It must be used in conjuction with | |||
250 | // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the | |||
251 | // verification of the H-CFGs built. | |||
252 | static cl::opt<bool> VPlanBuildStressTest( | |||
253 | "vplan-build-stress-test", cl::init(false), cl::Hidden, | |||
254 | cl::desc( | |||
255 | "Build VPlan for every supported loop nest in the function and bail " | |||
256 | "out right after the build (stress test the VPlan H-CFG construction " | |||
257 | "in the VPlan-native vectorization path).")); | |||
258 | ||||
259 | /// A helper function for converting Scalar types to vector types. | |||
260 | /// If the incoming type is void, we return void. If the VF is 1, we return | |||
261 | /// the scalar type. | |||
262 | static Type *ToVectorTy(Type *Scalar, unsigned VF) { | |||
263 | if (Scalar->isVoidTy() || VF == 1) | |||
264 | return Scalar; | |||
265 | return VectorType::get(Scalar, VF); | |||
266 | } | |||
267 | ||||
268 | // FIXME: The following helper functions have multiple implementations | |||
269 | // in the project. They can be effectively organized in a common Load/Store | |||
270 | // utilities unit. | |||
271 | ||||
272 | /// A helper function that returns the type of loaded or stored value. | |||
273 | static Type *getMemInstValueType(Value *I) { | |||
274 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 275, __extension__ __PRETTY_FUNCTION__)) | |||
275 | "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 275, __extension__ __PRETTY_FUNCTION__)); | |||
276 | if (auto *LI = dyn_cast<LoadInst>(I)) | |||
277 | return LI->getType(); | |||
278 | return cast<StoreInst>(I)->getValueOperand()->getType(); | |||
279 | } | |||
280 | ||||
281 | /// A helper function that returns the alignment of load or store instruction. | |||
282 | static unsigned getMemInstAlignment(Value *I) { | |||
283 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 284, __extension__ __PRETTY_FUNCTION__)) | |||
284 | "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 284, __extension__ __PRETTY_FUNCTION__)); | |||
285 | if (auto *LI = dyn_cast<LoadInst>(I)) | |||
286 | return LI->getAlignment(); | |||
287 | return cast<StoreInst>(I)->getAlignment(); | |||
288 | } | |||
289 | ||||
290 | /// A helper function that returns the address space of the pointer operand of | |||
291 | /// load or store instruction. | |||
292 | static unsigned getMemInstAddressSpace(Value *I) { | |||
293 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 294, __extension__ __PRETTY_FUNCTION__)) | |||
294 | "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa< StoreInst>(I)) && "Expected Load or Store instruction" ) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 294, __extension__ __PRETTY_FUNCTION__)); | |||
295 | if (auto *LI = dyn_cast<LoadInst>(I)) | |||
296 | return LI->getPointerAddressSpace(); | |||
297 | return cast<StoreInst>(I)->getPointerAddressSpace(); | |||
298 | } | |||
299 | ||||
300 | /// A helper function that returns true if the given type is irregular. The | |||
301 | /// type is irregular if its allocated size doesn't equal the store size of an | |||
302 | /// element of the corresponding vector type at the given vectorization factor. | |||
303 | static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) { | |||
304 | // Determine if an array of VF elements of type Ty is "bitcast compatible" | |||
305 | // with a <VF x Ty> vector. | |||
306 | if (VF > 1) { | |||
307 | auto *VectorTy = VectorType::get(Ty, VF); | |||
308 | return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy); | |||
309 | } | |||
310 | ||||
311 | // If the vectorization factor is one, we just check if an array of type Ty | |||
312 | // requires padding between elements. | |||
313 | return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty); | |||
314 | } | |||
315 | ||||
316 | /// A helper function that returns the reciprocal of the block probability of | |||
317 | /// predicated blocks. If we return X, we are assuming the predicated block | |||
318 | /// will execute once for every X iterations of the loop header. | |||
319 | /// | |||
320 | /// TODO: We should use actual block probability here, if available. Currently, | |||
321 | /// we always assume predicated blocks have a 50% chance of executing. | |||
322 | static unsigned getReciprocalPredBlockProb() { return 2; } | |||
323 | ||||
324 | /// A helper function that adds a 'fast' flag to floating-point operations. | |||
325 | static Value *addFastMathFlag(Value *V) { | |||
326 | if (isa<FPMathOperator>(V)) { | |||
327 | FastMathFlags Flags; | |||
328 | Flags.setFast(); | |||
329 | cast<Instruction>(V)->setFastMathFlags(Flags); | |||
330 | } | |||
331 | return V; | |||
332 | } | |||
333 | ||||
334 | /// A helper function that returns an integer or floating-point constant with | |||
335 | /// value C. | |||
336 | static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) { | |||
337 | return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C) | |||
338 | : ConstantFP::get(Ty, C); | |||
339 | } | |||
340 | ||||
341 | namespace llvm { | |||
342 | ||||
343 | /// InnerLoopVectorizer vectorizes loops which contain only one basic | |||
344 | /// block to a specified vectorization factor (VF). | |||
345 | /// This class performs the widening of scalars into vectors, or multiple | |||
346 | /// scalars. This class also implements the following features: | |||
347 | /// * It inserts an epilogue loop for handling loops that don't have iteration | |||
348 | /// counts that are known to be a multiple of the vectorization factor. | |||
349 | /// * It handles the code generation for reduction variables. | |||
350 | /// * Scalarization (implementation using scalars) of un-vectorizable | |||
351 | /// instructions. | |||
352 | /// InnerLoopVectorizer does not perform any vectorization-legality | |||
353 | /// checks, and relies on the caller to check for the different legality | |||
354 | /// aspects. The InnerLoopVectorizer relies on the | |||
355 | /// LoopVectorizationLegality class to provide information about the induction | |||
356 | /// and reduction variables that were found to a given vectorization factor. | |||
357 | class InnerLoopVectorizer { | |||
358 | public: | |||
359 | InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, | |||
360 | LoopInfo *LI, DominatorTree *DT, | |||
361 | const TargetLibraryInfo *TLI, | |||
362 | const TargetTransformInfo *TTI, AssumptionCache *AC, | |||
363 | OptimizationRemarkEmitter *ORE, unsigned VecWidth, | |||
364 | unsigned UnrollFactor, LoopVectorizationLegality *LVL, | |||
365 | LoopVectorizationCostModel *CM) | |||
366 | : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI), | |||
367 | AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor), | |||
368 | Builder(PSE.getSE()->getContext()), | |||
369 | VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {} | |||
370 | virtual ~InnerLoopVectorizer() = default; | |||
371 | ||||
372 | /// Create a new empty loop. Unlink the old loop and connect the new one. | |||
373 | /// Return the pre-header block of the new loop. | |||
374 | BasicBlock *createVectorizedLoopSkeleton(); | |||
375 | ||||
376 | /// Widen a single instruction within the innermost loop. | |||
377 | void widenInstruction(Instruction &I); | |||
378 | ||||
379 | /// Fix the vectorized code, taking care of header phi's, live-outs, and more. | |||
380 | void fixVectorizedLoop(); | |||
381 | ||||
382 | // Return true if any runtime check is added. | |||
383 | bool areSafetyChecksAdded() { return AddedSafetyChecks; } | |||
384 | ||||
385 | /// A type for vectorized values in the new loop. Each value from the | |||
386 | /// original loop, when vectorized, is represented by UF vector values in the | |||
387 | /// new unrolled loop, where UF is the unroll factor. | |||
388 | using VectorParts = SmallVector<Value *, 2>; | |||
389 | ||||
390 | /// Vectorize a single PHINode in a block. This method handles the induction | |||
391 | /// variable canonicalization. It supports both VF = 1 for unrolled loops and | |||
392 | /// arbitrary length vectors. | |||
393 | void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF); | |||
394 | ||||
395 | /// A helper function to scalarize a single Instruction in the innermost loop. | |||
396 | /// Generates a sequence of scalar instances for each lane between \p MinLane | |||
397 | /// and \p MaxLane, times each part between \p MinPart and \p MaxPart, | |||
398 | /// inclusive.. | |||
399 | void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance, | |||
400 | bool IfPredicateInstr); | |||
401 | ||||
402 | /// Widen an integer or floating-point induction variable \p IV. If \p Trunc | |||
403 | /// is provided, the integer induction variable will first be truncated to | |||
404 | /// the corresponding type. | |||
405 | void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr); | |||
406 | ||||
407 | /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a | |||
408 | /// vector or scalar value on-demand if one is not yet available. When | |||
409 | /// vectorizing a loop, we visit the definition of an instruction before its | |||
410 | /// uses. When visiting the definition, we either vectorize or scalarize the | |||
411 | /// instruction, creating an entry for it in the corresponding map. (In some | |||
412 | /// cases, such as induction variables, we will create both vector and scalar | |||
413 | /// entries.) Then, as we encounter uses of the definition, we derive values | |||
414 | /// for each scalar or vector use unless such a value is already available. | |||
415 | /// For example, if we scalarize a definition and one of its uses is vector, | |||
416 | /// we build the required vector on-demand with an insertelement sequence | |||
417 | /// when visiting the use. Otherwise, if the use is scalar, we can use the | |||
418 | /// existing scalar definition. | |||
419 | /// | |||
420 | /// Return a value in the new loop corresponding to \p V from the original | |||
421 | /// loop at unroll index \p Part. If the value has already been vectorized, | |||
422 | /// the corresponding vector entry in VectorLoopValueMap is returned. If, | |||
423 | /// however, the value has a scalar entry in VectorLoopValueMap, we construct | |||
424 | /// a new vector value on-demand by inserting the scalar values into a vector | |||
425 | /// with an insertelement sequence. If the value has been neither vectorized | |||
426 | /// nor scalarized, it must be loop invariant, so we simply broadcast the | |||
427 | /// value into a vector. | |||
428 | Value *getOrCreateVectorValue(Value *V, unsigned Part); | |||
429 | ||||
430 | /// Return a value in the new loop corresponding to \p V from the original | |||
431 | /// loop at unroll and vector indices \p Instance. If the value has been | |||
432 | /// vectorized but not scalarized, the necessary extractelement instruction | |||
433 | /// will be generated. | |||
434 | Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance); | |||
435 | ||||
436 | /// Construct the vector value of a scalarized value \p V one lane at a time. | |||
437 | void packScalarIntoVectorValue(Value *V, const VPIteration &Instance); | |||
438 | ||||
439 | /// Try to vectorize the interleaved access group that \p Instr belongs to. | |||
440 | void vectorizeInterleaveGroup(Instruction *Instr); | |||
441 | ||||
442 | /// Vectorize Load and Store instructions, optionally masking the vector | |||
443 | /// operations if \p BlockInMask is non-null. | |||
444 | void vectorizeMemoryInstruction(Instruction *Instr, | |||
445 | VectorParts *BlockInMask = nullptr); | |||
446 | ||||
447 | /// Set the debug location in the builder using the debug location in | |||
448 | /// the instruction. | |||
449 | void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr); | |||
450 | ||||
451 | protected: | |||
452 | friend class LoopVectorizationPlanner; | |||
453 | ||||
454 | /// A small list of PHINodes. | |||
455 | using PhiVector = SmallVector<PHINode *, 4>; | |||
456 | ||||
457 | /// A type for scalarized values in the new loop. Each value from the | |||
458 | /// original loop, when scalarized, is represented by UF x VF scalar values | |||
459 | /// in the new unrolled loop, where UF is the unroll factor and VF is the | |||
460 | /// vectorization factor. | |||
461 | using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>; | |||
462 | ||||
463 | /// Set up the values of the IVs correctly when exiting the vector loop. | |||
464 | void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II, | |||
465 | Value *CountRoundDown, Value *EndValue, | |||
466 | BasicBlock *MiddleBlock); | |||
467 | ||||
468 | /// Create a new induction variable inside L. | |||
469 | PHINode *createInductionVariable(Loop *L, Value *Start, Value *End, | |||
470 | Value *Step, Instruction *DL); | |||
471 | ||||
472 | /// Handle all cross-iteration phis in the header. | |||
473 | void fixCrossIterationPHIs(); | |||
474 | ||||
475 | /// Fix a first-order recurrence. This is the second phase of vectorizing | |||
476 | /// this phi node. | |||
477 | void fixFirstOrderRecurrence(PHINode *Phi); | |||
478 | ||||
479 | /// Fix a reduction cross-iteration phi. This is the second phase of | |||
480 | /// vectorizing this phi node. | |||
481 | void fixReduction(PHINode *Phi); | |||
482 | ||||
483 | /// The Loop exit block may have single value PHI nodes with some | |||
484 | /// incoming value. While vectorizing we only handled real values | |||
485 | /// that were defined inside the loop and we should have one value for | |||
486 | /// each predecessor of its parent basic block. See PR14725. | |||
487 | void fixLCSSAPHIs(); | |||
488 | ||||
489 | /// Iteratively sink the scalarized operands of a predicated instruction into | |||
490 | /// the block that was created for it. | |||
491 | void sinkScalarOperands(Instruction *PredInst); | |||
492 | ||||
493 | /// Shrinks vector element sizes to the smallest bitwidth they can be legally | |||
494 | /// represented as. | |||
495 | void truncateToMinimalBitwidths(); | |||
496 | ||||
497 | /// Insert the new loop to the loop hierarchy and pass manager | |||
498 | /// and update the analysis passes. | |||
499 | void updateAnalysis(); | |||
500 | ||||
501 | /// Create a broadcast instruction. This method generates a broadcast | |||
502 | /// instruction (shuffle) for loop invariant values and for the induction | |||
503 | /// value. If this is the induction variable then we extend it to N, N+1, ... | |||
504 | /// this is needed because each iteration in the loop corresponds to a SIMD | |||
505 | /// element. | |||
506 | virtual Value *getBroadcastInstrs(Value *V); | |||
507 | ||||
508 | /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...) | |||
509 | /// to each vector element of Val. The sequence starts at StartIndex. | |||
510 | /// \p Opcode is relevant for FP induction variable. | |||
511 | virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step, | |||
512 | Instruction::BinaryOps Opcode = | |||
513 | Instruction::BinaryOpsEnd); | |||
514 | ||||
515 | /// Compute scalar induction steps. \p ScalarIV is the scalar induction | |||
516 | /// variable on which to base the steps, \p Step is the size of the step, and | |||
517 | /// \p EntryVal is the value from the original loop that maps to the steps. | |||
518 | /// Note that \p EntryVal doesn't have to be an induction variable - it | |||
519 | /// can also be a truncate instruction. | |||
520 | void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal, | |||
521 | const InductionDescriptor &ID); | |||
522 | ||||
523 | /// Create a vector induction phi node based on an existing scalar one. \p | |||
524 | /// EntryVal is the value from the original loop that maps to the vector phi | |||
525 | /// node, and \p Step is the loop-invariant step. If \p EntryVal is a | |||
526 | /// truncate instruction, instead of widening the original IV, we widen a | |||
527 | /// version of the IV truncated to \p EntryVal's type. | |||
528 | void createVectorIntOrFpInductionPHI(const InductionDescriptor &II, | |||
529 | Value *Step, Instruction *EntryVal); | |||
530 | ||||
531 | /// Returns true if an instruction \p I should be scalarized instead of | |||
532 | /// vectorized for the chosen vectorization factor. | |||
533 | bool shouldScalarizeInstruction(Instruction *I) const; | |||
534 | ||||
535 | /// Returns true if we should generate a scalar version of \p IV. | |||
536 | bool needsScalarInduction(Instruction *IV) const; | |||
537 | ||||
538 | /// If there is a cast involved in the induction variable \p ID, which should | |||
539 | /// be ignored in the vectorized loop body, this function records the | |||
540 | /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the | |||
541 | /// cast. We had already proved that the casted Phi is equal to the uncasted | |||
542 | /// Phi in the vectorized loop (under a runtime guard), and therefore | |||
543 | /// there is no need to vectorize the cast - the same value can be used in the | |||
544 | /// vector loop for both the Phi and the cast. | |||
545 | /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified, | |||
546 | /// Otherwise, \p VectorLoopValue is a widened/vectorized value. | |||
547 | /// | |||
548 | /// \p EntryVal is the value from the original loop that maps to the vector | |||
549 | /// phi node and is used to distinguish what is the IV currently being | |||
550 | /// processed - original one (if \p EntryVal is a phi corresponding to the | |||
551 | /// original IV) or the "newly-created" one based on the proof mentioned above | |||
552 | /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the | |||
553 | /// latter case \p EntryVal is a TruncInst and we must not record anything for | |||
554 | /// that IV, but it's error-prone to expect callers of this routine to care | |||
555 | /// about that, hence this explicit parameter. | |||
556 | void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID, | |||
557 | const Instruction *EntryVal, | |||
558 | Value *VectorLoopValue, | |||
559 | unsigned Part, | |||
560 | unsigned Lane = UINT_MAX(2147483647 *2U +1U)); | |||
561 | ||||
562 | /// Generate a shuffle sequence that will reverse the vector Vec. | |||
563 | virtual Value *reverseVector(Value *Vec); | |||
564 | ||||
565 | /// Returns (and creates if needed) the original loop trip count. | |||
566 | Value *getOrCreateTripCount(Loop *NewLoop); | |||
567 | ||||
568 | /// Returns (and creates if needed) the trip count of the widened loop. | |||
569 | Value *getOrCreateVectorTripCount(Loop *NewLoop); | |||
570 | ||||
571 | /// Returns a bitcasted value to the requested vector type. | |||
572 | /// Also handles bitcasts of vector<float> <-> vector<pointer> types. | |||
573 | Value *createBitOrPointerCast(Value *V, VectorType *DstVTy, | |||
574 | const DataLayout &DL); | |||
575 | ||||
576 | /// Emit a bypass check to see if the vector trip count is zero, including if | |||
577 | /// it overflows. | |||
578 | void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass); | |||
579 | ||||
580 | /// Emit a bypass check to see if all of the SCEV assumptions we've | |||
581 | /// had to make are correct. | |||
582 | void emitSCEVChecks(Loop *L, BasicBlock *Bypass); | |||
583 | ||||
584 | /// Emit bypass checks to check any memory assumptions we may have made. | |||
585 | void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass); | |||
586 | ||||
587 | /// Add additional metadata to \p To that was not present on \p Orig. | |||
588 | /// | |||
589 | /// Currently this is used to add the noalias annotations based on the | |||
590 | /// inserted memchecks. Use this for instructions that are *cloned* into the | |||
591 | /// vector loop. | |||
592 | void addNewMetadata(Instruction *To, const Instruction *Orig); | |||
593 | ||||
594 | /// Add metadata from one instruction to another. | |||
595 | /// | |||
596 | /// This includes both the original MDs from \p From and additional ones (\see | |||
597 | /// addNewMetadata). Use this for *newly created* instructions in the vector | |||
598 | /// loop. | |||
599 | void addMetadata(Instruction *To, Instruction *From); | |||
600 | ||||
601 | /// Similar to the previous function but it adds the metadata to a | |||
602 | /// vector of instructions. | |||
603 | void addMetadata(ArrayRef<Value *> To, Instruction *From); | |||
604 | ||||
605 | /// The original loop. | |||
606 | Loop *OrigLoop; | |||
607 | ||||
608 | /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies | |||
609 | /// dynamic knowledge to simplify SCEV expressions and converts them to a | |||
610 | /// more usable form. | |||
611 | PredicatedScalarEvolution &PSE; | |||
612 | ||||
613 | /// Loop Info. | |||
614 | LoopInfo *LI; | |||
615 | ||||
616 | /// Dominator Tree. | |||
617 | DominatorTree *DT; | |||
618 | ||||
619 | /// Alias Analysis. | |||
620 | AliasAnalysis *AA; | |||
621 | ||||
622 | /// Target Library Info. | |||
623 | const TargetLibraryInfo *TLI; | |||
624 | ||||
625 | /// Target Transform Info. | |||
626 | const TargetTransformInfo *TTI; | |||
627 | ||||
628 | /// Assumption Cache. | |||
629 | AssumptionCache *AC; | |||
630 | ||||
631 | /// Interface to emit optimization remarks. | |||
632 | OptimizationRemarkEmitter *ORE; | |||
633 | ||||
634 | /// LoopVersioning. It's only set up (non-null) if memchecks were | |||
635 | /// used. | |||
636 | /// | |||
637 | /// This is currently only used to add no-alias metadata based on the | |||
638 | /// memchecks. The actually versioning is performed manually. | |||
639 | std::unique_ptr<LoopVersioning> LVer; | |||
640 | ||||
641 | /// The vectorization SIMD factor to use. Each vector will have this many | |||
642 | /// vector elements. | |||
643 | unsigned VF; | |||
644 | ||||
645 | /// The vectorization unroll factor to use. Each scalar is vectorized to this | |||
646 | /// many different vector instructions. | |||
647 | unsigned UF; | |||
648 | ||||
649 | /// The builder that we use | |||
650 | IRBuilder<> Builder; | |||
651 | ||||
652 | // --- Vectorization state --- | |||
653 | ||||
654 | /// The vector-loop preheader. | |||
655 | BasicBlock *LoopVectorPreHeader; | |||
656 | ||||
657 | /// The scalar-loop preheader. | |||
658 | BasicBlock *LoopScalarPreHeader; | |||
659 | ||||
660 | /// Middle Block between the vector and the scalar. | |||
661 | BasicBlock *LoopMiddleBlock; | |||
662 | ||||
663 | /// The ExitBlock of the scalar loop. | |||
664 | BasicBlock *LoopExitBlock; | |||
665 | ||||
666 | /// The vector loop body. | |||
667 | BasicBlock *LoopVectorBody; | |||
668 | ||||
669 | /// The scalar loop body. | |||
670 | BasicBlock *LoopScalarBody; | |||
671 | ||||
672 | /// A list of all bypass blocks. The first block is the entry of the loop. | |||
673 | SmallVector<BasicBlock *, 4> LoopBypassBlocks; | |||
674 | ||||
675 | /// The new Induction variable which was added to the new block. | |||
676 | PHINode *Induction = nullptr; | |||
677 | ||||
678 | /// The induction variable of the old basic block. | |||
679 | PHINode *OldInduction = nullptr; | |||
680 | ||||
681 | /// Maps values from the original loop to their corresponding values in the | |||
682 | /// vectorized loop. A key value can map to either vector values, scalar | |||
683 | /// values or both kinds of values, depending on whether the key was | |||
684 | /// vectorized and scalarized. | |||
685 | VectorizerValueMap VectorLoopValueMap; | |||
686 | ||||
687 | /// Store instructions that were predicated. | |||
688 | SmallVector<Instruction *, 4> PredicatedInstructions; | |||
689 | ||||
690 | /// Trip count of the original loop. | |||
691 | Value *TripCount = nullptr; | |||
692 | ||||
693 | /// Trip count of the widened loop (TripCount - TripCount % (VF*UF)) | |||
694 | Value *VectorTripCount = nullptr; | |||
695 | ||||
696 | /// The legality analysis. | |||
697 | LoopVectorizationLegality *Legal; | |||
698 | ||||
699 | /// The profitablity analysis. | |||
700 | LoopVectorizationCostModel *Cost; | |||
701 | ||||
702 | // Record whether runtime checks are added. | |||
703 | bool AddedSafetyChecks = false; | |||
704 | ||||
705 | // Holds the end values for each induction variable. We save the end values | |||
706 | // so we can later fix-up the external users of the induction variables. | |||
707 | DenseMap<PHINode *, Value *> IVEndValues; | |||
708 | }; | |||
709 | ||||
710 | class InnerLoopUnroller : public InnerLoopVectorizer { | |||
711 | public: | |||
712 | InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE, | |||
713 | LoopInfo *LI, DominatorTree *DT, | |||
714 | const TargetLibraryInfo *TLI, | |||
715 | const TargetTransformInfo *TTI, AssumptionCache *AC, | |||
716 | OptimizationRemarkEmitter *ORE, unsigned UnrollFactor, | |||
717 | LoopVectorizationLegality *LVL, | |||
718 | LoopVectorizationCostModel *CM) | |||
719 | : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1, | |||
720 | UnrollFactor, LVL, CM) {} | |||
721 | ||||
722 | private: | |||
723 | Value *getBroadcastInstrs(Value *V) override; | |||
724 | Value *getStepVector(Value *Val, int StartIdx, Value *Step, | |||
725 | Instruction::BinaryOps Opcode = | |||
726 | Instruction::BinaryOpsEnd) override; | |||
727 | Value *reverseVector(Value *Vec) override; | |||
728 | }; | |||
729 | ||||
730 | } // end namespace llvm | |||
731 | ||||
732 | /// Look for a meaningful debug location on the instruction or it's | |||
733 | /// operands. | |||
734 | static Instruction *getDebugLocFromInstOrOperands(Instruction *I) { | |||
735 | if (!I) | |||
736 | return I; | |||
737 | ||||
738 | DebugLoc Empty; | |||
739 | if (I->getDebugLoc() != Empty) | |||
740 | return I; | |||
741 | ||||
742 | for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) { | |||
743 | if (Instruction *OpInst = dyn_cast<Instruction>(*OI)) | |||
744 | if (OpInst->getDebugLoc() != Empty) | |||
745 | return OpInst; | |||
746 | } | |||
747 | ||||
748 | return I; | |||
749 | } | |||
750 | ||||
751 | void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) { | |||
752 | if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) { | |||
753 | const DILocation *DIL = Inst->getDebugLoc(); | |||
754 | if (DIL && Inst->getFunction()->isDebugInfoForProfiling() && | |||
755 | !isa<DbgInfoIntrinsic>(Inst)) | |||
756 | B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF)); | |||
757 | else | |||
758 | B.SetCurrentDebugLocation(DIL); | |||
759 | } else | |||
760 | B.SetCurrentDebugLocation(DebugLoc()); | |||
761 | } | |||
762 | ||||
763 | #ifndef NDEBUG | |||
764 | /// \return string containing a file name and a line # for the given loop. | |||
765 | static std::string getDebugLocString(const Loop *L) { | |||
766 | std::string Result; | |||
767 | if (L) { | |||
768 | raw_string_ostream OS(Result); | |||
769 | if (const DebugLoc LoopDbgLoc = L->getStartLoc()) | |||
770 | LoopDbgLoc.print(OS); | |||
771 | else | |||
772 | // Just print the module name. | |||
773 | OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier(); | |||
774 | OS.flush(); | |||
775 | } | |||
776 | return Result; | |||
777 | } | |||
778 | #endif | |||
779 | ||||
780 | void InnerLoopVectorizer::addNewMetadata(Instruction *To, | |||
781 | const Instruction *Orig) { | |||
782 | // If the loop was versioned with memchecks, add the corresponding no-alias | |||
783 | // metadata. | |||
784 | if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig))) | |||
785 | LVer->annotateInstWithNoAlias(To, Orig); | |||
786 | } | |||
787 | ||||
788 | void InnerLoopVectorizer::addMetadata(Instruction *To, | |||
789 | Instruction *From) { | |||
790 | propagateMetadata(To, From); | |||
791 | addNewMetadata(To, From); | |||
792 | } | |||
793 | ||||
794 | void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To, | |||
795 | Instruction *From) { | |||
796 | for (Value *V : To) { | |||
797 | if (Instruction *I = dyn_cast<Instruction>(V)) | |||
798 | addMetadata(I, From); | |||
799 | } | |||
800 | } | |||
801 | ||||
802 | namespace llvm { | |||
803 | ||||
804 | /// The group of interleaved loads/stores sharing the same stride and | |||
805 | /// close to each other. | |||
806 | /// | |||
807 | /// Each member in this group has an index starting from 0, and the largest | |||
808 | /// index should be less than interleaved factor, which is equal to the absolute | |||
809 | /// value of the access's stride. | |||
810 | /// | |||
811 | /// E.g. An interleaved load group of factor 4: | |||
812 | /// for (unsigned i = 0; i < 1024; i+=4) { | |||
813 | /// a = A[i]; // Member of index 0 | |||
814 | /// b = A[i+1]; // Member of index 1 | |||
815 | /// d = A[i+3]; // Member of index 3 | |||
816 | /// ... | |||
817 | /// } | |||
818 | /// | |||
819 | /// An interleaved store group of factor 4: | |||
820 | /// for (unsigned i = 0; i < 1024; i+=4) { | |||
821 | /// ... | |||
822 | /// A[i] = a; // Member of index 0 | |||
823 | /// A[i+1] = b; // Member of index 1 | |||
824 | /// A[i+2] = c; // Member of index 2 | |||
825 | /// A[i+3] = d; // Member of index 3 | |||
826 | /// } | |||
827 | /// | |||
828 | /// Note: the interleaved load group could have gaps (missing members), but | |||
829 | /// the interleaved store group doesn't allow gaps. | |||
830 | class InterleaveGroup { | |||
831 | public: | |||
832 | InterleaveGroup(Instruction *Instr, int Stride, unsigned Align) | |||
833 | : Align(Align), InsertPos(Instr) { | |||
834 | assert(Align && "The alignment should be non-zero")(static_cast <bool> (Align && "The alignment should be non-zero" ) ? void (0) : __assert_fail ("Align && \"The alignment should be non-zero\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 834, __extension__ __PRETTY_FUNCTION__)); | |||
835 | ||||
836 | Factor = std::abs(Stride); | |||
837 | assert(Factor > 1 && "Invalid interleave factor")(static_cast <bool> (Factor > 1 && "Invalid interleave factor" ) ? void (0) : __assert_fail ("Factor > 1 && \"Invalid interleave factor\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 837, __extension__ __PRETTY_FUNCTION__)); | |||
838 | ||||
839 | Reverse = Stride < 0; | |||
840 | Members[0] = Instr; | |||
841 | } | |||
842 | ||||
843 | bool isReverse() const { return Reverse; } | |||
844 | unsigned getFactor() const { return Factor; } | |||
845 | unsigned getAlignment() const { return Align; } | |||
846 | unsigned getNumMembers() const { return Members.size(); } | |||
847 | ||||
848 | /// Try to insert a new member \p Instr with index \p Index and | |||
849 | /// alignment \p NewAlign. The index is related to the leader and it could be | |||
850 | /// negative if it is the new leader. | |||
851 | /// | |||
852 | /// \returns false if the instruction doesn't belong to the group. | |||
853 | bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) { | |||
854 | assert(NewAlign && "The new member's alignment should be non-zero")(static_cast <bool> (NewAlign && "The new member's alignment should be non-zero" ) ? void (0) : __assert_fail ("NewAlign && \"The new member's alignment should be non-zero\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 854, __extension__ __PRETTY_FUNCTION__)); | |||
855 | ||||
856 | int Key = Index + SmallestKey; | |||
857 | ||||
858 | // Skip if there is already a member with the same index. | |||
859 | if (Members.count(Key)) | |||
860 | return false; | |||
861 | ||||
862 | if (Key > LargestKey) { | |||
863 | // The largest index is always less than the interleave factor. | |||
864 | if (Index >= static_cast<int>(Factor)) | |||
865 | return false; | |||
866 | ||||
867 | LargestKey = Key; | |||
868 | } else if (Key < SmallestKey) { | |||
869 | // The largest index is always less than the interleave factor. | |||
870 | if (LargestKey - Key >= static_cast<int>(Factor)) | |||
871 | return false; | |||
872 | ||||
873 | SmallestKey = Key; | |||
874 | } | |||
875 | ||||
876 | // It's always safe to select the minimum alignment. | |||
877 | Align = std::min(Align, NewAlign); | |||
878 | Members[Key] = Instr; | |||
879 | return true; | |||
880 | } | |||
881 | ||||
882 | /// Get the member with the given index \p Index | |||
883 | /// | |||
884 | /// \returns nullptr if contains no such member. | |||
885 | Instruction *getMember(unsigned Index) const { | |||
886 | int Key = SmallestKey + Index; | |||
887 | if (!Members.count(Key)) | |||
888 | return nullptr; | |||
889 | ||||
890 | return Members.find(Key)->second; | |||
891 | } | |||
892 | ||||
893 | /// Get the index for the given member. Unlike the key in the member | |||
894 | /// map, the index starts from 0. | |||
895 | unsigned getIndex(Instruction *Instr) const { | |||
896 | for (auto I : Members) | |||
897 | if (I.second == Instr) | |||
898 | return I.first - SmallestKey; | |||
899 | ||||
900 | llvm_unreachable("InterleaveGroup contains no such member")::llvm::llvm_unreachable_internal("InterleaveGroup contains no such member" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 900); | |||
901 | } | |||
902 | ||||
903 | Instruction *getInsertPos() const { return InsertPos; } | |||
904 | void setInsertPos(Instruction *Inst) { InsertPos = Inst; } | |||
905 | ||||
906 | /// Add metadata (e.g. alias info) from the instructions in this group to \p | |||
907 | /// NewInst. | |||
908 | /// | |||
909 | /// FIXME: this function currently does not add noalias metadata a'la | |||
910 | /// addNewMedata. To do that we need to compute the intersection of the | |||
911 | /// noalias info from all members. | |||
912 | void addMetadata(Instruction *NewInst) const { | |||
913 | SmallVector<Value *, 4> VL; | |||
914 | std::transform(Members.begin(), Members.end(), std::back_inserter(VL), | |||
915 | [](std::pair<int, Instruction *> p) { return p.second; }); | |||
916 | propagateMetadata(NewInst, VL); | |||
917 | } | |||
918 | ||||
919 | private: | |||
920 | unsigned Factor; // Interleave Factor. | |||
921 | bool Reverse; | |||
922 | unsigned Align; | |||
923 | DenseMap<int, Instruction *> Members; | |||
924 | int SmallestKey = 0; | |||
925 | int LargestKey = 0; | |||
926 | ||||
927 | // To avoid breaking dependences, vectorized instructions of an interleave | |||
928 | // group should be inserted at either the first load or the last store in | |||
929 | // program order. | |||
930 | // | |||
931 | // E.g. %even = load i32 // Insert Position | |||
932 | // %add = add i32 %even // Use of %even | |||
933 | // %odd = load i32 | |||
934 | // | |||
935 | // store i32 %even | |||
936 | // %odd = add i32 // Def of %odd | |||
937 | // store i32 %odd // Insert Position | |||
938 | Instruction *InsertPos; | |||
939 | }; | |||
940 | } // end namespace llvm | |||
941 | ||||
942 | namespace { | |||
943 | ||||
944 | /// Drive the analysis of interleaved memory accesses in the loop. | |||
945 | /// | |||
946 | /// Use this class to analyze interleaved accesses only when we can vectorize | |||
947 | /// a loop. Otherwise it's meaningless to do analysis as the vectorization | |||
948 | /// on interleaved accesses is unsafe. | |||
949 | /// | |||
950 | /// The analysis collects interleave groups and records the relationships | |||
951 | /// between the member and the group in a map. | |||
952 | class InterleavedAccessInfo { | |||
953 | public: | |||
954 | InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L, | |||
955 | DominatorTree *DT, LoopInfo *LI, | |||
956 | const LoopAccessInfo *LAI) | |||
957 | : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(LAI) {} | |||
958 | ||||
959 | ~InterleavedAccessInfo() { | |||
960 | SmallPtrSet<InterleaveGroup *, 4> DelSet; | |||
961 | // Avoid releasing a pointer twice. | |||
962 | for (auto &I : InterleaveGroupMap) | |||
963 | DelSet.insert(I.second); | |||
964 | for (auto *Ptr : DelSet) | |||
965 | delete Ptr; | |||
966 | } | |||
967 | ||||
968 | /// Analyze the interleaved accesses and collect them in interleave | |||
969 | /// groups. Substitute symbolic strides using \p Strides. | |||
970 | void analyzeInterleaving(); | |||
971 | ||||
972 | /// Check if \p Instr belongs to any interleave group. | |||
973 | bool isInterleaved(Instruction *Instr) const { | |||
974 | return InterleaveGroupMap.count(Instr); | |||
975 | } | |||
976 | ||||
977 | /// Get the interleave group that \p Instr belongs to. | |||
978 | /// | |||
979 | /// \returns nullptr if doesn't have such group. | |||
980 | InterleaveGroup *getInterleaveGroup(Instruction *Instr) const { | |||
981 | if (InterleaveGroupMap.count(Instr)) | |||
982 | return InterleaveGroupMap.find(Instr)->second; | |||
983 | return nullptr; | |||
984 | } | |||
985 | ||||
986 | /// Returns true if an interleaved group that may access memory | |||
987 | /// out-of-bounds requires a scalar epilogue iteration for correctness. | |||
988 | bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; } | |||
989 | ||||
990 | private: | |||
991 | /// A wrapper around ScalarEvolution, used to add runtime SCEV checks. | |||
992 | /// Simplifies SCEV expressions in the context of existing SCEV assumptions. | |||
993 | /// The interleaved access analysis can also add new predicates (for example | |||
994 | /// by versioning strides of pointers). | |||
995 | PredicatedScalarEvolution &PSE; | |||
996 | ||||
997 | Loop *TheLoop; | |||
998 | DominatorTree *DT; | |||
999 | LoopInfo *LI; | |||
1000 | const LoopAccessInfo *LAI; | |||
1001 | ||||
1002 | /// True if the loop may contain non-reversed interleaved groups with | |||
1003 | /// out-of-bounds accesses. We ensure we don't speculatively access memory | |||
1004 | /// out-of-bounds by executing at least one scalar epilogue iteration. | |||
1005 | bool RequiresScalarEpilogue = false; | |||
1006 | ||||
1007 | /// Holds the relationships between the members and the interleave group. | |||
1008 | DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap; | |||
1009 | ||||
1010 | /// Holds dependences among the memory accesses in the loop. It maps a source | |||
1011 | /// access to a set of dependent sink accesses. | |||
1012 | DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences; | |||
1013 | ||||
1014 | /// The descriptor for a strided memory access. | |||
1015 | struct StrideDescriptor { | |||
1016 | StrideDescriptor() = default; | |||
1017 | StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size, | |||
1018 | unsigned Align) | |||
1019 | : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {} | |||
1020 | ||||
1021 | // The access's stride. It is negative for a reverse access. | |||
1022 | int64_t Stride = 0; | |||
1023 | ||||
1024 | // The scalar expression of this access. | |||
1025 | const SCEV *Scev = nullptr; | |||
1026 | ||||
1027 | // The size of the memory object. | |||
1028 | uint64_t Size = 0; | |||
1029 | ||||
1030 | // The alignment of this access. | |||
1031 | unsigned Align = 0; | |||
1032 | }; | |||
1033 | ||||
1034 | /// A type for holding instructions and their stride descriptors. | |||
1035 | using StrideEntry = std::pair<Instruction *, StrideDescriptor>; | |||
1036 | ||||
1037 | /// Create a new interleave group with the given instruction \p Instr, | |||
1038 | /// stride \p Stride and alignment \p Align. | |||
1039 | /// | |||
1040 | /// \returns the newly created interleave group. | |||
1041 | InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride, | |||
1042 | unsigned Align) { | |||
1043 | assert(!InterleaveGroupMap.count(Instr) &&(static_cast <bool> (!InterleaveGroupMap.count(Instr) && "Already in an interleaved access group") ? void (0) : __assert_fail ("!InterleaveGroupMap.count(Instr) && \"Already in an interleaved access group\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1044, __extension__ __PRETTY_FUNCTION__)) | |||
1044 | "Already in an interleaved access group")(static_cast <bool> (!InterleaveGroupMap.count(Instr) && "Already in an interleaved access group") ? void (0) : __assert_fail ("!InterleaveGroupMap.count(Instr) && \"Already in an interleaved access group\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1044, __extension__ __PRETTY_FUNCTION__)); | |||
1045 | InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align); | |||
1046 | return InterleaveGroupMap[Instr]; | |||
1047 | } | |||
1048 | ||||
1049 | /// Release the group and remove all the relationships. | |||
1050 | void releaseGroup(InterleaveGroup *Group) { | |||
1051 | for (unsigned i = 0; i < Group->getFactor(); i++) | |||
1052 | if (Instruction *Member = Group->getMember(i)) | |||
1053 | InterleaveGroupMap.erase(Member); | |||
1054 | ||||
1055 | delete Group; | |||
1056 | } | |||
1057 | ||||
1058 | /// Collect all the accesses with a constant stride in program order. | |||
1059 | void collectConstStrideAccesses( | |||
1060 | MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, | |||
1061 | const ValueToValueMap &Strides); | |||
1062 | ||||
1063 | /// Returns true if \p Stride is allowed in an interleaved group. | |||
1064 | static bool isStrided(int Stride) { | |||
1065 | unsigned Factor = std::abs(Stride); | |||
1066 | return Factor >= 2 && Factor <= MaxInterleaveGroupFactor; | |||
1067 | } | |||
1068 | ||||
1069 | /// Returns true if \p BB is a predicated block. | |||
1070 | bool isPredicated(BasicBlock *BB) const { | |||
1071 | return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); | |||
1072 | } | |||
1073 | ||||
1074 | /// Returns true if LoopAccessInfo can be used for dependence queries. | |||
1075 | bool areDependencesValid() const { | |||
1076 | return LAI && LAI->getDepChecker().getDependences(); | |||
1077 | } | |||
1078 | ||||
1079 | /// Returns true if memory accesses \p A and \p B can be reordered, if | |||
1080 | /// necessary, when constructing interleaved groups. | |||
1081 | /// | |||
1082 | /// \p A must precede \p B in program order. We return false if reordering is | |||
1083 | /// not necessary or is prevented because \p A and \p B may be dependent. | |||
1084 | bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A, | |||
1085 | StrideEntry *B) const { | |||
1086 | // Code motion for interleaved accesses can potentially hoist strided loads | |||
1087 | // and sink strided stores. The code below checks the legality of the | |||
1088 | // following two conditions: | |||
1089 | // | |||
1090 | // 1. Potentially moving a strided load (B) before any store (A) that | |||
1091 | // precedes B, or | |||
1092 | // | |||
1093 | // 2. Potentially moving a strided store (A) after any load or store (B) | |||
1094 | // that A precedes. | |||
1095 | // | |||
1096 | // It's legal to reorder A and B if we know there isn't a dependence from A | |||
1097 | // to B. Note that this determination is conservative since some | |||
1098 | // dependences could potentially be reordered safely. | |||
1099 | ||||
1100 | // A is potentially the source of a dependence. | |||
1101 | auto *Src = A->first; | |||
1102 | auto SrcDes = A->second; | |||
1103 | ||||
1104 | // B is potentially the sink of a dependence. | |||
1105 | auto *Sink = B->first; | |||
1106 | auto SinkDes = B->second; | |||
1107 | ||||
1108 | // Code motion for interleaved accesses can't violate WAR dependences. | |||
1109 | // Thus, reordering is legal if the source isn't a write. | |||
1110 | if (!Src->mayWriteToMemory()) | |||
1111 | return true; | |||
1112 | ||||
1113 | // At least one of the accesses must be strided. | |||
1114 | if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride)) | |||
1115 | return true; | |||
1116 | ||||
1117 | // If dependence information is not available from LoopAccessInfo, | |||
1118 | // conservatively assume the instructions can't be reordered. | |||
1119 | if (!areDependencesValid()) | |||
1120 | return false; | |||
1121 | ||||
1122 | // If we know there is a dependence from source to sink, assume the | |||
1123 | // instructions can't be reordered. Otherwise, reordering is legal. | |||
1124 | return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink); | |||
1125 | } | |||
1126 | ||||
1127 | /// Collect the dependences from LoopAccessInfo. | |||
1128 | /// | |||
1129 | /// We process the dependences once during the interleaved access analysis to | |||
1130 | /// enable constant-time dependence queries. | |||
1131 | void collectDependences() { | |||
1132 | if (!areDependencesValid()) | |||
1133 | return; | |||
1134 | auto *Deps = LAI->getDepChecker().getDependences(); | |||
1135 | for (auto Dep : *Deps) | |||
1136 | Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI)); | |||
1137 | } | |||
1138 | }; | |||
1139 | ||||
1140 | } // end anonymous namespace | |||
1141 | ||||
1142 | static void emitMissedWarning(Function *F, Loop *L, | |||
1143 | const LoopVectorizeHints &LH, | |||
1144 | OptimizationRemarkEmitter *ORE) { | |||
1145 | LH.emitRemarkWithHints(); | |||
1146 | ||||
1147 | if (LH.getForce() == LoopVectorizeHints::FK_Enabled) { | |||
1148 | if (LH.getWidth() != 1) | |||
1149 | ORE->emit(DiagnosticInfoOptimizationFailure( | |||
1150 | DEBUG_TYPE"loop-vectorize", "FailedRequestedVectorization", | |||
1151 | L->getStartLoc(), L->getHeader()) | |||
1152 | << "loop not vectorized: " | |||
1153 | << "failed explicitly specified loop vectorization"); | |||
1154 | else if (LH.getInterleave() != 1) | |||
1155 | ORE->emit(DiagnosticInfoOptimizationFailure( | |||
1156 | DEBUG_TYPE"loop-vectorize", "FailedRequestedInterleaving", L->getStartLoc(), | |||
1157 | L->getHeader()) | |||
1158 | << "loop not interleaved: " | |||
1159 | << "failed explicitly specified loop interleaving"); | |||
1160 | } | |||
1161 | } | |||
1162 | ||||
1163 | namespace llvm { | |||
1164 | ||||
1165 | /// LoopVectorizationCostModel - estimates the expected speedups due to | |||
1166 | /// vectorization. | |||
1167 | /// In many cases vectorization is not profitable. This can happen because of | |||
1168 | /// a number of reasons. In this class we mainly attempt to predict the | |||
1169 | /// expected speedup/slowdowns due to the supported instruction set. We use the | |||
1170 | /// TargetTransformInfo to query the different backends for the cost of | |||
1171 | /// different operations. | |||
1172 | class LoopVectorizationCostModel { | |||
1173 | public: | |||
1174 | LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE, | |||
1175 | LoopInfo *LI, LoopVectorizationLegality *Legal, | |||
1176 | const TargetTransformInfo &TTI, | |||
1177 | const TargetLibraryInfo *TLI, DemandedBits *DB, | |||
1178 | AssumptionCache *AC, | |||
1179 | OptimizationRemarkEmitter *ORE, const Function *F, | |||
1180 | const LoopVectorizeHints *Hints, | |||
1181 | InterleavedAccessInfo &IAI) | |||
1182 | : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB), | |||
1183 | AC(AC), ORE(ORE), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {} | |||
1184 | ||||
1185 | /// \return An upper bound for the vectorization factor, or None if | |||
1186 | /// vectorization should be avoided up front. | |||
1187 | Optional<unsigned> computeMaxVF(bool OptForSize); | |||
1188 | ||||
1189 | /// \return The most profitable vectorization factor and the cost of that VF. | |||
1190 | /// This method checks every power of two up to MaxVF. If UserVF is not ZERO | |||
1191 | /// then this vectorization factor will be selected if vectorization is | |||
1192 | /// possible. | |||
1193 | VectorizationFactor selectVectorizationFactor(unsigned MaxVF); | |||
1194 | ||||
1195 | /// Setup cost-based decisions for user vectorization factor. | |||
1196 | void selectUserVectorizationFactor(unsigned UserVF) { | |||
1197 | collectUniformsAndScalars(UserVF); | |||
1198 | collectInstsToScalarize(UserVF); | |||
1199 | } | |||
1200 | ||||
1201 | /// \return The size (in bits) of the smallest and widest types in the code | |||
1202 | /// that needs to be vectorized. We ignore values that remain scalar such as | |||
1203 | /// 64 bit loop indices. | |||
1204 | std::pair<unsigned, unsigned> getSmallestAndWidestTypes(); | |||
1205 | ||||
1206 | /// \return The desired interleave count. | |||
1207 | /// If interleave count has been specified by metadata it will be returned. | |||
1208 | /// Otherwise, the interleave count is computed and returned. VF and LoopCost | |||
1209 | /// are the selected vectorization factor and the cost of the selected VF. | |||
1210 | unsigned selectInterleaveCount(bool OptForSize, unsigned VF, | |||
1211 | unsigned LoopCost); | |||
1212 | ||||
1213 | /// Memory access instruction may be vectorized in more than one way. | |||
1214 | /// Form of instruction after vectorization depends on cost. | |||
1215 | /// This function takes cost-based decisions for Load/Store instructions | |||
1216 | /// and collects them in a map. This decisions map is used for building | |||
1217 | /// the lists of loop-uniform and loop-scalar instructions. | |||
1218 | /// The calculated cost is saved with widening decision in order to | |||
1219 | /// avoid redundant calculations. | |||
1220 | void setCostBasedWideningDecision(unsigned VF); | |||
1221 | ||||
1222 | /// A struct that represents some properties of the register usage | |||
1223 | /// of a loop. | |||
1224 | struct RegisterUsage { | |||
1225 | /// Holds the number of loop invariant values that are used in the loop. | |||
1226 | unsigned LoopInvariantRegs; | |||
1227 | ||||
1228 | /// Holds the maximum number of concurrent live intervals in the loop. | |||
1229 | unsigned MaxLocalUsers; | |||
1230 | }; | |||
1231 | ||||
1232 | /// \return Returns information about the register usages of the loop for the | |||
1233 | /// given vectorization factors. | |||
1234 | SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs); | |||
1235 | ||||
1236 | /// Collect values we want to ignore in the cost model. | |||
1237 | void collectValuesToIgnore(); | |||
1238 | ||||
1239 | /// \returns The smallest bitwidth each instruction can be represented with. | |||
1240 | /// The vector equivalents of these instructions should be truncated to this | |||
1241 | /// type. | |||
1242 | const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const { | |||
1243 | return MinBWs; | |||
1244 | } | |||
1245 | ||||
1246 | /// \returns True if it is more profitable to scalarize instruction \p I for | |||
1247 | /// vectorization factor \p VF. | |||
1248 | bool isProfitableToScalarize(Instruction *I, unsigned VF) const { | |||
1249 | assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.")(static_cast <bool> (VF > 1 && "Profitable to scalarize relevant only for VF > 1." ) ? void (0) : __assert_fail ("VF > 1 && \"Profitable to scalarize relevant only for VF > 1.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1249, __extension__ __PRETTY_FUNCTION__)); | |||
1250 | auto Scalars = InstsToScalarize.find(VF); | |||
1251 | assert(Scalars != InstsToScalarize.end() &&(static_cast <bool> (Scalars != InstsToScalarize.end() && "VF not yet analyzed for scalarization profitability") ? void (0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1252, __extension__ __PRETTY_FUNCTION__)) | |||
1252 | "VF not yet analyzed for scalarization profitability")(static_cast <bool> (Scalars != InstsToScalarize.end() && "VF not yet analyzed for scalarization profitability") ? void (0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1252, __extension__ __PRETTY_FUNCTION__)); | |||
1253 | return Scalars->second.count(I); | |||
1254 | } | |||
1255 | ||||
1256 | /// Returns true if \p I is known to be uniform after vectorization. | |||
1257 | bool isUniformAfterVectorization(Instruction *I, unsigned VF) const { | |||
1258 | if (VF == 1) | |||
1259 | return true; | |||
1260 | assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity")(static_cast <bool> (Uniforms.count(VF) && "VF not yet analyzed for uniformity" ) ? void (0) : __assert_fail ("Uniforms.count(VF) && \"VF not yet analyzed for uniformity\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1260, __extension__ __PRETTY_FUNCTION__)); | |||
1261 | auto UniformsPerVF = Uniforms.find(VF); | |||
1262 | return UniformsPerVF->second.count(I); | |||
1263 | } | |||
1264 | ||||
1265 | /// Returns true if \p I is known to be scalar after vectorization. | |||
1266 | bool isScalarAfterVectorization(Instruction *I, unsigned VF) const { | |||
1267 | if (VF == 1) | |||
1268 | return true; | |||
1269 | assert(Scalars.count(VF) && "Scalar values are not calculated for VF")(static_cast <bool> (Scalars.count(VF) && "Scalar values are not calculated for VF" ) ? void (0) : __assert_fail ("Scalars.count(VF) && \"Scalar values are not calculated for VF\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1269, __extension__ __PRETTY_FUNCTION__)); | |||
1270 | auto ScalarsPerVF = Scalars.find(VF); | |||
1271 | return ScalarsPerVF->second.count(I); | |||
1272 | } | |||
1273 | ||||
1274 | /// \returns True if instruction \p I can be truncated to a smaller bitwidth | |||
1275 | /// for vectorization factor \p VF. | |||
1276 | bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const { | |||
1277 | return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) && | |||
1278 | !isScalarAfterVectorization(I, VF); | |||
1279 | } | |||
1280 | ||||
1281 | /// Decision that was taken during cost calculation for memory instruction. | |||
1282 | enum InstWidening { | |||
1283 | CM_Unknown, | |||
1284 | CM_Widen, // For consecutive accesses with stride +1. | |||
1285 | CM_Widen_Reverse, // For consecutive accesses with stride -1. | |||
1286 | CM_Interleave, | |||
1287 | CM_GatherScatter, | |||
1288 | CM_Scalarize | |||
1289 | }; | |||
1290 | ||||
1291 | /// Save vectorization decision \p W and \p Cost taken by the cost model for | |||
1292 | /// instruction \p I and vector width \p VF. | |||
1293 | void setWideningDecision(Instruction *I, unsigned VF, InstWidening W, | |||
1294 | unsigned Cost) { | |||
1295 | assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2" ) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1295, __extension__ __PRETTY_FUNCTION__)); | |||
1296 | WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost); | |||
1297 | } | |||
1298 | ||||
1299 | /// Save vectorization decision \p W and \p Cost taken by the cost model for | |||
1300 | /// interleaving group \p Grp and vector width \p VF. | |||
1301 | void setWideningDecision(const InterleaveGroup *Grp, unsigned VF, | |||
1302 | InstWidening W, unsigned Cost) { | |||
1303 | assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2" ) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1303, __extension__ __PRETTY_FUNCTION__)); | |||
1304 | /// Broadcast this decicion to all instructions inside the group. | |||
1305 | /// But the cost will be assigned to one instruction only. | |||
1306 | for (unsigned i = 0; i < Grp->getFactor(); ++i) { | |||
1307 | if (auto *I = Grp->getMember(i)) { | |||
1308 | if (Grp->getInsertPos() == I) | |||
1309 | WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost); | |||
1310 | else | |||
1311 | WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0); | |||
1312 | } | |||
1313 | } | |||
1314 | } | |||
1315 | ||||
1316 | /// Return the cost model decision for the given instruction \p I and vector | |||
1317 | /// width \p VF. Return CM_Unknown if this instruction did not pass | |||
1318 | /// through the cost modeling. | |||
1319 | InstWidening getWideningDecision(Instruction *I, unsigned VF) { | |||
1320 | assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2" ) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1320, __extension__ __PRETTY_FUNCTION__)); | |||
1321 | std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF); | |||
1322 | auto Itr = WideningDecisions.find(InstOnVF); | |||
1323 | if (Itr == WideningDecisions.end()) | |||
1324 | return CM_Unknown; | |||
1325 | return Itr->second.first; | |||
1326 | } | |||
1327 | ||||
1328 | /// Return the vectorization cost for the given instruction \p I and vector | |||
1329 | /// width \p VF. | |||
1330 | unsigned getWideningCost(Instruction *I, unsigned VF) { | |||
1331 | assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2" ) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1331, __extension__ __PRETTY_FUNCTION__)); | |||
1332 | std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF); | |||
1333 | assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated")(static_cast <bool> (WideningDecisions.count(InstOnVF) && "The cost is not calculated") ? void (0) : __assert_fail ("WideningDecisions.count(InstOnVF) && \"The cost is not calculated\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1333, __extension__ __PRETTY_FUNCTION__)); | |||
1334 | return WideningDecisions[InstOnVF].second; | |||
1335 | } | |||
1336 | ||||
1337 | /// Return True if instruction \p I is an optimizable truncate whose operand | |||
1338 | /// is an induction variable. Such a truncate will be removed by adding a new | |||
1339 | /// induction variable with the destination type. | |||
1340 | bool isOptimizableIVTruncate(Instruction *I, unsigned VF) { | |||
1341 | // If the instruction is not a truncate, return false. | |||
1342 | auto *Trunc = dyn_cast<TruncInst>(I); | |||
1343 | if (!Trunc) | |||
1344 | return false; | |||
1345 | ||||
1346 | // Get the source and destination types of the truncate. | |||
1347 | Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF); | |||
1348 | Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF); | |||
1349 | ||||
1350 | // If the truncate is free for the given types, return false. Replacing a | |||
1351 | // free truncate with an induction variable would add an induction variable | |||
1352 | // update instruction to each iteration of the loop. We exclude from this | |||
1353 | // check the primary induction variable since it will need an update | |||
1354 | // instruction regardless. | |||
1355 | Value *Op = Trunc->getOperand(0); | |||
1356 | if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy)) | |||
1357 | return false; | |||
1358 | ||||
1359 | // If the truncated value is not an induction variable, return false. | |||
1360 | return Legal->isInductionPhi(Op); | |||
1361 | } | |||
1362 | ||||
1363 | /// Collects the instructions to scalarize for each predicated instruction in | |||
1364 | /// the loop. | |||
1365 | void collectInstsToScalarize(unsigned VF); | |||
1366 | ||||
1367 | /// Collect Uniform and Scalar values for the given \p VF. | |||
1368 | /// The sets depend on CM decision for Load/Store instructions | |||
1369 | /// that may be vectorized as interleave, gather-scatter or scalarized. | |||
1370 | void collectUniformsAndScalars(unsigned VF) { | |||
1371 | // Do the analysis once. | |||
1372 | if (VF == 1 || Uniforms.count(VF)) | |||
1373 | return; | |||
1374 | setCostBasedWideningDecision(VF); | |||
1375 | collectLoopUniforms(VF); | |||
1376 | collectLoopScalars(VF); | |||
1377 | } | |||
1378 | ||||
1379 | /// Returns true if the target machine supports masked store operation | |||
1380 | /// for the given \p DataType and kind of access to \p Ptr. | |||
1381 | bool isLegalMaskedStore(Type *DataType, Value *Ptr) { | |||
1382 | return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType); | |||
1383 | } | |||
1384 | ||||
1385 | /// Returns true if the target machine supports masked load operation | |||
1386 | /// for the given \p DataType and kind of access to \p Ptr. | |||
1387 | bool isLegalMaskedLoad(Type *DataType, Value *Ptr) { | |||
1388 | return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType); | |||
1389 | } | |||
1390 | ||||
1391 | /// Returns true if the target machine supports masked scatter operation | |||
1392 | /// for the given \p DataType. | |||
1393 | bool isLegalMaskedScatter(Type *DataType) { | |||
1394 | return TTI.isLegalMaskedScatter(DataType); | |||
1395 | } | |||
1396 | ||||
1397 | /// Returns true if the target machine supports masked gather operation | |||
1398 | /// for the given \p DataType. | |||
1399 | bool isLegalMaskedGather(Type *DataType) { | |||
1400 | return TTI.isLegalMaskedGather(DataType); | |||
1401 | } | |||
1402 | ||||
1403 | /// Returns true if the target machine can represent \p V as a masked gather | |||
1404 | /// or scatter operation. | |||
1405 | bool isLegalGatherOrScatter(Value *V) { | |||
1406 | bool LI = isa<LoadInst>(V); | |||
1407 | bool SI = isa<StoreInst>(V); | |||
1408 | if (!LI && !SI) | |||
1409 | return false; | |||
1410 | auto *Ty = getMemInstValueType(V); | |||
1411 | return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty)); | |||
1412 | } | |||
1413 | ||||
1414 | /// Returns true if \p I is an instruction that will be scalarized with | |||
1415 | /// predication. Such instructions include conditional stores and | |||
1416 | /// instructions that may divide by zero. | |||
1417 | bool isScalarWithPredication(Instruction *I); | |||
1418 | ||||
1419 | /// Returns true if \p I is a memory instruction with consecutive memory | |||
1420 | /// access that can be widened. | |||
1421 | bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1); | |||
1422 | ||||
1423 | /// Check if \p Instr belongs to any interleaved access group. | |||
1424 | bool isAccessInterleaved(Instruction *Instr) { | |||
1425 | return InterleaveInfo.isInterleaved(Instr); | |||
1426 | } | |||
1427 | ||||
1428 | /// Get the interleaved access group that \p Instr belongs to. | |||
1429 | const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) { | |||
1430 | return InterleaveInfo.getInterleaveGroup(Instr); | |||
1431 | } | |||
1432 | ||||
1433 | /// Returns true if an interleaved group requires a scalar iteration | |||
1434 | /// to handle accesses with gaps. | |||
1435 | bool requiresScalarEpilogue() const { | |||
1436 | return InterleaveInfo.requiresScalarEpilogue(); | |||
1437 | } | |||
1438 | ||||
1439 | private: | |||
1440 | unsigned NumPredStores = 0; | |||
1441 | ||||
1442 | /// \return An upper bound for the vectorization factor, larger than zero. | |||
1443 | /// One is returned if vectorization should best be avoided due to cost. | |||
1444 | unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount); | |||
1445 | ||||
1446 | /// The vectorization cost is a combination of the cost itself and a boolean | |||
1447 | /// indicating whether any of the contributing operations will actually | |||
1448 | /// operate on | |||
1449 | /// vector values after type legalization in the backend. If this latter value | |||
1450 | /// is | |||
1451 | /// false, then all operations will be scalarized (i.e. no vectorization has | |||
1452 | /// actually taken place). | |||
1453 | using VectorizationCostTy = std::pair<unsigned, bool>; | |||
1454 | ||||
1455 | /// Returns the expected execution cost. The unit of the cost does | |||
1456 | /// not matter because we use the 'cost' units to compare different | |||
1457 | /// vector widths. The cost that is returned is *not* normalized by | |||
1458 | /// the factor width. | |||
1459 | VectorizationCostTy expectedCost(unsigned VF); | |||
1460 | ||||
1461 | /// Returns the execution time cost of an instruction for a given vector | |||
1462 | /// width. Vector width of one means scalar. | |||
1463 | VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF); | |||
1464 | ||||
1465 | /// The cost-computation logic from getInstructionCost which provides | |||
1466 | /// the vector type as an output parameter. | |||
1467 | unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy); | |||
1468 | ||||
1469 | /// Calculate vectorization cost of memory instruction \p I. | |||
1470 | unsigned getMemoryInstructionCost(Instruction *I, unsigned VF); | |||
1471 | ||||
1472 | /// The cost computation for scalarized memory instruction. | |||
1473 | unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF); | |||
1474 | ||||
1475 | /// The cost computation for interleaving group of memory instructions. | |||
1476 | unsigned getInterleaveGroupCost(Instruction *I, unsigned VF); | |||
1477 | ||||
1478 | /// The cost computation for Gather/Scatter instruction. | |||
1479 | unsigned getGatherScatterCost(Instruction *I, unsigned VF); | |||
1480 | ||||
1481 | /// The cost computation for widening instruction \p I with consecutive | |||
1482 | /// memory access. | |||
1483 | unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF); | |||
1484 | ||||
1485 | /// The cost calculation for Load instruction \p I with uniform pointer - | |||
1486 | /// scalar load + broadcast. | |||
1487 | unsigned getUniformMemOpCost(Instruction *I, unsigned VF); | |||
1488 | ||||
1489 | /// Returns whether the instruction is a load or store and will be a emitted | |||
1490 | /// as a vector operation. | |||
1491 | bool isConsecutiveLoadOrStore(Instruction *I); | |||
1492 | ||||
1493 | /// Returns true if an artificially high cost for emulated masked memrefs | |||
1494 | /// should be used. | |||
1495 | bool useEmulatedMaskMemRefHack(Instruction *I); | |||
1496 | ||||
1497 | /// Create an analysis remark that explains why vectorization failed | |||
1498 | /// | |||
1499 | /// \p RemarkName is the identifier for the remark. \return the remark object | |||
1500 | /// that can be streamed to. | |||
1501 | OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) { | |||
1502 | return createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(), | |||
1503 | RemarkName, TheLoop); | |||
1504 | } | |||
1505 | ||||
1506 | /// Map of scalar integer values to the smallest bitwidth they can be legally | |||
1507 | /// represented as. The vector equivalents of these values should be truncated | |||
1508 | /// to this type. | |||
1509 | MapVector<Instruction *, uint64_t> MinBWs; | |||
1510 | ||||
1511 | /// A type representing the costs for instructions if they were to be | |||
1512 | /// scalarized rather than vectorized. The entries are Instruction-Cost | |||
1513 | /// pairs. | |||
1514 | using ScalarCostsTy = DenseMap<Instruction *, unsigned>; | |||
1515 | ||||
1516 | /// A set containing all BasicBlocks that are known to present after | |||
1517 | /// vectorization as a predicated block. | |||
1518 | SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization; | |||
1519 | ||||
1520 | /// A map holding scalar costs for different vectorization factors. The | |||
1521 | /// presence of a cost for an instruction in the mapping indicates that the | |||
1522 | /// instruction will be scalarized when vectorizing with the associated | |||
1523 | /// vectorization factor. The entries are VF-ScalarCostTy pairs. | |||
1524 | DenseMap<unsigned, ScalarCostsTy> InstsToScalarize; | |||
1525 | ||||
1526 | /// Holds the instructions known to be uniform after vectorization. | |||
1527 | /// The data is collected per VF. | |||
1528 | DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms; | |||
1529 | ||||
1530 | /// Holds the instructions known to be scalar after vectorization. | |||
1531 | /// The data is collected per VF. | |||
1532 | DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars; | |||
1533 | ||||
1534 | /// Holds the instructions (address computations) that are forced to be | |||
1535 | /// scalarized. | |||
1536 | DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars; | |||
1537 | ||||
1538 | /// Returns the expected difference in cost from scalarizing the expression | |||
1539 | /// feeding a predicated instruction \p PredInst. The instructions to | |||
1540 | /// scalarize and their scalar costs are collected in \p ScalarCosts. A | |||
1541 | /// non-negative return value implies the expression will be scalarized. | |||
1542 | /// Currently, only single-use chains are considered for scalarization. | |||
1543 | int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts, | |||
1544 | unsigned VF); | |||
1545 | ||||
1546 | /// Collect the instructions that are uniform after vectorization. An | |||
1547 | /// instruction is uniform if we represent it with a single scalar value in | |||
1548 | /// the vectorized loop corresponding to each vector iteration. Examples of | |||
1549 | /// uniform instructions include pointer operands of consecutive or | |||
1550 | /// interleaved memory accesses. Note that although uniformity implies an | |||
1551 | /// instruction will be scalar, the reverse is not true. In general, a | |||
1552 | /// scalarized instruction will be represented by VF scalar values in the | |||
1553 | /// vectorized loop, each corresponding to an iteration of the original | |||
1554 | /// scalar loop. | |||
1555 | void collectLoopUniforms(unsigned VF); | |||
1556 | ||||
1557 | /// Collect the instructions that are scalar after vectorization. An | |||
1558 | /// instruction is scalar if it is known to be uniform or will be scalarized | |||
1559 | /// during vectorization. Non-uniform scalarized instructions will be | |||
1560 | /// represented by VF values in the vectorized loop, each corresponding to an | |||
1561 | /// iteration of the original scalar loop. | |||
1562 | void collectLoopScalars(unsigned VF); | |||
1563 | ||||
1564 | /// Keeps cost model vectorization decision and cost for instructions. | |||
1565 | /// Right now it is used for memory instructions only. | |||
1566 | using DecisionList = DenseMap<std::pair<Instruction *, unsigned>, | |||
1567 | std::pair<InstWidening, unsigned>>; | |||
1568 | ||||
1569 | DecisionList WideningDecisions; | |||
1570 | ||||
1571 | public: | |||
1572 | /// The loop that we evaluate. | |||
1573 | Loop *TheLoop; | |||
1574 | ||||
1575 | /// Predicated scalar evolution analysis. | |||
1576 | PredicatedScalarEvolution &PSE; | |||
1577 | ||||
1578 | /// Loop Info analysis. | |||
1579 | LoopInfo *LI; | |||
1580 | ||||
1581 | /// Vectorization legality. | |||
1582 | LoopVectorizationLegality *Legal; | |||
1583 | ||||
1584 | /// Vector target information. | |||
1585 | const TargetTransformInfo &TTI; | |||
1586 | ||||
1587 | /// Target Library Info. | |||
1588 | const TargetLibraryInfo *TLI; | |||
1589 | ||||
1590 | /// Demanded bits analysis. | |||
1591 | DemandedBits *DB; | |||
1592 | ||||
1593 | /// Assumption cache. | |||
1594 | AssumptionCache *AC; | |||
1595 | ||||
1596 | /// Interface to emit optimization remarks. | |||
1597 | OptimizationRemarkEmitter *ORE; | |||
1598 | ||||
1599 | const Function *TheFunction; | |||
1600 | ||||
1601 | /// Loop Vectorize Hint. | |||
1602 | const LoopVectorizeHints *Hints; | |||
1603 | ||||
1604 | /// The interleave access information contains groups of interleaved accesses | |||
1605 | /// with the same stride and close to each other. | |||
1606 | InterleavedAccessInfo &InterleaveInfo; | |||
1607 | ||||
1608 | /// Values to ignore in the cost model. | |||
1609 | SmallPtrSet<const Value *, 16> ValuesToIgnore; | |||
1610 | ||||
1611 | /// Values to ignore in the cost model when VF > 1. | |||
1612 | SmallPtrSet<const Value *, 16> VecValuesToIgnore; | |||
1613 | }; | |||
1614 | ||||
1615 | } // end namespace llvm | |||
1616 | ||||
1617 | // Return true if \p OuterLp is an outer loop annotated with hints for explicit | |||
1618 | // vectorization. The loop needs to be annotated with #pragma omp simd | |||
1619 | // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the | |||
1620 | // vector length information is not provided, vectorization is not considered | |||
1621 | // explicit. Interleave hints are not allowed either. These limitations will be | |||
1622 | // relaxed in the future. | |||
1623 | // Please, note that we are currently forced to abuse the pragma 'clang | |||
1624 | // vectorize' semantics. This pragma provides *auto-vectorization hints* | |||
1625 | // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd' | |||
1626 | // provides *explicit vectorization hints* (LV can bypass legal checks and | |||
1627 | // assume that vectorization is legal). However, both hints are implemented | |||
1628 | // using the same metadata (llvm.loop.vectorize, processed by | |||
1629 | // LoopVectorizeHints). This will be fixed in the future when the native IR | |||
1630 | // representation for pragma 'omp simd' is introduced. | |||
1631 | static bool isExplicitVecOuterLoop(Loop *OuterLp, | |||
1632 | OptimizationRemarkEmitter *ORE) { | |||
1633 | assert(!OuterLp->empty() && "This is not an outer loop")(static_cast <bool> (!OuterLp->empty() && "This is not an outer loop" ) ? void (0) : __assert_fail ("!OuterLp->empty() && \"This is not an outer loop\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1633, __extension__ __PRETTY_FUNCTION__)); | |||
1634 | LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE); | |||
1635 | ||||
1636 | // Only outer loops with an explicit vectorization hint are supported. | |||
1637 | // Unannotated outer loops are ignored. | |||
1638 | if (Hints.getForce() == LoopVectorizeHints::FK_Undefined) | |||
1639 | return false; | |||
1640 | ||||
1641 | Function *Fn = OuterLp->getHeader()->getParent(); | |||
1642 | if (!Hints.allowVectorization(Fn, OuterLp, false /*AlwaysVectorize*/)) { | |||
1643 | LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints prevent outer loop vectorization.\n" ; } } while (false); | |||
1644 | return false; | |||
1645 | } | |||
1646 | ||||
1647 | if (!Hints.getWidth()) { | |||
1648 | LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No user vector width.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing: No user vector width.\n" ; } } while (false); | |||
1649 | emitMissedWarning(Fn, OuterLp, Hints, ORE); | |||
1650 | return false; | |||
1651 | } | |||
1652 | ||||
1653 | if (Hints.getInterleave() > 1) { | |||
1654 | // TODO: Interleave support is future work. | |||
1655 | LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing: Interleave is not supported for " "outer loops.\n"; } } while (false) | |||
1656 | "outer loops.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing: Interleave is not supported for " "outer loops.\n"; } } while (false); | |||
1657 | emitMissedWarning(Fn, OuterLp, Hints, ORE); | |||
1658 | return false; | |||
1659 | } | |||
1660 | ||||
1661 | return true; | |||
1662 | } | |||
1663 | ||||
1664 | static void collectSupportedLoops(Loop &L, LoopInfo *LI, | |||
1665 | OptimizationRemarkEmitter *ORE, | |||
1666 | SmallVectorImpl<Loop *> &V) { | |||
1667 | // Collect inner loops and outer loops without irreducible control flow. For | |||
1668 | // now, only collect outer loops that have explicit vectorization hints. If we | |||
1669 | // are stress testing the VPlan H-CFG construction, we collect the outermost | |||
1670 | // loop of every loop nest. | |||
1671 | if (L.empty() || VPlanBuildStressTest || | |||
1672 | (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) { | |||
1673 | LoopBlocksRPO RPOT(&L); | |||
1674 | RPOT.perform(LI); | |||
1675 | if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) { | |||
1676 | V.push_back(&L); | |||
1677 | // TODO: Collect inner loops inside marked outer loops in case | |||
1678 | // vectorization fails for the outer loop. Do not invoke | |||
1679 | // 'containsIrreducibleCFG' again for inner loops when the outer loop is | |||
1680 | // already known to be reducible. We can use an inherited attribute for | |||
1681 | // that. | |||
1682 | return; | |||
1683 | } | |||
1684 | } | |||
1685 | for (Loop *InnerL : L) | |||
1686 | collectSupportedLoops(*InnerL, LI, ORE, V); | |||
1687 | } | |||
1688 | ||||
1689 | namespace { | |||
1690 | ||||
1691 | /// The LoopVectorize Pass. | |||
1692 | struct LoopVectorize : public FunctionPass { | |||
1693 | /// Pass identification, replacement for typeid | |||
1694 | static char ID; | |||
1695 | ||||
1696 | LoopVectorizePass Impl; | |||
1697 | ||||
1698 | explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true) | |||
1699 | : FunctionPass(ID) { | |||
1700 | Impl.DisableUnrolling = NoUnrolling; | |||
1701 | Impl.AlwaysVectorize = AlwaysVectorize; | |||
1702 | initializeLoopVectorizePass(*PassRegistry::getPassRegistry()); | |||
1703 | } | |||
1704 | ||||
1705 | bool runOnFunction(Function &F) override { | |||
1706 | if (skipFunction(F)) | |||
1707 | return false; | |||
1708 | ||||
1709 | auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); | |||
1710 | auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); | |||
1711 | auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); | |||
1712 | auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); | |||
1713 | auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(); | |||
1714 | auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); | |||
1715 | auto *TLI = TLIP ? &TLIP->getTLI() : nullptr; | |||
1716 | auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); | |||
1717 | auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); | |||
1718 | auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>(); | |||
1719 | auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); | |||
1720 | auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); | |||
1721 | ||||
1722 | std::function<const LoopAccessInfo &(Loop &)> GetLAA = | |||
1723 | [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); }; | |||
1724 | ||||
1725 | return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC, | |||
1726 | GetLAA, *ORE); | |||
1727 | } | |||
1728 | ||||
1729 | void getAnalysisUsage(AnalysisUsage &AU) const override { | |||
1730 | AU.addRequired<AssumptionCacheTracker>(); | |||
1731 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); | |||
1732 | AU.addRequired<DominatorTreeWrapperPass>(); | |||
1733 | AU.addRequired<LoopInfoWrapperPass>(); | |||
1734 | AU.addRequired<ScalarEvolutionWrapperPass>(); | |||
1735 | AU.addRequired<TargetTransformInfoWrapperPass>(); | |||
1736 | AU.addRequired<AAResultsWrapperPass>(); | |||
1737 | AU.addRequired<LoopAccessLegacyAnalysis>(); | |||
1738 | AU.addRequired<DemandedBitsWrapperPass>(); | |||
1739 | AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); | |||
1740 | AU.addPreserved<LoopInfoWrapperPass>(); | |||
1741 | AU.addPreserved<DominatorTreeWrapperPass>(); | |||
1742 | AU.addPreserved<BasicAAWrapperPass>(); | |||
1743 | AU.addPreserved<GlobalsAAWrapperPass>(); | |||
1744 | } | |||
1745 | }; | |||
1746 | ||||
1747 | } // end anonymous namespace | |||
1748 | ||||
1749 | //===----------------------------------------------------------------------===// | |||
1750 | // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and | |||
1751 | // LoopVectorizationCostModel and LoopVectorizationPlanner. | |||
1752 | //===----------------------------------------------------------------------===// | |||
1753 | ||||
1754 | Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) { | |||
1755 | // We need to place the broadcast of invariant variables outside the loop, | |||
1756 | // but only if it's proven safe to do so. Else, broadcast will be inside | |||
1757 | // vector loop body. | |||
1758 | Instruction *Instr = dyn_cast<Instruction>(V); | |||
1759 | bool SafeToHoist = OrigLoop->isLoopInvariant(V) && | |||
1760 | (!Instr || | |||
1761 | DT->dominates(Instr->getParent(), LoopVectorPreHeader)); | |||
1762 | // Place the code for broadcasting invariant variables in the new preheader. | |||
1763 | IRBuilder<>::InsertPointGuard Guard(Builder); | |||
1764 | if (SafeToHoist) | |||
1765 | Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); | |||
1766 | ||||
1767 | // Broadcast the scalar into all locations in the vector. | |||
1768 | Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); | |||
1769 | ||||
1770 | return Shuf; | |||
1771 | } | |||
1772 | ||||
1773 | void InnerLoopVectorizer::createVectorIntOrFpInductionPHI( | |||
1774 | const InductionDescriptor &II, Value *Step, Instruction *EntryVal) { | |||
1775 | assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&(static_cast <bool> ((isa<PHINode>(EntryVal) || isa <TruncInst>(EntryVal)) && "Expected either an induction phi-node or a truncate of it!" ) ? void (0) : __assert_fail ("(isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) && \"Expected either an induction phi-node or a truncate of it!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1776, __extension__ __PRETTY_FUNCTION__)) | |||
1776 | "Expected either an induction phi-node or a truncate of it!")(static_cast <bool> ((isa<PHINode>(EntryVal) || isa <TruncInst>(EntryVal)) && "Expected either an induction phi-node or a truncate of it!" ) ? void (0) : __assert_fail ("(isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) && \"Expected either an induction phi-node or a truncate of it!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1776, __extension__ __PRETTY_FUNCTION__)); | |||
1777 | Value *Start = II.getStartValue(); | |||
1778 | ||||
1779 | // Construct the initial value of the vector IV in the vector loop preheader | |||
1780 | auto CurrIP = Builder.saveIP(); | |||
1781 | Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); | |||
1782 | if (isa<TruncInst>(EntryVal)) { | |||
1783 | assert(Start->getType()->isIntegerTy() &&(static_cast <bool> (Start->getType()->isIntegerTy () && "Truncation requires an integer type") ? void ( 0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1784, __extension__ __PRETTY_FUNCTION__)) | |||
1784 | "Truncation requires an integer type")(static_cast <bool> (Start->getType()->isIntegerTy () && "Truncation requires an integer type") ? void ( 0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1784, __extension__ __PRETTY_FUNCTION__)); | |||
1785 | auto *TruncType = cast<IntegerType>(EntryVal->getType()); | |||
1786 | Step = Builder.CreateTrunc(Step, TruncType); | |||
1787 | Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType); | |||
1788 | } | |||
1789 | Value *SplatStart = Builder.CreateVectorSplat(VF, Start); | |||
1790 | Value *SteppedStart = | |||
1791 | getStepVector(SplatStart, 0, Step, II.getInductionOpcode()); | |||
1792 | ||||
1793 | // We create vector phi nodes for both integer and floating-point induction | |||
1794 | // variables. Here, we determine the kind of arithmetic we will perform. | |||
1795 | Instruction::BinaryOps AddOp; | |||
1796 | Instruction::BinaryOps MulOp; | |||
1797 | if (Step->getType()->isIntegerTy()) { | |||
1798 | AddOp = Instruction::Add; | |||
1799 | MulOp = Instruction::Mul; | |||
1800 | } else { | |||
1801 | AddOp = II.getInductionOpcode(); | |||
1802 | MulOp = Instruction::FMul; | |||
1803 | } | |||
1804 | ||||
1805 | // Multiply the vectorization factor by the step using integer or | |||
1806 | // floating-point arithmetic as appropriate. | |||
1807 | Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF); | |||
1808 | Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF)); | |||
1809 | ||||
1810 | // Create a vector splat to use in the induction update. | |||
1811 | // | |||
1812 | // FIXME: If the step is non-constant, we create the vector splat with | |||
1813 | // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't | |||
1814 | // handle a constant vector splat. | |||
1815 | Value *SplatVF = isa<Constant>(Mul) | |||
1816 | ? ConstantVector::getSplat(VF, cast<Constant>(Mul)) | |||
1817 | : Builder.CreateVectorSplat(VF, Mul); | |||
1818 | Builder.restoreIP(CurrIP); | |||
1819 | ||||
1820 | // We may need to add the step a number of times, depending on the unroll | |||
1821 | // factor. The last of those goes into the PHI. | |||
1822 | PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind", | |||
1823 | &*LoopVectorBody->getFirstInsertionPt()); | |||
1824 | VecInd->setDebugLoc(EntryVal->getDebugLoc()); | |||
1825 | Instruction *LastInduction = VecInd; | |||
1826 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
1827 | VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction); | |||
1828 | ||||
1829 | if (isa<TruncInst>(EntryVal)) | |||
1830 | addMetadata(LastInduction, EntryVal); | |||
1831 | recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part); | |||
1832 | ||||
1833 | LastInduction = cast<Instruction>(addFastMathFlag( | |||
1834 | Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"))); | |||
1835 | LastInduction->setDebugLoc(EntryVal->getDebugLoc()); | |||
1836 | } | |||
1837 | ||||
1838 | // Move the last step to the end of the latch block. This ensures consistent | |||
1839 | // placement of all induction updates. | |||
1840 | auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch(); | |||
1841 | auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator()); | |||
1842 | auto *ICmp = cast<Instruction>(Br->getCondition()); | |||
1843 | LastInduction->moveBefore(ICmp); | |||
1844 | LastInduction->setName("vec.ind.next"); | |||
1845 | ||||
1846 | VecInd->addIncoming(SteppedStart, LoopVectorPreHeader); | |||
1847 | VecInd->addIncoming(LastInduction, LoopVectorLatch); | |||
1848 | } | |||
1849 | ||||
1850 | bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const { | |||
1851 | return Cost->isScalarAfterVectorization(I, VF) || | |||
1852 | Cost->isProfitableToScalarize(I, VF); | |||
1853 | } | |||
1854 | ||||
1855 | bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const { | |||
1856 | if (shouldScalarizeInstruction(IV)) | |||
1857 | return true; | |||
1858 | auto isScalarInst = [&](User *U) -> bool { | |||
1859 | auto *I = cast<Instruction>(U); | |||
1860 | return (OrigLoop->contains(I) && shouldScalarizeInstruction(I)); | |||
1861 | }; | |||
1862 | return llvm::any_of(IV->users(), isScalarInst); | |||
1863 | } | |||
1864 | ||||
1865 | void InnerLoopVectorizer::recordVectorLoopValueForInductionCast( | |||
1866 | const InductionDescriptor &ID, const Instruction *EntryVal, | |||
1867 | Value *VectorLoopVal, unsigned Part, unsigned Lane) { | |||
1868 | assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&(static_cast <bool> ((isa<PHINode>(EntryVal) || isa <TruncInst>(EntryVal)) && "Expected either an induction phi-node or a truncate of it!" ) ? void (0) : __assert_fail ("(isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) && \"Expected either an induction phi-node or a truncate of it!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1869, __extension__ __PRETTY_FUNCTION__)) | |||
1869 | "Expected either an induction phi-node or a truncate of it!")(static_cast <bool> ((isa<PHINode>(EntryVal) || isa <TruncInst>(EntryVal)) && "Expected either an induction phi-node or a truncate of it!" ) ? void (0) : __assert_fail ("(isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) && \"Expected either an induction phi-node or a truncate of it!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1869, __extension__ __PRETTY_FUNCTION__)); | |||
1870 | ||||
1871 | // This induction variable is not the phi from the original loop but the | |||
1872 | // newly-created IV based on the proof that casted Phi is equal to the | |||
1873 | // uncasted Phi in the vectorized loop (under a runtime guard possibly). It | |||
1874 | // re-uses the same InductionDescriptor that original IV uses but we don't | |||
1875 | // have to do any recording in this case - that is done when original IV is | |||
1876 | // processed. | |||
1877 | if (isa<TruncInst>(EntryVal)) | |||
1878 | return; | |||
1879 | ||||
1880 | const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts(); | |||
1881 | if (Casts.empty()) | |||
1882 | return; | |||
1883 | // Only the first Cast instruction in the Casts vector is of interest. | |||
1884 | // The rest of the Casts (if exist) have no uses outside the | |||
1885 | // induction update chain itself. | |||
1886 | Instruction *CastInst = *Casts.begin(); | |||
1887 | if (Lane < UINT_MAX(2147483647 *2U +1U)) | |||
1888 | VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal); | |||
1889 | else | |||
1890 | VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal); | |||
1891 | } | |||
1892 | ||||
1893 | void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) { | |||
1894 | assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&(static_cast <bool> ((IV->getType()->isIntegerTy( ) || IV != OldInduction) && "Primary induction variable must have an integer type" ) ? void (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1895, __extension__ __PRETTY_FUNCTION__)) | |||
1895 | "Primary induction variable must have an integer type")(static_cast <bool> ((IV->getType()->isIntegerTy( ) || IV != OldInduction) && "Primary induction variable must have an integer type" ) ? void (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1895, __extension__ __PRETTY_FUNCTION__)); | |||
1896 | ||||
1897 | auto II = Legal->getInductionVars()->find(IV); | |||
1898 | assert(II != Legal->getInductionVars()->end() && "IV is not an induction")(static_cast <bool> (II != Legal->getInductionVars() ->end() && "IV is not an induction") ? void (0) : __assert_fail ("II != Legal->getInductionVars()->end() && \"IV is not an induction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1898, __extension__ __PRETTY_FUNCTION__)); | |||
1899 | ||||
1900 | auto ID = II->second; | |||
1901 | assert(IV->getType() == ID.getStartValue()->getType() && "Types must match")(static_cast <bool> (IV->getType() == ID.getStartValue ()->getType() && "Types must match") ? void (0) : __assert_fail ("IV->getType() == ID.getStartValue()->getType() && \"Types must match\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1901, __extension__ __PRETTY_FUNCTION__)); | |||
1902 | ||||
1903 | // The scalar value to broadcast. This will be derived from the canonical | |||
1904 | // induction variable. | |||
1905 | Value *ScalarIV = nullptr; | |||
1906 | ||||
1907 | // The value from the original loop to which we are mapping the new induction | |||
1908 | // variable. | |||
1909 | Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV; | |||
1910 | ||||
1911 | // True if we have vectorized the induction variable. | |||
1912 | auto VectorizedIV = false; | |||
1913 | ||||
1914 | // Determine if we want a scalar version of the induction variable. This is | |||
1915 | // true if the induction variable itself is not widened, or if it has at | |||
1916 | // least one user in the loop that is not widened. | |||
1917 | auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal); | |||
1918 | ||||
1919 | // Generate code for the induction step. Note that induction steps are | |||
1920 | // required to be loop-invariant | |||
1921 | assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&(static_cast <bool> (PSE.getSE()->isLoopInvariant(ID .getStep(), OrigLoop) && "Induction step should be loop invariant" ) ? void (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1922, __extension__ __PRETTY_FUNCTION__)) | |||
1922 | "Induction step should be loop invariant")(static_cast <bool> (PSE.getSE()->isLoopInvariant(ID .getStep(), OrigLoop) && "Induction step should be loop invariant" ) ? void (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1922, __extension__ __PRETTY_FUNCTION__)); | |||
1923 | auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); | |||
1924 | Value *Step = nullptr; | |||
1925 | if (PSE.getSE()->isSCEVable(IV->getType())) { | |||
1926 | SCEVExpander Exp(*PSE.getSE(), DL, "induction"); | |||
1927 | Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(), | |||
1928 | LoopVectorPreHeader->getTerminator()); | |||
1929 | } else { | |||
1930 | Step = cast<SCEVUnknown>(ID.getStep())->getValue(); | |||
1931 | } | |||
1932 | ||||
1933 | // Try to create a new independent vector induction variable. If we can't | |||
1934 | // create the phi node, we will splat the scalar induction variable in each | |||
1935 | // loop iteration. | |||
1936 | if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) { | |||
1937 | createVectorIntOrFpInductionPHI(ID, Step, EntryVal); | |||
1938 | VectorizedIV = true; | |||
1939 | } | |||
1940 | ||||
1941 | // If we haven't yet vectorized the induction variable, or if we will create | |||
1942 | // a scalar one, we need to define the scalar induction variable and step | |||
1943 | // values. If we were given a truncation type, truncate the canonical | |||
1944 | // induction variable and step. Otherwise, derive these values from the | |||
1945 | // induction descriptor. | |||
1946 | if (!VectorizedIV || NeedsScalarIV) { | |||
1947 | ScalarIV = Induction; | |||
1948 | if (IV != OldInduction) { | |||
1949 | ScalarIV = IV->getType()->isIntegerTy() | |||
1950 | ? Builder.CreateSExtOrTrunc(Induction, IV->getType()) | |||
1951 | : Builder.CreateCast(Instruction::SIToFP, Induction, | |||
1952 | IV->getType()); | |||
1953 | ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL); | |||
1954 | ScalarIV->setName("offset.idx"); | |||
1955 | } | |||
1956 | if (Trunc) { | |||
1957 | auto *TruncType = cast<IntegerType>(Trunc->getType()); | |||
1958 | assert(Step->getType()->isIntegerTy() &&(static_cast <bool> (Step->getType()->isIntegerTy () && "Truncation requires an integer step") ? void ( 0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1959, __extension__ __PRETTY_FUNCTION__)) | |||
1959 | "Truncation requires an integer step")(static_cast <bool> (Step->getType()->isIntegerTy () && "Truncation requires an integer step") ? void ( 0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1959, __extension__ __PRETTY_FUNCTION__)); | |||
1960 | ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType); | |||
1961 | Step = Builder.CreateTrunc(Step, TruncType); | |||
1962 | } | |||
1963 | } | |||
1964 | ||||
1965 | // If we haven't yet vectorized the induction variable, splat the scalar | |||
1966 | // induction variable, and build the necessary step vectors. | |||
1967 | // TODO: Don't do it unless the vectorized IV is really required. | |||
1968 | if (!VectorizedIV) { | |||
1969 | Value *Broadcasted = getBroadcastInstrs(ScalarIV); | |||
1970 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
1971 | Value *EntryPart = | |||
1972 | getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode()); | |||
1973 | VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart); | |||
1974 | if (Trunc) | |||
1975 | addMetadata(EntryPart, Trunc); | |||
1976 | recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part); | |||
1977 | } | |||
1978 | } | |||
1979 | ||||
1980 | // If an induction variable is only used for counting loop iterations or | |||
1981 | // calculating addresses, it doesn't need to be widened. Create scalar steps | |||
1982 | // that can be used by instructions we will later scalarize. Note that the | |||
1983 | // addition of the scalar steps will not increase the number of instructions | |||
1984 | // in the loop in the common case prior to InstCombine. We will be trading | |||
1985 | // one vector extract for each scalar step. | |||
1986 | if (NeedsScalarIV) | |||
1987 | buildScalarSteps(ScalarIV, Step, EntryVal, ID); | |||
1988 | } | |||
1989 | ||||
1990 | Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step, | |||
1991 | Instruction::BinaryOps BinOp) { | |||
1992 | // Create and check the types. | |||
1993 | assert(Val->getType()->isVectorTy() && "Must be a vector")(static_cast <bool> (Val->getType()->isVectorTy() && "Must be a vector") ? void (0) : __assert_fail ("Val->getType()->isVectorTy() && \"Must be a vector\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1993, __extension__ __PRETTY_FUNCTION__)); | |||
1994 | int VLen = Val->getType()->getVectorNumElements(); | |||
1995 | ||||
1996 | Type *STy = Val->getType()->getScalarType(); | |||
1997 | assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&(static_cast <bool> ((STy->isIntegerTy() || STy-> isFloatingPointTy()) && "Induction Step must be an integer or FP" ) ? void (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1998, __extension__ __PRETTY_FUNCTION__)) | |||
1998 | "Induction Step must be an integer or FP")(static_cast <bool> ((STy->isIntegerTy() || STy-> isFloatingPointTy()) && "Induction Step must be an integer or FP" ) ? void (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1998, __extension__ __PRETTY_FUNCTION__)); | |||
1999 | assert(Step->getType() == STy && "Step has wrong type")(static_cast <bool> (Step->getType() == STy && "Step has wrong type") ? void (0) : __assert_fail ("Step->getType() == STy && \"Step has wrong type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 1999, __extension__ __PRETTY_FUNCTION__)); | |||
2000 | ||||
2001 | SmallVector<Constant *, 8> Indices; | |||
2002 | ||||
2003 | if (STy->isIntegerTy()) { | |||
2004 | // Create a vector of consecutive numbers from zero to VF. | |||
2005 | for (int i = 0; i < VLen; ++i) | |||
2006 | Indices.push_back(ConstantInt::get(STy, StartIdx + i)); | |||
2007 | ||||
2008 | // Add the consecutive indices to the vector value. | |||
2009 | Constant *Cv = ConstantVector::get(Indices); | |||
2010 | assert(Cv->getType() == Val->getType() && "Invalid consecutive vec")(static_cast <bool> (Cv->getType() == Val->getType () && "Invalid consecutive vec") ? void (0) : __assert_fail ("Cv->getType() == Val->getType() && \"Invalid consecutive vec\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2010, __extension__ __PRETTY_FUNCTION__)); | |||
2011 | Step = Builder.CreateVectorSplat(VLen, Step); | |||
2012 | assert(Step->getType() == Val->getType() && "Invalid step vec")(static_cast <bool> (Step->getType() == Val->getType () && "Invalid step vec") ? void (0) : __assert_fail ( "Step->getType() == Val->getType() && \"Invalid step vec\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2012, __extension__ __PRETTY_FUNCTION__)); | |||
2013 | // FIXME: The newly created binary instructions should contain nsw/nuw flags, | |||
2014 | // which can be found from the original scalar operations. | |||
2015 | Step = Builder.CreateMul(Cv, Step); | |||
2016 | return Builder.CreateAdd(Val, Step, "induction"); | |||
2017 | } | |||
2018 | ||||
2019 | // Floating point induction. | |||
2020 | assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&(static_cast <bool> ((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && "Binary Opcode should be specified for FP induction" ) ? void (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2021, __extension__ __PRETTY_FUNCTION__)) | |||
2021 | "Binary Opcode should be specified for FP induction")(static_cast <bool> ((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && "Binary Opcode should be specified for FP induction" ) ? void (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2021, __extension__ __PRETTY_FUNCTION__)); | |||
2022 | // Create a vector of consecutive numbers from zero to VF. | |||
2023 | for (int i = 0; i < VLen; ++i) | |||
2024 | Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i))); | |||
2025 | ||||
2026 | // Add the consecutive indices to the vector value. | |||
2027 | Constant *Cv = ConstantVector::get(Indices); | |||
2028 | ||||
2029 | Step = Builder.CreateVectorSplat(VLen, Step); | |||
2030 | ||||
2031 | // Floating point operations had to be 'fast' to enable the induction. | |||
2032 | FastMathFlags Flags; | |||
2033 | Flags.setFast(); | |||
2034 | ||||
2035 | Value *MulOp = Builder.CreateFMul(Cv, Step); | |||
2036 | if (isa<Instruction>(MulOp)) | |||
2037 | // Have to check, MulOp may be a constant | |||
2038 | cast<Instruction>(MulOp)->setFastMathFlags(Flags); | |||
2039 | ||||
2040 | Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction"); | |||
2041 | if (isa<Instruction>(BOp)) | |||
2042 | cast<Instruction>(BOp)->setFastMathFlags(Flags); | |||
2043 | return BOp; | |||
2044 | } | |||
2045 | ||||
2046 | void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step, | |||
2047 | Instruction *EntryVal, | |||
2048 | const InductionDescriptor &ID) { | |||
2049 | // We shouldn't have to build scalar steps if we aren't vectorizing. | |||
2050 | assert(VF > 1 && "VF should be greater than one")(static_cast <bool> (VF > 1 && "VF should be greater than one" ) ? void (0) : __assert_fail ("VF > 1 && \"VF should be greater than one\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2050, __extension__ __PRETTY_FUNCTION__)); | |||
2051 | ||||
2052 | // Get the value type and ensure it and the step have the same integer type. | |||
2053 | Type *ScalarIVTy = ScalarIV->getType()->getScalarType(); | |||
2054 | assert(ScalarIVTy == Step->getType() &&(static_cast <bool> (ScalarIVTy == Step->getType() && "Val and Step should have the same type") ? void (0) : __assert_fail ("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2055, __extension__ __PRETTY_FUNCTION__)) | |||
2055 | "Val and Step should have the same type")(static_cast <bool> (ScalarIVTy == Step->getType() && "Val and Step should have the same type") ? void (0) : __assert_fail ("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2055, __extension__ __PRETTY_FUNCTION__)); | |||
2056 | ||||
2057 | // We build scalar steps for both integer and floating-point induction | |||
2058 | // variables. Here, we determine the kind of arithmetic we will perform. | |||
2059 | Instruction::BinaryOps AddOp; | |||
2060 | Instruction::BinaryOps MulOp; | |||
2061 | if (ScalarIVTy->isIntegerTy()) { | |||
2062 | AddOp = Instruction::Add; | |||
2063 | MulOp = Instruction::Mul; | |||
2064 | } else { | |||
2065 | AddOp = ID.getInductionOpcode(); | |||
2066 | MulOp = Instruction::FMul; | |||
2067 | } | |||
2068 | ||||
2069 | // Determine the number of scalars we need to generate for each unroll | |||
2070 | // iteration. If EntryVal is uniform, we only need to generate the first | |||
2071 | // lane. Otherwise, we generate all VF values. | |||
2072 | unsigned Lanes = | |||
2073 | Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1 | |||
2074 | : VF; | |||
2075 | // Compute the scalar steps and save the results in VectorLoopValueMap. | |||
2076 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
2077 | for (unsigned Lane = 0; Lane < Lanes; ++Lane) { | |||
2078 | auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane); | |||
2079 | auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step)); | |||
2080 | auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul)); | |||
2081 | VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add); | |||
2082 | recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane); | |||
2083 | } | |||
2084 | } | |||
2085 | } | |||
2086 | ||||
2087 | Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) { | |||
2088 | assert(V != Induction && "The new induction variable should not be used.")(static_cast <bool> (V != Induction && "The new induction variable should not be used." ) ? void (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2088, __extension__ __PRETTY_FUNCTION__)); | |||
2089 | assert(!V->getType()->isVectorTy() && "Can't widen a vector")(static_cast <bool> (!V->getType()->isVectorTy() && "Can't widen a vector") ? void (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't widen a vector\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2089, __extension__ __PRETTY_FUNCTION__)); | |||
2090 | assert(!V->getType()->isVoidTy() && "Type does not produce a value")(static_cast <bool> (!V->getType()->isVoidTy() && "Type does not produce a value") ? void (0) : __assert_fail ( "!V->getType()->isVoidTy() && \"Type does not produce a value\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2090, __extension__ __PRETTY_FUNCTION__)); | |||
2091 | ||||
2092 | // If we have a stride that is replaced by one, do it here. | |||
2093 | if (Legal->hasStride(V)) | |||
2094 | V = ConstantInt::get(V->getType(), 1); | |||
2095 | ||||
2096 | // If we have a vector mapped to this value, return it. | |||
2097 | if (VectorLoopValueMap.hasVectorValue(V, Part)) | |||
2098 | return VectorLoopValueMap.getVectorValue(V, Part); | |||
2099 | ||||
2100 | // If the value has not been vectorized, check if it has been scalarized | |||
2101 | // instead. If it has been scalarized, and we actually need the value in | |||
2102 | // vector form, we will construct the vector values on demand. | |||
2103 | if (VectorLoopValueMap.hasAnyScalarValue(V)) { | |||
2104 | Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0}); | |||
2105 | ||||
2106 | // If we've scalarized a value, that value should be an instruction. | |||
2107 | auto *I = cast<Instruction>(V); | |||
2108 | ||||
2109 | // If we aren't vectorizing, we can just copy the scalar map values over to | |||
2110 | // the vector map. | |||
2111 | if (VF == 1) { | |||
2112 | VectorLoopValueMap.setVectorValue(V, Part, ScalarValue); | |||
2113 | return ScalarValue; | |||
2114 | } | |||
2115 | ||||
2116 | // Get the last scalar instruction we generated for V and Part. If the value | |||
2117 | // is known to be uniform after vectorization, this corresponds to lane zero | |||
2118 | // of the Part unroll iteration. Otherwise, the last instruction is the one | |||
2119 | // we created for the last vector lane of the Part unroll iteration. | |||
2120 | unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1; | |||
2121 | auto *LastInst = cast<Instruction>( | |||
2122 | VectorLoopValueMap.getScalarValue(V, {Part, LastLane})); | |||
2123 | ||||
2124 | // Set the insert point after the last scalarized instruction. This ensures | |||
2125 | // the insertelement sequence will directly follow the scalar definitions. | |||
2126 | auto OldIP = Builder.saveIP(); | |||
2127 | auto NewIP = std::next(BasicBlock::iterator(LastInst)); | |||
2128 | Builder.SetInsertPoint(&*NewIP); | |||
2129 | ||||
2130 | // However, if we are vectorizing, we need to construct the vector values. | |||
2131 | // If the value is known to be uniform after vectorization, we can just | |||
2132 | // broadcast the scalar value corresponding to lane zero for each unroll | |||
2133 | // iteration. Otherwise, we construct the vector values using insertelement | |||
2134 | // instructions. Since the resulting vectors are stored in | |||
2135 | // VectorLoopValueMap, we will only generate the insertelements once. | |||
2136 | Value *VectorValue = nullptr; | |||
2137 | if (Cost->isUniformAfterVectorization(I, VF)) { | |||
2138 | VectorValue = getBroadcastInstrs(ScalarValue); | |||
2139 | VectorLoopValueMap.setVectorValue(V, Part, VectorValue); | |||
2140 | } else { | |||
2141 | // Initialize packing with insertelements to start from undef. | |||
2142 | Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF)); | |||
2143 | VectorLoopValueMap.setVectorValue(V, Part, Undef); | |||
2144 | for (unsigned Lane = 0; Lane < VF; ++Lane) | |||
2145 | packScalarIntoVectorValue(V, {Part, Lane}); | |||
2146 | VectorValue = VectorLoopValueMap.getVectorValue(V, Part); | |||
2147 | } | |||
2148 | Builder.restoreIP(OldIP); | |||
2149 | return VectorValue; | |||
2150 | } | |||
2151 | ||||
2152 | // If this scalar is unknown, assume that it is a constant or that it is | |||
2153 | // loop invariant. Broadcast V and save the value for future uses. | |||
2154 | Value *B = getBroadcastInstrs(V); | |||
2155 | VectorLoopValueMap.setVectorValue(V, Part, B); | |||
2156 | return B; | |||
2157 | } | |||
2158 | ||||
2159 | Value * | |||
2160 | InnerLoopVectorizer::getOrCreateScalarValue(Value *V, | |||
2161 | const VPIteration &Instance) { | |||
2162 | // If the value is not an instruction contained in the loop, it should | |||
2163 | // already be scalar. | |||
2164 | if (OrigLoop->isLoopInvariant(V)) | |||
2165 | return V; | |||
2166 | ||||
2167 | assert(Instance.Lane > 0(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization (cast<Instruction>(V), VF) : true && "Uniform values only have lane zero" ) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2169, __extension__ __PRETTY_FUNCTION__)) | |||
2168 | ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization (cast<Instruction>(V), VF) : true && "Uniform values only have lane zero" ) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2169, __extension__ __PRETTY_FUNCTION__)) | |||
2169 | : true && "Uniform values only have lane zero")(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization (cast<Instruction>(V), VF) : true && "Uniform values only have lane zero" ) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2169, __extension__ __PRETTY_FUNCTION__)); | |||
2170 | ||||
2171 | // If the value from the original loop has not been vectorized, it is | |||
2172 | // represented by UF x VF scalar values in the new loop. Return the requested | |||
2173 | // scalar value. | |||
2174 | if (VectorLoopValueMap.hasScalarValue(V, Instance)) | |||
2175 | return VectorLoopValueMap.getScalarValue(V, Instance); | |||
2176 | ||||
2177 | // If the value has not been scalarized, get its entry in VectorLoopValueMap | |||
2178 | // for the given unroll part. If this entry is not a vector type (i.e., the | |||
2179 | // vectorization factor is one), there is no need to generate an | |||
2180 | // extractelement instruction. | |||
2181 | auto *U = getOrCreateVectorValue(V, Instance.Part); | |||
2182 | if (!U->getType()->isVectorTy()) { | |||
2183 | assert(VF == 1 && "Value not scalarized has non-vector type")(static_cast <bool> (VF == 1 && "Value not scalarized has non-vector type" ) ? void (0) : __assert_fail ("VF == 1 && \"Value not scalarized has non-vector type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2183, __extension__ __PRETTY_FUNCTION__)); | |||
2184 | return U; | |||
2185 | } | |||
2186 | ||||
2187 | // Otherwise, the value from the original loop has been vectorized and is | |||
2188 | // represented by UF vector values. Extract and return the requested scalar | |||
2189 | // value from the appropriate vector lane. | |||
2190 | return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane)); | |||
2191 | } | |||
2192 | ||||
2193 | void InnerLoopVectorizer::packScalarIntoVectorValue( | |||
2194 | Value *V, const VPIteration &Instance) { | |||
2195 | assert(V != Induction && "The new induction variable should not be used.")(static_cast <bool> (V != Induction && "The new induction variable should not be used." ) ? void (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2195, __extension__ __PRETTY_FUNCTION__)); | |||
2196 | assert(!V->getType()->isVectorTy() && "Can't pack a vector")(static_cast <bool> (!V->getType()->isVectorTy() && "Can't pack a vector") ? void (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't pack a vector\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2196, __extension__ __PRETTY_FUNCTION__)); | |||
2197 | assert(!V->getType()->isVoidTy() && "Type does not produce a value")(static_cast <bool> (!V->getType()->isVoidTy() && "Type does not produce a value") ? void (0) : __assert_fail ( "!V->getType()->isVoidTy() && \"Type does not produce a value\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2197, __extension__ __PRETTY_FUNCTION__)); | |||
2198 | ||||
2199 | Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance); | |||
2200 | Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part); | |||
2201 | VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst, | |||
2202 | Builder.getInt32(Instance.Lane)); | |||
2203 | VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue); | |||
2204 | } | |||
2205 | ||||
2206 | Value *InnerLoopVectorizer::reverseVector(Value *Vec) { | |||
2207 | assert(Vec->getType()->isVectorTy() && "Invalid type")(static_cast <bool> (Vec->getType()->isVectorTy() && "Invalid type") ? void (0) : __assert_fail ("Vec->getType()->isVectorTy() && \"Invalid type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2207, __extension__ __PRETTY_FUNCTION__)); | |||
2208 | SmallVector<Constant *, 8> ShuffleMask; | |||
2209 | for (unsigned i = 0; i < VF; ++i) | |||
2210 | ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); | |||
2211 | ||||
2212 | return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), | |||
2213 | ConstantVector::get(ShuffleMask), | |||
2214 | "reverse"); | |||
2215 | } | |||
2216 | ||||
2217 | // Try to vectorize the interleave group that \p Instr belongs to. | |||
2218 | // | |||
2219 | // E.g. Translate following interleaved load group (factor = 3): | |||
2220 | // for (i = 0; i < N; i+=3) { | |||
2221 | // R = Pic[i]; // Member of index 0 | |||
2222 | // G = Pic[i+1]; // Member of index 1 | |||
2223 | // B = Pic[i+2]; // Member of index 2 | |||
2224 | // ... // do something to R, G, B | |||
2225 | // } | |||
2226 | // To: | |||
2227 | // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B | |||
2228 | // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements | |||
2229 | // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements | |||
2230 | // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements | |||
2231 | // | |||
2232 | // Or translate following interleaved store group (factor = 3): | |||
2233 | // for (i = 0; i < N; i+=3) { | |||
2234 | // ... do something to R, G, B | |||
2235 | // Pic[i] = R; // Member of index 0 | |||
2236 | // Pic[i+1] = G; // Member of index 1 | |||
2237 | // Pic[i+2] = B; // Member of index 2 | |||
2238 | // } | |||
2239 | // To: | |||
2240 | // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7> | |||
2241 | // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u> | |||
2242 | // %interleaved.vec = shuffle %R_G.vec, %B_U.vec, | |||
2243 | // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements | |||
2244 | // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B | |||
2245 | void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) { | |||
2246 | const InterleaveGroup *Group = Cost->getInterleavedAccessGroup(Instr); | |||
2247 | assert(Group && "Fail to get an interleaved access group.")(static_cast <bool> (Group && "Fail to get an interleaved access group." ) ? void (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2247, __extension__ __PRETTY_FUNCTION__)); | |||
2248 | ||||
2249 | // Skip if current instruction is not the insert position. | |||
2250 | if (Instr != Group->getInsertPos()) | |||
2251 | return; | |||
2252 | ||||
2253 | const DataLayout &DL = Instr->getModule()->getDataLayout(); | |||
2254 | Value *Ptr = getLoadStorePointerOperand(Instr); | |||
2255 | ||||
2256 | // Prepare for the vector type of the interleaved load/store. | |||
2257 | Type *ScalarTy = getMemInstValueType(Instr); | |||
2258 | unsigned InterleaveFactor = Group->getFactor(); | |||
2259 | Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF); | |||
2260 | Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr)); | |||
2261 | ||||
2262 | // Prepare for the new pointers. | |||
2263 | setDebugLocFromInst(Builder, Ptr); | |||
2264 | SmallVector<Value *, 2> NewPtrs; | |||
2265 | unsigned Index = Group->getIndex(Instr); | |||
2266 | ||||
2267 | // If the group is reverse, adjust the index to refer to the last vector lane | |||
2268 | // instead of the first. We adjust the index from the first vector lane, | |||
2269 | // rather than directly getting the pointer for lane VF - 1, because the | |||
2270 | // pointer operand of the interleaved access is supposed to be uniform. For | |||
2271 | // uniform instructions, we're only required to generate a value for the | |||
2272 | // first vector lane in each unroll iteration. | |||
2273 | if (Group->isReverse()) | |||
2274 | Index += (VF - 1) * Group->getFactor(); | |||
2275 | ||||
2276 | bool InBounds = false; | |||
2277 | if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts())) | |||
2278 | InBounds = gep->isInBounds(); | |||
2279 | ||||
2280 | for (unsigned Part = 0; Part < UF; Part++) { | |||
2281 | Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0}); | |||
2282 | ||||
2283 | // Notice current instruction could be any index. Need to adjust the address | |||
2284 | // to the member of index 0. | |||
2285 | // | |||
2286 | // E.g. a = A[i+1]; // Member of index 1 (Current instruction) | |||
2287 | // b = A[i]; // Member of index 0 | |||
2288 | // Current pointer is pointed to A[i+1], adjust it to A[i]. | |||
2289 | // | |||
2290 | // E.g. A[i+1] = a; // Member of index 1 | |||
2291 | // A[i] = b; // Member of index 0 | |||
2292 | // A[i+2] = c; // Member of index 2 (Current instruction) | |||
2293 | // Current pointer is pointed to A[i+2], adjust it to A[i]. | |||
2294 | NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index)); | |||
2295 | if (InBounds) | |||
2296 | cast<GetElementPtrInst>(NewPtr)->setIsInBounds(true); | |||
2297 | ||||
2298 | // Cast to the vector pointer type. | |||
2299 | NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy)); | |||
2300 | } | |||
2301 | ||||
2302 | setDebugLocFromInst(Builder, Instr); | |||
2303 | Value *UndefVec = UndefValue::get(VecTy); | |||
2304 | ||||
2305 | // Vectorize the interleaved load group. | |||
2306 | if (isa<LoadInst>(Instr)) { | |||
2307 | // For each unroll part, create a wide load for the group. | |||
2308 | SmallVector<Value *, 2> NewLoads; | |||
2309 | for (unsigned Part = 0; Part < UF; Part++) { | |||
2310 | auto *NewLoad = Builder.CreateAlignedLoad( | |||
2311 | NewPtrs[Part], Group->getAlignment(), "wide.vec"); | |||
2312 | Group->addMetadata(NewLoad); | |||
2313 | NewLoads.push_back(NewLoad); | |||
2314 | } | |||
2315 | ||||
2316 | // For each member in the group, shuffle out the appropriate data from the | |||
2317 | // wide loads. | |||
2318 | for (unsigned I = 0; I < InterleaveFactor; ++I) { | |||
2319 | Instruction *Member = Group->getMember(I); | |||
2320 | ||||
2321 | // Skip the gaps in the group. | |||
2322 | if (!Member) | |||
2323 | continue; | |||
2324 | ||||
2325 | Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF); | |||
2326 | for (unsigned Part = 0; Part < UF; Part++) { | |||
2327 | Value *StridedVec = Builder.CreateShuffleVector( | |||
2328 | NewLoads[Part], UndefVec, StrideMask, "strided.vec"); | |||
2329 | ||||
2330 | // If this member has different type, cast the result type. | |||
2331 | if (Member->getType() != ScalarTy) { | |||
2332 | VectorType *OtherVTy = VectorType::get(Member->getType(), VF); | |||
2333 | StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL); | |||
2334 | } | |||
2335 | ||||
2336 | if (Group->isReverse()) | |||
2337 | StridedVec = reverseVector(StridedVec); | |||
2338 | ||||
2339 | VectorLoopValueMap.setVectorValue(Member, Part, StridedVec); | |||
2340 | } | |||
2341 | } | |||
2342 | return; | |||
2343 | } | |||
2344 | ||||
2345 | // The sub vector type for current instruction. | |||
2346 | VectorType *SubVT = VectorType::get(ScalarTy, VF); | |||
2347 | ||||
2348 | // Vectorize the interleaved store group. | |||
2349 | for (unsigned Part = 0; Part < UF; Part++) { | |||
2350 | // Collect the stored vector from each member. | |||
2351 | SmallVector<Value *, 4> StoredVecs; | |||
2352 | for (unsigned i = 0; i < InterleaveFactor; i++) { | |||
2353 | // Interleaved store group doesn't allow a gap, so each index has a member | |||
2354 | Instruction *Member = Group->getMember(i); | |||
2355 | assert(Member && "Fail to get a member from an interleaved store group")(static_cast <bool> (Member && "Fail to get a member from an interleaved store group" ) ? void (0) : __assert_fail ("Member && \"Fail to get a member from an interleaved store group\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2355, __extension__ __PRETTY_FUNCTION__)); | |||
2356 | ||||
2357 | Value *StoredVec = getOrCreateVectorValue( | |||
2358 | cast<StoreInst>(Member)->getValueOperand(), Part); | |||
2359 | if (Group->isReverse()) | |||
2360 | StoredVec = reverseVector(StoredVec); | |||
2361 | ||||
2362 | // If this member has different type, cast it to a unified type. | |||
2363 | ||||
2364 | if (StoredVec->getType() != SubVT) | |||
2365 | StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL); | |||
2366 | ||||
2367 | StoredVecs.push_back(StoredVec); | |||
2368 | } | |||
2369 | ||||
2370 | // Concatenate all vectors into a wide vector. | |||
2371 | Value *WideVec = concatenateVectors(Builder, StoredVecs); | |||
2372 | ||||
2373 | // Interleave the elements in the wide vector. | |||
2374 | Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor); | |||
2375 | Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask, | |||
2376 | "interleaved.vec"); | |||
2377 | ||||
2378 | Instruction *NewStoreInstr = | |||
2379 | Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment()); | |||
2380 | ||||
2381 | Group->addMetadata(NewStoreInstr); | |||
2382 | } | |||
2383 | } | |||
2384 | ||||
2385 | void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr, | |||
2386 | VectorParts *BlockInMask) { | |||
2387 | // Attempt to issue a wide load. | |||
2388 | LoadInst *LI = dyn_cast<LoadInst>(Instr); | |||
2389 | StoreInst *SI = dyn_cast<StoreInst>(Instr); | |||
2390 | ||||
2391 | assert((LI || SI) && "Invalid Load/Store instruction")(static_cast <bool> ((LI || SI) && "Invalid Load/Store instruction" ) ? void (0) : __assert_fail ("(LI || SI) && \"Invalid Load/Store instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2391, __extension__ __PRETTY_FUNCTION__)); | |||
2392 | ||||
2393 | LoopVectorizationCostModel::InstWidening Decision = | |||
2394 | Cost->getWideningDecision(Instr, VF); | |||
2395 | assert(Decision != LoopVectorizationCostModel::CM_Unknown &&(static_cast <bool> (Decision != LoopVectorizationCostModel ::CM_Unknown && "CM decision should be taken at this point" ) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2396, __extension__ __PRETTY_FUNCTION__)) | |||
2396 | "CM decision should be taken at this point")(static_cast <bool> (Decision != LoopVectorizationCostModel ::CM_Unknown && "CM decision should be taken at this point" ) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2396, __extension__ __PRETTY_FUNCTION__)); | |||
2397 | if (Decision == LoopVectorizationCostModel::CM_Interleave) | |||
2398 | return vectorizeInterleaveGroup(Instr); | |||
2399 | ||||
2400 | Type *ScalarDataTy = getMemInstValueType(Instr); | |||
2401 | Type *DataTy = VectorType::get(ScalarDataTy, VF); | |||
2402 | Value *Ptr = getLoadStorePointerOperand(Instr); | |||
2403 | unsigned Alignment = getMemInstAlignment(Instr); | |||
2404 | // An alignment of 0 means target abi alignment. We need to use the scalar's | |||
2405 | // target abi alignment in such a case. | |||
2406 | const DataLayout &DL = Instr->getModule()->getDataLayout(); | |||
2407 | if (!Alignment) | |||
2408 | Alignment = DL.getABITypeAlignment(ScalarDataTy); | |||
2409 | unsigned AddressSpace = getMemInstAddressSpace(Instr); | |||
2410 | ||||
2411 | // Determine if the pointer operand of the access is either consecutive or | |||
2412 | // reverse consecutive. | |||
2413 | bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse); | |||
2414 | bool ConsecutiveStride = | |||
2415 | Reverse || (Decision == LoopVectorizationCostModel::CM_Widen); | |||
2416 | bool CreateGatherScatter = | |||
2417 | (Decision == LoopVectorizationCostModel::CM_GatherScatter); | |||
2418 | ||||
2419 | // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector | |||
2420 | // gather/scatter. Otherwise Decision should have been to Scalarize. | |||
2421 | assert((ConsecutiveStride || CreateGatherScatter) &&(static_cast <bool> ((ConsecutiveStride || CreateGatherScatter ) && "The instruction should be scalarized") ? void ( 0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2422, __extension__ __PRETTY_FUNCTION__)) | |||
2422 | "The instruction should be scalarized")(static_cast <bool> ((ConsecutiveStride || CreateGatherScatter ) && "The instruction should be scalarized") ? void ( 0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2422, __extension__ __PRETTY_FUNCTION__)); | |||
2423 | ||||
2424 | // Handle consecutive loads/stores. | |||
2425 | if (ConsecutiveStride) | |||
2426 | Ptr = getOrCreateScalarValue(Ptr, {0, 0}); | |||
2427 | ||||
2428 | VectorParts Mask; | |||
2429 | bool isMaskRequired = BlockInMask; | |||
2430 | if (isMaskRequired) | |||
2431 | Mask = *BlockInMask; | |||
2432 | ||||
2433 | bool InBounds = false; | |||
2434 | if (auto *gep = dyn_cast<GetElementPtrInst>( | |||
2435 | getLoadStorePointerOperand(Instr)->stripPointerCasts())) | |||
2436 | InBounds = gep->isInBounds(); | |||
2437 | ||||
2438 | const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * { | |||
2439 | // Calculate the pointer for the specific unroll-part. | |||
2440 | GetElementPtrInst *PartPtr = nullptr; | |||
2441 | ||||
2442 | if (Reverse) { | |||
2443 | // If the address is consecutive but reversed, then the | |||
2444 | // wide store needs to start at the last vector element. | |||
2445 | PartPtr = cast<GetElementPtrInst>( | |||
2446 | Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF))); | |||
2447 | PartPtr->setIsInBounds(InBounds); | |||
2448 | PartPtr = cast<GetElementPtrInst>( | |||
2449 | Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF))); | |||
2450 | PartPtr->setIsInBounds(InBounds); | |||
2451 | if (isMaskRequired) // Reverse of a null all-one mask is a null mask. | |||
2452 | Mask[Part] = reverseVector(Mask[Part]); | |||
2453 | } else { | |||
2454 | PartPtr = cast<GetElementPtrInst>( | |||
2455 | Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF))); | |||
2456 | PartPtr->setIsInBounds(InBounds); | |||
2457 | } | |||
2458 | ||||
2459 | return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace)); | |||
2460 | }; | |||
2461 | ||||
2462 | // Handle Stores: | |||
2463 | if (SI) { | |||
2464 | setDebugLocFromInst(Builder, SI); | |||
2465 | ||||
2466 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
2467 | Instruction *NewSI = nullptr; | |||
2468 | Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part); | |||
2469 | if (CreateGatherScatter) { | |||
2470 | Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr; | |||
2471 | Value *VectorGep = getOrCreateVectorValue(Ptr, Part); | |||
2472 | NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment, | |||
2473 | MaskPart); | |||
2474 | } else { | |||
2475 | if (Reverse) { | |||
2476 | // If we store to reverse consecutive memory locations, then we need | |||
2477 | // to reverse the order of elements in the stored value. | |||
2478 | StoredVal = reverseVector(StoredVal); | |||
2479 | // We don't want to update the value in the map as it might be used in | |||
2480 | // another expression. So don't call resetVectorValue(StoredVal). | |||
2481 | } | |||
2482 | auto *VecPtr = CreateVecPtr(Part, Ptr); | |||
2483 | if (isMaskRequired) | |||
2484 | NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment, | |||
2485 | Mask[Part]); | |||
2486 | else | |||
2487 | NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment); | |||
2488 | } | |||
2489 | addMetadata(NewSI, SI); | |||
2490 | } | |||
2491 | return; | |||
2492 | } | |||
2493 | ||||
2494 | // Handle loads. | |||
2495 | assert(LI && "Must have a load instruction")(static_cast <bool> (LI && "Must have a load instruction" ) ? void (0) : __assert_fail ("LI && \"Must have a load instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2495, __extension__ __PRETTY_FUNCTION__)); | |||
2496 | setDebugLocFromInst(Builder, LI); | |||
2497 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
2498 | Value *NewLI; | |||
2499 | if (CreateGatherScatter) { | |||
2500 | Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr; | |||
2501 | Value *VectorGep = getOrCreateVectorValue(Ptr, Part); | |||
2502 | NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart, | |||
2503 | nullptr, "wide.masked.gather"); | |||
2504 | addMetadata(NewLI, LI); | |||
2505 | } else { | |||
2506 | auto *VecPtr = CreateVecPtr(Part, Ptr); | |||
2507 | if (isMaskRequired) | |||
2508 | NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part], | |||
2509 | UndefValue::get(DataTy), | |||
2510 | "wide.masked.load"); | |||
2511 | else | |||
2512 | NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load"); | |||
2513 | ||||
2514 | // Add metadata to the load, but setVectorValue to the reverse shuffle. | |||
2515 | addMetadata(NewLI, LI); | |||
2516 | if (Reverse) | |||
2517 | NewLI = reverseVector(NewLI); | |||
2518 | } | |||
2519 | VectorLoopValueMap.setVectorValue(Instr, Part, NewLI); | |||
2520 | } | |||
2521 | } | |||
2522 | ||||
2523 | void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, | |||
2524 | const VPIteration &Instance, | |||
2525 | bool IfPredicateInstr) { | |||
2526 | assert(!Instr->getType()->isAggregateType() && "Can't handle vectors")(static_cast <bool> (!Instr->getType()->isAggregateType () && "Can't handle vectors") ? void (0) : __assert_fail ("!Instr->getType()->isAggregateType() && \"Can't handle vectors\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2526, __extension__ __PRETTY_FUNCTION__)); | |||
2527 | ||||
2528 | setDebugLocFromInst(Builder, Instr); | |||
2529 | ||||
2530 | // Does this instruction return a value ? | |||
2531 | bool IsVoidRetTy = Instr->getType()->isVoidTy(); | |||
2532 | ||||
2533 | Instruction *Cloned = Instr->clone(); | |||
2534 | if (!IsVoidRetTy) | |||
2535 | Cloned->setName(Instr->getName() + ".cloned"); | |||
2536 | ||||
2537 | // Replace the operands of the cloned instructions with their scalar | |||
2538 | // equivalents in the new loop. | |||
2539 | for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { | |||
2540 | auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance); | |||
2541 | Cloned->setOperand(op, NewOp); | |||
2542 | } | |||
2543 | addNewMetadata(Cloned, Instr); | |||
2544 | ||||
2545 | // Place the cloned scalar in the new loop. | |||
2546 | Builder.Insert(Cloned); | |||
2547 | ||||
2548 | // Add the cloned scalar to the scalar map entry. | |||
2549 | VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned); | |||
2550 | ||||
2551 | // If we just cloned a new assumption, add it the assumption cache. | |||
2552 | if (auto *II = dyn_cast<IntrinsicInst>(Cloned)) | |||
2553 | if (II->getIntrinsicID() == Intrinsic::assume) | |||
2554 | AC->registerAssumption(II); | |||
2555 | ||||
2556 | // End if-block. | |||
2557 | if (IfPredicateInstr) | |||
2558 | PredicatedInstructions.push_back(Cloned); | |||
2559 | } | |||
2560 | ||||
2561 | PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start, | |||
2562 | Value *End, Value *Step, | |||
2563 | Instruction *DL) { | |||
2564 | BasicBlock *Header = L->getHeader(); | |||
2565 | BasicBlock *Latch = L->getLoopLatch(); | |||
2566 | // As we're just creating this loop, it's possible no latch exists | |||
2567 | // yet. If so, use the header as this will be a single block loop. | |||
2568 | if (!Latch) | |||
2569 | Latch = Header; | |||
2570 | ||||
2571 | IRBuilder<> Builder(&*Header->getFirstInsertionPt()); | |||
2572 | Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction); | |||
2573 | setDebugLocFromInst(Builder, OldInst); | |||
2574 | auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index"); | |||
2575 | ||||
2576 | Builder.SetInsertPoint(Latch->getTerminator()); | |||
2577 | setDebugLocFromInst(Builder, OldInst); | |||
2578 | ||||
2579 | // Create i+1 and fill the PHINode. | |||
2580 | Value *Next = Builder.CreateAdd(Induction, Step, "index.next"); | |||
2581 | Induction->addIncoming(Start, L->getLoopPreheader()); | |||
2582 | Induction->addIncoming(Next, Latch); | |||
2583 | // Create the compare. | |||
2584 | Value *ICmp = Builder.CreateICmpEQ(Next, End); | |||
2585 | Builder.CreateCondBr(ICmp, L->getExitBlock(), Header); | |||
2586 | ||||
2587 | // Now we have two terminators. Remove the old one from the block. | |||
2588 | Latch->getTerminator()->eraseFromParent(); | |||
2589 | ||||
2590 | return Induction; | |||
2591 | } | |||
2592 | ||||
2593 | Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) { | |||
2594 | if (TripCount) | |||
2595 | return TripCount; | |||
2596 | ||||
2597 | IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); | |||
2598 | // Find the loop boundaries. | |||
2599 | ScalarEvolution *SE = PSE.getSE(); | |||
2600 | const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount(); | |||
2601 | assert(BackedgeTakenCount != SE->getCouldNotCompute() &&(static_cast <bool> (BackedgeTakenCount != SE->getCouldNotCompute () && "Invalid loop count") ? void (0) : __assert_fail ("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2602, __extension__ __PRETTY_FUNCTION__)) | |||
2602 | "Invalid loop count")(static_cast <bool> (BackedgeTakenCount != SE->getCouldNotCompute () && "Invalid loop count") ? void (0) : __assert_fail ("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2602, __extension__ __PRETTY_FUNCTION__)); | |||
2603 | ||||
2604 | Type *IdxTy = Legal->getWidestInductionType(); | |||
2605 | ||||
2606 | // The exit count might have the type of i64 while the phi is i32. This can | |||
2607 | // happen if we have an induction variable that is sign extended before the | |||
2608 | // compare. The only way that we get a backedge taken count is that the | |||
2609 | // induction variable was signed and as such will not overflow. In such a case | |||
2610 | // truncation is legal. | |||
2611 | if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() > | |||
2612 | IdxTy->getPrimitiveSizeInBits()) | |||
2613 | BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy); | |||
2614 | BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy); | |||
2615 | ||||
2616 | // Get the total trip count from the count by adding 1. | |||
2617 | const SCEV *ExitCount = SE->getAddExpr( | |||
2618 | BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType())); | |||
2619 | ||||
2620 | const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); | |||
2621 | ||||
2622 | // Expand the trip count and place the new instructions in the preheader. | |||
2623 | // Notice that the pre-header does not change, only the loop body. | |||
2624 | SCEVExpander Exp(*SE, DL, "induction"); | |||
2625 | ||||
2626 | // Count holds the overall loop count (N). | |||
2627 | TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(), | |||
2628 | L->getLoopPreheader()->getTerminator()); | |||
2629 | ||||
2630 | if (TripCount->getType()->isPointerTy()) | |||
2631 | TripCount = | |||
2632 | CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int", | |||
2633 | L->getLoopPreheader()->getTerminator()); | |||
2634 | ||||
2635 | return TripCount; | |||
2636 | } | |||
2637 | ||||
2638 | Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) { | |||
2639 | if (VectorTripCount) | |||
2640 | return VectorTripCount; | |||
2641 | ||||
2642 | Value *TC = getOrCreateTripCount(L); | |||
2643 | IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); | |||
2644 | ||||
2645 | // Now we need to generate the expression for the part of the loop that the | |||
2646 | // vectorized body will execute. This is equal to N - (N % Step) if scalar | |||
2647 | // iterations are not required for correctness, or N - Step, otherwise. Step | |||
2648 | // is equal to the vectorization factor (number of SIMD elements) times the | |||
2649 | // unroll factor (number of SIMD instructions). | |||
2650 | Constant *Step = ConstantInt::get(TC->getType(), VF * UF); | |||
2651 | Value *R = Builder.CreateURem(TC, Step, "n.mod.vf"); | |||
2652 | ||||
2653 | // If there is a non-reversed interleaved group that may speculatively access | |||
2654 | // memory out-of-bounds, we need to ensure that there will be at least one | |||
2655 | // iteration of the scalar epilogue loop. Thus, if the step evenly divides | |||
2656 | // the trip count, we set the remainder to be equal to the step. If the step | |||
2657 | // does not evenly divide the trip count, no adjustment is necessary since | |||
2658 | // there will already be scalar iterations. Note that the minimum iterations | |||
2659 | // check ensures that N >= Step. | |||
2660 | if (VF > 1 && Cost->requiresScalarEpilogue()) { | |||
2661 | auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0)); | |||
2662 | R = Builder.CreateSelect(IsZero, Step, R); | |||
2663 | } | |||
2664 | ||||
2665 | VectorTripCount = Builder.CreateSub(TC, R, "n.vec"); | |||
2666 | ||||
2667 | return VectorTripCount; | |||
2668 | } | |||
2669 | ||||
2670 | Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy, | |||
2671 | const DataLayout &DL) { | |||
2672 | // Verify that V is a vector type with same number of elements as DstVTy. | |||
2673 | unsigned VF = DstVTy->getNumElements(); | |||
2674 | VectorType *SrcVecTy = cast<VectorType>(V->getType()); | |||
2675 | assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match")(static_cast <bool> ((VF == SrcVecTy->getNumElements ()) && "Vector dimensions do not match") ? void (0) : __assert_fail ("(VF == SrcVecTy->getNumElements()) && \"Vector dimensions do not match\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2675, __extension__ __PRETTY_FUNCTION__)); | |||
2676 | Type *SrcElemTy = SrcVecTy->getElementType(); | |||
2677 | Type *DstElemTy = DstVTy->getElementType(); | |||
2678 | assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&(static_cast <bool> ((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && "Vector elements must have same size" ) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2679, __extension__ __PRETTY_FUNCTION__)) | |||
2679 | "Vector elements must have same size")(static_cast <bool> ((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && "Vector elements must have same size" ) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2679, __extension__ __PRETTY_FUNCTION__)); | |||
2680 | ||||
2681 | // Do a direct cast if element types are castable. | |||
2682 | if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) { | |||
2683 | return Builder.CreateBitOrPointerCast(V, DstVTy); | |||
2684 | } | |||
2685 | // V cannot be directly casted to desired vector type. | |||
2686 | // May happen when V is a floating point vector but DstVTy is a vector of | |||
2687 | // pointers or vice-versa. Handle this using a two-step bitcast using an | |||
2688 | // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float. | |||
2689 | assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&(static_cast <bool> ((DstElemTy->isPointerTy() != SrcElemTy ->isPointerTy()) && "Only one type should be a pointer type" ) ? void (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2690, __extension__ __PRETTY_FUNCTION__)) | |||
2690 | "Only one type should be a pointer type")(static_cast <bool> ((DstElemTy->isPointerTy() != SrcElemTy ->isPointerTy()) && "Only one type should be a pointer type" ) ? void (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2690, __extension__ __PRETTY_FUNCTION__)); | |||
2691 | assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&(static_cast <bool> ((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && "Only one type should be a floating point type" ) ? void (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2692, __extension__ __PRETTY_FUNCTION__)) | |||
2692 | "Only one type should be a floating point type")(static_cast <bool> ((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && "Only one type should be a floating point type" ) ? void (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2692, __extension__ __PRETTY_FUNCTION__)); | |||
2693 | Type *IntTy = | |||
2694 | IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy)); | |||
2695 | VectorType *VecIntTy = VectorType::get(IntTy, VF); | |||
2696 | Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy); | |||
2697 | return Builder.CreateBitOrPointerCast(CastVal, DstVTy); | |||
2698 | } | |||
2699 | ||||
2700 | void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L, | |||
2701 | BasicBlock *Bypass) { | |||
2702 | Value *Count = getOrCreateTripCount(L); | |||
2703 | BasicBlock *BB = L->getLoopPreheader(); | |||
2704 | IRBuilder<> Builder(BB->getTerminator()); | |||
2705 | ||||
2706 | // Generate code to check if the loop's trip count is less than VF * UF, or | |||
2707 | // equal to it in case a scalar epilogue is required; this implies that the | |||
2708 | // vector trip count is zero. This check also covers the case where adding one | |||
2709 | // to the backedge-taken count overflowed leading to an incorrect trip count | |||
2710 | // of zero. In this case we will also jump to the scalar loop. | |||
2711 | auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE | |||
2712 | : ICmpInst::ICMP_ULT; | |||
2713 | Value *CheckMinIters = Builder.CreateICmp( | |||
2714 | P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check"); | |||
2715 | ||||
2716 | BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); | |||
2717 | // Update dominator tree immediately if the generated block is a | |||
2718 | // LoopBypassBlock because SCEV expansions to generate loop bypass | |||
2719 | // checks may query it before the current function is finished. | |||
2720 | DT->addNewBlock(NewBB, BB); | |||
2721 | if (L->getParentLoop()) | |||
2722 | L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); | |||
2723 | ReplaceInstWithInst(BB->getTerminator(), | |||
2724 | BranchInst::Create(Bypass, NewBB, CheckMinIters)); | |||
2725 | LoopBypassBlocks.push_back(BB); | |||
2726 | } | |||
2727 | ||||
2728 | void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) { | |||
2729 | BasicBlock *BB = L->getLoopPreheader(); | |||
2730 | ||||
2731 | // Generate the code to check that the SCEV assumptions that we made. | |||
2732 | // We want the new basic block to start at the first instruction in a | |||
2733 | // sequence of instructions that form a check. | |||
2734 | SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(), | |||
2735 | "scev.check"); | |||
2736 | Value *SCEVCheck = | |||
2737 | Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator()); | |||
2738 | ||||
2739 | if (auto *C = dyn_cast<ConstantInt>(SCEVCheck)) | |||
2740 | if (C->isZero()) | |||
2741 | return; | |||
2742 | ||||
2743 | // Create a new block containing the stride check. | |||
2744 | BB->setName("vector.scevcheck"); | |||
2745 | auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); | |||
2746 | // Update dominator tree immediately if the generated block is a | |||
2747 | // LoopBypassBlock because SCEV expansions to generate loop bypass | |||
2748 | // checks may query it before the current function is finished. | |||
2749 | DT->addNewBlock(NewBB, BB); | |||
2750 | if (L->getParentLoop()) | |||
2751 | L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); | |||
2752 | ReplaceInstWithInst(BB->getTerminator(), | |||
2753 | BranchInst::Create(Bypass, NewBB, SCEVCheck)); | |||
2754 | LoopBypassBlocks.push_back(BB); | |||
2755 | AddedSafetyChecks = true; | |||
2756 | } | |||
2757 | ||||
2758 | void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) { | |||
2759 | BasicBlock *BB = L->getLoopPreheader(); | |||
2760 | ||||
2761 | // Generate the code that checks in runtime if arrays overlap. We put the | |||
2762 | // checks into a separate block to make the more common case of few elements | |||
2763 | // faster. | |||
2764 | Instruction *FirstCheckInst; | |||
2765 | Instruction *MemRuntimeCheck; | |||
2766 | std::tie(FirstCheckInst, MemRuntimeCheck) = | |||
2767 | Legal->getLAI()->addRuntimeChecks(BB->getTerminator()); | |||
2768 | if (!MemRuntimeCheck) | |||
2769 | return; | |||
2770 | ||||
2771 | // Create a new block containing the memory check. | |||
2772 | BB->setName("vector.memcheck"); | |||
2773 | auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); | |||
2774 | // Update dominator tree immediately if the generated block is a | |||
2775 | // LoopBypassBlock because SCEV expansions to generate loop bypass | |||
2776 | // checks may query it before the current function is finished. | |||
2777 | DT->addNewBlock(NewBB, BB); | |||
2778 | if (L->getParentLoop()) | |||
2779 | L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); | |||
2780 | ReplaceInstWithInst(BB->getTerminator(), | |||
2781 | BranchInst::Create(Bypass, NewBB, MemRuntimeCheck)); | |||
2782 | LoopBypassBlocks.push_back(BB); | |||
2783 | AddedSafetyChecks = true; | |||
2784 | ||||
2785 | // We currently don't use LoopVersioning for the actual loop cloning but we | |||
2786 | // still use it to add the noalias metadata. | |||
2787 | LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT, | |||
2788 | PSE.getSE()); | |||
2789 | LVer->prepareNoAliasMetadata(); | |||
2790 | } | |||
2791 | ||||
2792 | BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() { | |||
2793 | /* | |||
2794 | In this function we generate a new loop. The new loop will contain | |||
2795 | the vectorized instructions while the old loop will continue to run the | |||
2796 | scalar remainder. | |||
2797 | ||||
2798 | [ ] <-- loop iteration number check. | |||
2799 | / | | |||
2800 | / v | |||
2801 | | [ ] <-- vector loop bypass (may consist of multiple blocks). | |||
2802 | | / | | |||
2803 | | / v | |||
2804 | || [ ] <-- vector pre header. | |||
2805 | |/ | | |||
2806 | | v | |||
2807 | | [ ] \ | |||
2808 | | [ ]_| <-- vector loop. | |||
2809 | | | | |||
2810 | | v | |||
2811 | | -[ ] <--- middle-block. | |||
2812 | | / | | |||
2813 | | / v | |||
2814 | -|- >[ ] <--- new preheader. | |||
2815 | | | | |||
2816 | | v | |||
2817 | | [ ] \ | |||
2818 | | [ ]_| <-- old scalar loop to handle remainder. | |||
2819 | \ | | |||
2820 | \ v | |||
2821 | >[ ] <-- exit block. | |||
2822 | ... | |||
2823 | */ | |||
2824 | ||||
2825 | BasicBlock *OldBasicBlock = OrigLoop->getHeader(); | |||
2826 | BasicBlock *VectorPH = OrigLoop->getLoopPreheader(); | |||
2827 | BasicBlock *ExitBlock = OrigLoop->getExitBlock(); | |||
2828 | assert(VectorPH && "Invalid loop structure")(static_cast <bool> (VectorPH && "Invalid loop structure" ) ? void (0) : __assert_fail ("VectorPH && \"Invalid loop structure\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2828, __extension__ __PRETTY_FUNCTION__)); | |||
2829 | assert(ExitBlock && "Must have an exit block")(static_cast <bool> (ExitBlock && "Must have an exit block" ) ? void (0) : __assert_fail ("ExitBlock && \"Must have an exit block\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2829, __extension__ __PRETTY_FUNCTION__)); | |||
2830 | ||||
2831 | // Some loops have a single integer induction variable, while other loops | |||
2832 | // don't. One example is c++ iterators that often have multiple pointer | |||
2833 | // induction variables. In the code below we also support a case where we | |||
2834 | // don't have a single induction variable. | |||
2835 | // | |||
2836 | // We try to obtain an induction variable from the original loop as hard | |||
2837 | // as possible. However if we don't find one that: | |||
2838 | // - is an integer | |||
2839 | // - counts from zero, stepping by one | |||
2840 | // - is the size of the widest induction variable type | |||
2841 | // then we create a new one. | |||
2842 | OldInduction = Legal->getPrimaryInduction(); | |||
2843 | Type *IdxTy = Legal->getWidestInductionType(); | |||
2844 | ||||
2845 | // Split the single block loop into the two loop structure described above. | |||
2846 | BasicBlock *VecBody = | |||
2847 | VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); | |||
2848 | BasicBlock *MiddleBlock = | |||
2849 | VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); | |||
2850 | BasicBlock *ScalarPH = | |||
2851 | MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); | |||
2852 | ||||
2853 | // Create and register the new vector loop. | |||
2854 | Loop *Lp = LI->AllocateLoop(); | |||
2855 | Loop *ParentLoop = OrigLoop->getParentLoop(); | |||
2856 | ||||
2857 | // Insert the new loop into the loop nest and register the new basic blocks | |||
2858 | // before calling any utilities such as SCEV that require valid LoopInfo. | |||
2859 | if (ParentLoop) { | |||
2860 | ParentLoop->addChildLoop(Lp); | |||
2861 | ParentLoop->addBasicBlockToLoop(ScalarPH, *LI); | |||
2862 | ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI); | |||
2863 | } else { | |||
2864 | LI->addTopLevelLoop(Lp); | |||
2865 | } | |||
2866 | Lp->addBasicBlockToLoop(VecBody, *LI); | |||
2867 | ||||
2868 | // Find the loop boundaries. | |||
2869 | Value *Count = getOrCreateTripCount(Lp); | |||
2870 | ||||
2871 | Value *StartIdx = ConstantInt::get(IdxTy, 0); | |||
2872 | ||||
2873 | // Now, compare the new count to zero. If it is zero skip the vector loop and | |||
2874 | // jump to the scalar loop. This check also covers the case where the | |||
2875 | // backedge-taken count is uint##_max: adding one to it will overflow leading | |||
2876 | // to an incorrect trip count of zero. In this (rare) case we will also jump | |||
2877 | // to the scalar loop. | |||
2878 | emitMinimumIterationCountCheck(Lp, ScalarPH); | |||
2879 | ||||
2880 | // Generate the code to check any assumptions that we've made for SCEV | |||
2881 | // expressions. | |||
2882 | emitSCEVChecks(Lp, ScalarPH); | |||
2883 | ||||
2884 | // Generate the code that checks in runtime if arrays overlap. We put the | |||
2885 | // checks into a separate block to make the more common case of few elements | |||
2886 | // faster. | |||
2887 | emitMemRuntimeChecks(Lp, ScalarPH); | |||
2888 | ||||
2889 | // Generate the induction variable. | |||
2890 | // The loop step is equal to the vectorization factor (num of SIMD elements) | |||
2891 | // times the unroll factor (num of SIMD instructions). | |||
2892 | Value *CountRoundDown = getOrCreateVectorTripCount(Lp); | |||
2893 | Constant *Step = ConstantInt::get(IdxTy, VF * UF); | |||
2894 | Induction = | |||
2895 | createInductionVariable(Lp, StartIdx, CountRoundDown, Step, | |||
2896 | getDebugLocFromInstOrOperands(OldInduction)); | |||
2897 | ||||
2898 | // We are going to resume the execution of the scalar loop. | |||
2899 | // Go over all of the induction variables that we found and fix the | |||
2900 | // PHIs that are left in the scalar version of the loop. | |||
2901 | // The starting values of PHI nodes depend on the counter of the last | |||
2902 | // iteration in the vectorized loop. | |||
2903 | // If we come from a bypass edge then we need to start from the original | |||
2904 | // start value. | |||
2905 | ||||
2906 | // This variable saves the new starting index for the scalar loop. It is used | |||
2907 | // to test if there are any tail iterations left once the vector loop has | |||
2908 | // completed. | |||
2909 | LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); | |||
2910 | for (auto &InductionEntry : *List) { | |||
2911 | PHINode *OrigPhi = InductionEntry.first; | |||
2912 | InductionDescriptor II = InductionEntry.second; | |||
2913 | ||||
2914 | // Create phi nodes to merge from the backedge-taken check block. | |||
2915 | PHINode *BCResumeVal = PHINode::Create( | |||
2916 | OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator()); | |||
2917 | // Copy original phi DL over to the new one. | |||
2918 | BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc()); | |||
2919 | Value *&EndValue = IVEndValues[OrigPhi]; | |||
2920 | if (OrigPhi == OldInduction) { | |||
2921 | // We know what the end value is. | |||
2922 | EndValue = CountRoundDown; | |||
2923 | } else { | |||
2924 | IRBuilder<> B(Lp->getLoopPreheader()->getTerminator()); | |||
2925 | Type *StepType = II.getStep()->getType(); | |||
2926 | Instruction::CastOps CastOp = | |||
2927 | CastInst::getCastOpcode(CountRoundDown, true, StepType, true); | |||
2928 | Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd"); | |||
2929 | const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); | |||
2930 | EndValue = II.transform(B, CRD, PSE.getSE(), DL); | |||
2931 | EndValue->setName("ind.end"); | |||
2932 | } | |||
2933 | ||||
2934 | // The new PHI merges the original incoming value, in case of a bypass, | |||
2935 | // or the value at the end of the vectorized loop. | |||
2936 | BCResumeVal->addIncoming(EndValue, MiddleBlock); | |||
2937 | ||||
2938 | // Fix the scalar body counter (PHI node). | |||
2939 | unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); | |||
2940 | ||||
2941 | // The old induction's phi node in the scalar body needs the truncated | |||
2942 | // value. | |||
2943 | for (BasicBlock *BB : LoopBypassBlocks) | |||
2944 | BCResumeVal->addIncoming(II.getStartValue(), BB); | |||
2945 | OrigPhi->setIncomingValue(BlockIdx, BCResumeVal); | |||
2946 | } | |||
2947 | ||||
2948 | // Add a check in the middle block to see if we have completed | |||
2949 | // all of the iterations in the first vector loop. | |||
2950 | // If (N - N%VF) == N, then we *don't* need to run the remainder. | |||
2951 | Value *CmpN = | |||
2952 | CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count, | |||
2953 | CountRoundDown, "cmp.n", MiddleBlock->getTerminator()); | |||
2954 | ReplaceInstWithInst(MiddleBlock->getTerminator(), | |||
2955 | BranchInst::Create(ExitBlock, ScalarPH, CmpN)); | |||
2956 | ||||
2957 | // Get ready to start creating new instructions into the vectorized body. | |||
2958 | Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt()); | |||
2959 | ||||
2960 | // Save the state. | |||
2961 | LoopVectorPreHeader = Lp->getLoopPreheader(); | |||
2962 | LoopScalarPreHeader = ScalarPH; | |||
2963 | LoopMiddleBlock = MiddleBlock; | |||
2964 | LoopExitBlock = ExitBlock; | |||
2965 | LoopVectorBody = VecBody; | |||
2966 | LoopScalarBody = OldBasicBlock; | |||
2967 | ||||
2968 | // Keep all loop hints from the original loop on the vector loop (we'll | |||
2969 | // replace the vectorizer-specific hints below). | |||
2970 | if (MDNode *LID = OrigLoop->getLoopID()) | |||
2971 | Lp->setLoopID(LID); | |||
2972 | ||||
2973 | LoopVectorizeHints Hints(Lp, true, *ORE); | |||
2974 | Hints.setAlreadyVectorized(); | |||
2975 | ||||
2976 | return LoopVectorPreHeader; | |||
2977 | } | |||
2978 | ||||
2979 | // Fix up external users of the induction variable. At this point, we are | |||
2980 | // in LCSSA form, with all external PHIs that use the IV having one input value, | |||
2981 | // coming from the remainder loop. We need those PHIs to also have a correct | |||
2982 | // value for the IV when arriving directly from the middle block. | |||
2983 | void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi, | |||
2984 | const InductionDescriptor &II, | |||
2985 | Value *CountRoundDown, Value *EndValue, | |||
2986 | BasicBlock *MiddleBlock) { | |||
2987 | // There are two kinds of external IV usages - those that use the value | |||
2988 | // computed in the last iteration (the PHI) and those that use the penultimate | |||
2989 | // value (the value that feeds into the phi from the loop latch). | |||
2990 | // We allow both, but they, obviously, have different values. | |||
2991 | ||||
2992 | assert(OrigLoop->getExitBlock() && "Expected a single exit block")(static_cast <bool> (OrigLoop->getExitBlock() && "Expected a single exit block") ? void (0) : __assert_fail ( "OrigLoop->getExitBlock() && \"Expected a single exit block\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 2992, __extension__ __PRETTY_FUNCTION__)); | |||
2993 | ||||
2994 | DenseMap<Value *, Value *> MissingVals; | |||
2995 | ||||
2996 | // An external user of the last iteration's value should see the value that | |||
2997 | // the remainder loop uses to initialize its own IV. | |||
2998 | Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()); | |||
2999 | for (User *U : PostInc->users()) { | |||
3000 | Instruction *UI = cast<Instruction>(U); | |||
3001 | if (!OrigLoop->contains(UI)) { | |||
3002 | assert(isa<PHINode>(UI) && "Expected LCSSA form")(static_cast <bool> (isa<PHINode>(UI) && "Expected LCSSA form" ) ? void (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3002, __extension__ __PRETTY_FUNCTION__)); | |||
3003 | MissingVals[UI] = EndValue; | |||
3004 | } | |||
3005 | } | |||
3006 | ||||
3007 | // An external user of the penultimate value need to see EndValue - Step. | |||
3008 | // The simplest way to get this is to recompute it from the constituent SCEVs, | |||
3009 | // that is Start + (Step * (CRD - 1)). | |||
3010 | for (User *U : OrigPhi->users()) { | |||
3011 | auto *UI = cast<Instruction>(U); | |||
3012 | if (!OrigLoop->contains(UI)) { | |||
3013 | const DataLayout &DL = | |||
3014 | OrigLoop->getHeader()->getModule()->getDataLayout(); | |||
3015 | assert(isa<PHINode>(UI) && "Expected LCSSA form")(static_cast <bool> (isa<PHINode>(UI) && "Expected LCSSA form" ) ? void (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3015, __extension__ __PRETTY_FUNCTION__)); | |||
3016 | ||||
3017 | IRBuilder<> B(MiddleBlock->getTerminator()); | |||
3018 | Value *CountMinusOne = B.CreateSub( | |||
3019 | CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1)); | |||
3020 | Value *CMO = | |||
3021 | !II.getStep()->getType()->isIntegerTy() | |||
3022 | ? B.CreateCast(Instruction::SIToFP, CountMinusOne, | |||
3023 | II.getStep()->getType()) | |||
3024 | : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType()); | |||
3025 | CMO->setName("cast.cmo"); | |||
3026 | Value *Escape = II.transform(B, CMO, PSE.getSE(), DL); | |||
3027 | Escape->setName("ind.escape"); | |||
3028 | MissingVals[UI] = Escape; | |||
3029 | } | |||
3030 | } | |||
3031 | ||||
3032 | for (auto &I : MissingVals) { | |||
3033 | PHINode *PHI = cast<PHINode>(I.first); | |||
3034 | // One corner case we have to handle is two IVs "chasing" each-other, | |||
3035 | // that is %IV2 = phi [...], [ %IV1, %latch ] | |||
3036 | // In this case, if IV1 has an external use, we need to avoid adding both | |||
3037 | // "last value of IV1" and "penultimate value of IV2". So, verify that we | |||
3038 | // don't already have an incoming value for the middle block. | |||
3039 | if (PHI->getBasicBlockIndex(MiddleBlock) == -1) | |||
3040 | PHI->addIncoming(I.second, MiddleBlock); | |||
3041 | } | |||
3042 | } | |||
3043 | ||||
3044 | namespace { | |||
3045 | ||||
3046 | struct CSEDenseMapInfo { | |||
3047 | static bool canHandle(const Instruction *I) { | |||
3048 | return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || | |||
3049 | isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I); | |||
3050 | } | |||
3051 | ||||
3052 | static inline Instruction *getEmptyKey() { | |||
3053 | return DenseMapInfo<Instruction *>::getEmptyKey(); | |||
3054 | } | |||
3055 | ||||
3056 | static inline Instruction *getTombstoneKey() { | |||
3057 | return DenseMapInfo<Instruction *>::getTombstoneKey(); | |||
3058 | } | |||
3059 | ||||
3060 | static unsigned getHashValue(const Instruction *I) { | |||
3061 | assert(canHandle(I) && "Unknown instruction!")(static_cast <bool> (canHandle(I) && "Unknown instruction!" ) ? void (0) : __assert_fail ("canHandle(I) && \"Unknown instruction!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3061, __extension__ __PRETTY_FUNCTION__)); | |||
3062 | return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(), | |||
3063 | I->value_op_end())); | |||
3064 | } | |||
3065 | ||||
3066 | static bool isEqual(const Instruction *LHS, const Instruction *RHS) { | |||
3067 | if (LHS == getEmptyKey() || RHS == getEmptyKey() || | |||
3068 | LHS == getTombstoneKey() || RHS == getTombstoneKey()) | |||
3069 | return LHS == RHS; | |||
3070 | return LHS->isIdenticalTo(RHS); | |||
3071 | } | |||
3072 | }; | |||
3073 | ||||
3074 | } // end anonymous namespace | |||
3075 | ||||
3076 | ///Perform cse of induction variable instructions. | |||
3077 | static void cse(BasicBlock *BB) { | |||
3078 | // Perform simple cse. | |||
3079 | SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap; | |||
3080 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { | |||
3081 | Instruction *In = &*I++; | |||
3082 | ||||
3083 | if (!CSEDenseMapInfo::canHandle(In)) | |||
3084 | continue; | |||
3085 | ||||
3086 | // Check if we can replace this instruction with any of the | |||
3087 | // visited instructions. | |||
3088 | if (Instruction *V = CSEMap.lookup(In)) { | |||
3089 | In->replaceAllUsesWith(V); | |||
3090 | In->eraseFromParent(); | |||
3091 | continue; | |||
3092 | } | |||
3093 | ||||
3094 | CSEMap[In] = In; | |||
3095 | } | |||
3096 | } | |||
3097 | ||||
3098 | /// Estimate the overhead of scalarizing an instruction. This is a | |||
3099 | /// convenience wrapper for the type-based getScalarizationOverhead API. | |||
3100 | static unsigned getScalarizationOverhead(Instruction *I, unsigned VF, | |||
3101 | const TargetTransformInfo &TTI) { | |||
3102 | if (VF == 1) | |||
3103 | return 0; | |||
3104 | ||||
3105 | unsigned Cost = 0; | |||
3106 | Type *RetTy = ToVectorTy(I->getType(), VF); | |||
3107 | if (!RetTy->isVoidTy() && | |||
3108 | (!isa<LoadInst>(I) || | |||
3109 | !TTI.supportsEfficientVectorElementLoadStore())) | |||
3110 | Cost += TTI.getScalarizationOverhead(RetTy, true, false); | |||
3111 | ||||
3112 | if (CallInst *CI = dyn_cast<CallInst>(I)) { | |||
3113 | SmallVector<const Value *, 4> Operands(CI->arg_operands()); | |||
3114 | Cost += TTI.getOperandsScalarizationOverhead(Operands, VF); | |||
3115 | } | |||
3116 | else if (!isa<StoreInst>(I) || | |||
3117 | !TTI.supportsEfficientVectorElementLoadStore()) { | |||
3118 | SmallVector<const Value *, 4> Operands(I->operand_values()); | |||
3119 | Cost += TTI.getOperandsScalarizationOverhead(Operands, VF); | |||
3120 | } | |||
3121 | ||||
3122 | return Cost; | |||
3123 | } | |||
3124 | ||||
3125 | // Estimate cost of a call instruction CI if it were vectorized with factor VF. | |||
3126 | // Return the cost of the instruction, including scalarization overhead if it's | |||
3127 | // needed. The flag NeedToScalarize shows if the call needs to be scalarized - | |||
3128 | // i.e. either vector version isn't available, or is too expensive. | |||
3129 | static unsigned getVectorCallCost(CallInst *CI, unsigned VF, | |||
3130 | const TargetTransformInfo &TTI, | |||
3131 | const TargetLibraryInfo *TLI, | |||
3132 | bool &NeedToScalarize) { | |||
3133 | Function *F = CI->getCalledFunction(); | |||
3134 | StringRef FnName = CI->getCalledFunction()->getName(); | |||
3135 | Type *ScalarRetTy = CI->getType(); | |||
3136 | SmallVector<Type *, 4> Tys, ScalarTys; | |||
3137 | for (auto &ArgOp : CI->arg_operands()) | |||
3138 | ScalarTys.push_back(ArgOp->getType()); | |||
3139 | ||||
3140 | // Estimate cost of scalarized vector call. The source operands are assumed | |||
3141 | // to be vectors, so we need to extract individual elements from there, | |||
3142 | // execute VF scalar calls, and then gather the result into the vector return | |||
3143 | // value. | |||
3144 | unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys); | |||
3145 | if (VF == 1) | |||
3146 | return ScalarCallCost; | |||
3147 | ||||
3148 | // Compute corresponding vector type for return value and arguments. | |||
3149 | Type *RetTy = ToVectorTy(ScalarRetTy, VF); | |||
3150 | for (Type *ScalarTy : ScalarTys) | |||
3151 | Tys.push_back(ToVectorTy(ScalarTy, VF)); | |||
3152 | ||||
3153 | // Compute costs of unpacking argument values for the scalar calls and | |||
3154 | // packing the return values to a vector. | |||
3155 | unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI); | |||
3156 | ||||
3157 | unsigned Cost = ScalarCallCost * VF + ScalarizationCost; | |||
3158 | ||||
3159 | // If we can't emit a vector call for this function, then the currently found | |||
3160 | // cost is the cost we need to return. | |||
3161 | NeedToScalarize = true; | |||
3162 | if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin()) | |||
3163 | return Cost; | |||
3164 | ||||
3165 | // If the corresponding vector cost is cheaper, return its cost. | |||
3166 | unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys); | |||
3167 | if (VectorCallCost < Cost) { | |||
3168 | NeedToScalarize = false; | |||
3169 | return VectorCallCost; | |||
3170 | } | |||
3171 | return Cost; | |||
3172 | } | |||
3173 | ||||
3174 | // Estimate cost of an intrinsic call instruction CI if it were vectorized with | |||
3175 | // factor VF. Return the cost of the instruction, including scalarization | |||
3176 | // overhead if it's needed. | |||
3177 | static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF, | |||
3178 | const TargetTransformInfo &TTI, | |||
3179 | const TargetLibraryInfo *TLI) { | |||
3180 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
3181 | assert(ID && "Expected intrinsic call!")(static_cast <bool> (ID && "Expected intrinsic call!" ) ? void (0) : __assert_fail ("ID && \"Expected intrinsic call!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3181, __extension__ __PRETTY_FUNCTION__)); | |||
3182 | ||||
3183 | FastMathFlags FMF; | |||
3184 | if (auto *FPMO = dyn_cast<FPMathOperator>(CI)) | |||
3185 | FMF = FPMO->getFastMathFlags(); | |||
3186 | ||||
3187 | SmallVector<Value *, 4> Operands(CI->arg_operands()); | |||
3188 | return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF); | |||
3189 | } | |||
3190 | ||||
3191 | static Type *smallestIntegerVectorType(Type *T1, Type *T2) { | |||
3192 | auto *I1 = cast<IntegerType>(T1->getVectorElementType()); | |||
3193 | auto *I2 = cast<IntegerType>(T2->getVectorElementType()); | |||
3194 | return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2; | |||
3195 | } | |||
3196 | static Type *largestIntegerVectorType(Type *T1, Type *T2) { | |||
3197 | auto *I1 = cast<IntegerType>(T1->getVectorElementType()); | |||
3198 | auto *I2 = cast<IntegerType>(T2->getVectorElementType()); | |||
3199 | return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2; | |||
3200 | } | |||
3201 | ||||
3202 | void InnerLoopVectorizer::truncateToMinimalBitwidths() { | |||
3203 | // For every instruction `I` in MinBWs, truncate the operands, create a | |||
3204 | // truncated version of `I` and reextend its result. InstCombine runs | |||
3205 | // later and will remove any ext/trunc pairs. | |||
3206 | SmallPtrSet<Value *, 4> Erased; | |||
3207 | for (const auto &KV : Cost->getMinimalBitwidths()) { | |||
3208 | // If the value wasn't vectorized, we must maintain the original scalar | |||
3209 | // type. The absence of the value from VectorLoopValueMap indicates that it | |||
3210 | // wasn't vectorized. | |||
3211 | if (!VectorLoopValueMap.hasAnyVectorValue(KV.first)) | |||
3212 | continue; | |||
3213 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3214 | Value *I = getOrCreateVectorValue(KV.first, Part); | |||
3215 | if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I)) | |||
3216 | continue; | |||
3217 | Type *OriginalTy = I->getType(); | |||
3218 | Type *ScalarTruncatedTy = | |||
3219 | IntegerType::get(OriginalTy->getContext(), KV.second); | |||
3220 | Type *TruncatedTy = VectorType::get(ScalarTruncatedTy, | |||
3221 | OriginalTy->getVectorNumElements()); | |||
3222 | if (TruncatedTy == OriginalTy) | |||
3223 | continue; | |||
3224 | ||||
3225 | IRBuilder<> B(cast<Instruction>(I)); | |||
3226 | auto ShrinkOperand = [&](Value *V) -> Value * { | |||
3227 | if (auto *ZI = dyn_cast<ZExtInst>(V)) | |||
3228 | if (ZI->getSrcTy() == TruncatedTy) | |||
3229 | return ZI->getOperand(0); | |||
3230 | return B.CreateZExtOrTrunc(V, TruncatedTy); | |||
3231 | }; | |||
3232 | ||||
3233 | // The actual instruction modification depends on the instruction type, | |||
3234 | // unfortunately. | |||
3235 | Value *NewI = nullptr; | |||
3236 | if (auto *BO = dyn_cast<BinaryOperator>(I)) { | |||
3237 | NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)), | |||
3238 | ShrinkOperand(BO->getOperand(1))); | |||
3239 | ||||
3240 | // Any wrapping introduced by shrinking this operation shouldn't be | |||
3241 | // considered undefined behavior. So, we can't unconditionally copy | |||
3242 | // arithmetic wrapping flags to NewI. | |||
3243 | cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false); | |||
3244 | } else if (auto *CI = dyn_cast<ICmpInst>(I)) { | |||
3245 | NewI = | |||
3246 | B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)), | |||
3247 | ShrinkOperand(CI->getOperand(1))); | |||
3248 | } else if (auto *SI = dyn_cast<SelectInst>(I)) { | |||
3249 | NewI = B.CreateSelect(SI->getCondition(), | |||
3250 | ShrinkOperand(SI->getTrueValue()), | |||
3251 | ShrinkOperand(SI->getFalseValue())); | |||
3252 | } else if (auto *CI = dyn_cast<CastInst>(I)) { | |||
3253 | switch (CI->getOpcode()) { | |||
3254 | default: | |||
3255 | llvm_unreachable("Unhandled cast!")::llvm::llvm_unreachable_internal("Unhandled cast!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3255); | |||
3256 | case Instruction::Trunc: | |||
3257 | NewI = ShrinkOperand(CI->getOperand(0)); | |||
3258 | break; | |||
3259 | case Instruction::SExt: | |||
3260 | NewI = B.CreateSExtOrTrunc( | |||
3261 | CI->getOperand(0), | |||
3262 | smallestIntegerVectorType(OriginalTy, TruncatedTy)); | |||
3263 | break; | |||
3264 | case Instruction::ZExt: | |||
3265 | NewI = B.CreateZExtOrTrunc( | |||
3266 | CI->getOperand(0), | |||
3267 | smallestIntegerVectorType(OriginalTy, TruncatedTy)); | |||
3268 | break; | |||
3269 | } | |||
3270 | } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) { | |||
3271 | auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements(); | |||
3272 | auto *O0 = B.CreateZExtOrTrunc( | |||
3273 | SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0)); | |||
3274 | auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements(); | |||
3275 | auto *O1 = B.CreateZExtOrTrunc( | |||
3276 | SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1)); | |||
3277 | ||||
3278 | NewI = B.CreateShuffleVector(O0, O1, SI->getMask()); | |||
3279 | } else if (isa<LoadInst>(I) || isa<PHINode>(I)) { | |||
3280 | // Don't do anything with the operands, just extend the result. | |||
3281 | continue; | |||
3282 | } else if (auto *IE = dyn_cast<InsertElementInst>(I)) { | |||
3283 | auto Elements = IE->getOperand(0)->getType()->getVectorNumElements(); | |||
3284 | auto *O0 = B.CreateZExtOrTrunc( | |||
3285 | IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); | |||
3286 | auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy); | |||
3287 | NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2)); | |||
3288 | } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) { | |||
3289 | auto Elements = EE->getOperand(0)->getType()->getVectorNumElements(); | |||
3290 | auto *O0 = B.CreateZExtOrTrunc( | |||
3291 | EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); | |||
3292 | NewI = B.CreateExtractElement(O0, EE->getOperand(2)); | |||
3293 | } else { | |||
3294 | // If we don't know what to do, be conservative and don't do anything. | |||
3295 | continue; | |||
3296 | } | |||
3297 | ||||
3298 | // Lastly, extend the result. | |||
3299 | NewI->takeName(cast<Instruction>(I)); | |||
3300 | Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy); | |||
3301 | I->replaceAllUsesWith(Res); | |||
3302 | cast<Instruction>(I)->eraseFromParent(); | |||
3303 | Erased.insert(I); | |||
3304 | VectorLoopValueMap.resetVectorValue(KV.first, Part, Res); | |||
3305 | } | |||
3306 | } | |||
3307 | ||||
3308 | // We'll have created a bunch of ZExts that are now parentless. Clean up. | |||
3309 | for (const auto &KV : Cost->getMinimalBitwidths()) { | |||
3310 | // If the value wasn't vectorized, we must maintain the original scalar | |||
3311 | // type. The absence of the value from VectorLoopValueMap indicates that it | |||
3312 | // wasn't vectorized. | |||
3313 | if (!VectorLoopValueMap.hasAnyVectorValue(KV.first)) | |||
3314 | continue; | |||
3315 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3316 | Value *I = getOrCreateVectorValue(KV.first, Part); | |||
3317 | ZExtInst *Inst = dyn_cast<ZExtInst>(I); | |||
3318 | if (Inst && Inst->use_empty()) { | |||
3319 | Value *NewI = Inst->getOperand(0); | |||
3320 | Inst->eraseFromParent(); | |||
3321 | VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI); | |||
3322 | } | |||
3323 | } | |||
3324 | } | |||
3325 | } | |||
3326 | ||||
3327 | void InnerLoopVectorizer::fixVectorizedLoop() { | |||
3328 | // Insert truncates and extends for any truncated instructions as hints to | |||
3329 | // InstCombine. | |||
3330 | if (VF > 1) | |||
3331 | truncateToMinimalBitwidths(); | |||
3332 | ||||
3333 | // At this point every instruction in the original loop is widened to a | |||
3334 | // vector form. Now we need to fix the recurrences in the loop. These PHI | |||
3335 | // nodes are currently empty because we did not want to introduce cycles. | |||
3336 | // This is the second stage of vectorizing recurrences. | |||
3337 | fixCrossIterationPHIs(); | |||
3338 | ||||
3339 | // Update the dominator tree. | |||
3340 | // | |||
3341 | // FIXME: After creating the structure of the new loop, the dominator tree is | |||
3342 | // no longer up-to-date, and it remains that way until we update it | |||
3343 | // here. An out-of-date dominator tree is problematic for SCEV, | |||
3344 | // because SCEVExpander uses it to guide code generation. The | |||
3345 | // vectorizer use SCEVExpanders in several places. Instead, we should | |||
3346 | // keep the dominator tree up-to-date as we go. | |||
3347 | updateAnalysis(); | |||
3348 | ||||
3349 | // Fix-up external users of the induction variables. | |||
3350 | for (auto &Entry : *Legal->getInductionVars()) | |||
3351 | fixupIVUsers(Entry.first, Entry.second, | |||
3352 | getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)), | |||
3353 | IVEndValues[Entry.first], LoopMiddleBlock); | |||
3354 | ||||
3355 | fixLCSSAPHIs(); | |||
3356 | for (Instruction *PI : PredicatedInstructions) | |||
3357 | sinkScalarOperands(&*PI); | |||
3358 | ||||
3359 | // Remove redundant induction instructions. | |||
3360 | cse(LoopVectorBody); | |||
3361 | } | |||
3362 | ||||
3363 | void InnerLoopVectorizer::fixCrossIterationPHIs() { | |||
3364 | // In order to support recurrences we need to be able to vectorize Phi nodes. | |||
3365 | // Phi nodes have cycles, so we need to vectorize them in two stages. This is | |||
3366 | // stage #2: We now need to fix the recurrences by adding incoming edges to | |||
3367 | // the currently empty PHI nodes. At this point every instruction in the | |||
3368 | // original loop is widened to a vector form so we can use them to construct | |||
3369 | // the incoming edges. | |||
3370 | for (PHINode &Phi : OrigLoop->getHeader()->phis()) { | |||
3371 | // Handle first-order recurrences and reductions that need to be fixed. | |||
3372 | if (Legal->isFirstOrderRecurrence(&Phi)) | |||
3373 | fixFirstOrderRecurrence(&Phi); | |||
3374 | else if (Legal->isReductionVariable(&Phi)) | |||
3375 | fixReduction(&Phi); | |||
3376 | } | |||
3377 | } | |||
3378 | ||||
3379 | void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) { | |||
3380 | // This is the second phase of vectorizing first-order recurrences. An | |||
3381 | // overview of the transformation is described below. Suppose we have the | |||
3382 | // following loop. | |||
3383 | // | |||
3384 | // for (int i = 0; i < n; ++i) | |||
3385 | // b[i] = a[i] - a[i - 1]; | |||
3386 | // | |||
3387 | // There is a first-order recurrence on "a". For this loop, the shorthand | |||
3388 | // scalar IR looks like: | |||
3389 | // | |||
3390 | // scalar.ph: | |||
3391 | // s_init = a[-1] | |||
3392 | // br scalar.body | |||
3393 | // | |||
3394 | // scalar.body: | |||
3395 | // i = phi [0, scalar.ph], [i+1, scalar.body] | |||
3396 | // s1 = phi [s_init, scalar.ph], [s2, scalar.body] | |||
3397 | // s2 = a[i] | |||
3398 | // b[i] = s2 - s1 | |||
3399 | // br cond, scalar.body, ... | |||
3400 | // | |||
3401 | // In this example, s1 is a recurrence because it's value depends on the | |||
3402 | // previous iteration. In the first phase of vectorization, we created a | |||
3403 | // temporary value for s1. We now complete the vectorization and produce the | |||
3404 | // shorthand vector IR shown below (for VF = 4, UF = 1). | |||
3405 | // | |||
3406 | // vector.ph: | |||
3407 | // v_init = vector(..., ..., ..., a[-1]) | |||
3408 | // br vector.body | |||
3409 | // | |||
3410 | // vector.body | |||
3411 | // i = phi [0, vector.ph], [i+4, vector.body] | |||
3412 | // v1 = phi [v_init, vector.ph], [v2, vector.body] | |||
3413 | // v2 = a[i, i+1, i+2, i+3]; | |||
3414 | // v3 = vector(v1(3), v2(0, 1, 2)) | |||
3415 | // b[i, i+1, i+2, i+3] = v2 - v3 | |||
3416 | // br cond, vector.body, middle.block | |||
3417 | // | |||
3418 | // middle.block: | |||
3419 | // x = v2(3) | |||
3420 | // br scalar.ph | |||
3421 | // | |||
3422 | // scalar.ph: | |||
3423 | // s_init = phi [x, middle.block], [a[-1], otherwise] | |||
3424 | // br scalar.body | |||
3425 | // | |||
3426 | // After execution completes the vector loop, we extract the next value of | |||
3427 | // the recurrence (x) to use as the initial value in the scalar loop. | |||
3428 | ||||
3429 | // Get the original loop preheader and single loop latch. | |||
3430 | auto *Preheader = OrigLoop->getLoopPreheader(); | |||
3431 | auto *Latch = OrigLoop->getLoopLatch(); | |||
3432 | ||||
3433 | // Get the initial and previous values of the scalar recurrence. | |||
3434 | auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader); | |||
3435 | auto *Previous = Phi->getIncomingValueForBlock(Latch); | |||
3436 | ||||
3437 | // Create a vector from the initial value. | |||
3438 | auto *VectorInit = ScalarInit; | |||
3439 | if (VF > 1) { | |||
3440 | Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); | |||
3441 | VectorInit = Builder.CreateInsertElement( | |||
3442 | UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit, | |||
3443 | Builder.getInt32(VF - 1), "vector.recur.init"); | |||
3444 | } | |||
3445 | ||||
3446 | // We constructed a temporary phi node in the first phase of vectorization. | |||
3447 | // This phi node will eventually be deleted. | |||
3448 | Builder.SetInsertPoint( | |||
3449 | cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0))); | |||
3450 | ||||
3451 | // Create a phi node for the new recurrence. The current value will either be | |||
3452 | // the initial value inserted into a vector or loop-varying vector value. | |||
3453 | auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur"); | |||
3454 | VecPhi->addIncoming(VectorInit, LoopVectorPreHeader); | |||
3455 | ||||
3456 | // Get the vectorized previous value of the last part UF - 1. It appears last | |||
3457 | // among all unrolled iterations, due to the order of their construction. | |||
3458 | Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1); | |||
3459 | ||||
3460 | // Set the insertion point after the previous value if it is an instruction. | |||
3461 | // Note that the previous value may have been constant-folded so it is not | |||
3462 | // guaranteed to be an instruction in the vector loop. Also, if the previous | |||
3463 | // value is a phi node, we should insert after all the phi nodes to avoid | |||
3464 | // breaking basic block verification. | |||
3465 | if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) || | |||
3466 | isa<PHINode>(PreviousLastPart)) | |||
3467 | Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt()); | |||
3468 | else | |||
3469 | Builder.SetInsertPoint( | |||
3470 | &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart))); | |||
3471 | ||||
3472 | // We will construct a vector for the recurrence by combining the values for | |||
3473 | // the current and previous iterations. This is the required shuffle mask. | |||
3474 | SmallVector<Constant *, 8> ShuffleMask(VF); | |||
3475 | ShuffleMask[0] = Builder.getInt32(VF - 1); | |||
3476 | for (unsigned I = 1; I < VF; ++I) | |||
3477 | ShuffleMask[I] = Builder.getInt32(I + VF - 1); | |||
3478 | ||||
3479 | // The vector from which to take the initial value for the current iteration | |||
3480 | // (actual or unrolled). Initially, this is the vector phi node. | |||
3481 | Value *Incoming = VecPhi; | |||
3482 | ||||
3483 | // Shuffle the current and previous vector and update the vector parts. | |||
3484 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3485 | Value *PreviousPart = getOrCreateVectorValue(Previous, Part); | |||
3486 | Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part); | |||
3487 | auto *Shuffle = | |||
3488 | VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart, | |||
3489 | ConstantVector::get(ShuffleMask)) | |||
3490 | : Incoming; | |||
3491 | PhiPart->replaceAllUsesWith(Shuffle); | |||
3492 | cast<Instruction>(PhiPart)->eraseFromParent(); | |||
3493 | VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle); | |||
3494 | Incoming = PreviousPart; | |||
3495 | } | |||
3496 | ||||
3497 | // Fix the latch value of the new recurrence in the vector loop. | |||
3498 | VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch()); | |||
3499 | ||||
3500 | // Extract the last vector element in the middle block. This will be the | |||
3501 | // initial value for the recurrence when jumping to the scalar loop. | |||
3502 | auto *ExtractForScalar = Incoming; | |||
3503 | if (VF > 1) { | |||
3504 | Builder.SetInsertPoint(LoopMiddleBlock->getTerminator()); | |||
3505 | ExtractForScalar = Builder.CreateExtractElement( | |||
3506 | ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract"); | |||
3507 | } | |||
3508 | // Extract the second last element in the middle block if the | |||
3509 | // Phi is used outside the loop. We need to extract the phi itself | |||
3510 | // and not the last element (the phi update in the current iteration). This | |||
3511 | // will be the value when jumping to the exit block from the LoopMiddleBlock, | |||
3512 | // when the scalar loop is not run at all. | |||
3513 | Value *ExtractForPhiUsedOutsideLoop = nullptr; | |||
3514 | if (VF > 1) | |||
3515 | ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement( | |||
3516 | Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi"); | |||
3517 | // When loop is unrolled without vectorizing, initialize | |||
3518 | // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of | |||
3519 | // `Incoming`. This is analogous to the vectorized case above: extracting the | |||
3520 | // second last element when VF > 1. | |||
3521 | else if (UF > 1) | |||
3522 | ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2); | |||
3523 | ||||
3524 | // Fix the initial value of the original recurrence in the scalar loop. | |||
3525 | Builder.SetInsertPoint(&*LoopScalarPreHeader->begin()); | |||
3526 | auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init"); | |||
3527 | for (auto *BB : predecessors(LoopScalarPreHeader)) { | |||
3528 | auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit; | |||
3529 | Start->addIncoming(Incoming, BB); | |||
3530 | } | |||
3531 | ||||
3532 | Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start); | |||
3533 | Phi->setName("scalar.recur"); | |||
3534 | ||||
3535 | // Finally, fix users of the recurrence outside the loop. The users will need | |||
3536 | // either the last value of the scalar recurrence or the last value of the | |||
3537 | // vector recurrence we extracted in the middle block. Since the loop is in | |||
3538 | // LCSSA form, we just need to find all the phi nodes for the original scalar | |||
3539 | // recurrence in the exit block, and then add an edge for the middle block. | |||
3540 | for (PHINode &LCSSAPhi : LoopExitBlock->phis()) { | |||
3541 | if (LCSSAPhi.getIncomingValue(0) == Phi) { | |||
3542 | LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock); | |||
3543 | } | |||
3544 | } | |||
3545 | } | |||
3546 | ||||
3547 | void InnerLoopVectorizer::fixReduction(PHINode *Phi) { | |||
3548 | Constant *Zero = Builder.getInt32(0); | |||
3549 | ||||
3550 | // Get it's reduction variable descriptor. | |||
3551 | assert(Legal->isReductionVariable(Phi) &&(static_cast <bool> (Legal->isReductionVariable(Phi) && "Unable to find the reduction variable") ? void ( 0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3552, __extension__ __PRETTY_FUNCTION__)) | |||
3552 | "Unable to find the reduction variable")(static_cast <bool> (Legal->isReductionVariable(Phi) && "Unable to find the reduction variable") ? void ( 0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3552, __extension__ __PRETTY_FUNCTION__)); | |||
3553 | RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi]; | |||
3554 | ||||
3555 | RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind(); | |||
3556 | TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue(); | |||
3557 | Instruction *LoopExitInst = RdxDesc.getLoopExitInstr(); | |||
3558 | RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind = | |||
3559 | RdxDesc.getMinMaxRecurrenceKind(); | |||
3560 | setDebugLocFromInst(Builder, ReductionStartValue); | |||
3561 | ||||
3562 | // We need to generate a reduction vector from the incoming scalar. | |||
3563 | // To do so, we need to generate the 'identity' vector and override | |||
3564 | // one of the elements with the incoming scalar reduction. We need | |||
3565 | // to do it in the vector-loop preheader. | |||
3566 | Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); | |||
3567 | ||||
3568 | // This is the vector-clone of the value that leaves the loop. | |||
3569 | Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType(); | |||
3570 | ||||
3571 | // Find the reduction identity variable. Zero for addition, or, xor, | |||
3572 | // one for multiplication, -1 for And. | |||
3573 | Value *Identity; | |||
3574 | Value *VectorStart; | |||
3575 | if (RK == RecurrenceDescriptor::RK_IntegerMinMax || | |||
3576 | RK == RecurrenceDescriptor::RK_FloatMinMax) { | |||
3577 | // MinMax reduction have the start value as their identify. | |||
3578 | if (VF == 1) { | |||
3579 | VectorStart = Identity = ReductionStartValue; | |||
3580 | } else { | |||
3581 | VectorStart = Identity = | |||
3582 | Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident"); | |||
3583 | } | |||
3584 | } else { | |||
3585 | // Handle other reduction kinds: | |||
3586 | Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity( | |||
3587 | RK, VecTy->getScalarType()); | |||
3588 | if (VF == 1) { | |||
3589 | Identity = Iden; | |||
3590 | // This vector is the Identity vector where the first element is the | |||
3591 | // incoming scalar reduction. | |||
3592 | VectorStart = ReductionStartValue; | |||
3593 | } else { | |||
3594 | Identity = ConstantVector::getSplat(VF, Iden); | |||
3595 | ||||
3596 | // This vector is the Identity vector where the first element is the | |||
3597 | // incoming scalar reduction. | |||
3598 | VectorStart = | |||
3599 | Builder.CreateInsertElement(Identity, ReductionStartValue, Zero); | |||
3600 | } | |||
3601 | } | |||
3602 | ||||
3603 | // Fix the vector-loop phi. | |||
3604 | ||||
3605 | // Reductions do not have to start at zero. They can start with | |||
3606 | // any loop invariant values. | |||
3607 | BasicBlock *Latch = OrigLoop->getLoopLatch(); | |||
3608 | Value *LoopVal = Phi->getIncomingValueForBlock(Latch); | |||
3609 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3610 | Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part); | |||
3611 | Value *Val = getOrCreateVectorValue(LoopVal, Part); | |||
3612 | // Make sure to add the reduction stat value only to the | |||
3613 | // first unroll part. | |||
3614 | Value *StartVal = (Part == 0) ? VectorStart : Identity; | |||
3615 | cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader); | |||
3616 | cast<PHINode>(VecRdxPhi) | |||
3617 | ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch()); | |||
3618 | } | |||
3619 | ||||
3620 | // Before each round, move the insertion point right between | |||
3621 | // the PHIs and the values we are going to write. | |||
3622 | // This allows us to write both PHINodes and the extractelement | |||
3623 | // instructions. | |||
3624 | Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); | |||
3625 | ||||
3626 | setDebugLocFromInst(Builder, LoopExitInst); | |||
3627 | ||||
3628 | // If the vector reduction can be performed in a smaller type, we truncate | |||
3629 | // then extend the loop exit value to enable InstCombine to evaluate the | |||
3630 | // entire expression in the smaller type. | |||
3631 | if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) { | |||
3632 | Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF); | |||
3633 | Builder.SetInsertPoint( | |||
3634 | LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator()); | |||
3635 | VectorParts RdxParts(UF); | |||
3636 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3637 | RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part); | |||
3638 | Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy); | |||
3639 | Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy) | |||
3640 | : Builder.CreateZExt(Trunc, VecTy); | |||
3641 | for (Value::user_iterator UI = RdxParts[Part]->user_begin(); | |||
3642 | UI != RdxParts[Part]->user_end();) | |||
3643 | if (*UI != Trunc) { | |||
3644 | (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd); | |||
3645 | RdxParts[Part] = Extnd; | |||
3646 | } else { | |||
3647 | ++UI; | |||
3648 | } | |||
3649 | } | |||
3650 | Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); | |||
3651 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3652 | RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy); | |||
3653 | VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]); | |||
3654 | } | |||
3655 | } | |||
3656 | ||||
3657 | // Reduce all of the unrolled parts into a single vector. | |||
3658 | Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0); | |||
3659 | unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK); | |||
3660 | setDebugLocFromInst(Builder, ReducedPartRdx); | |||
3661 | for (unsigned Part = 1; Part < UF; ++Part) { | |||
3662 | Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part); | |||
3663 | if (Op != Instruction::ICmp && Op != Instruction::FCmp) | |||
3664 | // Floating point operations had to be 'fast' to enable the reduction. | |||
3665 | ReducedPartRdx = addFastMathFlag( | |||
3666 | Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart, | |||
3667 | ReducedPartRdx, "bin.rdx")); | |||
3668 | else | |||
3669 | ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp( | |||
3670 | Builder, MinMaxKind, ReducedPartRdx, RdxPart); | |||
3671 | } | |||
3672 | ||||
3673 | if (VF > 1) { | |||
3674 | bool NoNaN = Legal->hasFunNoNaNAttr(); | |||
3675 | ReducedPartRdx = | |||
3676 | createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN); | |||
3677 | // If the reduction can be performed in a smaller type, we need to extend | |||
3678 | // the reduction to the wider type before we branch to the original loop. | |||
3679 | if (Phi->getType() != RdxDesc.getRecurrenceType()) | |||
3680 | ReducedPartRdx = | |||
3681 | RdxDesc.isSigned() | |||
3682 | ? Builder.CreateSExt(ReducedPartRdx, Phi->getType()) | |||
3683 | : Builder.CreateZExt(ReducedPartRdx, Phi->getType()); | |||
3684 | } | |||
3685 | ||||
3686 | // Create a phi node that merges control-flow from the backedge-taken check | |||
3687 | // block and the middle block. | |||
3688 | PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx", | |||
3689 | LoopScalarPreHeader->getTerminator()); | |||
3690 | for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) | |||
3691 | BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]); | |||
3692 | BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); | |||
3693 | ||||
3694 | // Now, we need to fix the users of the reduction variable | |||
3695 | // inside and outside of the scalar remainder loop. | |||
3696 | // We know that the loop is in LCSSA form. We need to update the | |||
3697 | // PHI nodes in the exit blocks. | |||
3698 | for (PHINode &LCSSAPhi : LoopExitBlock->phis()) { | |||
3699 | // All PHINodes need to have a single entry edge, or two if | |||
3700 | // we already fixed them. | |||
3701 | assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI")(static_cast <bool> (LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI") ? void (0) : __assert_fail ("LCSSAPhi.getNumIncomingValues() < 3 && \"Invalid LCSSA PHI\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3701, __extension__ __PRETTY_FUNCTION__)); | |||
3702 | ||||
3703 | // We found a reduction value exit-PHI. Update it with the | |||
3704 | // incoming bypass edge. | |||
3705 | if (LCSSAPhi.getIncomingValue(0) == LoopExitInst) | |||
3706 | LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock); | |||
3707 | } // end of the LCSSA phi scan. | |||
3708 | ||||
3709 | // Fix the scalar loop reduction variable with the incoming reduction sum | |||
3710 | // from the vector body and from the backedge value. | |||
3711 | int IncomingEdgeBlockIdx = | |||
3712 | Phi->getBasicBlockIndex(OrigLoop->getLoopLatch()); | |||
3713 | assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index")(static_cast <bool> (IncomingEdgeBlockIdx >= 0 && "Invalid block index") ? void (0) : __assert_fail ("IncomingEdgeBlockIdx >= 0 && \"Invalid block index\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3713, __extension__ __PRETTY_FUNCTION__)); | |||
3714 | // Pick the other block. | |||
3715 | int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); | |||
3716 | Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi); | |||
3717 | Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst); | |||
3718 | } | |||
3719 | ||||
3720 | void InnerLoopVectorizer::fixLCSSAPHIs() { | |||
3721 | for (PHINode &LCSSAPhi : LoopExitBlock->phis()) { | |||
3722 | if (LCSSAPhi.getNumIncomingValues() == 1) { | |||
3723 | assert(OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) &&(static_cast <bool> (OrigLoop->isLoopInvariant(LCSSAPhi .getIncomingValue(0)) && "Incoming value isn't loop invariant" ) ? void (0) : __assert_fail ("OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) && \"Incoming value isn't loop invariant\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3724, __extension__ __PRETTY_FUNCTION__)) | |||
3724 | "Incoming value isn't loop invariant")(static_cast <bool> (OrigLoop->isLoopInvariant(LCSSAPhi .getIncomingValue(0)) && "Incoming value isn't loop invariant" ) ? void (0) : __assert_fail ("OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) && \"Incoming value isn't loop invariant\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3724, __extension__ __PRETTY_FUNCTION__)); | |||
3725 | LCSSAPhi.addIncoming(LCSSAPhi.getIncomingValue(0), LoopMiddleBlock); | |||
3726 | } | |||
3727 | } | |||
3728 | } | |||
3729 | ||||
3730 | void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) { | |||
3731 | // The basic block and loop containing the predicated instruction. | |||
3732 | auto *PredBB = PredInst->getParent(); | |||
3733 | auto *VectorLoop = LI->getLoopFor(PredBB); | |||
3734 | ||||
3735 | // Initialize a worklist with the operands of the predicated instruction. | |||
3736 | SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end()); | |||
3737 | ||||
3738 | // Holds instructions that we need to analyze again. An instruction may be | |||
3739 | // reanalyzed if we don't yet know if we can sink it or not. | |||
3740 | SmallVector<Instruction *, 8> InstsToReanalyze; | |||
3741 | ||||
3742 | // Returns true if a given use occurs in the predicated block. Phi nodes use | |||
3743 | // their operands in their corresponding predecessor blocks. | |||
3744 | auto isBlockOfUsePredicated = [&](Use &U) -> bool { | |||
3745 | auto *I = cast<Instruction>(U.getUser()); | |||
3746 | BasicBlock *BB = I->getParent(); | |||
3747 | if (auto *Phi = dyn_cast<PHINode>(I)) | |||
3748 | BB = Phi->getIncomingBlock( | |||
3749 | PHINode::getIncomingValueNumForOperand(U.getOperandNo())); | |||
3750 | return BB == PredBB; | |||
3751 | }; | |||
3752 | ||||
3753 | // Iteratively sink the scalarized operands of the predicated instruction | |||
3754 | // into the block we created for it. When an instruction is sunk, it's | |||
3755 | // operands are then added to the worklist. The algorithm ends after one pass | |||
3756 | // through the worklist doesn't sink a single instruction. | |||
3757 | bool Changed; | |||
3758 | do { | |||
3759 | // Add the instructions that need to be reanalyzed to the worklist, and | |||
3760 | // reset the changed indicator. | |||
3761 | Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end()); | |||
3762 | InstsToReanalyze.clear(); | |||
3763 | Changed = false; | |||
3764 | ||||
3765 | while (!Worklist.empty()) { | |||
3766 | auto *I = dyn_cast<Instruction>(Worklist.pop_back_val()); | |||
3767 | ||||
3768 | // We can't sink an instruction if it is a phi node, is already in the | |||
3769 | // predicated block, is not in the loop, or may have side effects. | |||
3770 | if (!I || isa<PHINode>(I) || I->getParent() == PredBB || | |||
3771 | !VectorLoop->contains(I) || I->mayHaveSideEffects()) | |||
3772 | continue; | |||
3773 | ||||
3774 | // It's legal to sink the instruction if all its uses occur in the | |||
3775 | // predicated block. Otherwise, there's nothing to do yet, and we may | |||
3776 | // need to reanalyze the instruction. | |||
3777 | if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) { | |||
3778 | InstsToReanalyze.push_back(I); | |||
3779 | continue; | |||
3780 | } | |||
3781 | ||||
3782 | // Move the instruction to the beginning of the predicated block, and add | |||
3783 | // it's operands to the worklist. | |||
3784 | I->moveBefore(&*PredBB->getFirstInsertionPt()); | |||
3785 | Worklist.insert(I->op_begin(), I->op_end()); | |||
3786 | ||||
3787 | // The sinking may have enabled other instructions to be sunk, so we will | |||
3788 | // need to iterate. | |||
3789 | Changed = true; | |||
3790 | } | |||
3791 | } while (Changed); | |||
3792 | } | |||
3793 | ||||
3794 | void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF, | |||
3795 | unsigned VF) { | |||
3796 | assert(PN->getParent() == OrigLoop->getHeader() &&(static_cast <bool> (PN->getParent() == OrigLoop-> getHeader() && "Non-header phis should have been handled elsewhere" ) ? void (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3797, __extension__ __PRETTY_FUNCTION__)) | |||
3797 | "Non-header phis should have been handled elsewhere")(static_cast <bool> (PN->getParent() == OrigLoop-> getHeader() && "Non-header phis should have been handled elsewhere" ) ? void (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3797, __extension__ __PRETTY_FUNCTION__)); | |||
3798 | ||||
3799 | PHINode *P = cast<PHINode>(PN); | |||
3800 | // In order to support recurrences we need to be able to vectorize Phi nodes. | |||
3801 | // Phi nodes have cycles, so we need to vectorize them in two stages. This is | |||
3802 | // stage #1: We create a new vector PHI node with no incoming edges. We'll use | |||
3803 | // this value when we vectorize all of the instructions that use the PHI. | |||
3804 | if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) { | |||
3805 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3806 | // This is phase one of vectorizing PHIs. | |||
3807 | Type *VecTy = | |||
3808 | (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF); | |||
3809 | Value *EntryPart = PHINode::Create( | |||
3810 | VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt()); | |||
3811 | VectorLoopValueMap.setVectorValue(P, Part, EntryPart); | |||
3812 | } | |||
3813 | return; | |||
3814 | } | |||
3815 | ||||
3816 | setDebugLocFromInst(Builder, P); | |||
3817 | ||||
3818 | // This PHINode must be an induction variable. | |||
3819 | // Make sure that we know about it. | |||
3820 | assert(Legal->getInductionVars()->count(P) && "Not an induction variable")(static_cast <bool> (Legal->getInductionVars()->count (P) && "Not an induction variable") ? void (0) : __assert_fail ("Legal->getInductionVars()->count(P) && \"Not an induction variable\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3820, __extension__ __PRETTY_FUNCTION__)); | |||
3821 | ||||
3822 | InductionDescriptor II = Legal->getInductionVars()->lookup(P); | |||
3823 | const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); | |||
3824 | ||||
3825 | // FIXME: The newly created binary instructions should contain nsw/nuw flags, | |||
3826 | // which can be found from the original scalar operations. | |||
3827 | switch (II.getKind()) { | |||
3828 | case InductionDescriptor::IK_NoInduction: | |||
3829 | llvm_unreachable("Unknown induction")::llvm::llvm_unreachable_internal("Unknown induction", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3829); | |||
3830 | case InductionDescriptor::IK_IntInduction: | |||
3831 | case InductionDescriptor::IK_FpInduction: | |||
3832 | llvm_unreachable("Integer/fp induction is handled elsewhere.")::llvm::llvm_unreachable_internal("Integer/fp induction is handled elsewhere." , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3832); | |||
3833 | case InductionDescriptor::IK_PtrInduction: { | |||
3834 | // Handle the pointer induction variable case. | |||
3835 | assert(P->getType()->isPointerTy() && "Unexpected type.")(static_cast <bool> (P->getType()->isPointerTy() && "Unexpected type.") ? void (0) : __assert_fail ("P->getType()->isPointerTy() && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3835, __extension__ __PRETTY_FUNCTION__)); | |||
3836 | // This is the normalized GEP that starts counting at zero. | |||
3837 | Value *PtrInd = Induction; | |||
3838 | PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType()); | |||
3839 | // Determine the number of scalars we need to generate for each unroll | |||
3840 | // iteration. If the instruction is uniform, we only need to generate the | |||
3841 | // first lane. Otherwise, we generate all VF values. | |||
3842 | unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF; | |||
3843 | // These are the scalar results. Notice that we don't generate vector GEPs | |||
3844 | // because scalar GEPs result in better code. | |||
3845 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3846 | for (unsigned Lane = 0; Lane < Lanes; ++Lane) { | |||
3847 | Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF); | |||
3848 | Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx); | |||
3849 | Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL); | |||
3850 | SclrGep->setName("next.gep"); | |||
3851 | VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep); | |||
3852 | } | |||
3853 | } | |||
3854 | return; | |||
3855 | } | |||
3856 | } | |||
3857 | } | |||
3858 | ||||
3859 | /// A helper function for checking whether an integer division-related | |||
3860 | /// instruction may divide by zero (in which case it must be predicated if | |||
3861 | /// executed conditionally in the scalar code). | |||
3862 | /// TODO: It may be worthwhile to generalize and check isKnownNonZero(). | |||
3863 | /// Non-zero divisors that are non compile-time constants will not be | |||
3864 | /// converted into multiplication, so we will still end up scalarizing | |||
3865 | /// the division, but can do so w/o predication. | |||
3866 | static bool mayDivideByZero(Instruction &I) { | |||
3867 | assert((I.getOpcode() == Instruction::UDiv ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction ::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction" ) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3871, __extension__ __PRETTY_FUNCTION__)) | |||
3868 | I.getOpcode() == Instruction::SDiv ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction ::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction" ) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3871, __extension__ __PRETTY_FUNCTION__)) | |||
3869 | I.getOpcode() == Instruction::URem ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction ::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction" ) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3871, __extension__ __PRETTY_FUNCTION__)) | |||
3870 | I.getOpcode() == Instruction::SRem) &&(static_cast <bool> ((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction ::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction" ) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3871, __extension__ __PRETTY_FUNCTION__)) | |||
3871 | "Unexpected instruction")(static_cast <bool> ((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction ::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction" ) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3871, __extension__ __PRETTY_FUNCTION__)); | |||
3872 | Value *Divisor = I.getOperand(1); | |||
3873 | auto *CInt = dyn_cast<ConstantInt>(Divisor); | |||
3874 | return !CInt || CInt->isZero(); | |||
3875 | } | |||
3876 | ||||
3877 | void InnerLoopVectorizer::widenInstruction(Instruction &I) { | |||
3878 | switch (I.getOpcode()) { | |||
3879 | case Instruction::Br: | |||
3880 | case Instruction::PHI: | |||
3881 | llvm_unreachable("This instruction is handled by a different recipe.")::llvm::llvm_unreachable_internal("This instruction is handled by a different recipe." , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3881); | |||
3882 | case Instruction::GetElementPtr: { | |||
3883 | // Construct a vector GEP by widening the operands of the scalar GEP as | |||
3884 | // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP | |||
3885 | // results in a vector of pointers when at least one operand of the GEP | |||
3886 | // is vector-typed. Thus, to keep the representation compact, we only use | |||
3887 | // vector-typed operands for loop-varying values. | |||
3888 | auto *GEP = cast<GetElementPtrInst>(&I); | |||
3889 | ||||
3890 | if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) { | |||
3891 | // If we are vectorizing, but the GEP has only loop-invariant operands, | |||
3892 | // the GEP we build (by only using vector-typed operands for | |||
3893 | // loop-varying values) would be a scalar pointer. Thus, to ensure we | |||
3894 | // produce a vector of pointers, we need to either arbitrarily pick an | |||
3895 | // operand to broadcast, or broadcast a clone of the original GEP. | |||
3896 | // Here, we broadcast a clone of the original. | |||
3897 | // | |||
3898 | // TODO: If at some point we decide to scalarize instructions having | |||
3899 | // loop-invariant operands, this special case will no longer be | |||
3900 | // required. We would add the scalarization decision to | |||
3901 | // collectLoopScalars() and teach getVectorValue() to broadcast | |||
3902 | // the lane-zero scalar value. | |||
3903 | auto *Clone = Builder.Insert(GEP->clone()); | |||
3904 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3905 | Value *EntryPart = Builder.CreateVectorSplat(VF, Clone); | |||
3906 | VectorLoopValueMap.setVectorValue(&I, Part, EntryPart); | |||
3907 | addMetadata(EntryPart, GEP); | |||
3908 | } | |||
3909 | } else { | |||
3910 | // If the GEP has at least one loop-varying operand, we are sure to | |||
3911 | // produce a vector of pointers. But if we are only unrolling, we want | |||
3912 | // to produce a scalar GEP for each unroll part. Thus, the GEP we | |||
3913 | // produce with the code below will be scalar (if VF == 1) or vector | |||
3914 | // (otherwise). Note that for the unroll-only case, we still maintain | |||
3915 | // values in the vector mapping with initVector, as we do for other | |||
3916 | // instructions. | |||
3917 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3918 | // The pointer operand of the new GEP. If it's loop-invariant, we | |||
3919 | // won't broadcast it. | |||
3920 | auto *Ptr = | |||
3921 | OrigLoop->isLoopInvariant(GEP->getPointerOperand()) | |||
3922 | ? GEP->getPointerOperand() | |||
3923 | : getOrCreateVectorValue(GEP->getPointerOperand(), Part); | |||
3924 | ||||
3925 | // Collect all the indices for the new GEP. If any index is | |||
3926 | // loop-invariant, we won't broadcast it. | |||
3927 | SmallVector<Value *, 4> Indices; | |||
3928 | for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) { | |||
3929 | if (OrigLoop->isLoopInvariant(U.get())) | |||
3930 | Indices.push_back(U.get()); | |||
3931 | else | |||
3932 | Indices.push_back(getOrCreateVectorValue(U.get(), Part)); | |||
3933 | } | |||
3934 | ||||
3935 | // Create the new GEP. Note that this GEP may be a scalar if VF == 1, | |||
3936 | // but it should be a vector, otherwise. | |||
3937 | auto *NewGEP = GEP->isInBounds() | |||
3938 | ? Builder.CreateInBoundsGEP(Ptr, Indices) | |||
3939 | : Builder.CreateGEP(Ptr, Indices); | |||
3940 | assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&(static_cast <bool> ((VF == 1 || NewGEP->getType()-> isVectorTy()) && "NewGEP is not a pointer vector") ? void (0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3941, __extension__ __PRETTY_FUNCTION__)) | |||
3941 | "NewGEP is not a pointer vector")(static_cast <bool> ((VF == 1 || NewGEP->getType()-> isVectorTy()) && "NewGEP is not a pointer vector") ? void (0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 3941, __extension__ __PRETTY_FUNCTION__)); | |||
3942 | VectorLoopValueMap.setVectorValue(&I, Part, NewGEP); | |||
3943 | addMetadata(NewGEP, GEP); | |||
3944 | } | |||
3945 | } | |||
3946 | ||||
3947 | break; | |||
3948 | } | |||
3949 | case Instruction::UDiv: | |||
3950 | case Instruction::SDiv: | |||
3951 | case Instruction::SRem: | |||
3952 | case Instruction::URem: | |||
3953 | case Instruction::Add: | |||
3954 | case Instruction::FAdd: | |||
3955 | case Instruction::Sub: | |||
3956 | case Instruction::FSub: | |||
3957 | case Instruction::Mul: | |||
3958 | case Instruction::FMul: | |||
3959 | case Instruction::FDiv: | |||
3960 | case Instruction::FRem: | |||
3961 | case Instruction::Shl: | |||
3962 | case Instruction::LShr: | |||
3963 | case Instruction::AShr: | |||
3964 | case Instruction::And: | |||
3965 | case Instruction::Or: | |||
3966 | case Instruction::Xor: { | |||
3967 | // Just widen binops. | |||
3968 | auto *BinOp = cast<BinaryOperator>(&I); | |||
3969 | setDebugLocFromInst(Builder, BinOp); | |||
3970 | ||||
3971 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
3972 | Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part); | |||
3973 | Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part); | |||
3974 | Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B); | |||
3975 | ||||
3976 | if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V)) | |||
3977 | VecOp->copyIRFlags(BinOp); | |||
3978 | ||||
3979 | // Use this vector value for all users of the original instruction. | |||
3980 | VectorLoopValueMap.setVectorValue(&I, Part, V); | |||
3981 | addMetadata(V, BinOp); | |||
3982 | } | |||
3983 | ||||
3984 | break; | |||
3985 | } | |||
3986 | case Instruction::Select: { | |||
3987 | // Widen selects. | |||
3988 | // If the selector is loop invariant we can create a select | |||
3989 | // instruction with a scalar condition. Otherwise, use vector-select. | |||
3990 | auto *SE = PSE.getSE(); | |||
3991 | bool InvariantCond = | |||
3992 | SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop); | |||
3993 | setDebugLocFromInst(Builder, &I); | |||
3994 | ||||
3995 | // The condition can be loop invariant but still defined inside the | |||
3996 | // loop. This means that we can't just use the original 'cond' value. | |||
3997 | // We have to take the 'vectorized' value and pick the first lane. | |||
3998 | // Instcombine will make this a no-op. | |||
3999 | ||||
4000 | auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0}); | |||
4001 | ||||
4002 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
4003 | Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part); | |||
4004 | Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part); | |||
4005 | Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part); | |||
4006 | Value *Sel = | |||
4007 | Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1); | |||
4008 | VectorLoopValueMap.setVectorValue(&I, Part, Sel); | |||
4009 | addMetadata(Sel, &I); | |||
4010 | } | |||
4011 | ||||
4012 | break; | |||
4013 | } | |||
4014 | ||||
4015 | case Instruction::ICmp: | |||
4016 | case Instruction::FCmp: { | |||
4017 | // Widen compares. Generate vector compares. | |||
4018 | bool FCmp = (I.getOpcode() == Instruction::FCmp); | |||
4019 | auto *Cmp = dyn_cast<CmpInst>(&I); | |||
4020 | setDebugLocFromInst(Builder, Cmp); | |||
4021 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
4022 | Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part); | |||
4023 | Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part); | |||
4024 | Value *C = nullptr; | |||
4025 | if (FCmp) { | |||
4026 | // Propagate fast math flags. | |||
4027 | IRBuilder<>::FastMathFlagGuard FMFG(Builder); | |||
4028 | Builder.setFastMathFlags(Cmp->getFastMathFlags()); | |||
4029 | C = Builder.CreateFCmp(Cmp->getPredicate(), A, B); | |||
4030 | } else { | |||
4031 | C = Builder.CreateICmp(Cmp->getPredicate(), A, B); | |||
4032 | } | |||
4033 | VectorLoopValueMap.setVectorValue(&I, Part, C); | |||
4034 | addMetadata(C, &I); | |||
4035 | } | |||
4036 | ||||
4037 | break; | |||
4038 | } | |||
4039 | ||||
4040 | case Instruction::ZExt: | |||
4041 | case Instruction::SExt: | |||
4042 | case Instruction::FPToUI: | |||
4043 | case Instruction::FPToSI: | |||
4044 | case Instruction::FPExt: | |||
4045 | case Instruction::PtrToInt: | |||
4046 | case Instruction::IntToPtr: | |||
4047 | case Instruction::SIToFP: | |||
4048 | case Instruction::UIToFP: | |||
4049 | case Instruction::Trunc: | |||
4050 | case Instruction::FPTrunc: | |||
4051 | case Instruction::BitCast: { | |||
4052 | auto *CI = dyn_cast<CastInst>(&I); | |||
4053 | setDebugLocFromInst(Builder, CI); | |||
4054 | ||||
4055 | /// Vectorize casts. | |||
4056 | Type *DestTy = | |||
4057 | (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF); | |||
4058 | ||||
4059 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
4060 | Value *A = getOrCreateVectorValue(CI->getOperand(0), Part); | |||
4061 | Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy); | |||
4062 | VectorLoopValueMap.setVectorValue(&I, Part, Cast); | |||
4063 | addMetadata(Cast, &I); | |||
4064 | } | |||
4065 | break; | |||
4066 | } | |||
4067 | ||||
4068 | case Instruction::Call: { | |||
4069 | // Ignore dbg intrinsics. | |||
4070 | if (isa<DbgInfoIntrinsic>(I)) | |||
4071 | break; | |||
4072 | setDebugLocFromInst(Builder, &I); | |||
4073 | ||||
4074 | Module *M = I.getParent()->getParent()->getParent(); | |||
4075 | auto *CI = cast<CallInst>(&I); | |||
4076 | ||||
4077 | StringRef FnName = CI->getCalledFunction()->getName(); | |||
4078 | Function *F = CI->getCalledFunction(); | |||
4079 | Type *RetTy = ToVectorTy(CI->getType(), VF); | |||
4080 | SmallVector<Type *, 4> Tys; | |||
4081 | for (Value *ArgOperand : CI->arg_operands()) | |||
4082 | Tys.push_back(ToVectorTy(ArgOperand->getType(), VF)); | |||
4083 | ||||
4084 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
4085 | ||||
4086 | // The flag shows whether we use Intrinsic or a usual Call for vectorized | |||
4087 | // version of the instruction. | |||
4088 | // Is it beneficial to perform intrinsic call compared to lib call? | |||
4089 | bool NeedToScalarize; | |||
4090 | unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize); | |||
4091 | bool UseVectorIntrinsic = | |||
4092 | ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost; | |||
4093 | assert((UseVectorIntrinsic || !NeedToScalarize) &&(static_cast <bool> ((UseVectorIntrinsic || !NeedToScalarize ) && "Instruction should be scalarized elsewhere.") ? void (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4094, __extension__ __PRETTY_FUNCTION__)) | |||
4094 | "Instruction should be scalarized elsewhere.")(static_cast <bool> ((UseVectorIntrinsic || !NeedToScalarize ) && "Instruction should be scalarized elsewhere.") ? void (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4094, __extension__ __PRETTY_FUNCTION__)); | |||
4095 | ||||
4096 | for (unsigned Part = 0; Part < UF; ++Part) { | |||
4097 | SmallVector<Value *, 4> Args; | |||
4098 | for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) { | |||
4099 | Value *Arg = CI->getArgOperand(i); | |||
4100 | // Some intrinsics have a scalar argument - don't replace it with a | |||
4101 | // vector. | |||
4102 | if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) | |||
4103 | Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part); | |||
4104 | Args.push_back(Arg); | |||
4105 | } | |||
4106 | ||||
4107 | Function *VectorF; | |||
4108 | if (UseVectorIntrinsic) { | |||
4109 | // Use vector version of the intrinsic. | |||
4110 | Type *TysForDecl[] = {CI->getType()}; | |||
4111 | if (VF > 1) | |||
4112 | TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF); | |||
4113 | VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl); | |||
4114 | } else { | |||
4115 | // Use vector version of the library call. | |||
4116 | StringRef VFnName = TLI->getVectorizedFunction(FnName, VF); | |||
4117 | assert(!VFnName.empty() && "Vector function name is empty.")(static_cast <bool> (!VFnName.empty() && "Vector function name is empty." ) ? void (0) : __assert_fail ("!VFnName.empty() && \"Vector function name is empty.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4117, __extension__ __PRETTY_FUNCTION__)); | |||
4118 | VectorF = M->getFunction(VFnName); | |||
4119 | if (!VectorF) { | |||
4120 | // Generate a declaration | |||
4121 | FunctionType *FTy = FunctionType::get(RetTy, Tys, false); | |||
4122 | VectorF = | |||
4123 | Function::Create(FTy, Function::ExternalLinkage, VFnName, M); | |||
4124 | VectorF->copyAttributesFrom(F); | |||
4125 | } | |||
4126 | } | |||
4127 | assert(VectorF && "Can't create vector function.")(static_cast <bool> (VectorF && "Can't create vector function." ) ? void (0) : __assert_fail ("VectorF && \"Can't create vector function.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4127, __extension__ __PRETTY_FUNCTION__)); | |||
4128 | ||||
4129 | SmallVector<OperandBundleDef, 1> OpBundles; | |||
4130 | CI->getOperandBundlesAsDefs(OpBundles); | |||
4131 | CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles); | |||
4132 | ||||
4133 | if (isa<FPMathOperator>(V)) | |||
4134 | V->copyFastMathFlags(CI); | |||
4135 | ||||
4136 | VectorLoopValueMap.setVectorValue(&I, Part, V); | |||
4137 | addMetadata(V, &I); | |||
4138 | } | |||
4139 | ||||
4140 | break; | |||
4141 | } | |||
4142 | ||||
4143 | default: | |||
4144 | // This instruction is not vectorized by simple widening. | |||
4145 | LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found an unhandled instruction: " << I; } } while (false); | |||
4146 | llvm_unreachable("Unhandled instruction!")::llvm::llvm_unreachable_internal("Unhandled instruction!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4146); | |||
4147 | } // end of switch. | |||
4148 | } | |||
4149 | ||||
4150 | void InnerLoopVectorizer::updateAnalysis() { | |||
4151 | // Forget the original basic block. | |||
4152 | PSE.getSE()->forgetLoop(OrigLoop); | |||
4153 | ||||
4154 | // Update the dominator tree information. | |||
4155 | assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&(static_cast <bool> (DT->properlyDominates(LoopBypassBlocks .front(), LoopExitBlock) && "Entry does not dominate exit." ) ? void (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4156, __extension__ __PRETTY_FUNCTION__)) | |||
4156 | "Entry does not dominate exit.")(static_cast <bool> (DT->properlyDominates(LoopBypassBlocks .front(), LoopExitBlock) && "Entry does not dominate exit." ) ? void (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4156, __extension__ __PRETTY_FUNCTION__)); | |||
4157 | ||||
4158 | DT->addNewBlock(LoopMiddleBlock, | |||
4159 | LI->getLoopFor(LoopVectorBody)->getLoopLatch()); | |||
4160 | DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]); | |||
4161 | DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); | |||
4162 | DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]); | |||
4163 | assert(DT->verify(DominatorTree::VerificationLevel::Fast))(static_cast <bool> (DT->verify(DominatorTree::VerificationLevel ::Fast)) ? void (0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast)" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4163, __extension__ __PRETTY_FUNCTION__)); | |||
4164 | } | |||
4165 | ||||
4166 | void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) { | |||
4167 | // We should not collect Scalars more than once per VF. Right now, this | |||
4168 | // function is called from collectUniformsAndScalars(), which already does | |||
4169 | // this check. Collecting Scalars for VF=1 does not make any sense. | |||
4170 | assert(VF >= 2 && !Scalars.count(VF) &&(static_cast <bool> (VF >= 2 && !Scalars.count (VF) && "This function should not be visited twice for the same VF" ) ? void (0) : __assert_fail ("VF >= 2 && !Scalars.count(VF) && \"This function should not be visited twice for the same VF\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4171, __extension__ __PRETTY_FUNCTION__)) | |||
4171 | "This function should not be visited twice for the same VF")(static_cast <bool> (VF >= 2 && !Scalars.count (VF) && "This function should not be visited twice for the same VF" ) ? void (0) : __assert_fail ("VF >= 2 && !Scalars.count(VF) && \"This function should not be visited twice for the same VF\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4171, __extension__ __PRETTY_FUNCTION__)); | |||
4172 | ||||
4173 | SmallSetVector<Instruction *, 8> Worklist; | |||
4174 | ||||
4175 | // These sets are used to seed the analysis with pointers used by memory | |||
4176 | // accesses that will remain scalar. | |||
4177 | SmallSetVector<Instruction *, 8> ScalarPtrs; | |||
4178 | SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs; | |||
4179 | ||||
4180 | // A helper that returns true if the use of Ptr by MemAccess will be scalar. | |||
4181 | // The pointer operands of loads and stores will be scalar as long as the | |||
4182 | // memory access is not a gather or scatter operation. The value operand of a | |||
4183 | // store will remain scalar if the store is scalarized. | |||
4184 | auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) { | |||
4185 | InstWidening WideningDecision = getWideningDecision(MemAccess, VF); | |||
4186 | assert(WideningDecision != CM_Unknown &&(static_cast <bool> (WideningDecision != CM_Unknown && "Widening decision should be ready at this moment") ? void ( 0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4187, __extension__ __PRETTY_FUNCTION__)) | |||
4187 | "Widening decision should be ready at this moment")(static_cast <bool> (WideningDecision != CM_Unknown && "Widening decision should be ready at this moment") ? void ( 0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4187, __extension__ __PRETTY_FUNCTION__)); | |||
4188 | if (auto *Store = dyn_cast<StoreInst>(MemAccess)) | |||
4189 | if (Ptr == Store->getValueOperand()) | |||
4190 | return WideningDecision == CM_Scalarize; | |||
4191 | assert(Ptr == getLoadStorePointerOperand(MemAccess) &&(static_cast <bool> (Ptr == getLoadStorePointerOperand( MemAccess) && "Ptr is neither a value or pointer operand" ) ? void (0) : __assert_fail ("Ptr == getLoadStorePointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4192, __extension__ __PRETTY_FUNCTION__)) | |||
4192 | "Ptr is neither a value or pointer operand")(static_cast <bool> (Ptr == getLoadStorePointerOperand( MemAccess) && "Ptr is neither a value or pointer operand" ) ? void (0) : __assert_fail ("Ptr == getLoadStorePointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4192, __extension__ __PRETTY_FUNCTION__)); | |||
4193 | return WideningDecision != CM_GatherScatter; | |||
4194 | }; | |||
4195 | ||||
4196 | // A helper that returns true if the given value is a bitcast or | |||
4197 | // getelementptr instruction contained in the loop. | |||
4198 | auto isLoopVaryingBitCastOrGEP = [&](Value *V) { | |||
4199 | return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) || | |||
4200 | isa<GetElementPtrInst>(V)) && | |||
4201 | !TheLoop->isLoopInvariant(V); | |||
4202 | }; | |||
4203 | ||||
4204 | // A helper that evaluates a memory access's use of a pointer. If the use | |||
4205 | // will be a scalar use, and the pointer is only used by memory accesses, we | |||
4206 | // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in | |||
4207 | // PossibleNonScalarPtrs. | |||
4208 | auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) { | |||
4209 | // We only care about bitcast and getelementptr instructions contained in | |||
4210 | // the loop. | |||
4211 | if (!isLoopVaryingBitCastOrGEP(Ptr)) | |||
4212 | return; | |||
4213 | ||||
4214 | // If the pointer has already been identified as scalar (e.g., if it was | |||
4215 | // also identified as uniform), there's nothing to do. | |||
4216 | auto *I = cast<Instruction>(Ptr); | |||
4217 | if (Worklist.count(I)) | |||
4218 | return; | |||
4219 | ||||
4220 | // If the use of the pointer will be a scalar use, and all users of the | |||
4221 | // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise, | |||
4222 | // place the pointer in PossibleNonScalarPtrs. | |||
4223 | if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) { | |||
4224 | return isa<LoadInst>(U) || isa<StoreInst>(U); | |||
4225 | })) | |||
4226 | ScalarPtrs.insert(I); | |||
4227 | else | |||
4228 | PossibleNonScalarPtrs.insert(I); | |||
4229 | }; | |||
4230 | ||||
4231 | // We seed the scalars analysis with three classes of instructions: (1) | |||
4232 | // instructions marked uniform-after-vectorization, (2) bitcast and | |||
4233 | // getelementptr instructions used by memory accesses requiring a scalar use, | |||
4234 | // and (3) pointer induction variables and their update instructions (we | |||
4235 | // currently only scalarize these). | |||
4236 | // | |||
4237 | // (1) Add to the worklist all instructions that have been identified as | |||
4238 | // uniform-after-vectorization. | |||
4239 | Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end()); | |||
4240 | ||||
4241 | // (2) Add to the worklist all bitcast and getelementptr instructions used by | |||
4242 | // memory accesses requiring a scalar use. The pointer operands of loads and | |||
4243 | // stores will be scalar as long as the memory accesses is not a gather or | |||
4244 | // scatter operation. The value operand of a store will remain scalar if the | |||
4245 | // store is scalarized. | |||
4246 | for (auto *BB : TheLoop->blocks()) | |||
4247 | for (auto &I : *BB) { | |||
4248 | if (auto *Load = dyn_cast<LoadInst>(&I)) { | |||
4249 | evaluatePtrUse(Load, Load->getPointerOperand()); | |||
4250 | } else if (auto *Store = dyn_cast<StoreInst>(&I)) { | |||
4251 | evaluatePtrUse(Store, Store->getPointerOperand()); | |||
4252 | evaluatePtrUse(Store, Store->getValueOperand()); | |||
4253 | } | |||
4254 | } | |||
4255 | for (auto *I : ScalarPtrs) | |||
4256 | if (!PossibleNonScalarPtrs.count(I)) { | |||
4257 | LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *I << "\n"; } } while (false); | |||
4258 | Worklist.insert(I); | |||
4259 | } | |||
4260 | ||||
4261 | // (3) Add to the worklist all pointer induction variables and their update | |||
4262 | // instructions. | |||
4263 | // | |||
4264 | // TODO: Once we are able to vectorize pointer induction variables we should | |||
4265 | // no longer insert them into the worklist here. | |||
4266 | auto *Latch = TheLoop->getLoopLatch(); | |||
4267 | for (auto &Induction : *Legal->getInductionVars()) { | |||
4268 | auto *Ind = Induction.first; | |||
4269 | auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); | |||
4270 | if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction) | |||
4271 | continue; | |||
4272 | Worklist.insert(Ind); | |||
4273 | Worklist.insert(IndUpdate); | |||
4274 | LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *Ind << "\n"; } } while (false); | |||
4275 | LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdatedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n"; } } while (false) | |||
4276 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n"; } } while (false); | |||
4277 | } | |||
4278 | ||||
4279 | // Insert the forced scalars. | |||
4280 | // FIXME: Currently widenPHIInstruction() often creates a dead vector | |||
4281 | // induction variable when the PHI user is scalarized. | |||
4282 | if (ForcedScalars.count(VF)) | |||
4283 | for (auto *I : ForcedScalars.find(VF)->second) | |||
4284 | Worklist.insert(I); | |||
4285 | ||||
4286 | // Expand the worklist by looking through any bitcasts and getelementptr | |||
4287 | // instructions we've already identified as scalar. This is similar to the | |||
4288 | // expansion step in collectLoopUniforms(); however, here we're only | |||
4289 | // expanding to include additional bitcasts and getelementptr instructions. | |||
4290 | unsigned Idx = 0; | |||
4291 | while (Idx != Worklist.size()) { | |||
4292 | Instruction *Dst = Worklist[Idx++]; | |||
4293 | if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0))) | |||
4294 | continue; | |||
4295 | auto *Src = cast<Instruction>(Dst->getOperand(0)); | |||
4296 | if (llvm::all_of(Src->users(), [&](User *U) -> bool { | |||
4297 | auto *J = cast<Instruction>(U); | |||
4298 | return !TheLoop->contains(J) || Worklist.count(J) || | |||
4299 | ((isa<LoadInst>(J) || isa<StoreInst>(J)) && | |||
4300 | isScalarUse(J, Src)); | |||
4301 | })) { | |||
4302 | Worklist.insert(Src); | |||
4303 | LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *Src << "\n"; } } while (false); | |||
4304 | } | |||
4305 | } | |||
4306 | ||||
4307 | // An induction variable will remain scalar if all users of the induction | |||
4308 | // variable and induction variable update remain scalar. | |||
4309 | for (auto &Induction : *Legal->getInductionVars()) { | |||
4310 | auto *Ind = Induction.first; | |||
4311 | auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); | |||
4312 | ||||
4313 | // We already considered pointer induction variables, so there's no reason | |||
4314 | // to look at their users again. | |||
4315 | // | |||
4316 | // TODO: Once we are able to vectorize pointer induction variables we | |||
4317 | // should no longer skip over them here. | |||
4318 | if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction) | |||
4319 | continue; | |||
4320 | ||||
4321 | // Determine if all users of the induction variable are scalar after | |||
4322 | // vectorization. | |||
4323 | auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool { | |||
4324 | auto *I = cast<Instruction>(U); | |||
4325 | return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I); | |||
4326 | }); | |||
4327 | if (!ScalarInd) | |||
4328 | continue; | |||
4329 | ||||
4330 | // Determine if all users of the induction variable update instruction are | |||
4331 | // scalar after vectorization. | |||
4332 | auto ScalarIndUpdate = | |||
4333 | llvm::all_of(IndUpdate->users(), [&](User *U) -> bool { | |||
4334 | auto *I = cast<Instruction>(U); | |||
4335 | return I == Ind || !TheLoop->contains(I) || Worklist.count(I); | |||
4336 | }); | |||
4337 | if (!ScalarIndUpdate) | |||
4338 | continue; | |||
4339 | ||||
4340 | // The induction variable and its update instruction will remain scalar. | |||
4341 | Worklist.insert(Ind); | |||
4342 | Worklist.insert(IndUpdate); | |||
4343 | LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *Ind << "\n"; } } while (false); | |||
4344 | LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdatedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n"; } } while (false) | |||
4345 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n"; } } while (false); | |||
4346 | } | |||
4347 | ||||
4348 | Scalars[VF].insert(Worklist.begin(), Worklist.end()); | |||
4349 | } | |||
4350 | ||||
4351 | bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) { | |||
4352 | if (!Legal->blockNeedsPredication(I->getParent())) | |||
4353 | return false; | |||
4354 | switch(I->getOpcode()) { | |||
4355 | default: | |||
4356 | break; | |||
4357 | case Instruction::Load: | |||
4358 | case Instruction::Store: { | |||
4359 | if (!Legal->isMaskRequired(I)) | |||
4360 | return false; | |||
4361 | auto *Ptr = getLoadStorePointerOperand(I); | |||
4362 | auto *Ty = getMemInstValueType(I); | |||
4363 | return isa<LoadInst>(I) ? | |||
4364 | !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty)) | |||
4365 | : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty)); | |||
4366 | } | |||
4367 | case Instruction::UDiv: | |||
4368 | case Instruction::SDiv: | |||
4369 | case Instruction::SRem: | |||
4370 | case Instruction::URem: | |||
4371 | return mayDivideByZero(*I); | |||
4372 | } | |||
4373 | return false; | |||
4374 | } | |||
4375 | ||||
4376 | bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I, | |||
4377 | unsigned VF) { | |||
4378 | // Get and ensure we have a valid memory instruction. | |||
4379 | LoadInst *LI = dyn_cast<LoadInst>(I); | |||
4380 | StoreInst *SI = dyn_cast<StoreInst>(I); | |||
4381 | assert((LI || SI) && "Invalid memory instruction")(static_cast <bool> ((LI || SI) && "Invalid memory instruction" ) ? void (0) : __assert_fail ("(LI || SI) && \"Invalid memory instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4381, __extension__ __PRETTY_FUNCTION__)); | |||
4382 | ||||
4383 | auto *Ptr = getLoadStorePointerOperand(I); | |||
4384 | ||||
4385 | // In order to be widened, the pointer should be consecutive, first of all. | |||
4386 | if (!Legal->isConsecutivePtr(Ptr)) | |||
4387 | return false; | |||
4388 | ||||
4389 | // If the instruction is a store located in a predicated block, it will be | |||
4390 | // scalarized. | |||
4391 | if (isScalarWithPredication(I)) | |||
4392 | return false; | |||
4393 | ||||
4394 | // If the instruction's allocated size doesn't equal it's type size, it | |||
4395 | // requires padding and will be scalarized. | |||
4396 | auto &DL = I->getModule()->getDataLayout(); | |||
4397 | auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType(); | |||
4398 | if (hasIrregularType(ScalarTy, DL, VF)) | |||
4399 | return false; | |||
4400 | ||||
4401 | return true; | |||
4402 | } | |||
4403 | ||||
4404 | void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) { | |||
4405 | // We should not collect Uniforms more than once per VF. Right now, | |||
4406 | // this function is called from collectUniformsAndScalars(), which | |||
4407 | // already does this check. Collecting Uniforms for VF=1 does not make any | |||
4408 | // sense. | |||
4409 | ||||
4410 | assert(VF >= 2 && !Uniforms.count(VF) &&(static_cast <bool> (VF >= 2 && !Uniforms.count (VF) && "This function should not be visited twice for the same VF" ) ? void (0) : __assert_fail ("VF >= 2 && !Uniforms.count(VF) && \"This function should not be visited twice for the same VF\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4411, __extension__ __PRETTY_FUNCTION__)) | |||
4411 | "This function should not be visited twice for the same VF")(static_cast <bool> (VF >= 2 && !Uniforms.count (VF) && "This function should not be visited twice for the same VF" ) ? void (0) : __assert_fail ("VF >= 2 && !Uniforms.count(VF) && \"This function should not be visited twice for the same VF\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4411, __extension__ __PRETTY_FUNCTION__)); | |||
4412 | ||||
4413 | // Visit the list of Uniforms. If we'll not find any uniform value, we'll | |||
4414 | // not analyze again. Uniforms.count(VF) will return 1. | |||
4415 | Uniforms[VF].clear(); | |||
4416 | ||||
4417 | // We now know that the loop is vectorizable! | |||
4418 | // Collect instructions inside the loop that will remain uniform after | |||
4419 | // vectorization. | |||
4420 | ||||
4421 | // Global values, params and instructions outside of current loop are out of | |||
4422 | // scope. | |||
4423 | auto isOutOfScope = [&](Value *V) -> bool { | |||
4424 | Instruction *I = dyn_cast<Instruction>(V); | |||
4425 | return (!I || !TheLoop->contains(I)); | |||
4426 | }; | |||
4427 | ||||
4428 | SetVector<Instruction *> Worklist; | |||
4429 | BasicBlock *Latch = TheLoop->getLoopLatch(); | |||
4430 | ||||
4431 | // Start with the conditional branch. If the branch condition is an | |||
4432 | // instruction contained in the loop that is only used by the branch, it is | |||
4433 | // uniform. | |||
4434 | auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0)); | |||
4435 | if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) { | |||
4436 | Worklist.insert(Cmp); | |||
4437 | LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n"; } } while (false); | |||
4438 | } | |||
4439 | ||||
4440 | // Holds consecutive and consecutive-like pointers. Consecutive-like pointers | |||
4441 | // are pointers that are treated like consecutive pointers during | |||
4442 | // vectorization. The pointer operands of interleaved accesses are an | |||
4443 | // example. | |||
4444 | SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs; | |||
4445 | ||||
4446 | // Holds pointer operands of instructions that are possibly non-uniform. | |||
4447 | SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs; | |||
4448 | ||||
4449 | auto isUniformDecision = [&](Instruction *I, unsigned VF) { | |||
4450 | InstWidening WideningDecision = getWideningDecision(I, VF); | |||
4451 | assert(WideningDecision != CM_Unknown &&(static_cast <bool> (WideningDecision != CM_Unknown && "Widening decision should be ready at this moment") ? void ( 0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4452, __extension__ __PRETTY_FUNCTION__)) | |||
4452 | "Widening decision should be ready at this moment")(static_cast <bool> (WideningDecision != CM_Unknown && "Widening decision should be ready at this moment") ? void ( 0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4452, __extension__ __PRETTY_FUNCTION__)); | |||
4453 | ||||
4454 | return (WideningDecision == CM_Widen || | |||
4455 | WideningDecision == CM_Widen_Reverse || | |||
4456 | WideningDecision == CM_Interleave); | |||
4457 | }; | |||
4458 | // Iterate over the instructions in the loop, and collect all | |||
4459 | // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible | |||
4460 | // that a consecutive-like pointer operand will be scalarized, we collect it | |||
4461 | // in PossibleNonUniformPtrs instead. We use two sets here because a single | |||
4462 | // getelementptr instruction can be used by both vectorized and scalarized | |||
4463 | // memory instructions. For example, if a loop loads and stores from the same | |||
4464 | // location, but the store is conditional, the store will be scalarized, and | |||
4465 | // the getelementptr won't remain uniform. | |||
4466 | for (auto *BB : TheLoop->blocks()) | |||
4467 | for (auto &I : *BB) { | |||
4468 | // If there's no pointer operand, there's nothing to do. | |||
4469 | auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I)); | |||
4470 | if (!Ptr) | |||
4471 | continue; | |||
4472 | ||||
4473 | // True if all users of Ptr are memory accesses that have Ptr as their | |||
4474 | // pointer operand. | |||
4475 | auto UsersAreMemAccesses = | |||
4476 | llvm::all_of(Ptr->users(), [&](User *U) -> bool { | |||
4477 | return getLoadStorePointerOperand(U) == Ptr; | |||
4478 | }); | |||
4479 | ||||
4480 | // Ensure the memory instruction will not be scalarized or used by | |||
4481 | // gather/scatter, making its pointer operand non-uniform. If the pointer | |||
4482 | // operand is used by any instruction other than a memory access, we | |||
4483 | // conservatively assume the pointer operand may be non-uniform. | |||
4484 | if (!UsersAreMemAccesses || !isUniformDecision(&I, VF)) | |||
4485 | PossibleNonUniformPtrs.insert(Ptr); | |||
4486 | ||||
4487 | // If the memory instruction will be vectorized and its pointer operand | |||
4488 | // is consecutive-like, or interleaving - the pointer operand should | |||
4489 | // remain uniform. | |||
4490 | else | |||
4491 | ConsecutiveLikePtrs.insert(Ptr); | |||
4492 | } | |||
4493 | ||||
4494 | // Add to the Worklist all consecutive and consecutive-like pointers that | |||
4495 | // aren't also identified as possibly non-uniform. | |||
4496 | for (auto *V : ConsecutiveLikePtrs) | |||
4497 | if (!PossibleNonUniformPtrs.count(V)) { | |||
4498 | LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: " << *V << "\n"; } } while (false); | |||
4499 | Worklist.insert(V); | |||
4500 | } | |||
4501 | ||||
4502 | // Expand Worklist in topological order: whenever a new instruction | |||
4503 | // is added , its users should be either already inside Worklist, or | |||
4504 | // out of scope. It ensures a uniform instruction will only be used | |||
4505 | // by uniform instructions or out of scope instructions. | |||
4506 | unsigned idx = 0; | |||
4507 | while (idx != Worklist.size()) { | |||
4508 | Instruction *I = Worklist[idx++]; | |||
4509 | ||||
4510 | for (auto OV : I->operand_values()) { | |||
4511 | if (isOutOfScope(OV)) | |||
4512 | continue; | |||
4513 | auto *OI = cast<Instruction>(OV); | |||
4514 | if (llvm::all_of(OI->users(), [&](User *U) -> bool { | |||
4515 | auto *J = cast<Instruction>(U); | |||
4516 | return !TheLoop->contains(J) || Worklist.count(J) || | |||
4517 | (OI == getLoadStorePointerOperand(J) && | |||
4518 | isUniformDecision(J, VF)); | |||
4519 | })) { | |||
4520 | Worklist.insert(OI); | |||
4521 | LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: " << *OI << "\n"; } } while (false); | |||
4522 | } | |||
4523 | } | |||
4524 | } | |||
4525 | ||||
4526 | // Returns true if Ptr is the pointer operand of a memory access instruction | |||
4527 | // I, and I is known to not require scalarization. | |||
4528 | auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool { | |||
4529 | return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF); | |||
4530 | }; | |||
4531 | ||||
4532 | // For an instruction to be added into Worklist above, all its users inside | |||
4533 | // the loop should also be in Worklist. However, this condition cannot be | |||
4534 | // true for phi nodes that form a cyclic dependence. We must process phi | |||
4535 | // nodes separately. An induction variable will remain uniform if all users | |||
4536 | // of the induction variable and induction variable update remain uniform. | |||
4537 | // The code below handles both pointer and non-pointer induction variables. | |||
4538 | for (auto &Induction : *Legal->getInductionVars()) { | |||
4539 | auto *Ind = Induction.first; | |||
4540 | auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); | |||
4541 | ||||
4542 | // Determine if all users of the induction variable are uniform after | |||
4543 | // vectorization. | |||
4544 | auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool { | |||
4545 | auto *I = cast<Instruction>(U); | |||
4546 | return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) || | |||
4547 | isVectorizedMemAccessUse(I, Ind); | |||
4548 | }); | |||
4549 | if (!UniformInd) | |||
4550 | continue; | |||
4551 | ||||
4552 | // Determine if all users of the induction variable update instruction are | |||
4553 | // uniform after vectorization. | |||
4554 | auto UniformIndUpdate = | |||
4555 | llvm::all_of(IndUpdate->users(), [&](User *U) -> bool { | |||
4556 | auto *I = cast<Instruction>(U); | |||
4557 | return I == Ind || !TheLoop->contains(I) || Worklist.count(I) || | |||
4558 | isVectorizedMemAccessUse(I, IndUpdate); | |||
4559 | }); | |||
4560 | if (!UniformIndUpdate) | |||
4561 | continue; | |||
4562 | ||||
4563 | // The induction variable and its update instruction will remain uniform. | |||
4564 | Worklist.insert(Ind); | |||
4565 | Worklist.insert(IndUpdate); | |||
4566 | LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: " << *Ind << "\n"; } } while (false); | |||
4567 | LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdatedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n"; } } while (false) | |||
4568 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n"; } } while (false); | |||
4569 | } | |||
4570 | ||||
4571 | Uniforms[VF].insert(Worklist.begin(), Worklist.end()); | |||
4572 | } | |||
4573 | ||||
4574 | void InterleavedAccessInfo::collectConstStrideAccesses( | |||
4575 | MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, | |||
4576 | const ValueToValueMap &Strides) { | |||
4577 | auto &DL = TheLoop->getHeader()->getModule()->getDataLayout(); | |||
4578 | ||||
4579 | // Since it's desired that the load/store instructions be maintained in | |||
4580 | // "program order" for the interleaved access analysis, we have to visit the | |||
4581 | // blocks in the loop in reverse postorder (i.e., in a topological order). | |||
4582 | // Such an ordering will ensure that any load/store that may be executed | |||
4583 | // before a second load/store will precede the second load/store in | |||
4584 | // AccessStrideInfo. | |||
4585 | LoopBlocksDFS DFS(TheLoop); | |||
4586 | DFS.perform(LI); | |||
4587 | for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) | |||
4588 | for (auto &I : *BB) { | |||
4589 | auto *LI = dyn_cast<LoadInst>(&I); | |||
4590 | auto *SI = dyn_cast<StoreInst>(&I); | |||
4591 | if (!LI && !SI) | |||
4592 | continue; | |||
4593 | ||||
4594 | Value *Ptr = getLoadStorePointerOperand(&I); | |||
4595 | // We don't check wrapping here because we don't know yet if Ptr will be | |||
4596 | // part of a full group or a group with gaps. Checking wrapping for all | |||
4597 | // pointers (even those that end up in groups with no gaps) will be overly | |||
4598 | // conservative. For full groups, wrapping should be ok since if we would | |||
4599 | // wrap around the address space we would do a memory access at nullptr | |||
4600 | // even without the transformation. The wrapping checks are therefore | |||
4601 | // deferred until after we've formed the interleaved groups. | |||
4602 | int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, | |||
4603 | /*Assume=*/true, /*ShouldCheckWrap=*/false); | |||
4604 | ||||
4605 | const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr); | |||
4606 | PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType()); | |||
4607 | uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); | |||
4608 | ||||
4609 | // An alignment of 0 means target ABI alignment. | |||
4610 | unsigned Align = getMemInstAlignment(&I); | |||
4611 | if (!Align) | |||
4612 | Align = DL.getABITypeAlignment(PtrTy->getElementType()); | |||
4613 | ||||
4614 | AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align); | |||
4615 | } | |||
4616 | } | |||
4617 | ||||
4618 | // Analyze interleaved accesses and collect them into interleaved load and | |||
4619 | // store groups. | |||
4620 | // | |||
4621 | // When generating code for an interleaved load group, we effectively hoist all | |||
4622 | // loads in the group to the location of the first load in program order. When | |||
4623 | // generating code for an interleaved store group, we sink all stores to the | |||
4624 | // location of the last store. This code motion can change the order of load | |||
4625 | // and store instructions and may break dependences. | |||
4626 | // | |||
4627 | // The code generation strategy mentioned above ensures that we won't violate | |||
4628 | // any write-after-read (WAR) dependences. | |||
4629 | // | |||
4630 | // E.g., for the WAR dependence: a = A[i]; // (1) | |||
4631 | // A[i] = b; // (2) | |||
4632 | // | |||
4633 | // The store group of (2) is always inserted at or below (2), and the load | |||
4634 | // group of (1) is always inserted at or above (1). Thus, the instructions will | |||
4635 | // never be reordered. All other dependences are checked to ensure the | |||
4636 | // correctness of the instruction reordering. | |||
4637 | // | |||
4638 | // The algorithm visits all memory accesses in the loop in bottom-up program | |||
4639 | // order. Program order is established by traversing the blocks in the loop in | |||
4640 | // reverse postorder when collecting the accesses. | |||
4641 | // | |||
4642 | // We visit the memory accesses in bottom-up order because it can simplify the | |||
4643 | // construction of store groups in the presence of write-after-write (WAW) | |||
4644 | // dependences. | |||
4645 | // | |||
4646 | // E.g., for the WAW dependence: A[i] = a; // (1) | |||
4647 | // A[i] = b; // (2) | |||
4648 | // A[i + 1] = c; // (3) | |||
4649 | // | |||
4650 | // We will first create a store group with (3) and (2). (1) can't be added to | |||
4651 | // this group because it and (2) are dependent. However, (1) can be grouped | |||
4652 | // with other accesses that may precede it in program order. Note that a | |||
4653 | // bottom-up order does not imply that WAW dependences should not be checked. | |||
4654 | void InterleavedAccessInfo::analyzeInterleaving() { | |||
4655 | LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Analyzing interleaved accesses...\n" ; } } while (false); | |||
4656 | const ValueToValueMap &Strides = LAI->getSymbolicStrides(); | |||
4657 | ||||
4658 | // Holds all accesses with a constant stride. | |||
4659 | MapVector<Instruction *, StrideDescriptor> AccessStrideInfo; | |||
4660 | collectConstStrideAccesses(AccessStrideInfo, Strides); | |||
4661 | ||||
4662 | if (AccessStrideInfo.empty()) | |||
4663 | return; | |||
4664 | ||||
4665 | // Collect the dependences in the loop. | |||
4666 | collectDependences(); | |||
4667 | ||||
4668 | // Holds all interleaved store groups temporarily. | |||
4669 | SmallSetVector<InterleaveGroup *, 4> StoreGroups; | |||
4670 | // Holds all interleaved load groups temporarily. | |||
4671 | SmallSetVector<InterleaveGroup *, 4> LoadGroups; | |||
4672 | ||||
4673 | // Search in bottom-up program order for pairs of accesses (A and B) that can | |||
4674 | // form interleaved load or store groups. In the algorithm below, access A | |||
4675 | // precedes access B in program order. We initialize a group for B in the | |||
4676 | // outer loop of the algorithm, and then in the inner loop, we attempt to | |||
4677 | // insert each A into B's group if: | |||
4678 | // | |||
4679 | // 1. A and B have the same stride, | |||
4680 | // 2. A and B have the same memory object size, and | |||
4681 | // 3. A belongs in B's group according to its distance from B. | |||
4682 | // | |||
4683 | // Special care is taken to ensure group formation will not break any | |||
4684 | // dependences. | |||
4685 | for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend(); | |||
4686 | BI != E; ++BI) { | |||
4687 | Instruction *B = BI->first; | |||
4688 | StrideDescriptor DesB = BI->second; | |||
4689 | ||||
4690 | // Initialize a group for B if it has an allowable stride. Even if we don't | |||
4691 | // create a group for B, we continue with the bottom-up algorithm to ensure | |||
4692 | // we don't break any of B's dependences. | |||
4693 | InterleaveGroup *Group = nullptr; | |||
4694 | if (isStrided(DesB.Stride)) { | |||
4695 | Group = getInterleaveGroup(B); | |||
4696 | if (!Group) { | |||
4697 | LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *Bdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Creating an interleave group with:" << *B << '\n'; } } while (false) | |||
4698 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Creating an interleave group with:" << *B << '\n'; } } while (false); | |||
4699 | Group = createInterleaveGroup(B, DesB.Stride, DesB.Align); | |||
4700 | } | |||
4701 | if (B->mayWriteToMemory()) | |||
4702 | StoreGroups.insert(Group); | |||
4703 | else | |||
4704 | LoadGroups.insert(Group); | |||
4705 | } | |||
4706 | ||||
4707 | for (auto AI = std::next(BI); AI != E; ++AI) { | |||
4708 | Instruction *A = AI->first; | |||
4709 | StrideDescriptor DesA = AI->second; | |||
4710 | ||||
4711 | // Our code motion strategy implies that we can't have dependences | |||
4712 | // between accesses in an interleaved group and other accesses located | |||
4713 | // between the first and last member of the group. Note that this also | |||
4714 | // means that a group can't have more than one member at a given offset. | |||
4715 | // The accesses in a group can have dependences with other accesses, but | |||
4716 | // we must ensure we don't extend the boundaries of the group such that | |||
4717 | // we encompass those dependent accesses. | |||
4718 | // | |||
4719 | // For example, assume we have the sequence of accesses shown below in a | |||
4720 | // stride-2 loop: | |||
4721 | // | |||
4722 | // (1, 2) is a group | A[i] = a; // (1) | |||
4723 | // | A[i-1] = b; // (2) | | |||
4724 | // A[i-3] = c; // (3) | |||
4725 | // A[i] = d; // (4) | (2, 4) is not a group | |||
4726 | // | |||
4727 | // Because accesses (2) and (3) are dependent, we can group (2) with (1) | |||
4728 | // but not with (4). If we did, the dependent access (3) would be within | |||
4729 | // the boundaries of the (2, 4) group. | |||
4730 | if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) { | |||
4731 | // If a dependence exists and A is already in a group, we know that A | |||
4732 | // must be a store since A precedes B and WAR dependences are allowed. | |||
4733 | // Thus, A would be sunk below B. We release A's group to prevent this | |||
4734 | // illegal code motion. A will then be free to form another group with | |||
4735 | // instructions that precede it. | |||
4736 | if (isInterleaved(A)) { | |||
4737 | InterleaveGroup *StoreGroup = getInterleaveGroup(A); | |||
4738 | StoreGroups.remove(StoreGroup); | |||
4739 | releaseGroup(StoreGroup); | |||
4740 | } | |||
4741 | ||||
4742 | // If a dependence exists and A is not already in a group (or it was | |||
4743 | // and we just released it), B might be hoisted above A (if B is a | |||
4744 | // load) or another store might be sunk below A (if B is a store). In | |||
4745 | // either case, we can't add additional instructions to B's group. B | |||
4746 | // will only form a group with instructions that it precedes. | |||
4747 | break; | |||
4748 | } | |||
4749 | ||||
4750 | // At this point, we've checked for illegal code motion. If either A or B | |||
4751 | // isn't strided, there's nothing left to do. | |||
4752 | if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride)) | |||
4753 | continue; | |||
4754 | ||||
4755 | // Ignore A if it's already in a group or isn't the same kind of memory | |||
4756 | // operation as B. | |||
4757 | // Note that mayReadFromMemory() isn't mutually exclusive to mayWriteToMemory | |||
4758 | // in the case of atomic loads. We shouldn't see those here, canVectorizeMemory() | |||
4759 | // should have returned false - except for the case we asked for optimization | |||
4760 | // remarks. | |||
4761 | if (isInterleaved(A) || (A->mayReadFromMemory() != B->mayReadFromMemory()) | |||
4762 | || (A->mayWriteToMemory() != B->mayWriteToMemory())) | |||
4763 | continue; | |||
4764 | ||||
4765 | // Check rules 1 and 2. Ignore A if its stride or size is different from | |||
4766 | // that of B. | |||
4767 | if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size) | |||
4768 | continue; | |||
4769 | ||||
4770 | // Ignore A if the memory object of A and B don't belong to the same | |||
4771 | // address space | |||
4772 | if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B)) | |||
4773 | continue; | |||
4774 | ||||
4775 | // Calculate the distance from A to B. | |||
4776 | const SCEVConstant *DistToB = dyn_cast<SCEVConstant>( | |||
4777 | PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev)); | |||
4778 | if (!DistToB) | |||
4779 | continue; | |||
4780 | int64_t DistanceToB = DistToB->getAPInt().getSExtValue(); | |||
4781 | ||||
4782 | // Check rule 3. Ignore A if its distance to B is not a multiple of the | |||
4783 | // size. | |||
4784 | if (DistanceToB % static_cast<int64_t>(DesB.Size)) | |||
4785 | continue; | |||
4786 | ||||
4787 | // Ignore A if either A or B is in a predicated block. Although we | |||
4788 | // currently prevent group formation for predicated accesses, we may be | |||
4789 | // able to relax this limitation in the future once we handle more | |||
4790 | // complicated blocks. | |||
4791 | if (isPredicated(A->getParent()) || isPredicated(B->getParent())) | |||
4792 | continue; | |||
4793 | ||||
4794 | // The index of A is the index of B plus A's distance to B in multiples | |||
4795 | // of the size. | |||
4796 | int IndexA = | |||
4797 | Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size); | |||
4798 | ||||
4799 | // Try to insert A into B's group. | |||
4800 | if (Group->insertMember(A, IndexA, DesA.Align)) { | |||
4801 | LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Inserted:" << *A << '\n' << " into the interleave group with" << *B << '\n'; } } while (false) | |||
4802 | << " into the interleave group with" << *Bdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Inserted:" << *A << '\n' << " into the interleave group with" << *B << '\n'; } } while (false) | |||
4803 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Inserted:" << *A << '\n' << " into the interleave group with" << *B << '\n'; } } while (false); | |||
4804 | InterleaveGroupMap[A] = Group; | |||
4805 | ||||
4806 | // Set the first load in program order as the insert position. | |||
4807 | if (A->mayReadFromMemory()) | |||
4808 | Group->setInsertPos(A); | |||
4809 | } | |||
4810 | } // Iteration over A accesses. | |||
4811 | } // Iteration over B accesses. | |||
4812 | ||||
4813 | // Remove interleaved store groups with gaps. | |||
4814 | for (InterleaveGroup *Group : StoreGroups) | |||
4815 | if (Group->getNumMembers() != Group->getFactor()) { | |||
4816 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved store group due " "to gaps.\n"; } } while (false) | |||
4817 | dbgs() << "LV: Invalidate candidate interleaved store group due "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved store group due " "to gaps.\n"; } } while (false) | |||
4818 | "to gaps.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved store group due " "to gaps.\n"; } } while (false); | |||
4819 | releaseGroup(Group); | |||
4820 | } | |||
4821 | // Remove interleaved groups with gaps (currently only loads) whose memory | |||
4822 | // accesses may wrap around. We have to revisit the getPtrStride analysis, | |||
4823 | // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does | |||
4824 | // not check wrapping (see documentation there). | |||
4825 | // FORNOW we use Assume=false; | |||
4826 | // TODO: Change to Assume=true but making sure we don't exceed the threshold | |||
4827 | // of runtime SCEV assumptions checks (thereby potentially failing to | |||
4828 | // vectorize altogether). | |||
4829 | // Additional optional optimizations: | |||
4830 | // TODO: If we are peeling the loop and we know that the first pointer doesn't | |||
4831 | // wrap then we can deduce that all pointers in the group don't wrap. | |||
4832 | // This means that we can forcefully peel the loop in order to only have to | |||
4833 | // check the first pointer for no-wrap. When we'll change to use Assume=true | |||
4834 | // we'll only need at most one runtime check per interleaved group. | |||
4835 | for (InterleaveGroup *Group : LoadGroups) { | |||
4836 | // Case 1: A full group. Can Skip the checks; For full groups, if the wide | |||
4837 | // load would wrap around the address space we would do a memory access at | |||
4838 | // nullptr even without the transformation. | |||
4839 | if (Group->getNumMembers() == Group->getFactor()) | |||
4840 | continue; | |||
4841 | ||||
4842 | // Case 2: If first and last members of the group don't wrap this implies | |||
4843 | // that all the pointers in the group don't wrap. | |||
4844 | // So we check only group member 0 (which is always guaranteed to exist), | |||
4845 | // and group member Factor - 1; If the latter doesn't exist we rely on | |||
4846 | // peeling (if it is a non-reveresed accsess -- see Case 3). | |||
4847 | Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0)); | |||
4848 | if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false, | |||
4849 | /*ShouldCheckWrap=*/true)) { | |||
4850 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "first group member potentially pointer-wrapping.\n"; } } while (false) | |||
4851 | dbgs() << "LV: Invalidate candidate interleaved group due to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "first group member potentially pointer-wrapping.\n"; } } while (false) | |||
4852 | "first group member potentially pointer-wrapping.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "first group member potentially pointer-wrapping.\n"; } } while (false); | |||
4853 | releaseGroup(Group); | |||
4854 | continue; | |||
4855 | } | |||
4856 | Instruction *LastMember = Group->getMember(Group->getFactor() - 1); | |||
4857 | if (LastMember) { | |||
4858 | Value *LastMemberPtr = getLoadStorePointerOperand(LastMember); | |||
4859 | if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false, | |||
4860 | /*ShouldCheckWrap=*/true)) { | |||
4861 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "last group member potentially pointer-wrapping.\n"; } } while (false) | |||
4862 | dbgs() << "LV: Invalidate candidate interleaved group due to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "last group member potentially pointer-wrapping.\n"; } } while (false) | |||
4863 | "last group member potentially pointer-wrapping.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "last group member potentially pointer-wrapping.\n"; } } while (false); | |||
4864 | releaseGroup(Group); | |||
4865 | } | |||
4866 | } else { | |||
4867 | // Case 3: A non-reversed interleaved load group with gaps: We need | |||
4868 | // to execute at least one scalar epilogue iteration. This will ensure | |||
4869 | // we don't speculatively access memory out-of-bounds. We only need | |||
4870 | // to look for a member at index factor - 1, since every group must have | |||
4871 | // a member at index zero. | |||
4872 | if (Group->isReverse()) { | |||
4873 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "a reverse access with gaps.\n"; } } while (false) | |||
4874 | dbgs() << "LV: Invalidate candidate interleaved group due to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "a reverse access with gaps.\n"; } } while (false) | |||
4875 | "a reverse access with gaps.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to " "a reverse access with gaps.\n"; } } while (false); | |||
4876 | releaseGroup(Group); | |||
4877 | continue; | |||
4878 | } | |||
4879 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaved group requires epilogue iteration.\n" ; } } while (false) | |||
4880 | dbgs() << "LV: Interleaved group requires epilogue iteration.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaved group requires epilogue iteration.\n" ; } } while (false); | |||
4881 | RequiresScalarEpilogue = true; | |||
4882 | } | |||
4883 | } | |||
4884 | } | |||
4885 | ||||
4886 | Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) { | |||
4887 | if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) { | |||
4888 | // TODO: It may by useful to do since it's still likely to be dynamically | |||
4889 | // uniform if the target can skip. | |||
4890 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not inserting runtime ptr check for divergent target" ; } } while (false) | |||
4891 | dbgs() << "LV: Not inserting runtime ptr check for divergent target")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not inserting runtime ptr check for divergent target" ; } } while (false); | |||
4892 | ||||
4893 | ORE->emit( | |||
4894 | createMissedAnalysis("CantVersionLoopWithDivergentTarget") | |||
4895 | << "runtime pointer checks needed. Not enabled for divergent target"); | |||
4896 | ||||
4897 | return None; | |||
4898 | } | |||
4899 | ||||
4900 | unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); | |||
4901 | if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize. | |||
4902 | return computeFeasibleMaxVF(OptForSize, TC); | |||
4903 | ||||
4904 | if (Legal->getRuntimePointerChecking()->Need) { | |||
4905 | ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize") | |||
4906 | << "runtime pointer checks needed. Enable vectorization of this " | |||
4907 | "loop with '#pragma clang loop vectorize(enable)' when " | |||
4908 | "compiling with -Os/-Oz"); | |||
4909 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n" ; } } while (false) | |||
4910 | dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n" ; } } while (false) | |||
4911 | << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n" ; } } while (false); | |||
4912 | return None; | |||
4913 | } | |||
4914 | ||||
4915 | // If we optimize the program for size, avoid creating the tail loop. | |||
4916 | LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found trip count: " << TC << '\n'; } } while (false); | |||
4917 | ||||
4918 | // If we don't know the precise trip count, don't try to vectorize. | |||
4919 | if (TC < 2) { | |||
4920 | ORE->emit( | |||
4921 | createMissedAnalysis("UnknownLoopCountComplexCFG") | |||
4922 | << "unable to calculate the loop count due to complex control flow"); | |||
4923 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n" ; } } while (false) | |||
4924 | dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n" ; } } while (false); | |||
4925 | return None; | |||
4926 | } | |||
4927 | ||||
4928 | unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC); | |||
4929 | ||||
4930 | if (TC % MaxVF != 0) { | |||
4931 | // If the trip count that we found modulo the vectorization factor is not | |||
4932 | // zero then we require a tail. | |||
4933 | // FIXME: look for a smaller MaxVF that does divide TC rather than give up. | |||
4934 | // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a | |||
4935 | // smaller MaxVF that does not require a scalar epilog. | |||
4936 | ||||
4937 | ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize") | |||
4938 | << "cannot optimize for size and vectorize at the " | |||
4939 | "same time. Enable vectorization of this loop " | |||
4940 | "with '#pragma clang loop vectorize(enable)' " | |||
4941 | "when compiling with -Os/-Oz"); | |||
4942 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n" ; } } while (false) | |||
4943 | dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n" ; } } while (false); | |||
4944 | return None; | |||
4945 | } | |||
4946 | ||||
4947 | return MaxVF; | |||
4948 | } | |||
4949 | ||||
4950 | unsigned | |||
4951 | LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize, | |||
4952 | unsigned ConstTripCount) { | |||
4953 | MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI); | |||
4954 | unsigned SmallestType, WidestType; | |||
4955 | std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes(); | |||
4956 | unsigned WidestRegister = TTI.getRegisterBitWidth(true); | |||
4957 | ||||
4958 | // Get the maximum safe dependence distance in bits computed by LAA. | |||
4959 | // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from | |||
4960 | // the memory accesses that is most restrictive (involved in the smallest | |||
4961 | // dependence distance). | |||
4962 | unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth(); | |||
4963 | ||||
4964 | WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth); | |||
4965 | ||||
4966 | unsigned MaxVectorSize = WidestRegister / WidestType; | |||
4967 | ||||
4968 | LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestTypedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / " << WidestType << " bits.\n"; } } while (false) | |||
4969 | << " / " << WidestType << " bits.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / " << WidestType << " bits.\n"; } } while (false); | |||
4970 | LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: The Widest register safe to use is: " << WidestRegister << " bits.\n"; } } while (false ) | |||
4971 | << WidestRegister << " bits.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: The Widest register safe to use is: " << WidestRegister << " bits.\n"; } } while (false ); | |||
4972 | ||||
4973 | assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"(static_cast <bool> (MaxVectorSize <= 256 && "Did not expect to pack so many elements" " into one vector!" ) ? void (0) : __assert_fail ("MaxVectorSize <= 256 && \"Did not expect to pack so many elements\" \" into one vector!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4974, __extension__ __PRETTY_FUNCTION__)) | |||
4974 | " into one vector!")(static_cast <bool> (MaxVectorSize <= 256 && "Did not expect to pack so many elements" " into one vector!" ) ? void (0) : __assert_fail ("MaxVectorSize <= 256 && \"Did not expect to pack so many elements\" \" into one vector!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 4974, __extension__ __PRETTY_FUNCTION__)); | |||
4975 | if (MaxVectorSize == 0) { | |||
4976 | LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: The target has no vector registers.\n" ; } } while (false); | |||
4977 | MaxVectorSize = 1; | |||
4978 | return MaxVectorSize; | |||
4979 | } else if (ConstTripCount && ConstTripCount < MaxVectorSize && | |||
4980 | isPowerOf2_32(ConstTripCount)) { | |||
4981 | // We need to clamp the VF to be the ConstTripCount. There is no point in | |||
4982 | // choosing a higher viable VF as done in the loop below. | |||
4983 | LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Clamping the MaxVF to the constant trip count: " << ConstTripCount << "\n"; } } while (false) | |||
4984 | << ConstTripCount << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Clamping the MaxVF to the constant trip count: " << ConstTripCount << "\n"; } } while (false); | |||
4985 | MaxVectorSize = ConstTripCount; | |||
4986 | return MaxVectorSize; | |||
4987 | } | |||
4988 | ||||
4989 | unsigned MaxVF = MaxVectorSize; | |||
4990 | if (TTI.shouldMaximizeVectorBandwidth(OptForSize) || | |||
4991 | (MaximizeBandwidth && !OptForSize)) { | |||
4992 | // Collect all viable vectorization factors larger than the default MaxVF | |||
4993 | // (i.e. MaxVectorSize). | |||
4994 | SmallVector<unsigned, 8> VFs; | |||
4995 | unsigned NewMaxVectorSize = WidestRegister / SmallestType; | |||
4996 | for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2) | |||
4997 | VFs.push_back(VS); | |||
4998 | ||||
4999 | // For each VF calculate its register usage. | |||
5000 | auto RUs = calculateRegisterUsage(VFs); | |||
5001 | ||||
5002 | // Select the largest VF which doesn't require more registers than existing | |||
5003 | // ones. | |||
5004 | unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true); | |||
5005 | for (int i = RUs.size() - 1; i >= 0; --i) { | |||
5006 | if (RUs[i].MaxLocalUsers <= TargetNumRegisters) { | |||
5007 | MaxVF = VFs[i]; | |||
5008 | break; | |||
5009 | } | |||
5010 | } | |||
5011 | if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) { | |||
5012 | if (MaxVF < MinVF) { | |||
5013 | LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVFdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF << ") with target's minimum: " << MinVF << '\n'; } } while (false) | |||
5014 | << ") with target's minimum: " << MinVF << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF << ") with target's minimum: " << MinVF << '\n'; } } while (false); | |||
5015 | MaxVF = MinVF; | |||
5016 | } | |||
5017 | } | |||
5018 | } | |||
5019 | return MaxVF; | |||
5020 | } | |||
5021 | ||||
5022 | VectorizationFactor | |||
5023 | LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) { | |||
5024 | float Cost = expectedCost(1).first; | |||
5025 | const float ScalarCost = Cost; | |||
5026 | unsigned Width = 1; | |||
5027 | LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n"; } } while (false); | |||
5028 | ||||
5029 | bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled; | |||
5030 | if (ForceVectorization && MaxVF > 1) { | |||
5031 | // Ignore scalar width, because the user explicitly wants vectorization. | |||
5032 | // Initialize cost to max so that VF = 2 is, at least, chosen during cost | |||
5033 | // evaluation. | |||
5034 | Cost = std::numeric_limits<float>::max(); | |||
5035 | } | |||
5036 | ||||
5037 | for (unsigned i = 2; i <= MaxVF; i *= 2) { | |||
5038 | // Notice that the vector loop needs to be executed less times, so | |||
5039 | // we need to divide the cost of the vector loops by the width of | |||
5040 | // the vector elements. | |||
5041 | VectorizationCostTy C = expectedCost(i); | |||
5042 | float VectorCost = C.first / (float)i; | |||
5043 | LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Vector loop of width " << i << " costs: " << (int)VectorCost << ".\n"; } } while (false) | |||
5044 | << " costs: " << (int)VectorCost << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Vector loop of width " << i << " costs: " << (int)VectorCost << ".\n"; } } while (false); | |||
5045 | if (!C.second && !ForceVectorization) { | |||
5046 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not considering vector loop of width " << i << " because it will not generate any vector instructions.\n" ; } } while (false) | |||
5047 | dbgs() << "LV: Not considering vector loop of width " << ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not considering vector loop of width " << i << " because it will not generate any vector instructions.\n" ; } } while (false) | |||
5048 | << " because it will not generate any vector instructions.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not considering vector loop of width " << i << " because it will not generate any vector instructions.\n" ; } } while (false); | |||
5049 | continue; | |||
5050 | } | |||
5051 | if (VectorCost < Cost) { | |||
5052 | Cost = VectorCost; | |||
5053 | Width = i; | |||
5054 | } | |||
5055 | } | |||
5056 | ||||
5057 | if (!EnableCondStoresVectorization && NumPredStores) { | |||
5058 | ORE->emit(createMissedAnalysis("ConditionalStore") | |||
5059 | << "store that is conditionally executed prevents vectorization"); | |||
5060 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: No vectorization. There are conditional stores.\n" ; } } while (false) | |||
5061 | dbgs() << "LV: No vectorization. There are conditional stores.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: No vectorization. There are conditional stores.\n" ; } } while (false); | |||
5062 | Width = 1; | |||
5063 | Cost = ScalarCost; | |||
5064 | } | |||
5065 | ||||
5066 | LLVM_DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs() << "LV: Vectorization seems to be not beneficial, " << "but was forced by a user.\n"; } } while (false) | |||
5067 | << "LV: Vectorization seems to be not beneficial, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs() << "LV: Vectorization seems to be not beneficial, " << "but was forced by a user.\n"; } } while (false) | |||
5068 | << "but was forced by a user.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs() << "LV: Vectorization seems to be not beneficial, " << "but was forced by a user.\n"; } } while (false); | |||
5069 | LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Selecting VF: " << Width << ".\n"; } } while (false); | |||
5070 | VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)}; | |||
5071 | return Factor; | |||
5072 | } | |||
5073 | ||||
5074 | std::pair<unsigned, unsigned> | |||
5075 | LoopVectorizationCostModel::getSmallestAndWidestTypes() { | |||
5076 | unsigned MinWidth = -1U; | |||
5077 | unsigned MaxWidth = 8; | |||
5078 | const DataLayout &DL = TheFunction->getParent()->getDataLayout(); | |||
5079 | ||||
5080 | // For each block. | |||
5081 | for (BasicBlock *BB : TheLoop->blocks()) { | |||
5082 | // For each instruction in the loop. | |||
5083 | for (Instruction &I : *BB) { | |||
5084 | Type *T = I.getType(); | |||
5085 | ||||
5086 | // Skip ignored values. | |||
5087 | if (ValuesToIgnore.count(&I)) | |||
5088 | continue; | |||
5089 | ||||
5090 | // Only examine Loads, Stores and PHINodes. | |||
5091 | if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I)) | |||
5092 | continue; | |||
5093 | ||||
5094 | // Examine PHI nodes that are reduction variables. Update the type to | |||
5095 | // account for the recurrence type. | |||
5096 | if (auto *PN = dyn_cast<PHINode>(&I)) { | |||
5097 | if (!Legal->isReductionVariable(PN)) | |||
5098 | continue; | |||
5099 | RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN]; | |||
5100 | T = RdxDesc.getRecurrenceType(); | |||
5101 | } | |||
5102 | ||||
5103 | // Examine the stored values. | |||
5104 | if (auto *ST = dyn_cast<StoreInst>(&I)) | |||
5105 | T = ST->getValueOperand()->getType(); | |||
5106 | ||||
5107 | // Ignore loaded pointer types and stored pointer types that are not | |||
5108 | // vectorizable. | |||
5109 | // | |||
5110 | // FIXME: The check here attempts to predict whether a load or store will | |||
5111 | // be vectorized. We only know this for certain after a VF has | |||
5112 | // been selected. Here, we assume that if an access can be | |||
5113 | // vectorized, it will be. We should also look at extending this | |||
5114 | // optimization to non-pointer types. | |||
5115 | // | |||
5116 | if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) && | |||
5117 | !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I)) | |||
5118 | continue; | |||
5119 | ||||
5120 | MinWidth = std::min(MinWidth, | |||
5121 | (unsigned)DL.getTypeSizeInBits(T->getScalarType())); | |||
5122 | MaxWidth = std::max(MaxWidth, | |||
5123 | (unsigned)DL.getTypeSizeInBits(T->getScalarType())); | |||
5124 | } | |||
5125 | } | |||
5126 | ||||
5127 | return {MinWidth, MaxWidth}; | |||
5128 | } | |||
5129 | ||||
5130 | unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize, | |||
5131 | unsigned VF, | |||
5132 | unsigned LoopCost) { | |||
5133 | // -- The interleave heuristics -- | |||
5134 | // We interleave the loop in order to expose ILP and reduce the loop overhead. | |||
5135 | // There are many micro-architectural considerations that we can't predict | |||
5136 | // at this level. For example, frontend pressure (on decode or fetch) due to | |||
5137 | // code size, or the number and capabilities of the execution ports. | |||
5138 | // | |||
5139 | // We use the following heuristics to select the interleave count: | |||
5140 | // 1. If the code has reductions, then we interleave to break the cross | |||
5141 | // iteration dependency. | |||
5142 | // 2. If the loop is really small, then we interleave to reduce the loop | |||
5143 | // overhead. | |||
5144 | // 3. We don't interleave if we think that we will spill registers to memory | |||
5145 | // due to the increased register pressure. | |||
5146 | ||||
5147 | // When we optimize for size, we don't interleave. | |||
5148 | if (OptForSize) | |||
5149 | return 1; | |||
5150 | ||||
5151 | // We used the distance for the interleave count. | |||
5152 | if (Legal->getMaxSafeDepDistBytes() != -1U) | |||
5153 | return 1; | |||
5154 | ||||
5155 | // Do not interleave loops with a relatively small trip count. | |||
5156 | unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); | |||
5157 | if (TC > 1 && TC < TinyTripCountInterleaveThreshold) | |||
5158 | return 1; | |||
5159 | ||||
5160 | unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1); | |||
5161 | LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegistersdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: The target has " << TargetNumRegisters << " registers\n"; } } while (false ) | |||
5162 | << " registers\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: The target has " << TargetNumRegisters << " registers\n"; } } while (false ); | |||
5163 | ||||
5164 | if (VF == 1) { | |||
5165 | if (ForceTargetNumScalarRegs.getNumOccurrences() > 0) | |||
5166 | TargetNumRegisters = ForceTargetNumScalarRegs; | |||
5167 | } else { | |||
5168 | if (ForceTargetNumVectorRegs.getNumOccurrences() > 0) | |||
5169 | TargetNumRegisters = ForceTargetNumVectorRegs; | |||
5170 | } | |||
5171 | ||||
5172 | RegisterUsage R = calculateRegisterUsage({VF})[0]; | |||
5173 | // We divide by these constants so assume that we have at least one | |||
5174 | // instruction that uses at least one register. | |||
5175 | R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); | |||
5176 | ||||
5177 | // We calculate the interleave count using the following formula. | |||
5178 | // Subtract the number of loop invariants from the number of available | |||
5179 | // registers. These registers are used by all of the interleaved instances. | |||
5180 | // Next, divide the remaining registers by the number of registers that is | |||
5181 | // required by the loop, in order to estimate how many parallel instances | |||
5182 | // fit without causing spills. All of this is rounded down if necessary to be | |||
5183 | // a power of two. We want power of two interleave count to simplify any | |||
5184 | // addressing operations or alignment considerations. | |||
5185 | unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) / | |||
5186 | R.MaxLocalUsers); | |||
5187 | ||||
5188 | // Don't count the induction variable as interleaved. | |||
5189 | if (EnableIndVarRegisterHeur) | |||
5190 | IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) / | |||
5191 | std::max(1U, (R.MaxLocalUsers - 1))); | |||
5192 | ||||
5193 | // Clamp the interleave ranges to reasonable counts. | |||
5194 | unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF); | |||
5195 | ||||
5196 | // Check if the user has overridden the max. | |||
5197 | if (VF == 1) { | |||
5198 | if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0) | |||
5199 | MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor; | |||
5200 | } else { | |||
5201 | if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0) | |||
5202 | MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor; | |||
5203 | } | |||
5204 | ||||
5205 | // If we did not calculate the cost for VF (because the user selected the VF) | |||
5206 | // then we calculate the cost of VF here. | |||
5207 | if (LoopCost == 0) | |||
5208 | LoopCost = expectedCost(VF).first; | |||
5209 | ||||
5210 | // Clamp the calculated IC to be between the 1 and the max interleave count | |||
5211 | // that the target allows. | |||
5212 | if (IC > MaxInterleaveCount) | |||
5213 | IC = MaxInterleaveCount; | |||
5214 | else if (IC < 1) | |||
5215 | IC = 1; | |||
5216 | ||||
5217 | // Interleave if we vectorized this loop and there is a reduction that could | |||
5218 | // benefit from interleaving. | |||
5219 | if (VF > 1 && !Legal->getReductionVars()->empty()) { | |||
5220 | LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving because of reductions.\n" ; } } while (false); | |||
5221 | return IC; | |||
5222 | } | |||
5223 | ||||
5224 | // Note that if we've already vectorized the loop we will have done the | |||
5225 | // runtime check and so interleaving won't require further checks. | |||
5226 | bool InterleavingRequiresRuntimePointerCheck = | |||
5227 | (VF == 1 && Legal->getRuntimePointerChecking()->Need); | |||
5228 | ||||
5229 | // We want to interleave small loops in order to reduce the loop overhead and | |||
5230 | // potentially expose ILP opportunities. | |||
5231 | LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop cost is " << LoopCost << '\n'; } } while (false); | |||
5232 | if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) { | |||
5233 | // We assume that the cost overhead is 1 and we use the cost model | |||
5234 | // to estimate the cost of the loop and interleave until the cost of the | |||
5235 | // loop overhead is about 5% of the cost of the loop. | |||
5236 | unsigned SmallIC = | |||
5237 | std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost)); | |||
5238 | ||||
5239 | // Interleave until store/load ports (estimated by max interleave count) are | |||
5240 | // saturated. | |||
5241 | unsigned NumStores = Legal->getNumStores(); | |||
5242 | unsigned NumLoads = Legal->getNumLoads(); | |||
5243 | unsigned StoresIC = IC / (NumStores ? NumStores : 1); | |||
5244 | unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1); | |||
5245 | ||||
5246 | // If we have a scalar reduction (vector reductions are already dealt with | |||
5247 | // by this point), we can increase the critical path length if the loop | |||
5248 | // we're interleaving is inside another loop. Limit, by default to 2, so the | |||
5249 | // critical path only gets increased by one reduction operation. | |||
5250 | if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) { | |||
5251 | unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC); | |||
5252 | SmallIC = std::min(SmallIC, F); | |||
5253 | StoresIC = std::min(StoresIC, F); | |||
5254 | LoadsIC = std::min(LoadsIC, F); | |||
5255 | } | |||
5256 | ||||
5257 | if (EnableLoadStoreRuntimeInterleave && | |||
5258 | std::max(StoresIC, LoadsIC) > SmallIC) { | |||
5259 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving to saturate store or load ports.\n" ; } } while (false) | |||
5260 | dbgs() << "LV: Interleaving to saturate store or load ports.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving to saturate store or load ports.\n" ; } } while (false); | |||
5261 | return std::max(StoresIC, LoadsIC); | |||
5262 | } | |||
5263 | ||||
5264 | LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving to reduce branch cost.\n" ; } } while (false); | |||
5265 | return SmallIC; | |||
5266 | } | |||
5267 | ||||
5268 | // Interleave if this is a large loop (small loops are already dealt with by | |||
5269 | // this point) that could benefit from interleaving. | |||
5270 | bool HasReductions = !Legal->getReductionVars()->empty(); | |||
5271 | if (TTI.enableAggressiveInterleaving(HasReductions)) { | |||
5272 | LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving to expose ILP.\n" ; } } while (false); | |||
5273 | return IC; | |||
5274 | } | |||
5275 | ||||
5276 | LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not Interleaving.\n" ; } } while (false); | |||
5277 | return 1; | |||
5278 | } | |||
5279 | ||||
5280 | SmallVector<LoopVectorizationCostModel::RegisterUsage, 8> | |||
5281 | LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) { | |||
5282 | // This function calculates the register usage by measuring the highest number | |||
5283 | // of values that are alive at a single location. Obviously, this is a very | |||
5284 | // rough estimation. We scan the loop in a topological order in order and | |||
5285 | // assign a number to each instruction. We use RPO to ensure that defs are | |||
5286 | // met before their users. We assume that each instruction that has in-loop | |||
5287 | // users starts an interval. We record every time that an in-loop value is | |||
5288 | // used, so we have a list of the first and last occurrences of each | |||
5289 | // instruction. Next, we transpose this data structure into a multi map that | |||
5290 | // holds the list of intervals that *end* at a specific location. This multi | |||
5291 | // map allows us to perform a linear search. We scan the instructions linearly | |||
5292 | // and record each time that a new interval starts, by placing it in a set. | |||
5293 | // If we find this value in the multi-map then we remove it from the set. | |||
5294 | // The max register usage is the maximum size of the set. | |||
5295 | // We also search for instructions that are defined outside the loop, but are | |||
5296 | // used inside the loop. We need this number separately from the max-interval | |||
5297 | // usage number because when we unroll, loop-invariant values do not take | |||
5298 | // more register. | |||
5299 | LoopBlocksDFS DFS(TheLoop); | |||
5300 | DFS.perform(LI); | |||
5301 | ||||
5302 | RegisterUsage RU; | |||
5303 | ||||
5304 | // Each 'key' in the map opens a new interval. The values | |||
5305 | // of the map are the index of the 'last seen' usage of the | |||
5306 | // instruction that is the key. | |||
5307 | using IntervalMap = DenseMap<Instruction *, unsigned>; | |||
5308 | ||||
5309 | // Maps instruction to its index. | |||
5310 | DenseMap<unsigned, Instruction *> IdxToInstr; | |||
5311 | // Marks the end of each interval. | |||
5312 | IntervalMap EndPoint; | |||
5313 | // Saves the list of instruction indices that are used in the loop. | |||
5314 | SmallPtrSet<Instruction *, 8> Ends; | |||
5315 | // Saves the list of values that are used in the loop but are | |||
5316 | // defined outside the loop, such as arguments and constants. | |||
5317 | SmallPtrSet<Value *, 8> LoopInvariants; | |||
5318 | ||||
5319 | unsigned Index = 0; | |||
5320 | for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) { | |||
5321 | for (Instruction &I : *BB) { | |||
5322 | IdxToInstr[Index++] = &I; | |||
5323 | ||||
5324 | // Save the end location of each USE. | |||
5325 | for (Value *U : I.operands()) { | |||
5326 | auto *Instr = dyn_cast<Instruction>(U); | |||
5327 | ||||
5328 | // Ignore non-instruction values such as arguments, constants, etc. | |||
5329 | if (!Instr) | |||
5330 | continue; | |||
5331 | ||||
5332 | // If this instruction is outside the loop then record it and continue. | |||
5333 | if (!TheLoop->contains(Instr)) { | |||
5334 | LoopInvariants.insert(Instr); | |||
5335 | continue; | |||
5336 | } | |||
5337 | ||||
5338 | // Overwrite previous end points. | |||
5339 | EndPoint[Instr] = Index; | |||
5340 | Ends.insert(Instr); | |||
5341 | } | |||
5342 | } | |||
5343 | } | |||
5344 | ||||
5345 | // Saves the list of intervals that end with the index in 'key'. | |||
5346 | using InstrList = SmallVector<Instruction *, 2>; | |||
5347 | DenseMap<unsigned, InstrList> TransposeEnds; | |||
5348 | ||||
5349 | // Transpose the EndPoints to a list of values that end at each index. | |||
5350 | for (auto &Interval : EndPoint) | |||
5351 | TransposeEnds[Interval.second].push_back(Interval.first); | |||
5352 | ||||
5353 | SmallPtrSet<Instruction *, 8> OpenIntervals; | |||
5354 | ||||
5355 | // Get the size of the widest register. | |||
5356 | unsigned MaxSafeDepDist = -1U; | |||
5357 | if (Legal->getMaxSafeDepDistBytes() != -1U) | |||
5358 | MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8; | |||
5359 | unsigned WidestRegister = | |||
5360 | std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist); | |||
5361 | const DataLayout &DL = TheFunction->getParent()->getDataLayout(); | |||
5362 | ||||
5363 | SmallVector<RegisterUsage, 8> RUs(VFs.size()); | |||
5364 | SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0); | |||
5365 | ||||
5366 | LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV(REG): Calculating max register usage:\n" ; } } while (false); | |||
5367 | ||||
5368 | // A lambda that gets the register usage for the given type and VF. | |||
5369 | auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) { | |||
5370 | if (Ty->isTokenTy()) | |||
5371 | return 0U; | |||
5372 | unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType()); | |||
5373 | return std::max<unsigned>(1, VF * TypeSize / WidestRegister); | |||
5374 | }; | |||
5375 | ||||
5376 | for (unsigned int i = 0; i < Index; ++i) { | |||
5377 | Instruction *I = IdxToInstr[i]; | |||
5378 | ||||
5379 | // Remove all of the instructions that end at this location. | |||
5380 | InstrList &List = TransposeEnds[i]; | |||
5381 | for (Instruction *ToRemove : List) | |||
5382 | OpenIntervals.erase(ToRemove); | |||
5383 | ||||
5384 | // Ignore instructions that are never used within the loop. | |||
5385 | if (!Ends.count(I)) | |||
5386 | continue; | |||
5387 | ||||
5388 | // Skip ignored values. | |||
5389 | if (ValuesToIgnore.count(I)) | |||
5390 | continue; | |||
5391 | ||||
5392 | // For each VF find the maximum usage of registers. | |||
5393 | for (unsigned j = 0, e = VFs.size(); j < e; ++j) { | |||
5394 | if (VFs[j] == 1) { | |||
5395 | MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size()); | |||
5396 | continue; | |||
5397 | } | |||
5398 | collectUniformsAndScalars(VFs[j]); | |||
5399 | // Count the number of live intervals. | |||
5400 | unsigned RegUsage = 0; | |||
5401 | for (auto Inst : OpenIntervals) { | |||
5402 | // Skip ignored values for VF > 1. | |||
5403 | if (VecValuesToIgnore.count(Inst) || | |||
5404 | isScalarAfterVectorization(Inst, VFs[j])) | |||
5405 | continue; | |||
5406 | RegUsage += GetRegUsage(Inst->getType(), VFs[j]); | |||
5407 | } | |||
5408 | MaxUsages[j] = std::max(MaxUsages[j], RegUsage); | |||
5409 | } | |||
5410 | ||||
5411 | LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV(REG): At #" << i << " Interval # " << OpenIntervals.size() << '\n'; } } while (false) | |||
5412 | << OpenIntervals.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV(REG): At #" << i << " Interval # " << OpenIntervals.size() << '\n'; } } while (false); | |||
5413 | ||||
5414 | // Add the current instruction to the list of open intervals. | |||
5415 | OpenIntervals.insert(I); | |||
5416 | } | |||
5417 | ||||
5418 | for (unsigned i = 0, e = VFs.size(); i < e; ++i) { | |||
5419 | unsigned Invariant = 0; | |||
5420 | if (VFs[i] == 1) | |||
5421 | Invariant = LoopInvariants.size(); | |||
5422 | else { | |||
5423 | for (auto Inst : LoopInvariants) | |||
5424 | Invariant += GetRegUsage(Inst->getType(), VFs[i]); | |||
5425 | } | |||
5426 | ||||
5427 | LLVM_DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV(REG): VF = " << VFs[i] << '\n'; } } while (false); | |||
5428 | LLVM_DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n'; } } while (false); | |||
5429 | LLVM_DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariantdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n'; } } while (false) | |||
5430 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n'; } } while (false); | |||
5431 | ||||
5432 | RU.LoopInvariantRegs = Invariant; | |||
5433 | RU.MaxLocalUsers = MaxUsages[i]; | |||
5434 | RUs[i] = RU; | |||
5435 | } | |||
5436 | ||||
5437 | return RUs; | |||
5438 | } | |||
5439 | ||||
5440 | bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){ | |||
5441 | // TODO: Cost model for emulated masked load/store is completely | |||
5442 | // broken. This hack guides the cost model to use an artificially | |||
5443 | // high enough value to practically disable vectorization with such | |||
5444 | // operations, except where previously deployed legality hack allowed | |||
5445 | // using very low cost values. This is to avoid regressions coming simply | |||
5446 | // from moving "masked load/store" check from legality to cost model. | |||
5447 | // Masked Load/Gather emulation was previously never allowed. | |||
5448 | // Limited number of Masked Store/Scatter emulation was allowed. | |||
5449 | assert(isScalarWithPredication(I) &&(static_cast <bool> (isScalarWithPredication(I) && "Expecting a scalar emulated instruction") ? void (0) : __assert_fail ("isScalarWithPredication(I) && \"Expecting a scalar emulated instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5450, __extension__ __PRETTY_FUNCTION__)) | |||
5450 | "Expecting a scalar emulated instruction")(static_cast <bool> (isScalarWithPredication(I) && "Expecting a scalar emulated instruction") ? void (0) : __assert_fail ("isScalarWithPredication(I) && \"Expecting a scalar emulated instruction\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5450, __extension__ __PRETTY_FUNCTION__)); | |||
5451 | return isa<LoadInst>(I) || | |||
5452 | (isa<StoreInst>(I) && | |||
5453 | NumPredStores > NumberOfStoresToPredicate); | |||
5454 | } | |||
5455 | ||||
5456 | void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) { | |||
5457 | // If we aren't vectorizing the loop, or if we've already collected the | |||
5458 | // instructions to scalarize, there's nothing to do. Collection may already | |||
5459 | // have occurred if we have a user-selected VF and are now computing the | |||
5460 | // expected cost for interleaving. | |||
5461 | if (VF < 2 || InstsToScalarize.count(VF)) | |||
5462 | return; | |||
5463 | ||||
5464 | // Initialize a mapping for VF in InstsToScalalarize. If we find that it's | |||
5465 | // not profitable to scalarize any instructions, the presence of VF in the | |||
5466 | // map will indicate that we've analyzed it already. | |||
5467 | ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF]; | |||
5468 | ||||
5469 | // Find all the instructions that are scalar with predication in the loop and | |||
5470 | // determine if it would be better to not if-convert the blocks they are in. | |||
5471 | // If so, we also record the instructions to scalarize. | |||
5472 | for (BasicBlock *BB : TheLoop->blocks()) { | |||
5473 | if (!Legal->blockNeedsPredication(BB)) | |||
5474 | continue; | |||
5475 | for (Instruction &I : *BB) | |||
5476 | if (isScalarWithPredication(&I)) { | |||
5477 | ScalarCostsTy ScalarCosts; | |||
5478 | // Do not apply discount logic if hacked cost is needed | |||
5479 | // for emulated masked memrefs. | |||
5480 | if (!useEmulatedMaskMemRefHack(&I) && | |||
5481 | computePredInstDiscount(&I, ScalarCosts, VF) >= 0) | |||
5482 | ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end()); | |||
5483 | // Remember that BB will remain after vectorization. | |||
5484 | PredicatedBBsAfterVectorization.insert(BB); | |||
5485 | } | |||
5486 | } | |||
5487 | } | |||
5488 | ||||
5489 | int LoopVectorizationCostModel::computePredInstDiscount( | |||
5490 | Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts, | |||
5491 | unsigned VF) { | |||
5492 | assert(!isUniformAfterVectorization(PredInst, VF) &&(static_cast <bool> (!isUniformAfterVectorization(PredInst , VF) && "Instruction marked uniform-after-vectorization will be predicated" ) ? void (0) : __assert_fail ("!isUniformAfterVectorization(PredInst, VF) && \"Instruction marked uniform-after-vectorization will be predicated\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5493, __extension__ __PRETTY_FUNCTION__)) | |||
5493 | "Instruction marked uniform-after-vectorization will be predicated")(static_cast <bool> (!isUniformAfterVectorization(PredInst , VF) && "Instruction marked uniform-after-vectorization will be predicated" ) ? void (0) : __assert_fail ("!isUniformAfterVectorization(PredInst, VF) && \"Instruction marked uniform-after-vectorization will be predicated\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5493, __extension__ __PRETTY_FUNCTION__)); | |||
5494 | ||||
5495 | // Initialize the discount to zero, meaning that the scalar version and the | |||
5496 | // vector version cost the same. | |||
5497 | int Discount = 0; | |||
5498 | ||||
5499 | // Holds instructions to analyze. The instructions we visit are mapped in | |||
5500 | // ScalarCosts. Those instructions are the ones that would be scalarized if | |||
5501 | // we find that the scalar version costs less. | |||
5502 | SmallVector<Instruction *, 8> Worklist; | |||
5503 | ||||
5504 | // Returns true if the given instruction can be scalarized. | |||
5505 | auto canBeScalarized = [&](Instruction *I) -> bool { | |||
5506 | // We only attempt to scalarize instructions forming a single-use chain | |||
5507 | // from the original predicated block that would otherwise be vectorized. | |||
5508 | // Although not strictly necessary, we give up on instructions we know will | |||
5509 | // already be scalar to avoid traversing chains that are unlikely to be | |||
5510 | // beneficial. | |||
5511 | if (!I->hasOneUse() || PredInst->getParent() != I->getParent() || | |||
5512 | isScalarAfterVectorization(I, VF)) | |||
5513 | return false; | |||
5514 | ||||
5515 | // If the instruction is scalar with predication, it will be analyzed | |||
5516 | // separately. We ignore it within the context of PredInst. | |||
5517 | if (isScalarWithPredication(I)) | |||
5518 | return false; | |||
5519 | ||||
5520 | // If any of the instruction's operands are uniform after vectorization, | |||
5521 | // the instruction cannot be scalarized. This prevents, for example, a | |||
5522 | // masked load from being scalarized. | |||
5523 | // | |||
5524 | // We assume we will only emit a value for lane zero of an instruction | |||
5525 | // marked uniform after vectorization, rather than VF identical values. | |||
5526 | // Thus, if we scalarize an instruction that uses a uniform, we would | |||
5527 | // create uses of values corresponding to the lanes we aren't emitting code | |||
5528 | // for. This behavior can be changed by allowing getScalarValue to clone | |||
5529 | // the lane zero values for uniforms rather than asserting. | |||
5530 | for (Use &U : I->operands()) | |||
5531 | if (auto *J = dyn_cast<Instruction>(U.get())) | |||
5532 | if (isUniformAfterVectorization(J, VF)) | |||
5533 | return false; | |||
5534 | ||||
5535 | // Otherwise, we can scalarize the instruction. | |||
5536 | return true; | |||
5537 | }; | |||
5538 | ||||
5539 | // Returns true if an operand that cannot be scalarized must be extracted | |||
5540 | // from a vector. We will account for this scalarization overhead below. Note | |||
5541 | // that the non-void predicated instructions are placed in their own blocks, | |||
5542 | // and their return values are inserted into vectors. Thus, an extract would | |||
5543 | // still be required. | |||
5544 | auto needsExtract = [&](Instruction *I) -> bool { | |||
5545 | return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF); | |||
5546 | }; | |||
5547 | ||||
5548 | // Compute the expected cost discount from scalarizing the entire expression | |||
5549 | // feeding the predicated instruction. We currently only consider expressions | |||
5550 | // that are single-use instruction chains. | |||
5551 | Worklist.push_back(PredInst); | |||
5552 | while (!Worklist.empty()) { | |||
5553 | Instruction *I = Worklist.pop_back_val(); | |||
5554 | ||||
5555 | // If we've already analyzed the instruction, there's nothing to do. | |||
5556 | if (ScalarCosts.count(I)) | |||
5557 | continue; | |||
5558 | ||||
5559 | // Compute the cost of the vector instruction. Note that this cost already | |||
5560 | // includes the scalarization overhead of the predicated instruction. | |||
5561 | unsigned VectorCost = getInstructionCost(I, VF).first; | |||
5562 | ||||
5563 | // Compute the cost of the scalarized instruction. This cost is the cost of | |||
5564 | // the instruction as if it wasn't if-converted and instead remained in the | |||
5565 | // predicated block. We will scale this cost by block probability after | |||
5566 | // computing the scalarization overhead. | |||
5567 | unsigned ScalarCost = VF * getInstructionCost(I, 1).first; | |||
5568 | ||||
5569 | // Compute the scalarization overhead of needed insertelement instructions | |||
5570 | // and phi nodes. | |||
5571 | if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) { | |||
5572 | ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF), | |||
5573 | true, false); | |||
5574 | ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI); | |||
5575 | } | |||
5576 | ||||
5577 | // Compute the scalarization overhead of needed extractelement | |||
5578 | // instructions. For each of the instruction's operands, if the operand can | |||
5579 | // be scalarized, add it to the worklist; otherwise, account for the | |||
5580 | // overhead. | |||
5581 | for (Use &U : I->operands()) | |||
5582 | if (auto *J = dyn_cast<Instruction>(U.get())) { | |||
5583 | assert(VectorType::isValidElementType(J->getType()) &&(static_cast <bool> (VectorType::isValidElementType(J-> getType()) && "Instruction has non-scalar type") ? void (0) : __assert_fail ("VectorType::isValidElementType(J->getType()) && \"Instruction has non-scalar type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5584, __extension__ __PRETTY_FUNCTION__)) | |||
5584 | "Instruction has non-scalar type")(static_cast <bool> (VectorType::isValidElementType(J-> getType()) && "Instruction has non-scalar type") ? void (0) : __assert_fail ("VectorType::isValidElementType(J->getType()) && \"Instruction has non-scalar type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5584, __extension__ __PRETTY_FUNCTION__)); | |||
5585 | if (canBeScalarized(J)) | |||
5586 | Worklist.push_back(J); | |||
5587 | else if (needsExtract(J)) | |||
5588 | ScalarCost += TTI.getScalarizationOverhead( | |||
5589 | ToVectorTy(J->getType(),VF), false, true); | |||
5590 | } | |||
5591 | ||||
5592 | // Scale the total scalar cost by block probability. | |||
5593 | ScalarCost /= getReciprocalPredBlockProb(); | |||
5594 | ||||
5595 | // Compute the discount. A non-negative discount means the vector version | |||
5596 | // of the instruction costs more, and scalarizing would be beneficial. | |||
5597 | Discount += VectorCost - ScalarCost; | |||
5598 | ScalarCosts[I] = ScalarCost; | |||
5599 | } | |||
5600 | ||||
5601 | return Discount; | |||
5602 | } | |||
5603 | ||||
5604 | LoopVectorizationCostModel::VectorizationCostTy | |||
5605 | LoopVectorizationCostModel::expectedCost(unsigned VF) { | |||
5606 | VectorizationCostTy Cost; | |||
5607 | ||||
5608 | // For each block. | |||
5609 | for (BasicBlock *BB : TheLoop->blocks()) { | |||
5610 | VectorizationCostTy BlockCost; | |||
5611 | ||||
5612 | // For each instruction in the old loop. | |||
5613 | for (Instruction &I : BB->instructionsWithoutDebug()) { | |||
5614 | // Skip ignored values. | |||
5615 | if (ValuesToIgnore.count(&I) || | |||
5616 | (VF > 1 && VecValuesToIgnore.count(&I))) | |||
5617 | continue; | |||
5618 | ||||
5619 | VectorizationCostTy C = getInstructionCost(&I, VF); | |||
5620 | ||||
5621 | // Check if we should override the cost. | |||
5622 | if (ForceTargetInstructionCost.getNumOccurrences() > 0) | |||
5623 | C.first = ForceTargetInstructionCost; | |||
5624 | ||||
5625 | BlockCost.first += C.first; | |||
5626 | BlockCost.second |= C.second; | |||
5627 | LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.firstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found an estimated cost of " << C.first << " for VF " << VF << " For instruction: " << I << '\n'; } } while (false) | |||
5628 | << " for VF " << VF << " For instruction: " << Ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found an estimated cost of " << C.first << " for VF " << VF << " For instruction: " << I << '\n'; } } while (false) | |||
5629 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found an estimated cost of " << C.first << " for VF " << VF << " For instruction: " << I << '\n'; } } while (false); | |||
5630 | } | |||
5631 | ||||
5632 | // If we are vectorizing a predicated block, it will have been | |||
5633 | // if-converted. This means that the block's instructions (aside from | |||
5634 | // stores and instructions that may divide by zero) will now be | |||
5635 | // unconditionally executed. For the scalar case, we may not always execute | |||
5636 | // the predicated block. Thus, scale the block's cost by the probability of | |||
5637 | // executing it. | |||
5638 | if (VF == 1 && Legal->blockNeedsPredication(BB)) | |||
5639 | BlockCost.first /= getReciprocalPredBlockProb(); | |||
5640 | ||||
5641 | Cost.first += BlockCost.first; | |||
5642 | Cost.second |= BlockCost.second; | |||
5643 | } | |||
5644 | ||||
5645 | return Cost; | |||
5646 | } | |||
5647 | ||||
5648 | /// Gets Address Access SCEV after verifying that the access pattern | |||
5649 | /// is loop invariant except the induction variable dependence. | |||
5650 | /// | |||
5651 | /// This SCEV can be sent to the Target in order to estimate the address | |||
5652 | /// calculation cost. | |||
5653 | static const SCEV *getAddressAccessSCEV( | |||
5654 | Value *Ptr, | |||
5655 | LoopVectorizationLegality *Legal, | |||
5656 | PredicatedScalarEvolution &PSE, | |||
5657 | const Loop *TheLoop) { | |||
5658 | ||||
5659 | auto *Gep = dyn_cast<GetElementPtrInst>(Ptr); | |||
5660 | if (!Gep) | |||
5661 | return nullptr; | |||
5662 | ||||
5663 | // We are looking for a gep with all loop invariant indices except for one | |||
5664 | // which should be an induction variable. | |||
5665 | auto SE = PSE.getSE(); | |||
5666 | unsigned NumOperands = Gep->getNumOperands(); | |||
5667 | for (unsigned i = 1; i < NumOperands; ++i) { | |||
5668 | Value *Opd = Gep->getOperand(i); | |||
5669 | if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) && | |||
5670 | !Legal->isInductionVariable(Opd)) | |||
5671 | return nullptr; | |||
5672 | } | |||
5673 | ||||
5674 | // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV. | |||
5675 | return PSE.getSCEV(Ptr); | |||
5676 | } | |||
5677 | ||||
5678 | static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) { | |||
5679 | return Legal->hasStride(I->getOperand(0)) || | |||
5680 | Legal->hasStride(I->getOperand(1)); | |||
5681 | } | |||
5682 | ||||
5683 | unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I, | |||
5684 | unsigned VF) { | |||
5685 | Type *ValTy = getMemInstValueType(I); | |||
5686 | auto SE = PSE.getSE(); | |||
5687 | ||||
5688 | unsigned Alignment = getMemInstAlignment(I); | |||
5689 | unsigned AS = getMemInstAddressSpace(I); | |||
5690 | Value *Ptr = getLoadStorePointerOperand(I); | |||
5691 | Type *PtrTy = ToVectorTy(Ptr->getType(), VF); | |||
5692 | ||||
5693 | // Figure out whether the access is strided and get the stride value | |||
5694 | // if it's known in compile time | |||
5695 | const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop); | |||
5696 | ||||
5697 | // Get the cost of the scalar memory instruction and address computation. | |||
5698 | unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV); | |||
5699 | ||||
5700 | Cost += VF * | |||
5701 | TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment, | |||
5702 | AS, I); | |||
5703 | ||||
5704 | // Get the overhead of the extractelement and insertelement instructions | |||
5705 | // we might create due to scalarization. | |||
5706 | Cost += getScalarizationOverhead(I, VF, TTI); | |||
5707 | ||||
5708 | // If we have a predicated store, it may not be executed for each vector | |||
5709 | // lane. Scale the cost by the probability of executing the predicated | |||
5710 | // block. | |||
5711 | if (isScalarWithPredication(I)) { | |||
5712 | Cost /= getReciprocalPredBlockProb(); | |||
5713 | ||||
5714 | if (useEmulatedMaskMemRefHack(I)) | |||
5715 | // Artificially setting to a high enough value to practically disable | |||
5716 | // vectorization with such operations. | |||
5717 | Cost = 3000000; | |||
5718 | } | |||
5719 | ||||
5720 | return Cost; | |||
5721 | } | |||
5722 | ||||
5723 | unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I, | |||
5724 | unsigned VF) { | |||
5725 | Type *ValTy = getMemInstValueType(I); | |||
5726 | Type *VectorTy = ToVectorTy(ValTy, VF); | |||
5727 | unsigned Alignment = getMemInstAlignment(I); | |||
5728 | Value *Ptr = getLoadStorePointerOperand(I); | |||
5729 | unsigned AS = getMemInstAddressSpace(I); | |||
5730 | int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); | |||
5731 | ||||
5732 | assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride == -1) && "Stride should be 1 or -1 for consecutive memory access" ) ? void (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Stride should be 1 or -1 for consecutive memory access\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5733, __extension__ __PRETTY_FUNCTION__)) | |||
5733 | "Stride should be 1 or -1 for consecutive memory access")(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride == -1) && "Stride should be 1 or -1 for consecutive memory access" ) ? void (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Stride should be 1 or -1 for consecutive memory access\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5733, __extension__ __PRETTY_FUNCTION__)); | |||
5734 | unsigned Cost = 0; | |||
5735 | if (Legal->isMaskRequired(I)) | |||
5736 | Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); | |||
5737 | else | |||
5738 | Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I); | |||
5739 | ||||
5740 | bool Reverse = ConsecutiveStride < 0; | |||
5741 | if (Reverse) | |||
5742 | Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); | |||
5743 | return Cost; | |||
5744 | } | |||
5745 | ||||
5746 | unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I, | |||
5747 | unsigned VF) { | |||
5748 | LoadInst *LI = cast<LoadInst>(I); | |||
5749 | Type *ValTy = LI->getType(); | |||
5750 | Type *VectorTy = ToVectorTy(ValTy, VF); | |||
5751 | unsigned Alignment = LI->getAlignment(); | |||
5752 | unsigned AS = LI->getPointerAddressSpace(); | |||
5753 | ||||
5754 | return TTI.getAddressComputationCost(ValTy) + | |||
5755 | TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) + | |||
5756 | TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy); | |||
5757 | } | |||
5758 | ||||
5759 | unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I, | |||
5760 | unsigned VF) { | |||
5761 | Type *ValTy = getMemInstValueType(I); | |||
5762 | Type *VectorTy = ToVectorTy(ValTy, VF); | |||
5763 | unsigned Alignment = getMemInstAlignment(I); | |||
5764 | Value *Ptr = getLoadStorePointerOperand(I); | |||
5765 | ||||
5766 | return TTI.getAddressComputationCost(VectorTy) + | |||
5767 | TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr, | |||
5768 | Legal->isMaskRequired(I), Alignment); | |||
5769 | } | |||
5770 | ||||
5771 | unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I, | |||
5772 | unsigned VF) { | |||
5773 | Type *ValTy = getMemInstValueType(I); | |||
5774 | Type *VectorTy = ToVectorTy(ValTy, VF); | |||
5775 | unsigned AS = getMemInstAddressSpace(I); | |||
5776 | ||||
5777 | auto Group = getInterleavedAccessGroup(I); | |||
5778 | assert(Group && "Fail to get an interleaved access group.")(static_cast <bool> (Group && "Fail to get an interleaved access group." ) ? void (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5778, __extension__ __PRETTY_FUNCTION__)); | |||
5779 | ||||
5780 | unsigned InterleaveFactor = Group->getFactor(); | |||
5781 | Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor); | |||
5782 | ||||
5783 | // Holds the indices of existing members in an interleaved load group. | |||
5784 | // An interleaved store group doesn't need this as it doesn't allow gaps. | |||
5785 | SmallVector<unsigned, 4> Indices; | |||
5786 | if (isa<LoadInst>(I)) { | |||
5787 | for (unsigned i = 0; i < InterleaveFactor; i++) | |||
5788 | if (Group->getMember(i)) | |||
5789 | Indices.push_back(i); | |||
5790 | } | |||
5791 | ||||
5792 | // Calculate the cost of the whole interleaved group. | |||
5793 | unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy, | |||
5794 | Group->getFactor(), Indices, | |||
5795 | Group->getAlignment(), AS); | |||
5796 | ||||
5797 | if (Group->isReverse()) | |||
5798 | Cost += Group->getNumMembers() * | |||
5799 | TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); | |||
5800 | return Cost; | |||
5801 | } | |||
5802 | ||||
5803 | unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I, | |||
5804 | unsigned VF) { | |||
5805 | // Calculate scalar cost only. Vectorization cost should be ready at this | |||
5806 | // moment. | |||
5807 | if (VF == 1) { | |||
5808 | Type *ValTy = getMemInstValueType(I); | |||
5809 | unsigned Alignment = getMemInstAlignment(I); | |||
5810 | unsigned AS = getMemInstAddressSpace(I); | |||
5811 | ||||
5812 | return TTI.getAddressComputationCost(ValTy) + | |||
5813 | TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I); | |||
5814 | } | |||
5815 | return getWideningCost(I, VF); | |||
5816 | } | |||
5817 | ||||
5818 | LoopVectorizationCostModel::VectorizationCostTy | |||
5819 | LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { | |||
5820 | // If we know that this instruction will remain uniform, check the cost of | |||
5821 | // the scalar version. | |||
5822 | if (isUniformAfterVectorization(I, VF)) | |||
5823 | VF = 1; | |||
5824 | ||||
5825 | if (VF > 1 && isProfitableToScalarize(I, VF)) | |||
5826 | return VectorizationCostTy(InstsToScalarize[VF][I], false); | |||
5827 | ||||
5828 | // Forced scalars do not have any scalarization overhead. | |||
5829 | if (VF > 1 && ForcedScalars.count(VF) && | |||
5830 | ForcedScalars.find(VF)->second.count(I)) | |||
5831 | return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false); | |||
5832 | ||||
5833 | Type *VectorTy; | |||
5834 | unsigned C = getInstructionCost(I, VF, VectorTy); | |||
5835 | ||||
5836 | bool TypeNotScalarized = | |||
5837 | VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF; | |||
5838 | return VectorizationCostTy(C, TypeNotScalarized); | |||
5839 | } | |||
5840 | ||||
5841 | void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) { | |||
5842 | if (VF == 1) | |||
5843 | return; | |||
5844 | NumPredStores = 0; | |||
5845 | for (BasicBlock *BB : TheLoop->blocks()) { | |||
5846 | // For each instruction in the old loop. | |||
5847 | for (Instruction &I : *BB) { | |||
5848 | Value *Ptr = getLoadStorePointerOperand(&I); | |||
5849 | if (!Ptr) | |||
5850 | continue; | |||
5851 | ||||
5852 | if (isa<StoreInst>(&I) && isScalarWithPredication(&I)) | |||
5853 | NumPredStores++; | |||
5854 | if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) { | |||
5855 | // Scalar load + broadcast | |||
5856 | unsigned Cost = getUniformMemOpCost(&I, VF); | |||
5857 | setWideningDecision(&I, VF, CM_Scalarize, Cost); | |||
5858 | continue; | |||
5859 | } | |||
5860 | ||||
5861 | // We assume that widening is the best solution when possible. | |||
5862 | if (memoryInstructionCanBeWidened(&I, VF)) { | |||
5863 | unsigned Cost = getConsecutiveMemOpCost(&I, VF); | |||
5864 | int ConsecutiveStride = | |||
5865 | Legal->isConsecutivePtr(getLoadStorePointerOperand(&I)); | |||
5866 | assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride == -1) && "Expected consecutive stride.") ? void (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Expected consecutive stride.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5867, __extension__ __PRETTY_FUNCTION__)) | |||
5867 | "Expected consecutive stride.")(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride == -1) && "Expected consecutive stride.") ? void (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Expected consecutive stride.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5867, __extension__ __PRETTY_FUNCTION__)); | |||
5868 | InstWidening Decision = | |||
5869 | ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse; | |||
5870 | setWideningDecision(&I, VF, Decision, Cost); | |||
5871 | continue; | |||
5872 | } | |||
5873 | ||||
5874 | // Choose between Interleaving, Gather/Scatter or Scalarization. | |||
5875 | unsigned InterleaveCost = std::numeric_limits<unsigned>::max(); | |||
5876 | unsigned NumAccesses = 1; | |||
5877 | if (isAccessInterleaved(&I)) { | |||
5878 | auto Group = getInterleavedAccessGroup(&I); | |||
5879 | assert(Group && "Fail to get an interleaved access group.")(static_cast <bool> (Group && "Fail to get an interleaved access group." ) ? void (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 5879, __extension__ __PRETTY_FUNCTION__)); | |||
5880 | ||||
5881 | // Make one decision for the whole group. | |||
5882 | if (getWideningDecision(&I, VF) != CM_Unknown) | |||
5883 | continue; | |||
5884 | ||||
5885 | NumAccesses = Group->getNumMembers(); | |||
5886 | InterleaveCost = getInterleaveGroupCost(&I, VF); | |||
5887 | } | |||
5888 | ||||
5889 | unsigned GatherScatterCost = | |||
5890 | isLegalGatherOrScatter(&I) | |||
5891 | ? getGatherScatterCost(&I, VF) * NumAccesses | |||
5892 | : std::numeric_limits<unsigned>::max(); | |||
5893 | ||||
5894 | unsigned ScalarizationCost = | |||
5895 | getMemInstScalarizationCost(&I, VF) * NumAccesses; | |||
5896 | ||||
5897 | // Choose better solution for the current VF, | |||
5898 | // write down this decision and use it during vectorization. | |||
5899 | unsigned Cost; | |||
5900 | InstWidening Decision; | |||
5901 | if (InterleaveCost <= GatherScatterCost && | |||
5902 | InterleaveCost < ScalarizationCost) { | |||
5903 | Decision = CM_Interleave; | |||
5904 | Cost = InterleaveCost; | |||
5905 | } else if (GatherScatterCost < ScalarizationCost) { | |||
5906 | Decision = CM_GatherScatter; | |||
5907 | Cost = GatherScatterCost; | |||
5908 | } else { | |||
5909 | Decision = CM_Scalarize; | |||
5910 | Cost = ScalarizationCost; | |||
5911 | } | |||
5912 | // If the instructions belongs to an interleave group, the whole group | |||
5913 | // receives the same decision. The whole group receives the cost, but | |||
5914 | // the cost will actually be assigned to one instruction. | |||
5915 | if (auto Group = getInterleavedAccessGroup(&I)) | |||
5916 | setWideningDecision(Group, VF, Decision, Cost); | |||
5917 | else | |||
5918 | setWideningDecision(&I, VF, Decision, Cost); | |||
5919 | } | |||
5920 | } | |||
5921 | ||||
5922 | // Make sure that any load of address and any other address computation | |||
5923 | // remains scalar unless there is gather/scatter support. This avoids | |||
5924 | // inevitable extracts into address registers, and also has the benefit of | |||
5925 | // activating LSR more, since that pass can't optimize vectorized | |||
5926 | // addresses. | |||
5927 | if (TTI.prefersVectorizedAddressing()) | |||
5928 | return; | |||
5929 | ||||
5930 | // Start with all scalar pointer uses. | |||
5931 | SmallPtrSet<Instruction *, 8> AddrDefs; | |||
5932 | for (BasicBlock *BB : TheLoop->blocks()) | |||
5933 | for (Instruction &I : *BB) { | |||
5934 | Instruction *PtrDef = | |||
5935 | dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I)); | |||
5936 | if (PtrDef && TheLoop->contains(PtrDef) && | |||
5937 | getWideningDecision(&I, VF) != CM_GatherScatter) | |||
5938 | AddrDefs.insert(PtrDef); | |||
5939 | } | |||
5940 | ||||
5941 | // Add all instructions used to generate the addresses. | |||
5942 | SmallVector<Instruction *, 4> Worklist; | |||
5943 | for (auto *I : AddrDefs) | |||
5944 | Worklist.push_back(I); | |||
5945 | while (!Worklist.empty()) { | |||
5946 | Instruction *I = Worklist.pop_back_val(); | |||
5947 | for (auto &Op : I->operands()) | |||
5948 | if (auto *InstOp = dyn_cast<Instruction>(Op)) | |||
5949 | if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) && | |||
5950 | AddrDefs.insert(InstOp).second) | |||
5951 | Worklist.push_back(InstOp); | |||
5952 | } | |||
5953 | ||||
5954 | for (auto *I : AddrDefs) { | |||
5955 | if (isa<LoadInst>(I)) { | |||
5956 | // Setting the desired widening decision should ideally be handled in | |||
5957 | // by cost functions, but since this involves the task of finding out | |||
5958 | // if the loaded register is involved in an address computation, it is | |||
5959 | // instead changed here when we know this is the case. | |||
5960 | InstWidening Decision = getWideningDecision(I, VF); | |||
5961 | if (Decision == CM_Widen || Decision == CM_Widen_Reverse) | |||
5962 | // Scalarize a widened load of address. | |||
5963 | setWideningDecision(I, VF, CM_Scalarize, | |||
5964 | (VF * getMemoryInstructionCost(I, 1))); | |||
5965 | else if (auto Group = getInterleavedAccessGroup(I)) { | |||
5966 | // Scalarize an interleave group of address loads. | |||
5967 | for (unsigned I = 0; I < Group->getFactor(); ++I) { | |||
5968 | if (Instruction *Member = Group->getMember(I)) | |||
5969 | setWideningDecision(Member, VF, CM_Scalarize, | |||
5970 | (VF * getMemoryInstructionCost(Member, 1))); | |||
5971 | } | |||
5972 | } | |||
5973 | } else | |||
5974 | // Make sure I gets scalarized and a cost estimate without | |||
5975 | // scalarization overhead. | |||
5976 | ForcedScalars[VF].insert(I); | |||
5977 | } | |||
5978 | } | |||
5979 | ||||
5980 | unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I, | |||
5981 | unsigned VF, | |||
5982 | Type *&VectorTy) { | |||
5983 | Type *RetTy = I->getType(); | |||
5984 | if (canTruncateToMinimalBitwidth(I, VF)) | |||
5985 | RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]); | |||
5986 | VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF); | |||
5987 | auto SE = PSE.getSE(); | |||
5988 | ||||
5989 | // TODO: We need to estimate the cost of intrinsic calls. | |||
5990 | switch (I->getOpcode()) { | |||
5991 | case Instruction::GetElementPtr: | |||
5992 | // We mark this instruction as zero-cost because the cost of GEPs in | |||
5993 | // vectorized code depends on whether the corresponding memory instruction | |||
5994 | // is scalarized or not. Therefore, we handle GEPs with the memory | |||
5995 | // instruction cost. | |||
5996 | return 0; | |||
5997 | case Instruction::Br: { | |||
5998 | // In cases of scalarized and predicated instructions, there will be VF | |||
5999 | // predicated blocks in the vectorized loop. Each branch around these | |||
6000 | // blocks requires also an extract of its vector compare i1 element. | |||
6001 | bool ScalarPredicatedBB = false; | |||
6002 | BranchInst *BI = cast<BranchInst>(I); | |||
6003 | if (VF > 1 && BI->isConditional() && | |||
6004 | (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) || | |||
6005 | PredicatedBBsAfterVectorization.count(BI->getSuccessor(1)))) | |||
6006 | ScalarPredicatedBB = true; | |||
6007 | ||||
6008 | if (ScalarPredicatedBB) { | |||
6009 | // Return cost for branches around scalarized and predicated blocks. | |||
6010 | Type *Vec_i1Ty = | |||
6011 | VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF); | |||
6012 | return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) + | |||
6013 | (TTI.getCFInstrCost(Instruction::Br) * VF)); | |||
6014 | } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1) | |||
6015 | // The back-edge branch will remain, as will all scalar branches. | |||
6016 | return TTI.getCFInstrCost(Instruction::Br); | |||
6017 | else | |||
6018 | // This branch will be eliminated by if-conversion. | |||
6019 | return 0; | |||
6020 | // Note: We currently assume zero cost for an unconditional branch inside | |||
6021 | // a predicated block since it will become a fall-through, although we | |||
6022 | // may decide in the future to call TTI for all branches. | |||
6023 | } | |||
6024 | case Instruction::PHI: { | |||
6025 | auto *Phi = cast<PHINode>(I); | |||
6026 | ||||
6027 | // First-order recurrences are replaced by vector shuffles inside the loop. | |||
6028 | if (VF > 1 && Legal->isFirstOrderRecurrence(Phi)) | |||
6029 | return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, | |||
6030 | VectorTy, VF - 1, VectorTy); | |||
6031 | ||||
6032 | // Phi nodes in non-header blocks (not inductions, reductions, etc.) are | |||
6033 | // converted into select instructions. We require N - 1 selects per phi | |||
6034 | // node, where N is the number of incoming values. | |||
6035 | if (VF > 1 && Phi->getParent() != TheLoop->getHeader()) | |||
6036 | return (Phi->getNumIncomingValues() - 1) * | |||
6037 | TTI.getCmpSelInstrCost( | |||
6038 | Instruction::Select, ToVectorTy(Phi->getType(), VF), | |||
6039 | ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF)); | |||
6040 | ||||
6041 | return TTI.getCFInstrCost(Instruction::PHI); | |||
6042 | } | |||
6043 | case Instruction::UDiv: | |||
6044 | case Instruction::SDiv: | |||
6045 | case Instruction::URem: | |||
6046 | case Instruction::SRem: | |||
6047 | // If we have a predicated instruction, it may not be executed for each | |||
6048 | // vector lane. Get the scalarization cost and scale this amount by the | |||
6049 | // probability of executing the predicated block. If the instruction is not | |||
6050 | // predicated, we fall through to the next case. | |||
6051 | if (VF > 1 && isScalarWithPredication(I)) { | |||
6052 | unsigned Cost = 0; | |||
6053 | ||||
6054 | // These instructions have a non-void type, so account for the phi nodes | |||
6055 | // that we will create. This cost is likely to be zero. The phi node | |||
6056 | // cost, if any, should be scaled by the block probability because it | |||
6057 | // models a copy at the end of each predicated block. | |||
6058 | Cost += VF * TTI.getCFInstrCost(Instruction::PHI); | |||
6059 | ||||
6060 | // The cost of the non-predicated instruction. | |||
6061 | Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy); | |||
6062 | ||||
6063 | // The cost of insertelement and extractelement instructions needed for | |||
6064 | // scalarization. | |||
6065 | Cost += getScalarizationOverhead(I, VF, TTI); | |||
6066 | ||||
6067 | // Scale the cost by the probability of executing the predicated blocks. | |||
6068 | // This assumes the predicated block for each vector lane is equally | |||
6069 | // likely. | |||
6070 | return Cost / getReciprocalPredBlockProb(); | |||
6071 | } | |||
6072 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
6073 | case Instruction::Add: | |||
6074 | case Instruction::FAdd: | |||
6075 | case Instruction::Sub: | |||
6076 | case Instruction::FSub: | |||
6077 | case Instruction::Mul: | |||
6078 | case Instruction::FMul: | |||
6079 | case Instruction::FDiv: | |||
6080 | case Instruction::FRem: | |||
6081 | case Instruction::Shl: | |||
6082 | case Instruction::LShr: | |||
6083 | case Instruction::AShr: | |||
6084 | case Instruction::And: | |||
6085 | case Instruction::Or: | |||
6086 | case Instruction::Xor: { | |||
6087 | // Since we will replace the stride by 1 the multiplication should go away. | |||
6088 | if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal)) | |||
6089 | return 0; | |||
6090 | // Certain instructions can be cheaper to vectorize if they have a constant | |||
6091 | // second vector operand. One example of this are shifts on x86. | |||
6092 | TargetTransformInfo::OperandValueKind Op1VK = | |||
6093 | TargetTransformInfo::OK_AnyValue; | |||
6094 | TargetTransformInfo::OperandValueKind Op2VK = | |||
6095 | TargetTransformInfo::OK_AnyValue; | |||
6096 | TargetTransformInfo::OperandValueProperties Op1VP = | |||
6097 | TargetTransformInfo::OP_None; | |||
6098 | TargetTransformInfo::OperandValueProperties Op2VP = | |||
6099 | TargetTransformInfo::OP_None; | |||
6100 | Value *Op2 = I->getOperand(1); | |||
6101 | ||||
6102 | // Check for a splat or for a non uniform vector of constants. | |||
6103 | if (isa<ConstantInt>(Op2)) { | |||
6104 | ConstantInt *CInt = cast<ConstantInt>(Op2); | |||
6105 | if (CInt && CInt->getValue().isPowerOf2()) | |||
6106 | Op2VP = TargetTransformInfo::OP_PowerOf2; | |||
6107 | Op2VK = TargetTransformInfo::OK_UniformConstantValue; | |||
6108 | } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) { | |||
6109 | Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; | |||
6110 | Constant *SplatValue = cast<Constant>(Op2)->getSplatValue(); | |||
6111 | if (SplatValue) { | |||
6112 | ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue); | |||
6113 | if (CInt && CInt->getValue().isPowerOf2()) | |||
6114 | Op2VP = TargetTransformInfo::OP_PowerOf2; | |||
6115 | Op2VK = TargetTransformInfo::OK_UniformConstantValue; | |||
6116 | } | |||
6117 | } else if (Legal->isUniform(Op2)) { | |||
6118 | Op2VK = TargetTransformInfo::OK_UniformValue; | |||
6119 | } | |||
6120 | SmallVector<const Value *, 4> Operands(I->operand_values()); | |||
6121 | unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1; | |||
6122 | return N * TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, | |||
6123 | Op2VK, Op1VP, Op2VP, Operands); | |||
6124 | } | |||
6125 | case Instruction::Select: { | |||
6126 | SelectInst *SI = cast<SelectInst>(I); | |||
6127 | const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); | |||
6128 | bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); | |||
6129 | Type *CondTy = SI->getCondition()->getType(); | |||
6130 | if (!ScalarCond) | |||
6131 | CondTy = VectorType::get(CondTy, VF); | |||
6132 | ||||
6133 | return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I); | |||
6134 | } | |||
6135 | case Instruction::ICmp: | |||
6136 | case Instruction::FCmp: { | |||
6137 | Type *ValTy = I->getOperand(0)->getType(); | |||
6138 | Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0)); | |||
6139 | if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF)) | |||
6140 | ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]); | |||
6141 | VectorTy = ToVectorTy(ValTy, VF); | |||
6142 | return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I); | |||
6143 | } | |||
6144 | case Instruction::Store: | |||
6145 | case Instruction::Load: { | |||
6146 | unsigned Width = VF; | |||
6147 | if (Width > 1) { | |||
6148 | InstWidening Decision = getWideningDecision(I, Width); | |||
6149 | assert(Decision != CM_Unknown &&(static_cast <bool> (Decision != CM_Unknown && "CM decision should be taken at this point" ) ? void (0) : __assert_fail ("Decision != CM_Unknown && \"CM decision should be taken at this point\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6150, __extension__ __PRETTY_FUNCTION__)) | |||
6150 | "CM decision should be taken at this point")(static_cast <bool> (Decision != CM_Unknown && "CM decision should be taken at this point" ) ? void (0) : __assert_fail ("Decision != CM_Unknown && \"CM decision should be taken at this point\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6150, __extension__ __PRETTY_FUNCTION__)); | |||
6151 | if (Decision == CM_Scalarize) | |||
6152 | Width = 1; | |||
6153 | } | |||
6154 | VectorTy = ToVectorTy(getMemInstValueType(I), Width); | |||
6155 | return getMemoryInstructionCost(I, VF); | |||
6156 | } | |||
6157 | case Instruction::ZExt: | |||
6158 | case Instruction::SExt: | |||
6159 | case Instruction::FPToUI: | |||
6160 | case Instruction::FPToSI: | |||
6161 | case Instruction::FPExt: | |||
6162 | case Instruction::PtrToInt: | |||
6163 | case Instruction::IntToPtr: | |||
6164 | case Instruction::SIToFP: | |||
6165 | case Instruction::UIToFP: | |||
6166 | case Instruction::Trunc: | |||
6167 | case Instruction::FPTrunc: | |||
6168 | case Instruction::BitCast: { | |||
6169 | // We optimize the truncation of induction variables having constant | |||
6170 | // integer steps. The cost of these truncations is the same as the scalar | |||
6171 | // operation. | |||
6172 | if (isOptimizableIVTruncate(I, VF)) { | |||
6173 | auto *Trunc = cast<TruncInst>(I); | |||
6174 | return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(), | |||
6175 | Trunc->getSrcTy(), Trunc); | |||
6176 | } | |||
6177 | ||||
6178 | Type *SrcScalarTy = I->getOperand(0)->getType(); | |||
6179 | Type *SrcVecTy = | |||
6180 | VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy; | |||
6181 | if (canTruncateToMinimalBitwidth(I, VF)) { | |||
6182 | // This cast is going to be shrunk. This may remove the cast or it might | |||
6183 | // turn it into slightly different cast. For example, if MinBW == 16, | |||
6184 | // "zext i8 %1 to i32" becomes "zext i8 %1 to i16". | |||
6185 | // | |||
6186 | // Calculate the modified src and dest types. | |||
6187 | Type *MinVecTy = VectorTy; | |||
6188 | if (I->getOpcode() == Instruction::Trunc) { | |||
6189 | SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy); | |||
6190 | VectorTy = | |||
6191 | largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); | |||
6192 | } else if (I->getOpcode() == Instruction::ZExt || | |||
6193 | I->getOpcode() == Instruction::SExt) { | |||
6194 | SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy); | |||
6195 | VectorTy = | |||
6196 | smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); | |||
6197 | } | |||
6198 | } | |||
6199 | ||||
6200 | unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1; | |||
6201 | return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I); | |||
6202 | } | |||
6203 | case Instruction::Call: { | |||
6204 | bool NeedToScalarize; | |||
6205 | CallInst *CI = cast<CallInst>(I); | |||
6206 | unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize); | |||
6207 | if (getVectorIntrinsicIDForCall(CI, TLI)) | |||
6208 | return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI)); | |||
6209 | return CallCost; | |||
6210 | } | |||
6211 | default: | |||
6212 | // The cost of executing VF copies of the scalar instruction. This opcode | |||
6213 | // is unknown. Assume that it is the same as 'mul'. | |||
6214 | return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) + | |||
6215 | getScalarizationOverhead(I, VF, TTI); | |||
6216 | } // end of switch. | |||
6217 | } | |||
6218 | ||||
6219 | char LoopVectorize::ID = 0; | |||
6220 | ||||
6221 | static const char lv_name[] = "Loop Vectorization"; | |||
6222 | ||||
6223 | INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)static void *initializeLoopVectorizePassOnce(PassRegistry & Registry) { | |||
6224 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry); | |||
6225 | INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)initializeBasicAAWrapperPassPass(Registry); | |||
6226 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry); | |||
6227 | INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)initializeGlobalsAAWrapperPassPass(Registry); | |||
6228 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry); | |||
6229 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)initializeBlockFrequencyInfoWrapperPassPass(Registry); | |||
6230 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry); | |||
6231 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)initializeScalarEvolutionWrapperPassPass(Registry); | |||
6232 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry); | |||
6233 | INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)initializeLoopAccessLegacyAnalysisPass(Registry); | |||
6234 | INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)initializeDemandedBitsWrapperPassPass(Registry); | |||
6235 | INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)initializeOptimizationRemarkEmitterWrapperPassPass(Registry); | |||
6236 | INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)PassInfo *PI = new PassInfo( lv_name, "loop-vectorize", & LoopVectorize::ID, PassInfo::NormalCtor_t(callDefaultCtor< LoopVectorize>), false, false); Registry.registerPass(*PI, true); return PI; } static llvm::once_flag InitializeLoopVectorizePassFlag ; void llvm::initializeLoopVectorizePass(PassRegistry &Registry ) { llvm::call_once(InitializeLoopVectorizePassFlag, initializeLoopVectorizePassOnce , std::ref(Registry)); } | |||
6237 | ||||
6238 | namespace llvm { | |||
6239 | ||||
6240 | Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) { | |||
6241 | return new LoopVectorize(NoUnrolling, AlwaysVectorize); | |||
6242 | } | |||
6243 | ||||
6244 | } // end namespace llvm | |||
6245 | ||||
6246 | bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) { | |||
6247 | // Check if the pointer operand of a load or store instruction is | |||
6248 | // consecutive. | |||
6249 | if (auto *Ptr = getLoadStorePointerOperand(Inst)) | |||
6250 | return Legal->isConsecutivePtr(Ptr); | |||
6251 | return false; | |||
6252 | } | |||
6253 | ||||
6254 | void LoopVectorizationCostModel::collectValuesToIgnore() { | |||
6255 | // Ignore ephemeral values. | |||
6256 | CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore); | |||
6257 | ||||
6258 | // Ignore type-promoting instructions we identified during reduction | |||
6259 | // detection. | |||
6260 | for (auto &Reduction : *Legal->getReductionVars()) { | |||
6261 | RecurrenceDescriptor &RedDes = Reduction.second; | |||
6262 | SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts(); | |||
6263 | VecValuesToIgnore.insert(Casts.begin(), Casts.end()); | |||
6264 | } | |||
6265 | // Ignore type-casting instructions we identified during induction | |||
6266 | // detection. | |||
6267 | for (auto &Induction : *Legal->getInductionVars()) { | |||
6268 | InductionDescriptor &IndDes = Induction.second; | |||
6269 | const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts(); | |||
6270 | VecValuesToIgnore.insert(Casts.begin(), Casts.end()); | |||
6271 | } | |||
6272 | } | |||
6273 | ||||
6274 | VectorizationFactor | |||
6275 | LoopVectorizationPlanner::planInVPlanNativePath(bool OptForSize, | |||
6276 | unsigned UserVF) { | |||
6277 | // Width 1 means no vectorization, cost 0 means uncomputed cost. | |||
6278 | const VectorizationFactor NoVectorization = {1U, 0U}; | |||
6279 | ||||
6280 | // Outer loop handling: They may require CFG and instruction level | |||
6281 | // transformations before even evaluating whether vectorization is profitable. | |||
6282 | // Since we cannot modify the incoming IR, we need to build VPlan upfront in | |||
6283 | // the vectorization pipeline. | |||
6284 | if (!OrigLoop->empty()) { | |||
6285 | // TODO: If UserVF is not provided, we set UserVF to 4 for stress testing. | |||
6286 | // This won't be necessary when UserVF is not required in the VPlan-native | |||
6287 | // path. | |||
6288 | if (VPlanBuildStressTest && !UserVF) | |||
6289 | UserVF = 4; | |||
6290 | ||||
6291 | assert(EnableVPlanNativePath && "VPlan-native path is not enabled.")(static_cast <bool> (EnableVPlanNativePath && "VPlan-native path is not enabled." ) ? void (0) : __assert_fail ("EnableVPlanNativePath && \"VPlan-native path is not enabled.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6291, __extension__ __PRETTY_FUNCTION__)); | |||
6292 | assert(UserVF && "Expected UserVF for outer loop vectorization.")(static_cast <bool> (UserVF && "Expected UserVF for outer loop vectorization." ) ? void (0) : __assert_fail ("UserVF && \"Expected UserVF for outer loop vectorization.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6292, __extension__ __PRETTY_FUNCTION__)); | |||
6293 | assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two")(static_cast <bool> (isPowerOf2_32(UserVF) && "VF needs to be a power of two" ) ? void (0) : __assert_fail ("isPowerOf2_32(UserVF) && \"VF needs to be a power of two\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6293, __extension__ __PRETTY_FUNCTION__)); | |||
6294 | LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Using user VF " << UserVF << ".\n"; } } while (false); | |||
6295 | buildVPlans(UserVF, UserVF); | |||
6296 | ||||
6297 | // For VPlan build stress testing, we bail out after VPlan construction. | |||
6298 | if (VPlanBuildStressTest) | |||
6299 | return NoVectorization; | |||
6300 | ||||
6301 | return {UserVF, 0}; | |||
6302 | } | |||
6303 | ||||
6304 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the " "VPlan-native path.\n"; } } while (false) | |||
6305 | dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the " "VPlan-native path.\n"; } } while (false) | |||
6306 | "VPlan-native path.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the " "VPlan-native path.\n"; } } while (false); | |||
6307 | return NoVectorization; | |||
6308 | } | |||
6309 | ||||
6310 | VectorizationFactor | |||
6311 | LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) { | |||
6312 | assert(OrigLoop->empty() && "Inner loop expected.")(static_cast <bool> (OrigLoop->empty() && "Inner loop expected." ) ? void (0) : __assert_fail ("OrigLoop->empty() && \"Inner loop expected.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6312, __extension__ __PRETTY_FUNCTION__)); | |||
6313 | // Width 1 means no vectorization, cost 0 means uncomputed cost. | |||
6314 | const VectorizationFactor NoVectorization = {1U, 0U}; | |||
6315 | Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize); | |||
6316 | if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize. | |||
6317 | return NoVectorization; | |||
6318 | ||||
6319 | if (UserVF) { | |||
6320 | LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Using user VF " << UserVF << ".\n"; } } while (false); | |||
6321 | assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two")(static_cast <bool> (isPowerOf2_32(UserVF) && "VF needs to be a power of two" ) ? void (0) : __assert_fail ("isPowerOf2_32(UserVF) && \"VF needs to be a power of two\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6321, __extension__ __PRETTY_FUNCTION__)); | |||
6322 | // Collect the instructions (and their associated costs) that will be more | |||
6323 | // profitable to scalarize. | |||
6324 | CM.selectUserVectorizationFactor(UserVF); | |||
6325 | buildVPlansWithVPRecipes(UserVF, UserVF); | |||
6326 | LLVM_DEBUG(printPlans(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { printPlans(dbgs()); } } while (false); | |||
6327 | return {UserVF, 0}; | |||
6328 | } | |||
6329 | ||||
6330 | unsigned MaxVF = MaybeMaxVF.getValue(); | |||
6331 | assert(MaxVF != 0 && "MaxVF is zero.")(static_cast <bool> (MaxVF != 0 && "MaxVF is zero." ) ? void (0) : __assert_fail ("MaxVF != 0 && \"MaxVF is zero.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6331, __extension__ __PRETTY_FUNCTION__)); | |||
6332 | ||||
6333 | for (unsigned VF = 1; VF <= MaxVF; VF *= 2) { | |||
6334 | // Collect Uniform and Scalar instructions after vectorization with VF. | |||
6335 | CM.collectUniformsAndScalars(VF); | |||
6336 | ||||
6337 | // Collect the instructions (and their associated costs) that will be more | |||
6338 | // profitable to scalarize. | |||
6339 | if (VF > 1) | |||
6340 | CM.collectInstsToScalarize(VF); | |||
6341 | } | |||
6342 | ||||
6343 | buildVPlansWithVPRecipes(1, MaxVF); | |||
6344 | LLVM_DEBUG(printPlans(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { printPlans(dbgs()); } } while (false); | |||
6345 | if (MaxVF == 1) | |||
6346 | return NoVectorization; | |||
6347 | ||||
6348 | // Select the optimal vectorization factor. | |||
6349 | return CM.selectVectorizationFactor(MaxVF); | |||
6350 | } | |||
6351 | ||||
6352 | void LoopVectorizationPlanner::setBestPlan(unsigned VF, unsigned UF) { | |||
6353 | LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UFdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF << '\n'; } } while (false) | |||
6354 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF << '\n'; } } while (false); | |||
6355 | BestVF = VF; | |||
6356 | BestUF = UF; | |||
6357 | ||||
6358 | erase_if(VPlans, [VF](const VPlanPtr &Plan) { | |||
6359 | return !Plan->hasVF(VF); | |||
6360 | }); | |||
6361 | assert(VPlans.size() == 1 && "Best VF has not a single VPlan.")(static_cast <bool> (VPlans.size() == 1 && "Best VF has not a single VPlan." ) ? void (0) : __assert_fail ("VPlans.size() == 1 && \"Best VF has not a single VPlan.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6361, __extension__ __PRETTY_FUNCTION__)); | |||
6362 | } | |||
6363 | ||||
6364 | void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV, | |||
6365 | DominatorTree *DT) { | |||
6366 | // Perform the actual loop transformation. | |||
6367 | ||||
6368 | // 1. Create a new empty loop. Unlink the old loop and connect the new one. | |||
6369 | VPCallbackILV CallbackILV(ILV); | |||
6370 | ||||
6371 | VPTransformState State{BestVF, BestUF, LI, | |||
6372 | DT, ILV.Builder, ILV.VectorLoopValueMap, | |||
6373 | &ILV, CallbackILV}; | |||
6374 | State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton(); | |||
6375 | ||||
6376 | //===------------------------------------------------===// | |||
6377 | // | |||
6378 | // Notice: any optimization or new instruction that go | |||
6379 | // into the code below should also be implemented in | |||
6380 | // the cost-model. | |||
6381 | // | |||
6382 | //===------------------------------------------------===// | |||
6383 | ||||
6384 | // 2. Copy and widen instructions from the old loop into the new loop. | |||
6385 | assert(VPlans.size() == 1 && "Not a single VPlan to execute.")(static_cast <bool> (VPlans.size() == 1 && "Not a single VPlan to execute." ) ? void (0) : __assert_fail ("VPlans.size() == 1 && \"Not a single VPlan to execute.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6385, __extension__ __PRETTY_FUNCTION__)); | |||
6386 | VPlans.front()->execute(&State); | |||
6387 | ||||
6388 | // 3. Fix the vectorized code: take care of header phi's, live-outs, | |||
6389 | // predication, updating analyses. | |||
6390 | ILV.fixVectorizedLoop(); | |||
6391 | } | |||
6392 | ||||
6393 | void LoopVectorizationPlanner::collectTriviallyDeadInstructions( | |||
6394 | SmallPtrSetImpl<Instruction *> &DeadInstructions) { | |||
6395 | BasicBlock *Latch = OrigLoop->getLoopLatch(); | |||
6396 | ||||
6397 | // We create new control-flow for the vectorized loop, so the original | |||
6398 | // condition will be dead after vectorization if it's only used by the | |||
6399 | // branch. | |||
6400 | auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0)); | |||
6401 | if (Cmp && Cmp->hasOneUse()) | |||
6402 | DeadInstructions.insert(Cmp); | |||
6403 | ||||
6404 | // We create new "steps" for induction variable updates to which the original | |||
6405 | // induction variables map. An original update instruction will be dead if | |||
6406 | // all its users except the induction variable are dead. | |||
6407 | for (auto &Induction : *Legal->getInductionVars()) { | |||
6408 | PHINode *Ind = Induction.first; | |||
6409 | auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); | |||
6410 | if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool { | |||
6411 | return U == Ind || DeadInstructions.count(cast<Instruction>(U)); | |||
6412 | })) | |||
6413 | DeadInstructions.insert(IndUpdate); | |||
6414 | ||||
6415 | // We record as "Dead" also the type-casting instructions we had identified | |||
6416 | // during induction analysis. We don't need any handling for them in the | |||
6417 | // vectorized loop because we have proven that, under a proper runtime | |||
6418 | // test guarding the vectorized loop, the value of the phi, and the casted | |||
6419 | // value of the phi, are the same. The last instruction in this casting chain | |||
6420 | // will get its scalar/vector/widened def from the scalar/vector/widened def | |||
6421 | // of the respective phi node. Any other casts in the induction def-use chain | |||
6422 | // have no other uses outside the phi update chain, and will be ignored. | |||
6423 | InductionDescriptor &IndDes = Induction.second; | |||
6424 | const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts(); | |||
6425 | DeadInstructions.insert(Casts.begin(), Casts.end()); | |||
6426 | } | |||
6427 | } | |||
6428 | ||||
6429 | Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; } | |||
6430 | ||||
6431 | Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; } | |||
6432 | ||||
6433 | Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step, | |||
6434 | Instruction::BinaryOps BinOp) { | |||
6435 | // When unrolling and the VF is 1, we only need to add a simple scalar. | |||
6436 | Type *Ty = Val->getType(); | |||
6437 | assert(!Ty->isVectorTy() && "Val must be a scalar")(static_cast <bool> (!Ty->isVectorTy() && "Val must be a scalar" ) ? void (0) : __assert_fail ("!Ty->isVectorTy() && \"Val must be a scalar\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6437, __extension__ __PRETTY_FUNCTION__)); | |||
6438 | ||||
6439 | if (Ty->isFloatingPointTy()) { | |||
6440 | Constant *C = ConstantFP::get(Ty, (double)StartIdx); | |||
6441 | ||||
6442 | // Floating point operations had to be 'fast' to enable the unrolling. | |||
6443 | Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step)); | |||
6444 | return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp)); | |||
6445 | } | |||
6446 | Constant *C = ConstantInt::get(Ty, StartIdx); | |||
6447 | return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction"); | |||
6448 | } | |||
6449 | ||||
6450 | static void AddRuntimeUnrollDisableMetaData(Loop *L) { | |||
6451 | SmallVector<Metadata *, 4> MDs; | |||
6452 | // Reserve first location for self reference to the LoopID metadata node. | |||
6453 | MDs.push_back(nullptr); | |||
6454 | bool IsUnrollMetadata = false; | |||
6455 | MDNode *LoopID = L->getLoopID(); | |||
6456 | if (LoopID) { | |||
6457 | // First find existing loop unrolling disable metadata. | |||
6458 | for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { | |||
6459 | auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); | |||
6460 | if (MD) { | |||
6461 | const auto *S = dyn_cast<MDString>(MD->getOperand(0)); | |||
6462 | IsUnrollMetadata = | |||
6463 | S && S->getString().startswith("llvm.loop.unroll.disable"); | |||
6464 | } | |||
6465 | MDs.push_back(LoopID->getOperand(i)); | |||
6466 | } | |||
6467 | } | |||
6468 | ||||
6469 | if (!IsUnrollMetadata) { | |||
6470 | // Add runtime unroll disable metadata. | |||
6471 | LLVMContext &Context = L->getHeader()->getContext(); | |||
6472 | SmallVector<Metadata *, 1> DisableOperands; | |||
6473 | DisableOperands.push_back( | |||
6474 | MDString::get(Context, "llvm.loop.unroll.runtime.disable")); | |||
6475 | MDNode *DisableNode = MDNode::get(Context, DisableOperands); | |||
6476 | MDs.push_back(DisableNode); | |||
6477 | MDNode *NewLoopID = MDNode::get(Context, MDs); | |||
6478 | // Set operand 0 to refer to the loop id itself. | |||
6479 | NewLoopID->replaceOperandWith(0, NewLoopID); | |||
6480 | L->setLoopID(NewLoopID); | |||
6481 | } | |||
6482 | } | |||
6483 | ||||
6484 | bool LoopVectorizationPlanner::getDecisionAndClampRange( | |||
6485 | const std::function<bool(unsigned)> &Predicate, VFRange &Range) { | |||
6486 | assert(Range.End > Range.Start && "Trying to test an empty VF range.")(static_cast <bool> (Range.End > Range.Start && "Trying to test an empty VF range.") ? void (0) : __assert_fail ("Range.End > Range.Start && \"Trying to test an empty VF range.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6486, __extension__ __PRETTY_FUNCTION__)); | |||
6487 | bool PredicateAtRangeStart = Predicate(Range.Start); | |||
6488 | ||||
6489 | for (unsigned TmpVF = Range.Start * 2; TmpVF < Range.End; TmpVF *= 2) | |||
6490 | if (Predicate(TmpVF) != PredicateAtRangeStart) { | |||
6491 | Range.End = TmpVF; | |||
6492 | break; | |||
6493 | } | |||
6494 | ||||
6495 | return PredicateAtRangeStart; | |||
6496 | } | |||
6497 | ||||
6498 | /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF, | |||
6499 | /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range | |||
6500 | /// of VF's starting at a given VF and extending it as much as possible. Each | |||
6501 | /// vectorization decision can potentially shorten this sub-range during | |||
6502 | /// buildVPlan(). | |||
6503 | void LoopVectorizationPlanner::buildVPlans(unsigned MinVF, unsigned MaxVF) { | |||
6504 | for (unsigned VF = MinVF; VF < MaxVF + 1;) { | |||
6505 | VFRange SubRange = {VF, MaxVF + 1}; | |||
6506 | VPlans.push_back(buildVPlan(SubRange)); | |||
6507 | VF = SubRange.End; | |||
6508 | } | |||
6509 | } | |||
6510 | ||||
6511 | VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst, | |||
6512 | VPlanPtr &Plan) { | |||
6513 | assert(is_contained(predecessors(Dst), Src) && "Invalid edge")(static_cast <bool> (is_contained(predecessors(Dst), Src ) && "Invalid edge") ? void (0) : __assert_fail ("is_contained(predecessors(Dst), Src) && \"Invalid edge\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6513, __extension__ __PRETTY_FUNCTION__)); | |||
6514 | ||||
6515 | // Look for cached value. | |||
6516 | std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst); | |||
6517 | EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge); | |||
6518 | if (ECEntryIt != EdgeMaskCache.end()) | |||
6519 | return ECEntryIt->second; | |||
6520 | ||||
6521 | VPValue *SrcMask = createBlockInMask(Src, Plan); | |||
6522 | ||||
6523 | // The terminator has to be a branch inst! | |||
6524 | BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); | |||
6525 | assert(BI && "Unexpected terminator found")(static_cast <bool> (BI && "Unexpected terminator found" ) ? void (0) : __assert_fail ("BI && \"Unexpected terminator found\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6525, __extension__ __PRETTY_FUNCTION__)); | |||
6526 | ||||
6527 | if (!BI->isConditional()) | |||
6528 | return EdgeMaskCache[Edge] = SrcMask; | |||
6529 | ||||
6530 | VPValue *EdgeMask = Plan->getVPValue(BI->getCondition()); | |||
6531 | assert(EdgeMask && "No Edge Mask found for condition")(static_cast <bool> (EdgeMask && "No Edge Mask found for condition" ) ? void (0) : __assert_fail ("EdgeMask && \"No Edge Mask found for condition\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6531, __extension__ __PRETTY_FUNCTION__)); | |||
6532 | ||||
6533 | if (BI->getSuccessor(0) != Dst) | |||
6534 | EdgeMask = Builder.createNot(EdgeMask); | |||
6535 | ||||
6536 | if (SrcMask) // Otherwise block in-mask is all-one, no need to AND. | |||
6537 | EdgeMask = Builder.createAnd(EdgeMask, SrcMask); | |||
6538 | ||||
6539 | return EdgeMaskCache[Edge] = EdgeMask; | |||
6540 | } | |||
6541 | ||||
6542 | VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) { | |||
6543 | assert(OrigLoop->contains(BB) && "Block is not a part of a loop")(static_cast <bool> (OrigLoop->contains(BB) && "Block is not a part of a loop") ? void (0) : __assert_fail ( "OrigLoop->contains(BB) && \"Block is not a part of a loop\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6543, __extension__ __PRETTY_FUNCTION__)); | |||
6544 | ||||
6545 | // Look for cached value. | |||
6546 | BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB); | |||
6547 | if (BCEntryIt != BlockMaskCache.end()) | |||
6548 | return BCEntryIt->second; | |||
6549 | ||||
6550 | // All-one mask is modelled as no-mask following the convention for masked | |||
6551 | // load/store/gather/scatter. Initialize BlockMask to no-mask. | |||
6552 | VPValue *BlockMask = nullptr; | |||
6553 | ||||
6554 | // Loop incoming mask is all-one. | |||
6555 | if (OrigLoop->getHeader() == BB) | |||
6556 | return BlockMaskCache[BB] = BlockMask; | |||
6557 | ||||
6558 | // This is the block mask. We OR all incoming edges. | |||
6559 | for (auto *Predecessor : predecessors(BB)) { | |||
6560 | VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan); | |||
6561 | if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too. | |||
6562 | return BlockMaskCache[BB] = EdgeMask; | |||
| ||||
6563 | ||||
6564 | if (!BlockMask) { // BlockMask has its initialized nullptr value. | |||
6565 | BlockMask = EdgeMask; | |||
6566 | continue; | |||
6567 | } | |||
6568 | ||||
6569 | BlockMask = Builder.createOr(BlockMask, EdgeMask); | |||
6570 | } | |||
6571 | ||||
6572 | return BlockMaskCache[BB] = BlockMask; | |||
6573 | } | |||
6574 | ||||
6575 | VPInterleaveRecipe *VPRecipeBuilder::tryToInterleaveMemory(Instruction *I, | |||
6576 | VFRange &Range) { | |||
6577 | const InterleaveGroup *IG = CM.getInterleavedAccessGroup(I); | |||
6578 | if (!IG) | |||
6579 | return nullptr; | |||
6580 | ||||
6581 | // Now check if IG is relevant for VF's in the given range. | |||
6582 | auto isIGMember = [&](Instruction *I) -> std::function<bool(unsigned)> { | |||
6583 | return [=](unsigned VF) -> bool { | |||
6584 | return (VF >= 2 && // Query is illegal for VF == 1 | |||
6585 | CM.getWideningDecision(I, VF) == | |||
6586 | LoopVectorizationCostModel::CM_Interleave); | |||
6587 | }; | |||
6588 | }; | |||
6589 | if (!LoopVectorizationPlanner::getDecisionAndClampRange(isIGMember(I), Range)) | |||
6590 | return nullptr; | |||
6591 | ||||
6592 | // I is a member of an InterleaveGroup for VF's in the (possibly trimmed) | |||
6593 | // range. If it's the primary member of the IG construct a VPInterleaveRecipe. | |||
6594 | // Otherwise, it's an adjunct member of the IG, do not construct any Recipe. | |||
6595 | assert(I == IG->getInsertPos() &&(static_cast <bool> (I == IG->getInsertPos() && "Generating a recipe for an adjunct member of an interleave group" ) ? void (0) : __assert_fail ("I == IG->getInsertPos() && \"Generating a recipe for an adjunct member of an interleave group\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6596, __extension__ __PRETTY_FUNCTION__)) | |||
6596 | "Generating a recipe for an adjunct member of an interleave group")(static_cast <bool> (I == IG->getInsertPos() && "Generating a recipe for an adjunct member of an interleave group" ) ? void (0) : __assert_fail ("I == IG->getInsertPos() && \"Generating a recipe for an adjunct member of an interleave group\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6596, __extension__ __PRETTY_FUNCTION__)); | |||
6597 | ||||
6598 | return new VPInterleaveRecipe(IG); | |||
6599 | } | |||
6600 | ||||
6601 | VPWidenMemoryInstructionRecipe * | |||
6602 | VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range, | |||
6603 | VPlanPtr &Plan) { | |||
6604 | if (!isa<LoadInst>(I) && !isa<StoreInst>(I)) | |||
6605 | return nullptr; | |||
6606 | ||||
6607 | auto willWiden = [&](unsigned VF) -> bool { | |||
6608 | if (VF == 1) | |||
6609 | return false; | |||
6610 | if (CM.isScalarAfterVectorization(I, VF) || | |||
6611 | CM.isProfitableToScalarize(I, VF)) | |||
6612 | return false; | |||
6613 | LoopVectorizationCostModel::InstWidening Decision = | |||
6614 | CM.getWideningDecision(I, VF); | |||
6615 | assert(Decision != LoopVectorizationCostModel::CM_Unknown &&(static_cast <bool> (Decision != LoopVectorizationCostModel ::CM_Unknown && "CM decision should be taken at this point." ) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6616, __extension__ __PRETTY_FUNCTION__)) | |||
6616 | "CM decision should be taken at this point.")(static_cast <bool> (Decision != LoopVectorizationCostModel ::CM_Unknown && "CM decision should be taken at this point." ) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6616, __extension__ __PRETTY_FUNCTION__)); | |||
6617 | assert(Decision != LoopVectorizationCostModel::CM_Interleave &&(static_cast <bool> (Decision != LoopVectorizationCostModel ::CM_Interleave && "Interleave memory opportunity should be caught earlier." ) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Interleave && \"Interleave memory opportunity should be caught earlier.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6618, __extension__ __PRETTY_FUNCTION__)) | |||
6618 | "Interleave memory opportunity should be caught earlier.")(static_cast <bool> (Decision != LoopVectorizationCostModel ::CM_Interleave && "Interleave memory opportunity should be caught earlier." ) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Interleave && \"Interleave memory opportunity should be caught earlier.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6618, __extension__ __PRETTY_FUNCTION__)); | |||
6619 | return Decision != LoopVectorizationCostModel::CM_Scalarize; | |||
6620 | }; | |||
6621 | ||||
6622 | if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range)) | |||
6623 | return nullptr; | |||
6624 | ||||
6625 | VPValue *Mask = nullptr; | |||
6626 | if (Legal->isMaskRequired(I)) | |||
6627 | Mask = createBlockInMask(I->getParent(), Plan); | |||
6628 | ||||
6629 | return new VPWidenMemoryInstructionRecipe(*I, Mask); | |||
6630 | } | |||
6631 | ||||
6632 | VPWidenIntOrFpInductionRecipe * | |||
6633 | VPRecipeBuilder::tryToOptimizeInduction(Instruction *I, VFRange &Range) { | |||
6634 | if (PHINode *Phi = dyn_cast<PHINode>(I)) { | |||
6635 | // Check if this is an integer or fp induction. If so, build the recipe that | |||
6636 | // produces its scalar and vector values. | |||
6637 | InductionDescriptor II = Legal->getInductionVars()->lookup(Phi); | |||
6638 | if (II.getKind() == InductionDescriptor::IK_IntInduction || | |||
6639 | II.getKind() == InductionDescriptor::IK_FpInduction) | |||
6640 | return new VPWidenIntOrFpInductionRecipe(Phi); | |||
6641 | ||||
6642 | return nullptr; | |||
6643 | } | |||
6644 | ||||
6645 | // Optimize the special case where the source is a constant integer | |||
6646 | // induction variable. Notice that we can only optimize the 'trunc' case | |||
6647 | // because (a) FP conversions lose precision, (b) sext/zext may wrap, and | |||
6648 | // (c) other casts depend on pointer size. | |||
6649 | ||||
6650 | // Determine whether \p K is a truncation based on an induction variable that | |||
6651 | // can be optimized. | |||
6652 | auto isOptimizableIVTruncate = | |||
6653 | [&](Instruction *K) -> std::function<bool(unsigned)> { | |||
6654 | return | |||
6655 | [=](unsigned VF) -> bool { return CM.isOptimizableIVTruncate(K, VF); }; | |||
6656 | }; | |||
6657 | ||||
6658 | if (isa<TruncInst>(I) && LoopVectorizationPlanner::getDecisionAndClampRange( | |||
6659 | isOptimizableIVTruncate(I), Range)) | |||
6660 | return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)), | |||
6661 | cast<TruncInst>(I)); | |||
6662 | return nullptr; | |||
6663 | } | |||
6664 | ||||
6665 | VPBlendRecipe *VPRecipeBuilder::tryToBlend(Instruction *I, VPlanPtr &Plan) { | |||
6666 | PHINode *Phi = dyn_cast<PHINode>(I); | |||
6667 | if (!Phi || Phi->getParent() == OrigLoop->getHeader()) | |||
6668 | return nullptr; | |||
6669 | ||||
6670 | // We know that all PHIs in non-header blocks are converted into selects, so | |||
6671 | // we don't have to worry about the insertion order and we can just use the | |||
6672 | // builder. At this point we generate the predication tree. There may be | |||
6673 | // duplications since this is a simple recursive scan, but future | |||
6674 | // optimizations will clean it up. | |||
6675 | ||||
6676 | SmallVector<VPValue *, 2> Masks; | |||
6677 | unsigned NumIncoming = Phi->getNumIncomingValues(); | |||
6678 | for (unsigned In = 0; In < NumIncoming; In++) { | |||
6679 | VPValue *EdgeMask = | |||
6680 | createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan); | |||
6681 | assert((EdgeMask || NumIncoming == 1) &&(static_cast <bool> ((EdgeMask || NumIncoming == 1) && "Multiple predecessors with one having a full mask") ? void ( 0) : __assert_fail ("(EdgeMask || NumIncoming == 1) && \"Multiple predecessors with one having a full mask\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6682, __extension__ __PRETTY_FUNCTION__)) | |||
6682 | "Multiple predecessors with one having a full mask")(static_cast <bool> ((EdgeMask || NumIncoming == 1) && "Multiple predecessors with one having a full mask") ? void ( 0) : __assert_fail ("(EdgeMask || NumIncoming == 1) && \"Multiple predecessors with one having a full mask\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6682, __extension__ __PRETTY_FUNCTION__)); | |||
6683 | if (EdgeMask) | |||
6684 | Masks.push_back(EdgeMask); | |||
6685 | } | |||
6686 | return new VPBlendRecipe(Phi, Masks); | |||
6687 | } | |||
6688 | ||||
6689 | bool VPRecipeBuilder::tryToWiden(Instruction *I, VPBasicBlock *VPBB, | |||
6690 | VFRange &Range) { | |||
6691 | if (CM.isScalarWithPredication(I)) | |||
6692 | return false; | |||
6693 | ||||
6694 | auto IsVectorizableOpcode = [](unsigned Opcode) { | |||
6695 | switch (Opcode) { | |||
6696 | case Instruction::Add: | |||
6697 | case Instruction::And: | |||
6698 | case Instruction::AShr: | |||
6699 | case Instruction::BitCast: | |||
6700 | case Instruction::Br: | |||
6701 | case Instruction::Call: | |||
6702 | case Instruction::FAdd: | |||
6703 | case Instruction::FCmp: | |||
6704 | case Instruction::FDiv: | |||
6705 | case Instruction::FMul: | |||
6706 | case Instruction::FPExt: | |||
6707 | case Instruction::FPToSI: | |||
6708 | case Instruction::FPToUI: | |||
6709 | case Instruction::FPTrunc: | |||
6710 | case Instruction::FRem: | |||
6711 | case Instruction::FSub: | |||
6712 | case Instruction::GetElementPtr: | |||
6713 | case Instruction::ICmp: | |||
6714 | case Instruction::IntToPtr: | |||
6715 | case Instruction::Load: | |||
6716 | case Instruction::LShr: | |||
6717 | case Instruction::Mul: | |||
6718 | case Instruction::Or: | |||
6719 | case Instruction::PHI: | |||
6720 | case Instruction::PtrToInt: | |||
6721 | case Instruction::SDiv: | |||
6722 | case Instruction::Select: | |||
6723 | case Instruction::SExt: | |||
6724 | case Instruction::Shl: | |||
6725 | case Instruction::SIToFP: | |||
6726 | case Instruction::SRem: | |||
6727 | case Instruction::Store: | |||
6728 | case Instruction::Sub: | |||
6729 | case Instruction::Trunc: | |||
6730 | case Instruction::UDiv: | |||
6731 | case Instruction::UIToFP: | |||
6732 | case Instruction::URem: | |||
6733 | case Instruction::Xor: | |||
6734 | case Instruction::ZExt: | |||
6735 | return true; | |||
6736 | } | |||
6737 | return false; | |||
6738 | }; | |||
6739 | ||||
6740 | if (!IsVectorizableOpcode(I->getOpcode())) | |||
6741 | return false; | |||
6742 | ||||
6743 | if (CallInst *CI = dyn_cast<CallInst>(I)) { | |||
6744 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
6745 | if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end || | |||
6746 | ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect)) | |||
6747 | return false; | |||
6748 | } | |||
6749 | ||||
6750 | auto willWiden = [&](unsigned VF) -> bool { | |||
6751 | if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) || | |||
6752 | CM.isProfitableToScalarize(I, VF))) | |||
6753 | return false; | |||
6754 | if (CallInst *CI = dyn_cast<CallInst>(I)) { | |||
6755 | Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); | |||
6756 | // The following case may be scalarized depending on the VF. | |||
6757 | // The flag shows whether we use Intrinsic or a usual Call for vectorized | |||
6758 | // version of the instruction. | |||
6759 | // Is it beneficial to perform intrinsic call compared to lib call? | |||
6760 | bool NeedToScalarize; | |||
6761 | unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize); | |||
6762 | bool UseVectorIntrinsic = | |||
6763 | ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost; | |||
6764 | return UseVectorIntrinsic || !NeedToScalarize; | |||
6765 | } | |||
6766 | if (isa<LoadInst>(I) || isa<StoreInst>(I)) { | |||
6767 | assert(CM.getWideningDecision(I, VF) ==(static_cast <bool> (CM.getWideningDecision(I, VF) == LoopVectorizationCostModel ::CM_Scalarize && "Memory widening decisions should have been taken care by now" ) ? void (0) : __assert_fail ("CM.getWideningDecision(I, VF) == LoopVectorizationCostModel::CM_Scalarize && \"Memory widening decisions should have been taken care by now\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6769, __extension__ __PRETTY_FUNCTION__)) | |||
6768 | LoopVectorizationCostModel::CM_Scalarize &&(static_cast <bool> (CM.getWideningDecision(I, VF) == LoopVectorizationCostModel ::CM_Scalarize && "Memory widening decisions should have been taken care by now" ) ? void (0) : __assert_fail ("CM.getWideningDecision(I, VF) == LoopVectorizationCostModel::CM_Scalarize && \"Memory widening decisions should have been taken care by now\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6769, __extension__ __PRETTY_FUNCTION__)) | |||
6769 | "Memory widening decisions should have been taken care by now")(static_cast <bool> (CM.getWideningDecision(I, VF) == LoopVectorizationCostModel ::CM_Scalarize && "Memory widening decisions should have been taken care by now" ) ? void (0) : __assert_fail ("CM.getWideningDecision(I, VF) == LoopVectorizationCostModel::CM_Scalarize && \"Memory widening decisions should have been taken care by now\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6769, __extension__ __PRETTY_FUNCTION__)); | |||
6770 | return false; | |||
6771 | } | |||
6772 | return true; | |||
6773 | }; | |||
6774 | ||||
6775 | if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range)) | |||
6776 | return false; | |||
6777 | ||||
6778 | // Success: widen this instruction. We optimize the common case where | |||
6779 | // consecutive instructions can be represented by a single recipe. | |||
6780 | if (!VPBB->empty()) { | |||
6781 | VPWidenRecipe *LastWidenRecipe = dyn_cast<VPWidenRecipe>(&VPBB->back()); | |||
6782 | if (LastWidenRecipe && LastWidenRecipe->appendInstruction(I)) | |||
6783 | return true; | |||
6784 | } | |||
6785 | ||||
6786 | VPBB->appendRecipe(new VPWidenRecipe(I)); | |||
6787 | return true; | |||
6788 | } | |||
6789 | ||||
6790 | VPBasicBlock *VPRecipeBuilder::handleReplication( | |||
6791 | Instruction *I, VFRange &Range, VPBasicBlock *VPBB, | |||
6792 | DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe, | |||
6793 | VPlanPtr &Plan) { | |||
6794 | bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange( | |||
6795 | [&](unsigned VF) { return CM.isUniformAfterVectorization(I, VF); }, | |||
6796 | Range); | |||
6797 | ||||
6798 | bool IsPredicated = CM.isScalarWithPredication(I); | |||
6799 | auto *Recipe = new VPReplicateRecipe(I, IsUniform, IsPredicated); | |||
6800 | ||||
6801 | // Find if I uses a predicated instruction. If so, it will use its scalar | |||
6802 | // value. Avoid hoisting the insert-element which packs the scalar value into | |||
6803 | // a vector value, as that happens iff all users use the vector value. | |||
6804 | for (auto &Op : I->operands()) | |||
6805 | if (auto *PredInst = dyn_cast<Instruction>(Op)) | |||
6806 | if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end()) | |||
6807 | PredInst2Recipe[PredInst]->setAlsoPack(false); | |||
6808 | ||||
6809 | // Finalize the recipe for Instr, first if it is not predicated. | |||
6810 | if (!IsPredicated) { | |||
6811 | LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Scalarizing:" << *I << "\n"; } } while (false); | |||
6812 | VPBB->appendRecipe(Recipe); | |||
6813 | return VPBB; | |||
6814 | } | |||
6815 | LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Scalarizing and predicating:" << *I << "\n"; } } while (false); | |||
6816 | assert(VPBB->getSuccessors().empty() &&(static_cast <bool> (VPBB->getSuccessors().empty() && "VPBB has successors when handling predicated replication.") ? void (0) : __assert_fail ("VPBB->getSuccessors().empty() && \"VPBB has successors when handling predicated replication.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6817, __extension__ __PRETTY_FUNCTION__)) | |||
6817 | "VPBB has successors when handling predicated replication.")(static_cast <bool> (VPBB->getSuccessors().empty() && "VPBB has successors when handling predicated replication.") ? void (0) : __assert_fail ("VPBB->getSuccessors().empty() && \"VPBB has successors when handling predicated replication.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6817, __extension__ __PRETTY_FUNCTION__)); | |||
6818 | // Record predicated instructions for above packing optimizations. | |||
6819 | PredInst2Recipe[I] = Recipe; | |||
6820 | VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan); | |||
6821 | VPBlockUtils::insertBlockAfter(Region, VPBB); | |||
6822 | auto *RegSucc = new VPBasicBlock(); | |||
6823 | VPBlockUtils::insertBlockAfter(RegSucc, Region); | |||
6824 | return RegSucc; | |||
6825 | } | |||
6826 | ||||
6827 | VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr, | |||
6828 | VPRecipeBase *PredRecipe, | |||
6829 | VPlanPtr &Plan) { | |||
6830 | // Instructions marked for predication are replicated and placed under an | |||
6831 | // if-then construct to prevent side-effects. | |||
6832 | ||||
6833 | // Generate recipes to compute the block mask for this region. | |||
6834 | VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan); | |||
| ||||
6835 | ||||
6836 | // Build the triangular if-then region. | |||
6837 | std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str(); | |||
6838 | assert(Instr->getParent() && "Predicated instruction not in any basic block")(static_cast <bool> (Instr->getParent() && "Predicated instruction not in any basic block" ) ? void (0) : __assert_fail ("Instr->getParent() && \"Predicated instruction not in any basic block\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6838, __extension__ __PRETTY_FUNCTION__)); | |||
6839 | auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask); | |||
6840 | auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe); | |||
6841 | auto *PHIRecipe = | |||
6842 | Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr); | |||
6843 | auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe); | |||
6844 | auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe); | |||
6845 | VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true); | |||
6846 | ||||
6847 | // Note: first set Entry as region entry and then connect successors starting | |||
6848 | // from it in order, to propagate the "parent" of each VPBasicBlock. | |||
6849 | VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry); | |||
6850 | VPBlockUtils::connectBlocks(Pred, Exit); | |||
6851 | ||||
6852 | return Region; | |||
6853 | } | |||
6854 | ||||
6855 | bool VPRecipeBuilder::tryToCreateRecipe(Instruction *Instr, VFRange &Range, | |||
6856 | VPlanPtr &Plan, VPBasicBlock *VPBB) { | |||
6857 | VPRecipeBase *Recipe = nullptr; | |||
6858 | // Check if Instr should belong to an interleave memory recipe, or already | |||
6859 | // does. In the latter case Instr is irrelevant. | |||
6860 | if ((Recipe = tryToInterleaveMemory(Instr, Range))) { | |||
6861 | VPBB->appendRecipe(Recipe); | |||
6862 | return true; | |||
6863 | } | |||
6864 | ||||
6865 | // Check if Instr is a memory operation that should be widened. | |||
6866 | if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) { | |||
6867 | VPBB->appendRecipe(Recipe); | |||
6868 | return true; | |||
6869 | } | |||
6870 | ||||
6871 | // Check if Instr should form some PHI recipe. | |||
6872 | if ((Recipe = tryToOptimizeInduction(Instr, Range))) { | |||
6873 | VPBB->appendRecipe(Recipe); | |||
6874 | return true; | |||
6875 | } | |||
6876 | if ((Recipe = tryToBlend(Instr, Plan))) { | |||
6877 | VPBB->appendRecipe(Recipe); | |||
6878 | return true; | |||
6879 | } | |||
6880 | if (PHINode *Phi = dyn_cast<PHINode>(Instr)) { | |||
6881 | VPBB->appendRecipe(new VPWidenPHIRecipe(Phi)); | |||
6882 | return true; | |||
6883 | } | |||
6884 | ||||
6885 | // Check if Instr is to be widened by a general VPWidenRecipe, after | |||
6886 | // having first checked for specific widening recipes that deal with | |||
6887 | // Interleave Groups, Inductions and Phi nodes. | |||
6888 | if (tryToWiden(Instr, VPBB, Range)) | |||
6889 | return true; | |||
6890 | ||||
6891 | return false; | |||
6892 | } | |||
6893 | ||||
6894 | void LoopVectorizationPlanner::buildVPlansWithVPRecipes(unsigned MinVF, | |||
6895 | unsigned MaxVF) { | |||
6896 | assert(OrigLoop->empty() && "Inner loop expected.")(static_cast <bool> (OrigLoop->empty() && "Inner loop expected." ) ? void (0) : __assert_fail ("OrigLoop->empty() && \"Inner loop expected.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 6896, __extension__ __PRETTY_FUNCTION__)); | |||
6897 | ||||
6898 | // Collect conditions feeding internal conditional branches; they need to be | |||
6899 | // represented in VPlan for it to model masking. | |||
6900 | SmallPtrSet<Value *, 1> NeedDef; | |||
6901 | ||||
6902 | auto *Latch = OrigLoop->getLoopLatch(); | |||
6903 | for (BasicBlock *BB : OrigLoop->blocks()) { | |||
6904 | if (BB == Latch) | |||
6905 | continue; | |||
6906 | BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); | |||
6907 | if (Branch && Branch->isConditional()) | |||
6908 | NeedDef.insert(Branch->getCondition()); | |||
6909 | } | |||
6910 | ||||
6911 | // Collect instructions from the original loop that will become trivially dead | |||
6912 | // in the vectorized loop. We don't need to vectorize these instructions. For | |||
6913 | // example, original induction update instructions can become dead because we | |||
6914 | // separately emit induction "steps" when generating code for the new loop. | |||
6915 | // Similarly, we create a new latch condition when setting up the structure | |||
6916 | // of the new loop, so the old one can become dead. | |||
6917 | SmallPtrSet<Instruction *, 4> DeadInstructions; | |||
6918 | collectTriviallyDeadInstructions(DeadInstructions); | |||
6919 | ||||
6920 | for (unsigned VF = MinVF; VF < MaxVF + 1;) { | |||
6921 | VFRange SubRange = {VF, MaxVF + 1}; | |||
6922 | VPlans.push_back( | |||
6923 | buildVPlanWithVPRecipes(SubRange, NeedDef, DeadInstructions)); | |||
6924 | VF = SubRange.End; | |||
6925 | } | |||
6926 | } | |||
6927 | ||||
6928 | LoopVectorizationPlanner::VPlanPtr | |||
6929 | LoopVectorizationPlanner::buildVPlanWithVPRecipes( | |||
6930 | VFRange &Range, SmallPtrSetImpl<Value *> &NeedDef, | |||
6931 | SmallPtrSetImpl<Instruction *> &DeadInstructions) { | |||
6932 | // Hold a mapping from predicated instructions to their recipes, in order to | |||
6933 | // fix their AlsoPack behavior if a user is determined to replicate and use a | |||
6934 | // scalar instead of vector value. | |||
6935 | DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe; | |||
6936 | ||||
6937 | DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter(); | |||
6938 | DenseMap<Instruction *, Instruction *> SinkAfterInverse; | |||
6939 | ||||
6940 | // Create a dummy pre-entry VPBasicBlock to start building the VPlan. | |||
6941 | VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry"); | |||
6942 | auto Plan = llvm::make_unique<VPlan>(VPBB); | |||
6943 | ||||
6944 | VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, TTI, Legal, CM, Builder); | |||
6945 | // Represent values that will have defs inside VPlan. | |||
6946 | for (Value *V : NeedDef) | |||
6947 | Plan->addVPValue(V); | |||
6948 | ||||
6949 | // Scan the body of the loop in a topological order to visit each basic block | |||
6950 | // after having visited its predecessor basic blocks. | |||
6951 | LoopBlocksDFS DFS(OrigLoop); | |||
6952 | DFS.perform(LI); | |||
6953 | ||||
6954 | for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) { | |||
6955 | // Relevant instructions from basic block BB will be grouped into VPRecipe | |||
6956 | // ingredients and fill a new VPBasicBlock. | |||
6957 | unsigned VPBBsForBB = 0; | |||
6958 | auto *FirstVPBBForBB = new VPBasicBlock(BB->getName()); | |||
6959 | VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB); | |||
6960 | VPBB = FirstVPBBForBB; | |||
6961 | Builder.setInsertPoint(VPBB); | |||
6962 | ||||
6963 | std::vector<Instruction *> Ingredients; | |||
6964 | ||||
6965 | // Organize the ingredients to vectorize from current basic block in the | |||
6966 | // right order. | |||
6967 | for (Instruction &I : BB->instructionsWithoutDebug()) { | |||
6968 | Instruction *Instr = &I; | |||
6969 | ||||
6970 | // First filter out irrelevant instructions, to ensure no recipes are | |||
6971 | // built for them. | |||
6972 | if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr)) | |||
6973 | continue; | |||
6974 | ||||
6975 | // I is a member of an InterleaveGroup for Range.Start. If it's an adjunct | |||
6976 | // member of the IG, do not construct any Recipe for it. | |||
6977 | const InterleaveGroup *IG = CM.getInterleavedAccessGroup(Instr); | |||
6978 | if (IG && Instr != IG->getInsertPos() && | |||
6979 | Range.Start >= 2 && // Query is illegal for VF == 1 | |||
6980 | CM.getWideningDecision(Instr, Range.Start) == | |||
6981 | LoopVectorizationCostModel::CM_Interleave) { | |||
6982 | if (SinkAfterInverse.count(Instr)) | |||
6983 | Ingredients.push_back(SinkAfterInverse.find(Instr)->second); | |||
6984 | continue; | |||
6985 | } | |||
6986 | ||||
6987 | // Move instructions to handle first-order recurrences, step 1: avoid | |||
6988 | // handling this instruction until after we've handled the instruction it | |||
6989 | // should follow. | |||
6990 | auto SAIt = SinkAfter.find(Instr); | |||
6991 | if (SAIt != SinkAfter.end()) { | |||
6992 | LLVM_DEBUG(dbgs() << "Sinking" << *SAIt->first << " after"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "Sinking" << *SAIt ->first << " after" << *SAIt->second << " to vectorize a 1st order recurrence.\n"; } } while (false) | |||
6993 | << *SAIt->seconddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "Sinking" << *SAIt ->first << " after" << *SAIt->second << " to vectorize a 1st order recurrence.\n"; } } while (false) | |||
6994 | << " to vectorize a 1st order recurrence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "Sinking" << *SAIt ->first << " after" << *SAIt->second << " to vectorize a 1st order recurrence.\n"; } } while (false); | |||
6995 | SinkAfterInverse[SAIt->second] = Instr; | |||
6996 | continue; | |||
6997 | } | |||
6998 | ||||
6999 | Ingredients.push_back(Instr); | |||
7000 | ||||
7001 | // Move instructions to handle first-order recurrences, step 2: push the | |||
7002 | // instruction to be sunk at its insertion point. | |||
7003 | auto SAInvIt = SinkAfterInverse.find(Instr); | |||
7004 | if (SAInvIt != SinkAfterInverse.end()) | |||
7005 | Ingredients.push_back(SAInvIt->second); | |||
7006 | } | |||
7007 | ||||
7008 | // Introduce each ingredient into VPlan. | |||
7009 | for (Instruction *Instr : Ingredients) { | |||
7010 | if (RecipeBuilder.tryToCreateRecipe(Instr, Range, Plan, VPBB)) | |||
7011 | continue; | |||
7012 | ||||
7013 | // Otherwise, if all widening options failed, Instruction is to be | |||
7014 | // replicated. This may create a successor for VPBB. | |||
7015 | VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication( | |||
7016 | Instr, Range, VPBB, PredInst2Recipe, Plan); | |||
7017 | if (NextVPBB != VPBB) { | |||
7018 | VPBB = NextVPBB; | |||
7019 | VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++) | |||
7020 | : ""); | |||
7021 | } | |||
7022 | } | |||
7023 | } | |||
7024 | ||||
7025 | // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks | |||
7026 | // may also be empty, such as the last one VPBB, reflecting original | |||
7027 | // basic-blocks with no recipes. | |||
7028 | VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry()); | |||
7029 | assert(PreEntry->empty() && "Expecting empty pre-entry block.")(static_cast <bool> (PreEntry->empty() && "Expecting empty pre-entry block." ) ? void (0) : __assert_fail ("PreEntry->empty() && \"Expecting empty pre-entry block.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7029, __extension__ __PRETTY_FUNCTION__)); | |||
7030 | VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor()); | |||
7031 | VPBlockUtils::disconnectBlocks(PreEntry, Entry); | |||
7032 | delete PreEntry; | |||
7033 | ||||
7034 | std::string PlanName; | |||
7035 | raw_string_ostream RSO(PlanName); | |||
7036 | unsigned VF = Range.Start; | |||
7037 | Plan->addVF(VF); | |||
7038 | RSO << "Initial VPlan for VF={" << VF; | |||
7039 | for (VF *= 2; VF < Range.End; VF *= 2) { | |||
7040 | Plan->addVF(VF); | |||
7041 | RSO << "," << VF; | |||
7042 | } | |||
7043 | RSO << "},UF>=1"; | |||
7044 | RSO.flush(); | |||
7045 | Plan->setName(PlanName); | |||
7046 | ||||
7047 | return Plan; | |||
7048 | } | |||
7049 | ||||
7050 | LoopVectorizationPlanner::VPlanPtr | |||
7051 | LoopVectorizationPlanner::buildVPlan(VFRange &Range) { | |||
7052 | // Outer loop handling: They may require CFG and instruction level | |||
7053 | // transformations before even evaluating whether vectorization is profitable. | |||
7054 | // Since we cannot modify the incoming IR, we need to build VPlan upfront in | |||
7055 | // the vectorization pipeline. | |||
7056 | assert(!OrigLoop->empty())(static_cast <bool> (!OrigLoop->empty()) ? void (0) : __assert_fail ("!OrigLoop->empty()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7056, __extension__ __PRETTY_FUNCTION__)); | |||
7057 | assert(EnableVPlanNativePath && "VPlan-native path is not enabled.")(static_cast <bool> (EnableVPlanNativePath && "VPlan-native path is not enabled." ) ? void (0) : __assert_fail ("EnableVPlanNativePath && \"VPlan-native path is not enabled.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7057, __extension__ __PRETTY_FUNCTION__)); | |||
7058 | ||||
7059 | // Create new empty VPlan | |||
7060 | auto Plan = llvm::make_unique<VPlan>(); | |||
7061 | ||||
7062 | // Build hierarchical CFG | |||
7063 | VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI); | |||
7064 | HCFGBuilder.buildHierarchicalCFG(*Plan.get()); | |||
7065 | ||||
7066 | return Plan; | |||
7067 | } | |||
7068 | ||||
7069 | Value* LoopVectorizationPlanner::VPCallbackILV:: | |||
7070 | getOrCreateVectorValues(Value *V, unsigned Part) { | |||
7071 | return ILV.getOrCreateVectorValue(V, Part); | |||
7072 | } | |||
7073 | ||||
7074 | void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent) const { | |||
7075 | O << " +\n" | |||
7076 | << Indent << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at "; | |||
7077 | IG->getInsertPos()->printAsOperand(O, false); | |||
7078 | O << "\\l\""; | |||
7079 | for (unsigned i = 0; i < IG->getFactor(); ++i) | |||
7080 | if (Instruction *I = IG->getMember(i)) | |||
7081 | O << " +\n" | |||
7082 | << Indent << "\" " << VPlanIngredient(I) << " " << i << "\\l\""; | |||
7083 | } | |||
7084 | ||||
7085 | void VPWidenRecipe::execute(VPTransformState &State) { | |||
7086 | for (auto &Instr : make_range(Begin, End)) | |||
7087 | State.ILV->widenInstruction(Instr); | |||
7088 | } | |||
7089 | ||||
7090 | void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) { | |||
7091 | assert(!State.Instance && "Int or FP induction being replicated.")(static_cast <bool> (!State.Instance && "Int or FP induction being replicated." ) ? void (0) : __assert_fail ("!State.Instance && \"Int or FP induction being replicated.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7091, __extension__ __PRETTY_FUNCTION__)); | |||
7092 | State.ILV->widenIntOrFpInduction(IV, Trunc); | |||
7093 | } | |||
7094 | ||||
7095 | void VPWidenPHIRecipe::execute(VPTransformState &State) { | |||
7096 | State.ILV->widenPHIInstruction(Phi, State.UF, State.VF); | |||
7097 | } | |||
7098 | ||||
7099 | void VPBlendRecipe::execute(VPTransformState &State) { | |||
7100 | State.ILV->setDebugLocFromInst(State.Builder, Phi); | |||
7101 | // We know that all PHIs in non-header blocks are converted into | |||
7102 | // selects, so we don't have to worry about the insertion order and we | |||
7103 | // can just use the builder. | |||
7104 | // At this point we generate the predication tree. There may be | |||
7105 | // duplications since this is a simple recursive scan, but future | |||
7106 | // optimizations will clean it up. | |||
7107 | ||||
7108 | unsigned NumIncoming = Phi->getNumIncomingValues(); | |||
7109 | ||||
7110 | assert((User || NumIncoming == 1) &&(static_cast <bool> ((User || NumIncoming == 1) && "Multiple predecessors with predecessors having a full mask" ) ? void (0) : __assert_fail ("(User || NumIncoming == 1) && \"Multiple predecessors with predecessors having a full mask\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7111, __extension__ __PRETTY_FUNCTION__)) | |||
7111 | "Multiple predecessors with predecessors having a full mask")(static_cast <bool> ((User || NumIncoming == 1) && "Multiple predecessors with predecessors having a full mask" ) ? void (0) : __assert_fail ("(User || NumIncoming == 1) && \"Multiple predecessors with predecessors having a full mask\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7111, __extension__ __PRETTY_FUNCTION__)); | |||
7112 | // Generate a sequence of selects of the form: | |||
7113 | // SELECT(Mask3, In3, | |||
7114 | // SELECT(Mask2, In2, | |||
7115 | // ( ...))) | |||
7116 | InnerLoopVectorizer::VectorParts Entry(State.UF); | |||
7117 | for (unsigned In = 0; In < NumIncoming; ++In) { | |||
7118 | for (unsigned Part = 0; Part < State.UF; ++Part) { | |||
7119 | // We might have single edge PHIs (blocks) - use an identity | |||
7120 | // 'select' for the first PHI operand. | |||
7121 | Value *In0 = | |||
7122 | State.ILV->getOrCreateVectorValue(Phi->getIncomingValue(In), Part); | |||
7123 | if (In == 0) | |||
7124 | Entry[Part] = In0; // Initialize with the first incoming value. | |||
7125 | else { | |||
7126 | // Select between the current value and the previous incoming edge | |||
7127 | // based on the incoming mask. | |||
7128 | Value *Cond = State.get(User->getOperand(In), Part); | |||
7129 | Entry[Part] = | |||
7130 | State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi"); | |||
7131 | } | |||
7132 | } | |||
7133 | } | |||
7134 | for (unsigned Part = 0; Part < State.UF; ++Part) | |||
7135 | State.ValueMap.setVectorValue(Phi, Part, Entry[Part]); | |||
7136 | } | |||
7137 | ||||
7138 | void VPInterleaveRecipe::execute(VPTransformState &State) { | |||
7139 | assert(!State.Instance && "Interleave group being replicated.")(static_cast <bool> (!State.Instance && "Interleave group being replicated." ) ? void (0) : __assert_fail ("!State.Instance && \"Interleave group being replicated.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7139, __extension__ __PRETTY_FUNCTION__)); | |||
7140 | State.ILV->vectorizeInterleaveGroup(IG->getInsertPos()); | |||
7141 | } | |||
7142 | ||||
7143 | void VPReplicateRecipe::execute(VPTransformState &State) { | |||
7144 | if (State.Instance) { // Generate a single instance. | |||
7145 | State.ILV->scalarizeInstruction(Ingredient, *State.Instance, IsPredicated); | |||
7146 | // Insert scalar instance packing it into a vector. | |||
7147 | if (AlsoPack && State.VF > 1) { | |||
7148 | // If we're constructing lane 0, initialize to start from undef. | |||
7149 | if (State.Instance->Lane == 0) { | |||
7150 | Value *Undef = | |||
7151 | UndefValue::get(VectorType::get(Ingredient->getType(), State.VF)); | |||
7152 | State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef); | |||
7153 | } | |||
7154 | State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance); | |||
7155 | } | |||
7156 | return; | |||
7157 | } | |||
7158 | ||||
7159 | // Generate scalar instances for all VF lanes of all UF parts, unless the | |||
7160 | // instruction is uniform inwhich case generate only the first lane for each | |||
7161 | // of the UF parts. | |||
7162 | unsigned EndLane = IsUniform ? 1 : State.VF; | |||
7163 | for (unsigned Part = 0; Part < State.UF; ++Part) | |||
7164 | for (unsigned Lane = 0; Lane < EndLane; ++Lane) | |||
7165 | State.ILV->scalarizeInstruction(Ingredient, {Part, Lane}, IsPredicated); | |||
7166 | } | |||
7167 | ||||
7168 | void VPBranchOnMaskRecipe::execute(VPTransformState &State) { | |||
7169 | assert(State.Instance && "Branch on Mask works only on single instance.")(static_cast <bool> (State.Instance && "Branch on Mask works only on single instance." ) ? void (0) : __assert_fail ("State.Instance && \"Branch on Mask works only on single instance.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7169, __extension__ __PRETTY_FUNCTION__)); | |||
7170 | ||||
7171 | unsigned Part = State.Instance->Part; | |||
7172 | unsigned Lane = State.Instance->Lane; | |||
7173 | ||||
7174 | Value *ConditionBit = nullptr; | |||
7175 | if (!User) // Block in mask is all-one. | |||
7176 | ConditionBit = State.Builder.getTrue(); | |||
7177 | else { | |||
7178 | VPValue *BlockInMask = User->getOperand(0); | |||
7179 | ConditionBit = State.get(BlockInMask, Part); | |||
7180 | if (ConditionBit->getType()->isVectorTy()) | |||
7181 | ConditionBit = State.Builder.CreateExtractElement( | |||
7182 | ConditionBit, State.Builder.getInt32(Lane)); | |||
7183 | } | |||
7184 | ||||
7185 | // Replace the temporary unreachable terminator with a new conditional branch, | |||
7186 | // whose two destinations will be set later when they are created. | |||
7187 | auto *CurrentTerminator = State.CFG.PrevBB->getTerminator(); | |||
7188 | assert(isa<UnreachableInst>(CurrentTerminator) &&(static_cast <bool> (isa<UnreachableInst>(CurrentTerminator ) && "Expected to replace unreachable terminator with conditional branch." ) ? void (0) : __assert_fail ("isa<UnreachableInst>(CurrentTerminator) && \"Expected to replace unreachable terminator with conditional branch.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7189, __extension__ __PRETTY_FUNCTION__)) | |||
7189 | "Expected to replace unreachable terminator with conditional branch.")(static_cast <bool> (isa<UnreachableInst>(CurrentTerminator ) && "Expected to replace unreachable terminator with conditional branch." ) ? void (0) : __assert_fail ("isa<UnreachableInst>(CurrentTerminator) && \"Expected to replace unreachable terminator with conditional branch.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7189, __extension__ __PRETTY_FUNCTION__)); | |||
7190 | auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit); | |||
7191 | CondBr->setSuccessor(0, nullptr); | |||
7192 | ReplaceInstWithInst(CurrentTerminator, CondBr); | |||
7193 | } | |||
7194 | ||||
7195 | void VPPredInstPHIRecipe::execute(VPTransformState &State) { | |||
7196 | assert(State.Instance && "Predicated instruction PHI works per instance.")(static_cast <bool> (State.Instance && "Predicated instruction PHI works per instance." ) ? void (0) : __assert_fail ("State.Instance && \"Predicated instruction PHI works per instance.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7196, __extension__ __PRETTY_FUNCTION__)); | |||
7197 | Instruction *ScalarPredInst = cast<Instruction>( | |||
7198 | State.ValueMap.getScalarValue(PredInst, *State.Instance)); | |||
7199 | BasicBlock *PredicatedBB = ScalarPredInst->getParent(); | |||
7200 | BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor(); | |||
7201 | assert(PredicatingBB && "Predicated block has no single predecessor.")(static_cast <bool> (PredicatingBB && "Predicated block has no single predecessor." ) ? void (0) : __assert_fail ("PredicatingBB && \"Predicated block has no single predecessor.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7201, __extension__ __PRETTY_FUNCTION__)); | |||
7202 | ||||
7203 | // By current pack/unpack logic we need to generate only a single phi node: if | |||
7204 | // a vector value for the predicated instruction exists at this point it means | |||
7205 | // the instruction has vector users only, and a phi for the vector value is | |||
7206 | // needed. In this case the recipe of the predicated instruction is marked to | |||
7207 | // also do that packing, thereby "hoisting" the insert-element sequence. | |||
7208 | // Otherwise, a phi node for the scalar value is needed. | |||
7209 | unsigned Part = State.Instance->Part; | |||
7210 | if (State.ValueMap.hasVectorValue(PredInst, Part)) { | |||
7211 | Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part); | |||
7212 | InsertElementInst *IEI = cast<InsertElementInst>(VectorValue); | |||
7213 | PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2); | |||
7214 | VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector. | |||
7215 | VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element. | |||
7216 | State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache. | |||
7217 | } else { | |||
7218 | Type *PredInstType = PredInst->getType(); | |||
7219 | PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2); | |||
7220 | Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB); | |||
7221 | Phi->addIncoming(ScalarPredInst, PredicatedBB); | |||
7222 | State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi); | |||
7223 | } | |||
7224 | } | |||
7225 | ||||
7226 | void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) { | |||
7227 | if (!User) | |||
7228 | return State.ILV->vectorizeMemoryInstruction(&Instr); | |||
7229 | ||||
7230 | // Last (and currently only) operand is a mask. | |||
7231 | InnerLoopVectorizer::VectorParts MaskValues(State.UF); | |||
7232 | VPValue *Mask = User->getOperand(User->getNumOperands() - 1); | |||
7233 | for (unsigned Part = 0; Part < State.UF; ++Part) | |||
7234 | MaskValues[Part] = State.get(Mask, Part); | |||
7235 | State.ILV->vectorizeMemoryInstruction(&Instr, &MaskValues); | |||
7236 | } | |||
7237 | ||||
7238 | // Process the loop in the VPlan-native vectorization path. This path builds | |||
7239 | // VPlan upfront in the vectorization pipeline, which allows to apply | |||
7240 | // VPlan-to-VPlan transformations from the very beginning without modifying the | |||
7241 | // input LLVM IR. | |||
7242 | static bool processLoopInVPlanNativePath( | |||
7243 | Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, | |||
7244 | LoopVectorizationLegality *LVL, TargetTransformInfo *TTI, | |||
7245 | TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, | |||
7246 | OptimizationRemarkEmitter *ORE, LoopVectorizeHints &Hints) { | |||
7247 | ||||
7248 | assert(EnableVPlanNativePath && "VPlan-native path is disabled.")(static_cast <bool> (EnableVPlanNativePath && "VPlan-native path is disabled." ) ? void (0) : __assert_fail ("EnableVPlanNativePath && \"VPlan-native path is disabled.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7248, __extension__ __PRETTY_FUNCTION__)); | |||
7249 | Function *F = L->getHeader()->getParent(); | |||
7250 | InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI()); | |||
7251 | LoopVectorizationCostModel CM(L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F, | |||
7252 | &Hints, IAI); | |||
7253 | // Use the planner for outer loop vectorization. | |||
7254 | // TODO: CM is not used at this point inside the planner. Turn CM into an | |||
7255 | // optional argument if we don't need it in the future. | |||
7256 | LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM); | |||
7257 | ||||
7258 | // Get user vectorization factor. | |||
7259 | unsigned UserVF = Hints.getWidth(); | |||
7260 | ||||
7261 | // Check the function attributes to find out if this function should be | |||
7262 | // optimized for size. | |||
7263 | bool OptForSize = | |||
7264 | Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize(); | |||
7265 | ||||
7266 | // Plan how to best vectorize, return the best VF and its cost. | |||
7267 | LVP.planInVPlanNativePath(OptForSize, UserVF); | |||
7268 | ||||
7269 | // Returning false. We are currently not generating vector code in the VPlan | |||
7270 | // native path. | |||
7271 | return false; | |||
7272 | } | |||
7273 | ||||
7274 | bool LoopVectorizePass::processLoop(Loop *L) { | |||
7275 | assert((EnableVPlanNativePath || L->empty()) &&(static_cast <bool> ((EnableVPlanNativePath || L->empty ()) && "VPlan-native path is not enabled. Only process inner loops." ) ? void (0) : __assert_fail ("(EnableVPlanNativePath || L->empty()) && \"VPlan-native path is not enabled. Only process inner loops.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7276, __extension__ __PRETTY_FUNCTION__)) | |||
7276 | "VPlan-native path is not enabled. Only process inner loops.")(static_cast <bool> ((EnableVPlanNativePath || L->empty ()) && "VPlan-native path is not enabled. Only process inner loops." ) ? void (0) : __assert_fail ("(EnableVPlanNativePath || L->empty()) && \"VPlan-native path is not enabled. Only process inner loops.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7276, __extension__ __PRETTY_FUNCTION__)); | |||
7277 | ||||
7278 | #ifndef NDEBUG | |||
7279 | const std::string DebugLocStr = getDebugLocString(L); | |||
7280 | #endif /* NDEBUG */ | |||
7281 | ||||
7282 | LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "\nLV: Checking a loop in \"" << L->getHeader()->getParent()->getName() << "\" from " << DebugLocStr << "\n"; } } while (false ) | |||
7283 | << L->getHeader()->getParent()->getName() << "\" from "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "\nLV: Checking a loop in \"" << L->getHeader()->getParent()->getName() << "\" from " << DebugLocStr << "\n"; } } while (false ) | |||
7284 | << DebugLocStr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "\nLV: Checking a loop in \"" << L->getHeader()->getParent()->getName() << "\" from " << DebugLocStr << "\n"; } } while (false ); | |||
7285 | ||||
7286 | LoopVectorizeHints Hints(L, DisableUnrolling, *ORE); | |||
7287 | ||||
7288 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7289 | dbgs() << "LV: Loop hints:"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7290 | << " force="do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7291 | << (Hints.getForce() == LoopVectorizeHints::FK_Disableddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7292 | ? "disabled"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7293 | : (Hints.getForce() == LoopVectorizeHints::FK_Enableddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7294 | ? "enabled"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7295 | : "?"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7296 | << " width=" << Hints.getWidth()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false) | |||
7297 | << " unroll=" << Hints.getInterleave() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints:" << " force=" << (Hints.getForce() == LoopVectorizeHints:: FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints ::FK_Enabled ? "enabled" : "?")) << " width=" << Hints .getWidth() << " unroll=" << Hints.getInterleave( ) << "\n"; } } while (false); | |||
7298 | ||||
7299 | // Function containing loop | |||
7300 | Function *F = L->getHeader()->getParent(); | |||
7301 | ||||
7302 | // Looking at the diagnostic output is the only way to determine if a loop | |||
7303 | // was vectorized (other than looking at the IR or machine code), so it | |||
7304 | // is important to generate an optimization remark for each loop. Most of | |||
7305 | // these messages are generated as OptimizationRemarkAnalysis. Remarks | |||
7306 | // generated as OptimizationRemark and OptimizationRemarkMissed are | |||
7307 | // less verbose reporting vectorized loops and unvectorized loops that may | |||
7308 | // benefit from vectorization, respectively. | |||
7309 | ||||
7310 | if (!Hints.allowVectorization(F, L, AlwaysVectorize)) { | |||
7311 | LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Loop hints prevent vectorization.\n" ; } } while (false); | |||
7312 | return false; | |||
7313 | } | |||
7314 | ||||
7315 | PredicatedScalarEvolution PSE(*SE, *L); | |||
7316 | ||||
7317 | // Check if it is legal to vectorize the loop. | |||
7318 | LoopVectorizationRequirements Requirements(*ORE); | |||
7319 | LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, GetLAA, LI, ORE, | |||
7320 | &Requirements, &Hints, DB, AC); | |||
7321 | if (!LVL.canVectorize(EnableVPlanNativePath)) { | |||
7322 | LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing: Cannot prove legality.\n" ; } } while (false); | |||
7323 | emitMissedWarning(F, L, Hints, ORE); | |||
7324 | return false; | |||
7325 | } | |||
7326 | ||||
7327 | // Check the function attributes to find out if this function should be | |||
7328 | // optimized for size. | |||
7329 | bool OptForSize = | |||
7330 | Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize(); | |||
7331 | ||||
7332 | // Entrance to the VPlan-native vectorization path. Outer loops are processed | |||
7333 | // here. They may require CFG and instruction level transformations before | |||
7334 | // even evaluating whether vectorization is profitable. Since we cannot modify | |||
7335 | // the incoming IR, we need to build VPlan upfront in the vectorization | |||
7336 | // pipeline. | |||
7337 | if (!L->empty()) | |||
7338 | return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC, | |||
7339 | ORE, Hints); | |||
7340 | ||||
7341 | assert(L->empty() && "Inner loop expected.")(static_cast <bool> (L->empty() && "Inner loop expected." ) ? void (0) : __assert_fail ("L->empty() && \"Inner loop expected.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7341, __extension__ __PRETTY_FUNCTION__)); | |||
7342 | // Check the loop for a trip count threshold: vectorize loops with a tiny trip | |||
7343 | // count by optimizing for size, to minimize overheads. | |||
7344 | // Prefer constant trip counts over profile data, over upper bound estimate. | |||
7345 | unsigned ExpectedTC = 0; | |||
7346 | bool HasExpectedTC = false; | |||
7347 | if (const SCEVConstant *ConstExits = | |||
7348 | dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) { | |||
7349 | const APInt &ExitsCount = ConstExits->getAPInt(); | |||
7350 | // We are interested in small values for ExpectedTC. Skip over those that | |||
7351 | // can't fit an unsigned. | |||
7352 | if (ExitsCount.ult(std::numeric_limits<unsigned>::max())) { | |||
7353 | ExpectedTC = static_cast<unsigned>(ExitsCount.getZExtValue()) + 1; | |||
7354 | HasExpectedTC = true; | |||
7355 | } | |||
7356 | } | |||
7357 | // ExpectedTC may be large because it's bound by a variable. Check | |||
7358 | // profiling information to validate we should vectorize. | |||
7359 | if (!HasExpectedTC && LoopVectorizeWithBlockFrequency) { | |||
7360 | auto EstimatedTC = getLoopEstimatedTripCount(L); | |||
7361 | if (EstimatedTC) { | |||
7362 | ExpectedTC = *EstimatedTC; | |||
7363 | HasExpectedTC = true; | |||
7364 | } | |||
7365 | } | |||
7366 | if (!HasExpectedTC) { | |||
7367 | ExpectedTC = SE->getSmallConstantMaxTripCount(L); | |||
7368 | HasExpectedTC = (ExpectedTC > 0); | |||
7369 | } | |||
7370 | ||||
7371 | if (HasExpectedTC && ExpectedTC < TinyTripCountVectorThreshold) { | |||
7372 | LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found a loop with a very small trip count. " << "This loop is worth vectorizing only if no scalar " << "iteration overheads are incurred."; } } while (false ) | |||
7373 | << "This loop is worth vectorizing only if no scalar "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found a loop with a very small trip count. " << "This loop is worth vectorizing only if no scalar " << "iteration overheads are incurred."; } } while (false ) | |||
7374 | << "iteration overheads are incurred.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found a loop with a very small trip count. " << "This loop is worth vectorizing only if no scalar " << "iteration overheads are incurred."; } } while (false ); | |||
7375 | if (Hints.getForce() == LoopVectorizeHints::FK_Enabled) | |||
7376 | LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << " But vectorizing was explicitly forced.\n" ; } } while (false); | |||
7377 | else { | |||
7378 | LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "\n"; } } while (false); | |||
7379 | // Loops with a very small trip count are considered for vectorization | |||
7380 | // under OptForSize, thereby making sure the cost of their loop body is | |||
7381 | // dominant, free of runtime guards and scalar iteration overheads. | |||
7382 | OptForSize = true; | |||
7383 | } | |||
7384 | } | |||
7385 | ||||
7386 | // Check the function attributes to see if implicit floats are allowed. | |||
7387 | // FIXME: This check doesn't seem possibly correct -- what if the loop is | |||
7388 | // an integer loop and the vector instructions selected are purely integer | |||
7389 | // vector instructions? | |||
7390 | if (F->hasFnAttribute(Attribute::NoImplicitFloat)) { | |||
7391 | LLVM_DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Can't vectorize when the NoImplicitFloat" "attribute is used.\n"; } } while (false) | |||
7392 | "attribute is used.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Can't vectorize when the NoImplicitFloat" "attribute is used.\n"; } } while (false); | |||
7393 | ORE->emit(createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(), | |||
7394 | "NoImplicitFloat", L) | |||
7395 | << "loop not vectorized due to NoImplicitFloat attribute"); | |||
7396 | emitMissedWarning(F, L, Hints, ORE); | |||
7397 | return false; | |||
7398 | } | |||
7399 | ||||
7400 | // Check if the target supports potentially unsafe FP vectorization. | |||
7401 | // FIXME: Add a check for the type of safety issue (denormal, signaling) | |||
7402 | // for the target we're vectorizing for, to make sure none of the | |||
7403 | // additional fp-math flags can help. | |||
7404 | if (Hints.isPotentiallyUnsafe() && | |||
7405 | TTI->isFPVectorizationPotentiallyUnsafe()) { | |||
7406 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n" ; } } while (false) | |||
7407 | dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n" ; } } while (false); | |||
7408 | ORE->emit( | |||
7409 | createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L) | |||
7410 | << "loop not vectorized due to unsafe FP support."); | |||
7411 | emitMissedWarning(F, L, Hints, ORE); | |||
7412 | return false; | |||
7413 | } | |||
7414 | ||||
7415 | bool UseInterleaved = TTI->enableInterleavedAccessVectorization(); | |||
7416 | InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI()); | |||
7417 | ||||
7418 | // If an override option has been passed in for interleaved accesses, use it. | |||
7419 | if (EnableInterleavedMemAccesses.getNumOccurrences() > 0) | |||
7420 | UseInterleaved = EnableInterleavedMemAccesses; | |||
7421 | ||||
7422 | // Analyze interleaved memory accesses. | |||
7423 | if (UseInterleaved) { | |||
7424 | IAI.analyzeInterleaving(); | |||
7425 | } | |||
7426 | ||||
7427 | // Use the cost model. | |||
7428 | LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F, | |||
7429 | &Hints, IAI); | |||
7430 | CM.collectValuesToIgnore(); | |||
7431 | ||||
7432 | // Use the planner for vectorization. | |||
7433 | LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM); | |||
7434 | ||||
7435 | // Get user vectorization factor. | |||
7436 | unsigned UserVF = Hints.getWidth(); | |||
7437 | ||||
7438 | // Plan how to best vectorize, return the best VF and its cost. | |||
7439 | VectorizationFactor VF = LVP.plan(OptForSize, UserVF); | |||
7440 | ||||
7441 | // Select the interleave count. | |||
7442 | unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost); | |||
7443 | ||||
7444 | // Get user interleave count. | |||
7445 | unsigned UserIC = Hints.getInterleave(); | |||
7446 | ||||
7447 | // Identify the diagnostic messages that should be produced. | |||
7448 | std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg; | |||
7449 | bool VectorizeLoop = true, InterleaveLoop = true; | |||
7450 | if (Requirements.doesNotMeet(F, L, Hints)) { | |||
7451 | LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing: loop did not meet vectorization " "requirements.\n"; } } while (false) | |||
7452 | "requirements.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Not vectorizing: loop did not meet vectorization " "requirements.\n"; } } while (false); | |||
7453 | emitMissedWarning(F, L, Hints, ORE); | |||
7454 | return false; | |||
7455 | } | |||
7456 | ||||
7457 | if (VF.Width == 1) { | |||
7458 | LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Vectorization is possible but not beneficial.\n" ; } } while (false); | |||
7459 | VecDiagMsg = std::make_pair( | |||
7460 | "VectorizationNotBeneficial", | |||
7461 | "the cost-model indicates that vectorization is not beneficial"); | |||
7462 | VectorizeLoop = false; | |||
7463 | } | |||
7464 | ||||
7465 | if (IC == 1 && UserIC <= 1) { | |||
7466 | // Tell the user interleaving is not beneficial. | |||
7467 | LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving is not beneficial.\n" ; } } while (false); | |||
7468 | IntDiagMsg = std::make_pair( | |||
7469 | "InterleavingNotBeneficial", | |||
7470 | "the cost-model indicates that interleaving is not beneficial"); | |||
7471 | InterleaveLoop = false; | |||
7472 | if (UserIC == 1) { | |||
7473 | IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled"; | |||
7474 | IntDiagMsg.second += | |||
7475 | " and is explicitly disabled or interleave count is set to 1"; | |||
7476 | } | |||
7477 | } else if (IC > 1 && UserIC == 1) { | |||
7478 | // Tell the user interleaving is beneficial, but it explicitly disabled. | |||
7479 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving is beneficial but is explicitly disabled." ; } } while (false) | |||
7480 | dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleaving is beneficial but is explicitly disabled." ; } } while (false); | |||
7481 | IntDiagMsg = std::make_pair( | |||
7482 | "InterleavingBeneficialButDisabled", | |||
7483 | "the cost-model indicates that interleaving is beneficial " | |||
7484 | "but is explicitly disabled or interleave count is set to 1"); | |||
7485 | InterleaveLoop = false; | |||
7486 | } | |||
7487 | ||||
7488 | // Override IC if user provided an interleave count. | |||
7489 | IC = UserIC > 0 ? UserIC : IC; | |||
7490 | ||||
7491 | // Emit diagnostic messages, if any. | |||
7492 | const char *VAPassName = Hints.vectorizeAnalysisPassName(); | |||
7493 | if (!VectorizeLoop && !InterleaveLoop) { | |||
7494 | // Do not vectorize or interleaving the loop. | |||
7495 | ORE->emit([&]() { | |||
7496 | return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first, | |||
7497 | L->getStartLoc(), L->getHeader()) | |||
7498 | << VecDiagMsg.second; | |||
7499 | }); | |||
7500 | ORE->emit([&]() { | |||
7501 | return OptimizationRemarkMissed(LV_NAME"loop-vectorize", IntDiagMsg.first, | |||
7502 | L->getStartLoc(), L->getHeader()) | |||
7503 | << IntDiagMsg.second; | |||
7504 | }); | |||
7505 | return false; | |||
7506 | } else if (!VectorizeLoop && InterleaveLoop) { | |||
7507 | LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleave Count is " << IC << '\n'; } } while (false); | |||
7508 | ORE->emit([&]() { | |||
7509 | return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first, | |||
7510 | L->getStartLoc(), L->getHeader()) | |||
7511 | << VecDiagMsg.second; | |||
7512 | }); | |||
7513 | } else if (VectorizeLoop && !InterleaveLoop) { | |||
7514 | LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Widthdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " << DebugLocStr << '\n'; } } while (false) | |||
7515 | << ") in " << DebugLocStr << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " << DebugLocStr << '\n'; } } while (false); | |||
7516 | ORE->emit([&]() { | |||
7517 | return OptimizationRemarkAnalysis(LV_NAME"loop-vectorize", IntDiagMsg.first, | |||
7518 | L->getStartLoc(), L->getHeader()) | |||
7519 | << IntDiagMsg.second; | |||
7520 | }); | |||
7521 | } else if (VectorizeLoop && InterleaveLoop) { | |||
7522 | LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Widthdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " << DebugLocStr << '\n'; } } while (false) | |||
7523 | << ") in " << DebugLocStr << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " << DebugLocStr << '\n'; } } while (false); | |||
7524 | LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { dbgs() << "LV: Interleave Count is " << IC << '\n'; } } while (false); | |||
7525 | } | |||
7526 | ||||
7527 | LVP.setBestPlan(VF.Width, IC); | |||
7528 | ||||
7529 | using namespace ore; | |||
7530 | ||||
7531 | if (!VectorizeLoop) { | |||
7532 | assert(IC > 1 && "interleave count should not be 1 or 0")(static_cast <bool> (IC > 1 && "interleave count should not be 1 or 0" ) ? void (0) : __assert_fail ("IC > 1 && \"interleave count should not be 1 or 0\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorize.cpp" , 7532, __extension__ __PRETTY_FUNCTION__)); | |||
7533 | // If we decided that it is not legal to vectorize the loop, then | |||
7534 | // interleave it. | |||
7535 | InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL, | |||
7536 | &CM); | |||
7537 | LVP.executePlan(Unroller, DT); | |||
7538 | ||||
7539 | ORE->emit([&]() { | |||
7540 | return OptimizationRemark(LV_NAME"loop-vectorize", "Interleaved", L->getStartLoc(), | |||
7541 | L->getHeader()) | |||
7542 | << "interleaved loop (interleaved count: " | |||
7543 | << NV("InterleaveCount", IC) << ")"; | |||
7544 | }); | |||
7545 | } else { | |||
7546 | // If we decided that it is *legal* to vectorize the loop, then do it. | |||
7547 | InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC, | |||
7548 | &LVL, &CM); | |||
7549 | LVP.executePlan(LB, DT); | |||
7550 | ++LoopsVectorized; | |||
7551 | ||||
7552 | // Add metadata to disable runtime unrolling a scalar loop when there are | |||
7553 | // no runtime checks about strides and memory. A scalar loop that is | |||
7554 | // rarely used is not worth unrolling. | |||
7555 | if (!LB.areSafetyChecksAdded()) | |||
7556 | AddRuntimeUnrollDisableMetaData(L); | |||
7557 | ||||
7558 | // Report the vectorization decision. | |||
7559 | ORE->emit([&]() { | |||
7560 | return OptimizationRemark(LV_NAME"loop-vectorize", "Vectorized", L->getStartLoc(), | |||
7561 | L->getHeader()) | |||
7562 | << "vectorized loop (vectorization width: " | |||
7563 | << NV("VectorizationFactor", VF.Width) | |||
7564 | << ", interleaved count: " << NV("InterleaveCount", IC) << ")"; | |||
7565 | }); | |||
7566 | } | |||
7567 | ||||
7568 | // Mark the loop as already vectorized to avoid vectorizing again. | |||
7569 | Hints.setAlreadyVectorized(); | |||
7570 | ||||
7571 | LLVM_DEBUG(verifyFunction(*L->getHeader()->getParent()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-vectorize")) { verifyFunction(*L->getHeader()->getParent ()); } } while (false); | |||
7572 | return true; | |||
7573 | } | |||
7574 | ||||
7575 | bool LoopVectorizePass::runImpl( | |||
7576 | Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_, | |||
7577 | DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_, | |||
7578 | DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_, | |||
7579 | std::function<const LoopAccessInfo &(Loop &)> &GetLAA_, | |||
7580 | OptimizationRemarkEmitter &ORE_) { | |||
7581 | SE = &SE_; | |||
7582 | LI = &LI_; | |||
7583 | TTI = &TTI_; | |||
7584 | DT = &DT_; | |||
7585 | BFI = &BFI_; | |||
7586 | TLI = TLI_; | |||
7587 | AA = &AA_; | |||
7588 | AC = &AC_; | |||
7589 | GetLAA = &GetLAA_; | |||
7590 | DB = &DB_; | |||
7591 | ORE = &ORE_; | |||
7592 | ||||
7593 | // Don't attempt if | |||
7594 | // 1. the target claims to have no vector registers, and | |||
7595 | // 2. interleaving won't help ILP. | |||
7596 | // | |||
7597 | // The second condition is necessary because, even if the target has no | |||
7598 | // vector registers, loop vectorization may still enable scalar | |||
7599 | // interleaving. | |||
7600 | if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2) | |||
7601 | return false; | |||
7602 | ||||
7603 | bool Changed = false; | |||
7604 | ||||
7605 | // The vectorizer requires loops to be in simplified form. | |||
7606 | // Since simplification may add new inner loops, it has to run before the | |||
7607 | // legality and profitability checks. This means running the loop vectorizer | |||
7608 | // will simplify all loops, regardless of whether anything end up being | |||
7609 | // vectorized. | |||
7610 | for (auto &L : *LI) | |||
7611 | Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */); | |||
7612 | ||||
7613 | // Build up a worklist of inner-loops to vectorize. This is necessary as | |||
7614 | // the act of vectorizing or partially unrolling a loop creates new loops | |||
7615 | // and can invalidate iterators across the loops. | |||
7616 | SmallVector<Loop *, 8> Worklist; | |||
7617 | ||||
7618 | for (Loop *L : *LI) | |||
7619 | collectSupportedLoops(*L, LI, ORE, Worklist); | |||
7620 | ||||
7621 | LoopsAnalyzed += Worklist.size(); | |||
7622 | ||||
7623 | // Now walk the identified inner loops. | |||
7624 | while (!Worklist.empty()) { | |||
7625 | Loop *L = Worklist.pop_back_val(); | |||
7626 | ||||
7627 | // For the inner loops we actually process, form LCSSA to simplify the | |||
7628 | // transform. | |||
7629 | Changed |= formLCSSARecursively(*L, *DT, LI, SE); | |||
7630 | ||||
7631 | Changed |= processLoop(L); | |||
7632 | } | |||
7633 | ||||
7634 | // Process each loop nest in the function. | |||
7635 | return Changed; | |||
7636 | } | |||
7637 | ||||
7638 | PreservedAnalyses LoopVectorizePass::run(Function &F, | |||
7639 | FunctionAnalysisManager &AM) { | |||
7640 | auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); | |||
7641 | auto &LI = AM.getResult<LoopAnalysis>(F); | |||
7642 | auto &TTI = AM.getResult<TargetIRAnalysis>(F); | |||
7643 | auto &DT = AM.getResult<DominatorTreeAnalysis>(F); | |||
7644 | auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F); | |||
7645 | auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); | |||
7646 | auto &AA = AM.getResult<AAManager>(F); | |||
7647 | auto &AC = AM.getResult<AssumptionAnalysis>(F); | |||
7648 | auto &DB = AM.getResult<DemandedBitsAnalysis>(F); | |||
7649 | auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); | |||
7650 | ||||
7651 | auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager(); | |||
7652 | std::function<const LoopAccessInfo &(Loop &)> GetLAA = | |||
7653 | [&](Loop &L) -> const LoopAccessInfo & { | |||
7654 | LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, nullptr}; | |||
7655 | return LAM.getResult<LoopAccessAnalysis>(L, AR); | |||
7656 | }; | |||
7657 | bool Changed = | |||
7658 | runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE); | |||
7659 | if (!Changed) | |||
7660 | return PreservedAnalyses::all(); | |||
7661 | PreservedAnalyses PA; | |||
7662 | PA.preserve<LoopAnalysis>(); | |||
7663 | PA.preserve<DominatorTreeAnalysis>(); | |||
7664 | PA.preserve<BasicAA>(); | |||
7665 | PA.preserve<GlobalsAA>(); | |||
7666 | return PA; | |||
7667 | } |
1 | //===- LoopVectorizationPlanner.h - Planner for LoopVectorization ---------===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | /// |
10 | /// \file |
11 | /// This file provides a LoopVectorizationPlanner class. |
12 | /// InnerLoopVectorizer vectorizes loops which contain only one basic |
13 | /// LoopVectorizationPlanner - drives the vectorization process after having |
14 | /// passed Legality checks. |
15 | /// The planner builds and optimizes the Vectorization Plans which record the |
16 | /// decisions how to vectorize the given loop. In particular, represent the |
17 | /// control-flow of the vectorized version, the replication of instructions that |
18 | /// are to be scalarized, and interleave access groups. |
19 | /// |
20 | /// Also provides a VPlan-based builder utility analogous to IRBuilder. |
21 | /// It provides an instruction-level API for generating VPInstructions while |
22 | /// abstracting away the Recipe manipulation details. |
23 | //===----------------------------------------------------------------------===// |
24 | |
25 | #ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H |
26 | #define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H |
27 | |
28 | #include "VPlan.h" |
29 | #include "llvm/Analysis/LoopInfo.h" |
30 | #include "llvm/Analysis/TargetLibraryInfo.h" |
31 | #include "llvm/Analysis/TargetTransformInfo.h" |
32 | |
33 | namespace llvm { |
34 | |
35 | /// VPlan-based builder utility analogous to IRBuilder. |
36 | class VPBuilder { |
37 | private: |
38 | VPBasicBlock *BB = nullptr; |
39 | VPBasicBlock::iterator InsertPt = VPBasicBlock::iterator(); |
40 | |
41 | VPInstruction *createInstruction(unsigned Opcode, |
42 | ArrayRef<VPValue *> Operands) { |
43 | VPInstruction *Instr = new VPInstruction(Opcode, Operands); |
44 | if (BB) |
45 | BB->insert(Instr, InsertPt); |
46 | return Instr; |
47 | } |
48 | |
49 | VPInstruction *createInstruction(unsigned Opcode, |
50 | std::initializer_list<VPValue *> Operands) { |
51 | return createInstruction(Opcode, ArrayRef<VPValue *>(Operands)); |
52 | } |
53 | |
54 | public: |
55 | VPBuilder() {} |
56 | |
57 | /// Clear the insertion point: created instructions will not be inserted into |
58 | /// a block. |
59 | void clearInsertionPoint() { |
60 | BB = nullptr; |
61 | InsertPt = VPBasicBlock::iterator(); |
62 | } |
63 | |
64 | VPBasicBlock *getInsertBlock() const { return BB; } |
65 | VPBasicBlock::iterator getInsertPoint() const { return InsertPt; } |
66 | |
67 | /// InsertPoint - A saved insertion point. |
68 | class VPInsertPoint { |
69 | VPBasicBlock *Block = nullptr; |
70 | VPBasicBlock::iterator Point; |
71 | |
72 | public: |
73 | /// Creates a new insertion point which doesn't point to anything. |
74 | VPInsertPoint() = default; |
75 | |
76 | /// Creates a new insertion point at the given location. |
77 | VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint) |
78 | : Block(InsertBlock), Point(InsertPoint) {} |
79 | |
80 | /// Returns true if this insert point is set. |
81 | bool isSet() const { return Block != nullptr; } |
82 | |
83 | VPBasicBlock *getBlock() const { return Block; } |
84 | VPBasicBlock::iterator getPoint() const { return Point; } |
85 | }; |
86 | |
87 | /// Sets the current insert point to a previously-saved location. |
88 | void restoreIP(VPInsertPoint IP) { |
89 | if (IP.isSet()) |
90 | setInsertPoint(IP.getBlock(), IP.getPoint()); |
91 | else |
92 | clearInsertionPoint(); |
93 | } |
94 | |
95 | /// This specifies that created VPInstructions should be appended to the end |
96 | /// of the specified block. |
97 | void setInsertPoint(VPBasicBlock *TheBB) { |
98 | assert(TheBB && "Attempting to set a null insert point")(static_cast <bool> (TheBB && "Attempting to set a null insert point" ) ? void (0) : __assert_fail ("TheBB && \"Attempting to set a null insert point\"" , "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Vectorize/LoopVectorizationPlanner.h" , 98, __extension__ __PRETTY_FUNCTION__)); |
99 | BB = TheBB; |
100 | InsertPt = BB->end(); |
101 | } |
102 | |
103 | /// This specifies that created instructions should be inserted at the |
104 | /// specified point. |
105 | void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP) { |
106 | BB = TheBB; |
107 | InsertPt = IP; |
108 | } |
109 | |
110 | /// Insert and return the specified instruction. |
111 | VPInstruction *insert(VPInstruction *I) const { |
112 | BB->insert(I, InsertPt); |
113 | return I; |
114 | } |
115 | |
116 | /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as |
117 | /// its underlying Instruction. |
118 | VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands, |
119 | Instruction *Inst = nullptr) { |
120 | VPInstruction *NewVPInst = createInstruction(Opcode, Operands); |
121 | NewVPInst->setUnderlyingValue(Inst); |
122 | return NewVPInst; |
123 | } |
124 | VPValue *createNaryOp(unsigned Opcode, |
125 | std::initializer_list<VPValue *> Operands, |
126 | Instruction *Inst = nullptr) { |
127 | return createNaryOp(Opcode, ArrayRef<VPValue *>(Operands), Inst); |
128 | } |
129 | |
130 | VPValue *createNot(VPValue *Operand) { |
131 | return createInstruction(VPInstruction::Not, {Operand}); |
132 | } |
133 | |
134 | VPValue *createAnd(VPValue *LHS, VPValue *RHS) { |
135 | return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}); |
136 | } |
137 | |
138 | VPValue *createOr(VPValue *LHS, VPValue *RHS) { |
139 | return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS}); |
140 | } |
141 | |
142 | //===--------------------------------------------------------------------===// |
143 | // RAII helpers. |
144 | //===--------------------------------------------------------------------===// |
145 | |
146 | /// RAII object that stores the current insertion point and restores it when |
147 | /// the object is destroyed. |
148 | class InsertPointGuard { |
149 | VPBuilder &Builder; |
150 | VPBasicBlock *Block; |
151 | VPBasicBlock::iterator Point; |
152 | |
153 | public: |
154 | InsertPointGuard(VPBuilder &B) |
155 | : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {} |
156 | |
157 | InsertPointGuard(const InsertPointGuard &) = delete; |
158 | InsertPointGuard &operator=(const InsertPointGuard &) = delete; |
159 | |
160 | ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); } |
161 | }; |
162 | }; |
163 | |
164 | /// TODO: The following VectorizationFactor was pulled out of |
165 | /// LoopVectorizationCostModel class. LV also deals with |
166 | /// VectorizerParams::VectorizationFactor and VectorizationCostTy. |
167 | /// We need to streamline them. |
168 | |
169 | /// Information about vectorization costs |
170 | struct VectorizationFactor { |
171 | // Vector width with best cost |
172 | unsigned Width; |
173 | // Cost of the loop with that width |
174 | unsigned Cost; |
175 | }; |
176 | |
177 | /// Planner drives the vectorization process after having passed |
178 | /// Legality checks. |
179 | class LoopVectorizationPlanner { |
180 | /// The loop that we evaluate. |
181 | Loop *OrigLoop; |
182 | |
183 | /// Loop Info analysis. |
184 | LoopInfo *LI; |
185 | |
186 | /// Target Library Info. |
187 | const TargetLibraryInfo *TLI; |
188 | |
189 | /// Target Transform Info. |
190 | const TargetTransformInfo *TTI; |
191 | |
192 | /// The legality analysis. |
193 | LoopVectorizationLegality *Legal; |
194 | |
195 | /// The profitablity analysis. |
196 | LoopVectorizationCostModel &CM; |
197 | |
198 | using VPlanPtr = std::unique_ptr<VPlan>; |
199 | |
200 | SmallVector<VPlanPtr, 4> VPlans; |
201 | |
202 | /// This class is used to enable the VPlan to invoke a method of ILV. This is |
203 | /// needed until the method is refactored out of ILV and becomes reusable. |
204 | struct VPCallbackILV : public VPCallback { |
205 | InnerLoopVectorizer &ILV; |
206 | |
207 | VPCallbackILV(InnerLoopVectorizer &ILV) : ILV(ILV) {} |
208 | |
209 | Value *getOrCreateVectorValues(Value *V, unsigned Part) override; |
210 | }; |
211 | |
212 | /// A builder used to construct the current plan. |
213 | VPBuilder Builder; |
214 | |
215 | unsigned BestVF = 0; |
216 | unsigned BestUF = 0; |
217 | |
218 | public: |
219 | LoopVectorizationPlanner(Loop *L, LoopInfo *LI, const TargetLibraryInfo *TLI, |
220 | const TargetTransformInfo *TTI, |
221 | LoopVectorizationLegality *Legal, |
222 | LoopVectorizationCostModel &CM) |
223 | : OrigLoop(L), LI(LI), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM) {} |
224 | |
225 | /// Plan how to best vectorize, return the best VF and its cost. |
226 | VectorizationFactor plan(bool OptForSize, unsigned UserVF); |
227 | |
228 | /// Use the VPlan-native path to plan how to best vectorize, return the best |
229 | /// VF and its cost. |
230 | VectorizationFactor planInVPlanNativePath(bool OptForSize, unsigned UserVF); |
231 | |
232 | /// Finalize the best decision and dispose of all other VPlans. |
233 | void setBestPlan(unsigned VF, unsigned UF); |
234 | |
235 | /// Generate the IR code for the body of the vectorized loop according to the |
236 | /// best selected VPlan. |
237 | void executePlan(InnerLoopVectorizer &LB, DominatorTree *DT); |
238 | |
239 | void printPlans(raw_ostream &O) { |
240 | for (const auto &Plan : VPlans) |
241 | O << *Plan; |
242 | } |
243 | |
244 | /// Test a \p Predicate on a \p Range of VF's. Return the value of applying |
245 | /// \p Predicate on Range.Start, possibly decreasing Range.End such that the |
246 | /// returned value holds for the entire \p Range. |
247 | static bool |
248 | getDecisionAndClampRange(const std::function<bool(unsigned)> &Predicate, |
249 | VFRange &Range); |
250 | |
251 | protected: |
252 | /// Collect the instructions from the original loop that would be trivially |
253 | /// dead in the vectorized loop if generated. |
254 | void collectTriviallyDeadInstructions( |
255 | SmallPtrSetImpl<Instruction *> &DeadInstructions); |
256 | |
257 | /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive, |
258 | /// according to the information gathered by Legal when it checked if it is |
259 | /// legal to vectorize the loop. |
260 | void buildVPlans(unsigned MinVF, unsigned MaxVF); |
261 | |
262 | private: |
263 | /// Build a VPlan according to the information gathered by Legal. \return a |
264 | /// VPlan for vectorization factors \p Range.Start and up to \p Range.End |
265 | /// exclusive, possibly decreasing \p Range.End. |
266 | VPlanPtr buildVPlan(VFRange &Range); |
267 | |
268 | /// Build a VPlan using VPRecipes according to the information gather by |
269 | /// Legal. This method is only used for the legacy inner loop vectorizer. |
270 | VPlanPtr |
271 | buildVPlanWithVPRecipes(VFRange &Range, SmallPtrSetImpl<Value *> &NeedDef, |
272 | SmallPtrSetImpl<Instruction *> &DeadInstructions); |
273 | |
274 | /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive, |
275 | /// according to the information gathered by Legal when it checked if it is |
276 | /// legal to vectorize the loop. This method creates VPlans using VPRecipes. |
277 | void buildVPlansWithVPRecipes(unsigned MinVF, unsigned MaxVF); |
278 | }; |
279 | |
280 | } // namespace llvm |
281 | |
282 | #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H |