Bug Summary

File:lib/Transforms/Vectorize/LoopVectorize.cpp
Warning:line 4929, column 60
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LoopVectorize.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Transforms/Vectorize -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp -faddrsig
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 "VPlanHCFGTransforms.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/DenseMapInfo.h"
66#include "llvm/ADT/Hashing.h"
67#include "llvm/ADT/MapVector.h"
68#include "llvm/ADT/None.h"
69#include "llvm/ADT/Optional.h"
70#include "llvm/ADT/STLExtras.h"
71#include "llvm/ADT/SetVector.h"
72#include "llvm/ADT/SmallPtrSet.h"
73#include "llvm/ADT/SmallVector.h"
74#include "llvm/ADT/Statistic.h"
75#include "llvm/ADT/StringRef.h"
76#include "llvm/ADT/Twine.h"
77#include "llvm/ADT/iterator_range.h"
78#include "llvm/Analysis/AssumptionCache.h"
79#include "llvm/Analysis/BasicAliasAnalysis.h"
80#include "llvm/Analysis/BlockFrequencyInfo.h"
81#include "llvm/Analysis/CFG.h"
82#include "llvm/Analysis/CodeMetrics.h"
83#include "llvm/Analysis/DemandedBits.h"
84#include "llvm/Analysis/GlobalsModRef.h"
85#include "llvm/Analysis/LoopAccessAnalysis.h"
86#include "llvm/Analysis/LoopAnalysisManager.h"
87#include "llvm/Analysis/LoopInfo.h"
88#include "llvm/Analysis/LoopIterator.h"
89#include "llvm/Analysis/OptimizationRemarkEmitter.h"
90#include "llvm/Analysis/ScalarEvolution.h"
91#include "llvm/Analysis/ScalarEvolutionExpander.h"
92#include "llvm/Analysis/ScalarEvolutionExpressions.h"
93#include "llvm/Analysis/TargetLibraryInfo.h"
94#include "llvm/Analysis/TargetTransformInfo.h"
95#include "llvm/Analysis/VectorUtils.h"
96#include "llvm/IR/Attributes.h"
97#include "llvm/IR/BasicBlock.h"
98#include "llvm/IR/CFG.h"
99#include "llvm/IR/Constant.h"
100#include "llvm/IR/Constants.h"
101#include "llvm/IR/DataLayout.h"
102#include "llvm/IR/DebugInfoMetadata.h"
103#include "llvm/IR/DebugLoc.h"
104#include "llvm/IR/DerivedTypes.h"
105#include "llvm/IR/DiagnosticInfo.h"
106#include "llvm/IR/Dominators.h"
107#include "llvm/IR/Function.h"
108#include "llvm/IR/IRBuilder.h"
109#include "llvm/IR/InstrTypes.h"
110#include "llvm/IR/Instruction.h"
111#include "llvm/IR/Instructions.h"
112#include "llvm/IR/IntrinsicInst.h"
113#include "llvm/IR/Intrinsics.h"
114#include "llvm/IR/LLVMContext.h"
115#include "llvm/IR/Metadata.h"
116#include "llvm/IR/Module.h"
117#include "llvm/IR/Operator.h"
118#include "llvm/IR/Type.h"
119#include "llvm/IR/Use.h"
120#include "llvm/IR/User.h"
121#include "llvm/IR/Value.h"
122#include "llvm/IR/ValueHandle.h"
123#include "llvm/IR/Verifier.h"
124#include "llvm/Pass.h"
125#include "llvm/Support/Casting.h"
126#include "llvm/Support/CommandLine.h"
127#include "llvm/Support/Compiler.h"
128#include "llvm/Support/Debug.h"
129#include "llvm/Support/ErrorHandling.h"
130#include "llvm/Support/MathExtras.h"
131#include "llvm/Support/raw_ostream.h"
132#include "llvm/Transforms/Utils/BasicBlockUtils.h"
133#include "llvm/Transforms/Utils/LoopSimplify.h"
134#include "llvm/Transforms/Utils/LoopUtils.h"
135#include "llvm/Transforms/Utils/LoopVersioning.h"
136#include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
137#include <algorithm>
138#include <cassert>
139#include <cstdint>
140#include <cstdlib>
141#include <functional>
142#include <iterator>
143#include <limits>
144#include <memory>
145#include <string>
146#include <tuple>
147#include <utility>
148#include <vector>
149
150using namespace llvm;
151
152#define LV_NAME"loop-vectorize" "loop-vectorize"
153#define DEBUG_TYPE"loop-vectorize" LV_NAME"loop-vectorize"
154
155STATISTIC(LoopsVectorized, "Number of loops vectorized")static llvm::Statistic LoopsVectorized = {"loop-vectorize", "LoopsVectorized"
, "Number of loops vectorized", {0}, {false}}
;
156STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization")static llvm::Statistic LoopsAnalyzed = {"loop-vectorize", "LoopsAnalyzed"
, "Number of loops analyzed for vectorization", {0}, {false}}
;
157
158/// Loops with a known constant trip count below this number are vectorized only
159/// if no scalar iteration overheads are incurred.
160static cl::opt<unsigned> TinyTripCountVectorThreshold(
161 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
162 cl::desc("Loops with a constant trip count that is smaller than this "
163 "value are vectorized only if no scalar iteration overheads "
164 "are incurred."));
165
166static cl::opt<bool> MaximizeBandwidth(
167 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
168 cl::desc("Maximize bandwidth when selecting vectorization factor which "
169 "will be determined by the smallest type in loop."));
170
171static cl::opt<bool> EnableInterleavedMemAccesses(
172 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
173 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
174
175static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
176 "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
177 cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
178
179/// We don't interleave loops with a known constant trip count below this
180/// number.
181static const unsigned TinyTripCountInterleaveThreshold = 128;
182
183static cl::opt<unsigned> ForceTargetNumScalarRegs(
184 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
185 cl::desc("A flag that overrides the target's number of scalar registers."));
186
187static cl::opt<unsigned> ForceTargetNumVectorRegs(
188 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
189 cl::desc("A flag that overrides the target's number of vector registers."));
190
191static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
192 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
193 cl::desc("A flag that overrides the target's max interleave factor for "
194 "scalar loops."));
195
196static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
197 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
198 cl::desc("A flag that overrides the target's max interleave factor for "
199 "vectorized loops."));
200
201static cl::opt<unsigned> ForceTargetInstructionCost(
202 "force-target-instruction-cost", cl::init(0), cl::Hidden,
203 cl::desc("A flag that overrides the target's expected cost for "
204 "an instruction to a single constant value. Mostly "
205 "useful for getting consistent testing."));
206
207static cl::opt<unsigned> SmallLoopCost(
208 "small-loop-cost", cl::init(20), cl::Hidden,
209 cl::desc(
210 "The cost of a loop that is considered 'small' by the interleaver."));
211
212static cl::opt<bool> LoopVectorizeWithBlockFrequency(
213 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
214 cl::desc("Enable the use of the block frequency analysis to access PGO "
215 "heuristics minimizing code growth in cold regions and being more "
216 "aggressive in hot regions."));
217
218// Runtime interleave loops for load/store throughput.
219static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
220 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
221 cl::desc(
222 "Enable runtime interleaving until load/store ports are saturated"));
223
224/// The number of stores in a loop that are allowed to need predication.
225static cl::opt<unsigned> NumberOfStoresToPredicate(
226 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
227 cl::desc("Max number of stores to be predicated behind an if."));
228
229static cl::opt<bool> EnableIndVarRegisterHeur(
230 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
231 cl::desc("Count the induction variable only once when interleaving"));
232
233static cl::opt<bool> EnableCondStoresVectorization(
234 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
235 cl::desc("Enable if predication of stores during vectorization."));
236
237static cl::opt<unsigned> MaxNestedScalarReductionIC(
238 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
239 cl::desc("The maximum interleave count to use when interleaving a scalar "
240 "reduction in a nested loop."));
241
242cl::opt<bool> EnableVPlanNativePath(
243 "enable-vplan-native-path", cl::init(false), cl::Hidden,
244 cl::desc("Enable VPlan-native vectorization path with "
245 "support for outer loop vectorization."));
246
247// This flag enables the stress testing of the VPlan H-CFG construction in the
248// VPlan-native vectorization path. It must be used in conjuction with
249// -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
250// verification of the H-CFGs built.
251static cl::opt<bool> VPlanBuildStressTest(
252 "vplan-build-stress-test", cl::init(false), cl::Hidden,
253 cl::desc(
254 "Build VPlan for every supported loop nest in the function and bail "
255 "out right after the build (stress test the VPlan H-CFG construction "
256 "in the VPlan-native vectorization path)."));
257
258/// A helper function for converting Scalar types to vector types.
259/// If the incoming type is void, we return void. If the VF is 1, we return
260/// the scalar type.
261static Type *ToVectorTy(Type *Scalar, unsigned VF) {
262 if (Scalar->isVoidTy() || VF == 1)
263 return Scalar;
264 return VectorType::get(Scalar, VF);
265}
266
267/// A helper function that returns the type of loaded or stored value.
268static Type *getMemInstValueType(Value *I) {
269 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
"Expected Load or Store instruction") ? static_cast<void>
(0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 270, __PRETTY_FUNCTION__))
270 "Expected Load or Store instruction")(((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
"Expected Load or Store instruction") ? static_cast<void>
(0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 270, __PRETTY_FUNCTION__))
;
271 if (auto *LI = dyn_cast<LoadInst>(I))
272 return LI->getType();
273 return cast<StoreInst>(I)->getValueOperand()->getType();
274}
275
276/// A helper function that returns true if the given type is irregular. The
277/// type is irregular if its allocated size doesn't equal the store size of an
278/// element of the corresponding vector type at the given vectorization factor.
279static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
280 // Determine if an array of VF elements of type Ty is "bitcast compatible"
281 // with a <VF x Ty> vector.
282 if (VF > 1) {
283 auto *VectorTy = VectorType::get(Ty, VF);
284 return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
285 }
286
287 // If the vectorization factor is one, we just check if an array of type Ty
288 // requires padding between elements.
289 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
290}
291
292/// A helper function that returns the reciprocal of the block probability of
293/// predicated blocks. If we return X, we are assuming the predicated block
294/// will execute once for every X iterations of the loop header.
295///
296/// TODO: We should use actual block probability here, if available. Currently,
297/// we always assume predicated blocks have a 50% chance of executing.
298static unsigned getReciprocalPredBlockProb() { return 2; }
299
300/// A helper function that adds a 'fast' flag to floating-point operations.
301static Value *addFastMathFlag(Value *V) {
302 if (isa<FPMathOperator>(V)) {
303 FastMathFlags Flags;
304 Flags.setFast();
305 cast<Instruction>(V)->setFastMathFlags(Flags);
306 }
307 return V;
308}
309
310/// A helper function that returns an integer or floating-point constant with
311/// value C.
312static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
313 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
314 : ConstantFP::get(Ty, C);
315}
316
317namespace llvm {
318
319/// InnerLoopVectorizer vectorizes loops which contain only one basic
320/// block to a specified vectorization factor (VF).
321/// This class performs the widening of scalars into vectors, or multiple
322/// scalars. This class also implements the following features:
323/// * It inserts an epilogue loop for handling loops that don't have iteration
324/// counts that are known to be a multiple of the vectorization factor.
325/// * It handles the code generation for reduction variables.
326/// * Scalarization (implementation using scalars) of un-vectorizable
327/// instructions.
328/// InnerLoopVectorizer does not perform any vectorization-legality
329/// checks, and relies on the caller to check for the different legality
330/// aspects. The InnerLoopVectorizer relies on the
331/// LoopVectorizationLegality class to provide information about the induction
332/// and reduction variables that were found to a given vectorization factor.
333class InnerLoopVectorizer {
334public:
335 InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
336 LoopInfo *LI, DominatorTree *DT,
337 const TargetLibraryInfo *TLI,
338 const TargetTransformInfo *TTI, AssumptionCache *AC,
339 OptimizationRemarkEmitter *ORE, unsigned VecWidth,
340 unsigned UnrollFactor, LoopVectorizationLegality *LVL,
341 LoopVectorizationCostModel *CM)
342 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
343 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
344 Builder(PSE.getSE()->getContext()),
345 VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
346 virtual ~InnerLoopVectorizer() = default;
347
348 /// Create a new empty loop. Unlink the old loop and connect the new one.
349 /// Return the pre-header block of the new loop.
350 BasicBlock *createVectorizedLoopSkeleton();
351
352 /// Widen a single instruction within the innermost loop.
353 void widenInstruction(Instruction &I);
354
355 /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
356 void fixVectorizedLoop();
357
358 // Return true if any runtime check is added.
359 bool areSafetyChecksAdded() { return AddedSafetyChecks; }
360
361 /// A type for vectorized values in the new loop. Each value from the
362 /// original loop, when vectorized, is represented by UF vector values in the
363 /// new unrolled loop, where UF is the unroll factor.
364 using VectorParts = SmallVector<Value *, 2>;
365
366 /// Vectorize a single PHINode in a block. This method handles the induction
367 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
368 /// arbitrary length vectors.
369 void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
370
371 /// A helper function to scalarize a single Instruction in the innermost loop.
372 /// Generates a sequence of scalar instances for each lane between \p MinLane
373 /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
374 /// inclusive..
375 void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
376 bool IfPredicateInstr);
377
378 /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
379 /// is provided, the integer induction variable will first be truncated to
380 /// the corresponding type.
381 void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
382
383 /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
384 /// vector or scalar value on-demand if one is not yet available. When
385 /// vectorizing a loop, we visit the definition of an instruction before its
386 /// uses. When visiting the definition, we either vectorize or scalarize the
387 /// instruction, creating an entry for it in the corresponding map. (In some
388 /// cases, such as induction variables, we will create both vector and scalar
389 /// entries.) Then, as we encounter uses of the definition, we derive values
390 /// for each scalar or vector use unless such a value is already available.
391 /// For example, if we scalarize a definition and one of its uses is vector,
392 /// we build the required vector on-demand with an insertelement sequence
393 /// when visiting the use. Otherwise, if the use is scalar, we can use the
394 /// existing scalar definition.
395 ///
396 /// Return a value in the new loop corresponding to \p V from the original
397 /// loop at unroll index \p Part. If the value has already been vectorized,
398 /// the corresponding vector entry in VectorLoopValueMap is returned. If,
399 /// however, the value has a scalar entry in VectorLoopValueMap, we construct
400 /// a new vector value on-demand by inserting the scalar values into a vector
401 /// with an insertelement sequence. If the value has been neither vectorized
402 /// nor scalarized, it must be loop invariant, so we simply broadcast the
403 /// value into a vector.
404 Value *getOrCreateVectorValue(Value *V, unsigned Part);
405
406 /// Return a value in the new loop corresponding to \p V from the original
407 /// loop at unroll and vector indices \p Instance. If the value has been
408 /// vectorized but not scalarized, the necessary extractelement instruction
409 /// will be generated.
410 Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
411
412 /// Construct the vector value of a scalarized value \p V one lane at a time.
413 void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
414
415 /// Try to vectorize the interleaved access group that \p Instr belongs to,
416 /// optionally masking the vector operations if \p BlockInMask is non-null.
417 void vectorizeInterleaveGroup(Instruction *Instr,
418 VectorParts *BlockInMask = nullptr);
419
420 /// Vectorize Load and Store instructions, optionally masking the vector
421 /// operations if \p BlockInMask is non-null.
422 void vectorizeMemoryInstruction(Instruction *Instr,
423 VectorParts *BlockInMask = nullptr);
424
425 /// Set the debug location in the builder using the debug location in
426 /// the instruction.
427 void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
428
429 /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
430 void fixNonInductionPHIs(void);
431
432protected:
433 friend class LoopVectorizationPlanner;
434
435 /// A small list of PHINodes.
436 using PhiVector = SmallVector<PHINode *, 4>;
437
438 /// A type for scalarized values in the new loop. Each value from the
439 /// original loop, when scalarized, is represented by UF x VF scalar values
440 /// in the new unrolled loop, where UF is the unroll factor and VF is the
441 /// vectorization factor.
442 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
443
444 /// Set up the values of the IVs correctly when exiting the vector loop.
445 void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
446 Value *CountRoundDown, Value *EndValue,
447 BasicBlock *MiddleBlock);
448
449 /// Create a new induction variable inside L.
450 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
451 Value *Step, Instruction *DL);
452
453 /// Handle all cross-iteration phis in the header.
454 void fixCrossIterationPHIs();
455
456 /// Fix a first-order recurrence. This is the second phase of vectorizing
457 /// this phi node.
458 void fixFirstOrderRecurrence(PHINode *Phi);
459
460 /// Fix a reduction cross-iteration phi. This is the second phase of
461 /// vectorizing this phi node.
462 void fixReduction(PHINode *Phi);
463
464 /// The Loop exit block may have single value PHI nodes with some
465 /// incoming value. While vectorizing we only handled real values
466 /// that were defined inside the loop and we should have one value for
467 /// each predecessor of its parent basic block. See PR14725.
468 void fixLCSSAPHIs();
469
470 /// Iteratively sink the scalarized operands of a predicated instruction into
471 /// the block that was created for it.
472 void sinkScalarOperands(Instruction *PredInst);
473
474 /// Shrinks vector element sizes to the smallest bitwidth they can be legally
475 /// represented as.
476 void truncateToMinimalBitwidths();
477
478 /// Insert the new loop to the loop hierarchy and pass manager
479 /// and update the analysis passes.
480 void updateAnalysis();
481
482 /// Create a broadcast instruction. This method generates a broadcast
483 /// instruction (shuffle) for loop invariant values and for the induction
484 /// value. If this is the induction variable then we extend it to N, N+1, ...
485 /// this is needed because each iteration in the loop corresponds to a SIMD
486 /// element.
487 virtual Value *getBroadcastInstrs(Value *V);
488
489 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
490 /// to each vector element of Val. The sequence starts at StartIndex.
491 /// \p Opcode is relevant for FP induction variable.
492 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
493 Instruction::BinaryOps Opcode =
494 Instruction::BinaryOpsEnd);
495
496 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
497 /// variable on which to base the steps, \p Step is the size of the step, and
498 /// \p EntryVal is the value from the original loop that maps to the steps.
499 /// Note that \p EntryVal doesn't have to be an induction variable - it
500 /// can also be a truncate instruction.
501 void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
502 const InductionDescriptor &ID);
503
504 /// Create a vector induction phi node based on an existing scalar one. \p
505 /// EntryVal is the value from the original loop that maps to the vector phi
506 /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
507 /// truncate instruction, instead of widening the original IV, we widen a
508 /// version of the IV truncated to \p EntryVal's type.
509 void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
510 Value *Step, Instruction *EntryVal);
511
512 /// Returns true if an instruction \p I should be scalarized instead of
513 /// vectorized for the chosen vectorization factor.
514 bool shouldScalarizeInstruction(Instruction *I) const;
515
516 /// Returns true if we should generate a scalar version of \p IV.
517 bool needsScalarInduction(Instruction *IV) const;
518
519 /// If there is a cast involved in the induction variable \p ID, which should
520 /// be ignored in the vectorized loop body, this function records the
521 /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
522 /// cast. We had already proved that the casted Phi is equal to the uncasted
523 /// Phi in the vectorized loop (under a runtime guard), and therefore
524 /// there is no need to vectorize the cast - the same value can be used in the
525 /// vector loop for both the Phi and the cast.
526 /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
527 /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
528 ///
529 /// \p EntryVal is the value from the original loop that maps to the vector
530 /// phi node and is used to distinguish what is the IV currently being
531 /// processed - original one (if \p EntryVal is a phi corresponding to the
532 /// original IV) or the "newly-created" one based on the proof mentioned above
533 /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
534 /// latter case \p EntryVal is a TruncInst and we must not record anything for
535 /// that IV, but it's error-prone to expect callers of this routine to care
536 /// about that, hence this explicit parameter.
537 void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID,
538 const Instruction *EntryVal,
539 Value *VectorLoopValue,
540 unsigned Part,
541 unsigned Lane = UINT_MAX(2147483647 *2U +1U));
542
543 /// Generate a shuffle sequence that will reverse the vector Vec.
544 virtual Value *reverseVector(Value *Vec);
545
546 /// Returns (and creates if needed) the original loop trip count.
547 Value *getOrCreateTripCount(Loop *NewLoop);
548
549 /// Returns (and creates if needed) the trip count of the widened loop.
550 Value *getOrCreateVectorTripCount(Loop *NewLoop);
551
552 /// Returns a bitcasted value to the requested vector type.
553 /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
554 Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
555 const DataLayout &DL);
556
557 /// Emit a bypass check to see if the vector trip count is zero, including if
558 /// it overflows.
559 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
560
561 /// Emit a bypass check to see if all of the SCEV assumptions we've
562 /// had to make are correct.
563 void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
564
565 /// Emit bypass checks to check any memory assumptions we may have made.
566 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
567
568 /// Compute the transformed value of Index at offset StartValue using step
569 /// StepValue.
570 /// For integer induction, returns StartValue + Index * StepValue.
571 /// For pointer induction, returns StartValue[Index * StepValue].
572 /// FIXME: The newly created binary instructions should contain nsw/nuw
573 /// flags, which can be found from the original scalar operations.
574 Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
575 const DataLayout &DL,
576 const InductionDescriptor &ID) const;
577
578 /// Add additional metadata to \p To that was not present on \p Orig.
579 ///
580 /// Currently this is used to add the noalias annotations based on the
581 /// inserted memchecks. Use this for instructions that are *cloned* into the
582 /// vector loop.
583 void addNewMetadata(Instruction *To, const Instruction *Orig);
584
585 /// Add metadata from one instruction to another.
586 ///
587 /// This includes both the original MDs from \p From and additional ones (\see
588 /// addNewMetadata). Use this for *newly created* instructions in the vector
589 /// loop.
590 void addMetadata(Instruction *To, Instruction *From);
591
592 /// Similar to the previous function but it adds the metadata to a
593 /// vector of instructions.
594 void addMetadata(ArrayRef<Value *> To, Instruction *From);
595
596 /// The original loop.
597 Loop *OrigLoop;
598
599 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
600 /// dynamic knowledge to simplify SCEV expressions and converts them to a
601 /// more usable form.
602 PredicatedScalarEvolution &PSE;
603
604 /// Loop Info.
605 LoopInfo *LI;
606
607 /// Dominator Tree.
608 DominatorTree *DT;
609
610 /// Alias Analysis.
611 AliasAnalysis *AA;
612
613 /// Target Library Info.
614 const TargetLibraryInfo *TLI;
615
616 /// Target Transform Info.
617 const TargetTransformInfo *TTI;
618
619 /// Assumption Cache.
620 AssumptionCache *AC;
621
622 /// Interface to emit optimization remarks.
623 OptimizationRemarkEmitter *ORE;
624
625 /// LoopVersioning. It's only set up (non-null) if memchecks were
626 /// used.
627 ///
628 /// This is currently only used to add no-alias metadata based on the
629 /// memchecks. The actually versioning is performed manually.
630 std::unique_ptr<LoopVersioning> LVer;
631
632 /// The vectorization SIMD factor to use. Each vector will have this many
633 /// vector elements.
634 unsigned VF;
635
636 /// The vectorization unroll factor to use. Each scalar is vectorized to this
637 /// many different vector instructions.
638 unsigned UF;
639
640 /// The builder that we use
641 IRBuilder<> Builder;
642
643 // --- Vectorization state ---
644
645 /// The vector-loop preheader.
646 BasicBlock *LoopVectorPreHeader;
647
648 /// The scalar-loop preheader.
649 BasicBlock *LoopScalarPreHeader;
650
651 /// Middle Block between the vector and the scalar.
652 BasicBlock *LoopMiddleBlock;
653
654 /// The ExitBlock of the scalar loop.
655 BasicBlock *LoopExitBlock;
656
657 /// The vector loop body.
658 BasicBlock *LoopVectorBody;
659
660 /// The scalar loop body.
661 BasicBlock *LoopScalarBody;
662
663 /// A list of all bypass blocks. The first block is the entry of the loop.
664 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
665
666 /// The new Induction variable which was added to the new block.
667 PHINode *Induction = nullptr;
668
669 /// The induction variable of the old basic block.
670 PHINode *OldInduction = nullptr;
671
672 /// Maps values from the original loop to their corresponding values in the
673 /// vectorized loop. A key value can map to either vector values, scalar
674 /// values or both kinds of values, depending on whether the key was
675 /// vectorized and scalarized.
676 VectorizerValueMap VectorLoopValueMap;
677
678 /// Store instructions that were predicated.
679 SmallVector<Instruction *, 4> PredicatedInstructions;
680
681 /// Trip count of the original loop.
682 Value *TripCount = nullptr;
683
684 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
685 Value *VectorTripCount = nullptr;
686
687 /// The legality analysis.
688 LoopVectorizationLegality *Legal;
689
690 /// The profitablity analysis.
691 LoopVectorizationCostModel *Cost;
692
693 // Record whether runtime checks are added.
694 bool AddedSafetyChecks = false;
695
696 // Holds the end values for each induction variable. We save the end values
697 // so we can later fix-up the external users of the induction variables.
698 DenseMap<PHINode *, Value *> IVEndValues;
699
700 // Vector of original scalar PHIs whose corresponding widened PHIs need to be
701 // fixed up at the end of vector code generation.
702 SmallVector<PHINode *, 8> OrigPHIsToFix;
703};
704
705class InnerLoopUnroller : public InnerLoopVectorizer {
706public:
707 InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
708 LoopInfo *LI, DominatorTree *DT,
709 const TargetLibraryInfo *TLI,
710 const TargetTransformInfo *TTI, AssumptionCache *AC,
711 OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
712 LoopVectorizationLegality *LVL,
713 LoopVectorizationCostModel *CM)
714 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
715 UnrollFactor, LVL, CM) {}
716
717private:
718 Value *getBroadcastInstrs(Value *V) override;
719 Value *getStepVector(Value *Val, int StartIdx, Value *Step,
720 Instruction::BinaryOps Opcode =
721 Instruction::BinaryOpsEnd) override;
722 Value *reverseVector(Value *Vec) override;
723};
724
725} // end namespace llvm
726
727/// Look for a meaningful debug location on the instruction or it's
728/// operands.
729static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
730 if (!I)
731 return I;
732
733 DebugLoc Empty;
734 if (I->getDebugLoc() != Empty)
735 return I;
736
737 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
738 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
739 if (OpInst->getDebugLoc() != Empty)
740 return OpInst;
741 }
742
743 return I;
744}
745
746void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
747 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
748 const DILocation *DIL = Inst->getDebugLoc();
749 if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
750 !isa<DbgInfoIntrinsic>(Inst))
751 B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
752 else
753 B.SetCurrentDebugLocation(DIL);
754 } else
755 B.SetCurrentDebugLocation(DebugLoc());
756}
757
758#ifndef NDEBUG
759/// \return string containing a file name and a line # for the given loop.
760static std::string getDebugLocString(const Loop *L) {
761 std::string Result;
762 if (L) {
763 raw_string_ostream OS(Result);
764 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
765 LoopDbgLoc.print(OS);
766 else
767 // Just print the module name.
768 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
769 OS.flush();
770 }
771 return Result;
772}
773#endif
774
775void InnerLoopVectorizer::addNewMetadata(Instruction *To,
776 const Instruction *Orig) {
777 // If the loop was versioned with memchecks, add the corresponding no-alias
778 // metadata.
779 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
780 LVer->annotateInstWithNoAlias(To, Orig);
781}
782
783void InnerLoopVectorizer::addMetadata(Instruction *To,
784 Instruction *From) {
785 propagateMetadata(To, From);
786 addNewMetadata(To, From);
787}
788
789void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
790 Instruction *From) {
791 for (Value *V : To) {
792 if (Instruction *I = dyn_cast<Instruction>(V))
793 addMetadata(I, From);
794 }
795}
796
797static void emitMissedWarning(Function *F, Loop *L,
798 const LoopVectorizeHints &LH,
799 OptimizationRemarkEmitter *ORE) {
800 LH.emitRemarkWithHints();
801
802 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
803 if (LH.getWidth() != 1)
804 ORE->emit(DiagnosticInfoOptimizationFailure(
805 DEBUG_TYPE"loop-vectorize", "FailedRequestedVectorization",
806 L->getStartLoc(), L->getHeader())
807 << "loop not vectorized: "
808 << "failed explicitly specified loop vectorization");
809 else if (LH.getInterleave() != 1)
810 ORE->emit(DiagnosticInfoOptimizationFailure(
811 DEBUG_TYPE"loop-vectorize", "FailedRequestedInterleaving", L->getStartLoc(),
812 L->getHeader())
813 << "loop not interleaved: "
814 << "failed explicitly specified loop interleaving");
815 }
816}
817
818namespace llvm {
819
820/// LoopVectorizationCostModel - estimates the expected speedups due to
821/// vectorization.
822/// In many cases vectorization is not profitable. This can happen because of
823/// a number of reasons. In this class we mainly attempt to predict the
824/// expected speedup/slowdowns due to the supported instruction set. We use the
825/// TargetTransformInfo to query the different backends for the cost of
826/// different operations.
827class LoopVectorizationCostModel {
828public:
829 LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
830 LoopInfo *LI, LoopVectorizationLegality *Legal,
831 const TargetTransformInfo &TTI,
832 const TargetLibraryInfo *TLI, DemandedBits *DB,
833 AssumptionCache *AC,
834 OptimizationRemarkEmitter *ORE, const Function *F,
835 const LoopVectorizeHints *Hints,
836 InterleavedAccessInfo &IAI)
837 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
838 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {}
839
840 /// \return An upper bound for the vectorization factor, or None if
841 /// vectorization should be avoided up front.
842 Optional<unsigned> computeMaxVF(bool OptForSize);
843
844 /// \return The most profitable vectorization factor and the cost of that VF.
845 /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
846 /// then this vectorization factor will be selected if vectorization is
847 /// possible.
848 VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
849
850 /// Setup cost-based decisions for user vectorization factor.
851 void selectUserVectorizationFactor(unsigned UserVF) {
852 collectUniformsAndScalars(UserVF);
853 collectInstsToScalarize(UserVF);
854 }
855
856 /// \return The size (in bits) of the smallest and widest types in the code
857 /// that needs to be vectorized. We ignore values that remain scalar such as
858 /// 64 bit loop indices.
859 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
860
861 /// \return The desired interleave count.
862 /// If interleave count has been specified by metadata it will be returned.
863 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
864 /// are the selected vectorization factor and the cost of the selected VF.
865 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
866 unsigned LoopCost);
867
868 /// Memory access instruction may be vectorized in more than one way.
869 /// Form of instruction after vectorization depends on cost.
870 /// This function takes cost-based decisions for Load/Store instructions
871 /// and collects them in a map. This decisions map is used for building
872 /// the lists of loop-uniform and loop-scalar instructions.
873 /// The calculated cost is saved with widening decision in order to
874 /// avoid redundant calculations.
875 void setCostBasedWideningDecision(unsigned VF);
876
877 /// A struct that represents some properties of the register usage
878 /// of a loop.
879 struct RegisterUsage {
880 /// Holds the number of loop invariant values that are used in the loop.
881 unsigned LoopInvariantRegs;
882
883 /// Holds the maximum number of concurrent live intervals in the loop.
884 unsigned MaxLocalUsers;
885 };
886
887 /// \return Returns information about the register usages of the loop for the
888 /// given vectorization factors.
889 SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
890
891 /// Collect values we want to ignore in the cost model.
892 void collectValuesToIgnore();
893
894 /// \returns The smallest bitwidth each instruction can be represented with.
895 /// The vector equivalents of these instructions should be truncated to this
896 /// type.
897 const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
898 return MinBWs;
899 }
900
901 /// \returns True if it is more profitable to scalarize instruction \p I for
902 /// vectorization factor \p VF.
903 bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
904 assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.")((VF > 1 && "Profitable to scalarize relevant only for VF > 1."
) ? static_cast<void> (0) : __assert_fail ("VF > 1 && \"Profitable to scalarize relevant only for VF > 1.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 904, __PRETTY_FUNCTION__))
;
905
906 // Cost model is not run in the VPlan-native path - return conservative
907 // result until this changes.
908 if (EnableVPlanNativePath)
909 return false;
910
911 auto Scalars = InstsToScalarize.find(VF);
912 assert(Scalars != InstsToScalarize.end() &&((Scalars != InstsToScalarize.end() && "VF not yet analyzed for scalarization profitability"
) ? static_cast<void> (0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 913, __PRETTY_FUNCTION__))
913 "VF not yet analyzed for scalarization profitability")((Scalars != InstsToScalarize.end() && "VF not yet analyzed for scalarization profitability"
) ? static_cast<void> (0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 913, __PRETTY_FUNCTION__))
;
914 return Scalars->second.find(I) != Scalars->second.end();
915 }
916
917 /// Returns true if \p I is known to be uniform after vectorization.
918 bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
919 if (VF == 1)
920 return true;
921
922 // Cost model is not run in the VPlan-native path - return conservative
923 // result until this changes.
924 if (EnableVPlanNativePath)
925 return false;
926
927 auto UniformsPerVF = Uniforms.find(VF);
928 assert(UniformsPerVF != Uniforms.end() &&((UniformsPerVF != Uniforms.end() && "VF not yet analyzed for uniformity"
) ? static_cast<void> (0) : __assert_fail ("UniformsPerVF != Uniforms.end() && \"VF not yet analyzed for uniformity\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 929, __PRETTY_FUNCTION__))
929 "VF not yet analyzed for uniformity")((UniformsPerVF != Uniforms.end() && "VF not yet analyzed for uniformity"
) ? static_cast<void> (0) : __assert_fail ("UniformsPerVF != Uniforms.end() && \"VF not yet analyzed for uniformity\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 929, __PRETTY_FUNCTION__))
;
930 return UniformsPerVF->second.find(I) != UniformsPerVF->second.end();
931 }
932
933 /// Returns true if \p I is known to be scalar after vectorization.
934 bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
935 if (VF == 1)
936 return true;
937
938 // Cost model is not run in the VPlan-native path - return conservative
939 // result until this changes.
940 if (EnableVPlanNativePath)
941 return false;
942
943 auto ScalarsPerVF = Scalars.find(VF);
944 assert(ScalarsPerVF != Scalars.end() &&((ScalarsPerVF != Scalars.end() && "Scalar values are not calculated for VF"
) ? static_cast<void> (0) : __assert_fail ("ScalarsPerVF != Scalars.end() && \"Scalar values are not calculated for VF\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 945, __PRETTY_FUNCTION__))
945 "Scalar values are not calculated for VF")((ScalarsPerVF != Scalars.end() && "Scalar values are not calculated for VF"
) ? static_cast<void> (0) : __assert_fail ("ScalarsPerVF != Scalars.end() && \"Scalar values are not calculated for VF\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 945, __PRETTY_FUNCTION__))
;
946 return ScalarsPerVF->second.find(I) != ScalarsPerVF->second.end();
947 }
948
949 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
950 /// for vectorization factor \p VF.
951 bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
952 return VF > 1 && MinBWs.find(I) != MinBWs.end() &&
953 !isProfitableToScalarize(I, VF) &&
954 !isScalarAfterVectorization(I, VF);
955 }
956
957 /// Decision that was taken during cost calculation for memory instruction.
958 enum InstWidening {
959 CM_Unknown,
960 CM_Widen, // For consecutive accesses with stride +1.
961 CM_Widen_Reverse, // For consecutive accesses with stride -1.
962 CM_Interleave,
963 CM_GatherScatter,
964 CM_Scalarize
965 };
966
967 /// Save vectorization decision \p W and \p Cost taken by the cost model for
968 /// instruction \p I and vector width \p VF.
969 void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
970 unsigned Cost) {
971 assert(VF >= 2 && "Expected VF >=2")((VF >= 2 && "Expected VF >=2") ? static_cast<
void> (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 971, __PRETTY_FUNCTION__))
;
972 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
973 }
974
975 /// Save vectorization decision \p W and \p Cost taken by the cost model for
976 /// interleaving group \p Grp and vector width \p VF.
977 void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
978 InstWidening W, unsigned Cost) {
979 assert(VF >= 2 && "Expected VF >=2")((VF >= 2 && "Expected VF >=2") ? static_cast<
void> (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 979, __PRETTY_FUNCTION__))
;
980 /// Broadcast this decicion to all instructions inside the group.
981 /// But the cost will be assigned to one instruction only.
982 for (unsigned i = 0; i < Grp->getFactor(); ++i) {
983 if (auto *I = Grp->getMember(i)) {
984 if (Grp->getInsertPos() == I)
985 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
986 else
987 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
988 }
989 }
990 }
991
992 /// Return the cost model decision for the given instruction \p I and vector
993 /// width \p VF. Return CM_Unknown if this instruction did not pass
994 /// through the cost modeling.
995 InstWidening getWideningDecision(Instruction *I, unsigned VF) {
996 assert(VF >= 2 && "Expected VF >=2")((VF >= 2 && "Expected VF >=2") ? static_cast<
void> (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 996, __PRETTY_FUNCTION__))
;
997
998 // Cost model is not run in the VPlan-native path - return conservative
999 // result until this changes.
1000 if (EnableVPlanNativePath)
1001 return CM_GatherScatter;
1002
1003 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1004 auto Itr = WideningDecisions.find(InstOnVF);
1005 if (Itr == WideningDecisions.end())
1006 return CM_Unknown;
1007 return Itr->second.first;
1008 }
1009
1010 /// Return the vectorization cost for the given instruction \p I and vector
1011 /// width \p VF.
1012 unsigned getWideningCost(Instruction *I, unsigned VF) {
1013 assert(VF >= 2 && "Expected VF >=2")((VF >= 2 && "Expected VF >=2") ? static_cast<
void> (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1013, __PRETTY_FUNCTION__))
;
1014 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1015 assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&((WideningDecisions.find(InstOnVF) != WideningDecisions.end()
&& "The cost is not calculated") ? static_cast<void
> (0) : __assert_fail ("WideningDecisions.find(InstOnVF) != WideningDecisions.end() && \"The cost is not calculated\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1016, __PRETTY_FUNCTION__))
1016 "The cost is not calculated")((WideningDecisions.find(InstOnVF) != WideningDecisions.end()
&& "The cost is not calculated") ? static_cast<void
> (0) : __assert_fail ("WideningDecisions.find(InstOnVF) != WideningDecisions.end() && \"The cost is not calculated\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1016, __PRETTY_FUNCTION__))
;
1017 return WideningDecisions[InstOnVF].second;
1018 }
1019
1020 /// Return True if instruction \p I is an optimizable truncate whose operand
1021 /// is an induction variable. Such a truncate will be removed by adding a new
1022 /// induction variable with the destination type.
1023 bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
1024 // If the instruction is not a truncate, return false.
1025 auto *Trunc = dyn_cast<TruncInst>(I);
1026 if (!Trunc)
1027 return false;
1028
1029 // Get the source and destination types of the truncate.
1030 Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1031 Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1032
1033 // If the truncate is free for the given types, return false. Replacing a
1034 // free truncate with an induction variable would add an induction variable
1035 // update instruction to each iteration of the loop. We exclude from this
1036 // check the primary induction variable since it will need an update
1037 // instruction regardless.
1038 Value *Op = Trunc->getOperand(0);
1039 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1040 return false;
1041
1042 // If the truncated value is not an induction variable, return false.
1043 return Legal->isInductionPhi(Op);
1044 }
1045
1046 /// Collects the instructions to scalarize for each predicated instruction in
1047 /// the loop.
1048 void collectInstsToScalarize(unsigned VF);
1049
1050 /// Collect Uniform and Scalar values for the given \p VF.
1051 /// The sets depend on CM decision for Load/Store instructions
1052 /// that may be vectorized as interleave, gather-scatter or scalarized.
1053 void collectUniformsAndScalars(unsigned VF) {
1054 // Do the analysis once.
1055 if (VF == 1 || Uniforms.find(VF) != Uniforms.end())
1056 return;
1057 setCostBasedWideningDecision(VF);
1058 collectLoopUniforms(VF);
1059 collectLoopScalars(VF);
1060 }
1061
1062 /// Returns true if the target machine supports masked store operation
1063 /// for the given \p DataType and kind of access to \p Ptr.
1064 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1065 return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType);
1066 }
1067
1068 /// Returns true if the target machine supports masked load operation
1069 /// for the given \p DataType and kind of access to \p Ptr.
1070 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1071 return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType);
1072 }
1073
1074 /// Returns true if the target machine supports masked scatter operation
1075 /// for the given \p DataType.
1076 bool isLegalMaskedScatter(Type *DataType) {
1077 return TTI.isLegalMaskedScatter(DataType);
1078 }
1079
1080 /// Returns true if the target machine supports masked gather operation
1081 /// for the given \p DataType.
1082 bool isLegalMaskedGather(Type *DataType) {
1083 return TTI.isLegalMaskedGather(DataType);
1084 }
1085
1086 /// Returns true if the target machine can represent \p V as a masked gather
1087 /// or scatter operation.
1088 bool isLegalGatherOrScatter(Value *V) {
1089 bool LI = isa<LoadInst>(V);
1090 bool SI = isa<StoreInst>(V);
1091 if (!LI && !SI)
1092 return false;
1093 auto *Ty = getMemInstValueType(V);
1094 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1095 }
1096
1097 /// Returns true if \p I is an instruction that will be scalarized with
1098 /// predication. Such instructions include conditional stores and
1099 /// instructions that may divide by zero.
1100 /// If a non-zero VF has been calculated, we check if I will be scalarized
1101 /// predication for that VF.
1102 bool isScalarWithPredication(Instruction *I, unsigned VF = 1);
1103
1104 // Returns true if \p I is an instruction that will be predicated either
1105 // through scalar predication or masked load/store or masked gather/scatter.
1106 // Superset of instructions that return true for isScalarWithPredication.
1107 bool isPredicatedInst(Instruction *I) {
1108 if (!blockNeedsPredication(I->getParent()))
1109 return false;
1110 // Loads and stores that need some form of masked operation are predicated
1111 // instructions.
1112 if (isa<LoadInst>(I) || isa<StoreInst>(I))
1113 return Legal->isMaskRequired(I);
1114 return isScalarWithPredication(I);
1115 }
1116
1117 /// Returns true if \p I is a memory instruction with consecutive memory
1118 /// access that can be widened.
1119 bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
1120
1121 /// Returns true if \p I is a memory instruction in an interleaved-group
1122 /// of memory accesses that can be vectorized with wide vector loads/stores
1123 /// and shuffles.
1124 bool interleavedAccessCanBeWidened(Instruction *I, unsigned VF = 1);
1125
1126 /// Check if \p Instr belongs to any interleaved access group.
1127 bool isAccessInterleaved(Instruction *Instr) {
1128 return InterleaveInfo.isInterleaved(Instr);
1129 }
1130
1131 /// Get the interleaved access group that \p Instr belongs to.
1132 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1133 return InterleaveInfo.getInterleaveGroup(Instr);
1134 }
1135
1136 /// Returns true if an interleaved group requires a scalar iteration
1137 /// to handle accesses with gaps.
1138 bool requiresScalarEpilogue() const {
1139 return InterleaveInfo.requiresScalarEpilogue();
1140 }
1141
1142 /// Returns true if all loop blocks should be masked to fold tail loop.
1143 bool foldTailByMasking() const { return FoldTailByMasking; }
1144
1145 bool blockNeedsPredication(BasicBlock *BB) {
1146 return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1147 }
1148
1149private:
1150 unsigned NumPredStores = 0;
1151
1152 /// \return An upper bound for the vectorization factor, larger than zero.
1153 /// One is returned if vectorization should best be avoided due to cost.
1154 unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
1155
1156 /// The vectorization cost is a combination of the cost itself and a boolean
1157 /// indicating whether any of the contributing operations will actually
1158 /// operate on
1159 /// vector values after type legalization in the backend. If this latter value
1160 /// is
1161 /// false, then all operations will be scalarized (i.e. no vectorization has
1162 /// actually taken place).
1163 using VectorizationCostTy = std::pair<unsigned, bool>;
1164
1165 /// Returns the expected execution cost. The unit of the cost does
1166 /// not matter because we use the 'cost' units to compare different
1167 /// vector widths. The cost that is returned is *not* normalized by
1168 /// the factor width.
1169 VectorizationCostTy expectedCost(unsigned VF);
1170
1171 /// Returns the execution time cost of an instruction for a given vector
1172 /// width. Vector width of one means scalar.
1173 VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
1174
1175 /// The cost-computation logic from getInstructionCost which provides
1176 /// the vector type as an output parameter.
1177 unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
1178
1179 /// Calculate vectorization cost of memory instruction \p I.
1180 unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
1181
1182 /// The cost computation for scalarized memory instruction.
1183 unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
1184
1185 /// The cost computation for interleaving group of memory instructions.
1186 unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
1187
1188 /// The cost computation for Gather/Scatter instruction.
1189 unsigned getGatherScatterCost(Instruction *I, unsigned VF);
1190
1191 /// The cost computation for widening instruction \p I with consecutive
1192 /// memory access.
1193 unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
1194
1195 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1196 /// Load: scalar load + broadcast.
1197 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1198 /// element)
1199 unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
1200
1201 /// Returns whether the instruction is a load or store and will be a emitted
1202 /// as a vector operation.
1203 bool isConsecutiveLoadOrStore(Instruction *I);
1204
1205 /// Returns true if an artificially high cost for emulated masked memrefs
1206 /// should be used.
1207 bool useEmulatedMaskMemRefHack(Instruction *I);
1208
1209 /// Create an analysis remark that explains why vectorization failed
1210 ///
1211 /// \p RemarkName is the identifier for the remark. \return the remark object
1212 /// that can be streamed to.
1213 OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
1214 return createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1215 RemarkName, TheLoop);
1216 }
1217
1218 /// Map of scalar integer values to the smallest bitwidth they can be legally
1219 /// represented as. The vector equivalents of these values should be truncated
1220 /// to this type.
1221 MapVector<Instruction *, uint64_t> MinBWs;
1222
1223 /// A type representing the costs for instructions if they were to be
1224 /// scalarized rather than vectorized. The entries are Instruction-Cost
1225 /// pairs.
1226 using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
1227
1228 /// A set containing all BasicBlocks that are known to present after
1229 /// vectorization as a predicated block.
1230 SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1231
1232 /// All blocks of loop are to be masked to fold tail of scalar iterations.
1233 bool FoldTailByMasking = false;
1234
1235 /// A map holding scalar costs for different vectorization factors. The
1236 /// presence of a cost for an instruction in the mapping indicates that the
1237 /// instruction will be scalarized when vectorizing with the associated
1238 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1239 DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
1240
1241 /// Holds the instructions known to be uniform after vectorization.
1242 /// The data is collected per VF.
1243 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
1244
1245 /// Holds the instructions known to be scalar after vectorization.
1246 /// The data is collected per VF.
1247 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
1248
1249 /// Holds the instructions (address computations) that are forced to be
1250 /// scalarized.
1251 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1252
1253 /// Returns the expected difference in cost from scalarizing the expression
1254 /// feeding a predicated instruction \p PredInst. The instructions to
1255 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1256 /// non-negative return value implies the expression will be scalarized.
1257 /// Currently, only single-use chains are considered for scalarization.
1258 int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1259 unsigned VF);
1260
1261 /// Collect the instructions that are uniform after vectorization. An
1262 /// instruction is uniform if we represent it with a single scalar value in
1263 /// the vectorized loop corresponding to each vector iteration. Examples of
1264 /// uniform instructions include pointer operands of consecutive or
1265 /// interleaved memory accesses. Note that although uniformity implies an
1266 /// instruction will be scalar, the reverse is not true. In general, a
1267 /// scalarized instruction will be represented by VF scalar values in the
1268 /// vectorized loop, each corresponding to an iteration of the original
1269 /// scalar loop.
1270 void collectLoopUniforms(unsigned VF);
1271
1272 /// Collect the instructions that are scalar after vectorization. An
1273 /// instruction is scalar if it is known to be uniform or will be scalarized
1274 /// during vectorization. Non-uniform scalarized instructions will be
1275 /// represented by VF values in the vectorized loop, each corresponding to an
1276 /// iteration of the original scalar loop.
1277 void collectLoopScalars(unsigned VF);
1278
1279 /// Keeps cost model vectorization decision and cost for instructions.
1280 /// Right now it is used for memory instructions only.
1281 using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
1282 std::pair<InstWidening, unsigned>>;
1283
1284 DecisionList WideningDecisions;
1285
1286public:
1287 /// The loop that we evaluate.
1288 Loop *TheLoop;
1289
1290 /// Predicated scalar evolution analysis.
1291 PredicatedScalarEvolution &PSE;
1292
1293 /// Loop Info analysis.
1294 LoopInfo *LI;
1295
1296 /// Vectorization legality.
1297 LoopVectorizationLegality *Legal;
1298
1299 /// Vector target information.
1300 const TargetTransformInfo &TTI;
1301
1302 /// Target Library Info.
1303 const TargetLibraryInfo *TLI;
1304
1305 /// Demanded bits analysis.
1306 DemandedBits *DB;
1307
1308 /// Assumption cache.
1309 AssumptionCache *AC;
1310
1311 /// Interface to emit optimization remarks.
1312 OptimizationRemarkEmitter *ORE;
1313
1314 const Function *TheFunction;
1315
1316 /// Loop Vectorize Hint.
1317 const LoopVectorizeHints *Hints;
1318
1319 /// The interleave access information contains groups of interleaved accesses
1320 /// with the same stride and close to each other.
1321 InterleavedAccessInfo &InterleaveInfo;
1322
1323 /// Values to ignore in the cost model.
1324 SmallPtrSet<const Value *, 16> ValuesToIgnore;
1325
1326 /// Values to ignore in the cost model when VF > 1.
1327 SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1328};
1329
1330} // end namespace llvm
1331
1332// Return true if \p OuterLp is an outer loop annotated with hints for explicit
1333// vectorization. The loop needs to be annotated with #pragma omp simd
1334// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
1335// vector length information is not provided, vectorization is not considered
1336// explicit. Interleave hints are not allowed either. These limitations will be
1337// relaxed in the future.
1338// Please, note that we are currently forced to abuse the pragma 'clang
1339// vectorize' semantics. This pragma provides *auto-vectorization hints*
1340// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
1341// provides *explicit vectorization hints* (LV can bypass legal checks and
1342// assume that vectorization is legal). However, both hints are implemented
1343// using the same metadata (llvm.loop.vectorize, processed by
1344// LoopVectorizeHints). This will be fixed in the future when the native IR
1345// representation for pragma 'omp simd' is introduced.
1346static bool isExplicitVecOuterLoop(Loop *OuterLp,
1347 OptimizationRemarkEmitter *ORE) {
1348 assert(!OuterLp->empty() && "This is not an outer loop")((!OuterLp->empty() && "This is not an outer loop"
) ? static_cast<void> (0) : __assert_fail ("!OuterLp->empty() && \"This is not an outer loop\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1348, __PRETTY_FUNCTION__))
;
1349 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
1350
1351 // Only outer loops with an explicit vectorization hint are supported.
1352 // Unannotated outer loops are ignored.
1353 if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
1354 return false;
1355
1356 Function *Fn = OuterLp->getHeader()->getParent();
1357 if (!Hints.allowVectorization(Fn, OuterLp, false /*AlwaysVectorize*/)) {
1358 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)
;
1359 return false;
1360 }
1361
1362 if (!Hints.getWidth()) {
1363 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)
;
1364 emitMissedWarning(Fn, OuterLp, Hints, ORE);
1365 return false;
1366 }
1367
1368 if (Hints.getInterleave() > 1) {
1369 // TODO: Interleave support is future work.
1370 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)
1371 "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)
;
1372 emitMissedWarning(Fn, OuterLp, Hints, ORE);
1373 return false;
1374 }
1375
1376 return true;
1377}
1378
1379static void collectSupportedLoops(Loop &L, LoopInfo *LI,
1380 OptimizationRemarkEmitter *ORE,
1381 SmallVectorImpl<Loop *> &V) {
1382 // Collect inner loops and outer loops without irreducible control flow. For
1383 // now, only collect outer loops that have explicit vectorization hints. If we
1384 // are stress testing the VPlan H-CFG construction, we collect the outermost
1385 // loop of every loop nest.
1386 if (L.empty() || VPlanBuildStressTest ||
1387 (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
1388 LoopBlocksRPO RPOT(&L);
1389 RPOT.perform(LI);
1390 if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
1391 V.push_back(&L);
1392 // TODO: Collect inner loops inside marked outer loops in case
1393 // vectorization fails for the outer loop. Do not invoke
1394 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
1395 // already known to be reducible. We can use an inherited attribute for
1396 // that.
1397 return;
1398 }
1399 }
1400 for (Loop *InnerL : L)
1401 collectSupportedLoops(*InnerL, LI, ORE, V);
1402}
1403
1404namespace {
1405
1406/// The LoopVectorize Pass.
1407struct LoopVectorize : public FunctionPass {
1408 /// Pass identification, replacement for typeid
1409 static char ID;
1410
1411 LoopVectorizePass Impl;
1412
1413 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1414 : FunctionPass(ID) {
1415 Impl.DisableUnrolling = NoUnrolling;
1416 Impl.AlwaysVectorize = AlwaysVectorize;
1417 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1418 }
1419
1420 bool runOnFunction(Function &F) override {
1421 if (skipFunction(F))
1422 return false;
1423
1424 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1425 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1426 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1427 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1428 auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1429 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1430 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
1431 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1432 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1433 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
1434 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
1435 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1436
1437 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1438 [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
1439
1440 return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
1441 GetLAA, *ORE);
1442 }
1443
1444 void getAnalysisUsage(AnalysisUsage &AU) const override {
1445 AU.addRequired<AssumptionCacheTracker>();
1446 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1447 AU.addRequired<DominatorTreeWrapperPass>();
1448 AU.addRequired<LoopInfoWrapperPass>();
1449 AU.addRequired<ScalarEvolutionWrapperPass>();
1450 AU.addRequired<TargetTransformInfoWrapperPass>();
1451 AU.addRequired<AAResultsWrapperPass>();
1452 AU.addRequired<LoopAccessLegacyAnalysis>();
1453 AU.addRequired<DemandedBitsWrapperPass>();
1454 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1455
1456 // We currently do not preserve loopinfo/dominator analyses with outer loop
1457 // vectorization. Until this is addressed, mark these analyses as preserved
1458 // only for non-VPlan-native path.
1459 // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
1460 if (!EnableVPlanNativePath) {
1461 AU.addPreserved<LoopInfoWrapperPass>();
1462 AU.addPreserved<DominatorTreeWrapperPass>();
1463 }
1464
1465 AU.addPreserved<BasicAAWrapperPass>();
1466 AU.addPreserved<GlobalsAAWrapperPass>();
1467 }
1468};
1469
1470} // end anonymous namespace
1471
1472//===----------------------------------------------------------------------===//
1473// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1474// LoopVectorizationCostModel and LoopVectorizationPlanner.
1475//===----------------------------------------------------------------------===//
1476
1477Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1478 // We need to place the broadcast of invariant variables outside the loop,
1479 // but only if it's proven safe to do so. Else, broadcast will be inside
1480 // vector loop body.
1481 Instruction *Instr = dyn_cast<Instruction>(V);
1482 bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
1483 (!Instr ||
1484 DT->dominates(Instr->getParent(), LoopVectorPreHeader));
1485 // Place the code for broadcasting invariant variables in the new preheader.
1486 IRBuilder<>::InsertPointGuard Guard(Builder);
1487 if (SafeToHoist)
1488 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1489
1490 // Broadcast the scalar into all locations in the vector.
1491 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1492
1493 return Shuf;
1494}
1495
1496void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
1497 const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
1498 assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&(((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal
)) && "Expected either an induction phi-node or a truncate of it!"
) ? static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1499, __PRETTY_FUNCTION__))
1499 "Expected either an induction phi-node or a truncate of it!")(((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal
)) && "Expected either an induction phi-node or a truncate of it!"
) ? static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1499, __PRETTY_FUNCTION__))
;
1500 Value *Start = II.getStartValue();
1501
1502 // Construct the initial value of the vector IV in the vector loop preheader
1503 auto CurrIP = Builder.saveIP();
1504 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1505 if (isa<TruncInst>(EntryVal)) {
1506 assert(Start->getType()->isIntegerTy() &&((Start->getType()->isIntegerTy() && "Truncation requires an integer type"
) ? static_cast<void> (0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1507, __PRETTY_FUNCTION__))
1507 "Truncation requires an integer type")((Start->getType()->isIntegerTy() && "Truncation requires an integer type"
) ? static_cast<void> (0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1507, __PRETTY_FUNCTION__))
;
1508 auto *TruncType = cast<IntegerType>(EntryVal->getType());
1509 Step = Builder.CreateTrunc(Step, TruncType);
1510 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
1511 }
1512 Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
1513 Value *SteppedStart =
1514 getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
1515
1516 // We create vector phi nodes for both integer and floating-point induction
1517 // variables. Here, we determine the kind of arithmetic we will perform.
1518 Instruction::BinaryOps AddOp;
1519 Instruction::BinaryOps MulOp;
1520 if (Step->getType()->isIntegerTy()) {
1521 AddOp = Instruction::Add;
1522 MulOp = Instruction::Mul;
1523 } else {
1524 AddOp = II.getInductionOpcode();
1525 MulOp = Instruction::FMul;
1526 }
1527
1528 // Multiply the vectorization factor by the step using integer or
1529 // floating-point arithmetic as appropriate.
1530 Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
1531 Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
1532
1533 // Create a vector splat to use in the induction update.
1534 //
1535 // FIXME: If the step is non-constant, we create the vector splat with
1536 // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
1537 // handle a constant vector splat.
1538 Value *SplatVF = isa<Constant>(Mul)
1539 ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
1540 : Builder.CreateVectorSplat(VF, Mul);
1541 Builder.restoreIP(CurrIP);
1542
1543 // We may need to add the step a number of times, depending on the unroll
1544 // factor. The last of those goes into the PHI.
1545 PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
1546 &*LoopVectorBody->getFirstInsertionPt());
1547 VecInd->setDebugLoc(EntryVal->getDebugLoc());
1548 Instruction *LastInduction = VecInd;
1549 for (unsigned Part = 0; Part < UF; ++Part) {
1550 VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
1551
1552 if (isa<TruncInst>(EntryVal))
1553 addMetadata(LastInduction, EntryVal);
1554 recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
1555
1556 LastInduction = cast<Instruction>(addFastMathFlag(
1557 Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
1558 LastInduction->setDebugLoc(EntryVal->getDebugLoc());
1559 }
1560
1561 // Move the last step to the end of the latch block. This ensures consistent
1562 // placement of all induction updates.
1563 auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
1564 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
1565 auto *ICmp = cast<Instruction>(Br->getCondition());
1566 LastInduction->moveBefore(ICmp);
1567 LastInduction->setName("vec.ind.next");
1568
1569 VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
1570 VecInd->addIncoming(LastInduction, LoopVectorLatch);
1571}
1572
1573bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
1574 return Cost->isScalarAfterVectorization(I, VF) ||
1575 Cost->isProfitableToScalarize(I, VF);
1576}
1577
1578bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
1579 if (shouldScalarizeInstruction(IV))
1580 return true;
1581 auto isScalarInst = [&](User *U) -> bool {
1582 auto *I = cast<Instruction>(U);
1583 return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
1584 };
1585 return llvm::any_of(IV->users(), isScalarInst);
1586}
1587
1588void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
1589 const InductionDescriptor &ID, const Instruction *EntryVal,
1590 Value *VectorLoopVal, unsigned Part, unsigned Lane) {
1591 assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&(((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal
)) && "Expected either an induction phi-node or a truncate of it!"
) ? static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1592, __PRETTY_FUNCTION__))
1592 "Expected either an induction phi-node or a truncate of it!")(((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal
)) && "Expected either an induction phi-node or a truncate of it!"
) ? static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1592, __PRETTY_FUNCTION__))
;
1593
1594 // This induction variable is not the phi from the original loop but the
1595 // newly-created IV based on the proof that casted Phi is equal to the
1596 // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
1597 // re-uses the same InductionDescriptor that original IV uses but we don't
1598 // have to do any recording in this case - that is done when original IV is
1599 // processed.
1600 if (isa<TruncInst>(EntryVal))
1601 return;
1602
1603 const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
1604 if (Casts.empty())
1605 return;
1606 // Only the first Cast instruction in the Casts vector is of interest.
1607 // The rest of the Casts (if exist) have no uses outside the
1608 // induction update chain itself.
1609 Instruction *CastInst = *Casts.begin();
1610 if (Lane < UINT_MAX(2147483647 *2U +1U))
1611 VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
1612 else
1613 VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
1614}
1615
1616void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
1617 assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&(((IV->getType()->isIntegerTy() || IV != OldInduction) &&
"Primary induction variable must have an integer type") ? static_cast
<void> (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1618, __PRETTY_FUNCTION__))
1618 "Primary induction variable must have an integer type")(((IV->getType()->isIntegerTy() || IV != OldInduction) &&
"Primary induction variable must have an integer type") ? static_cast
<void> (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1618, __PRETTY_FUNCTION__))
;
1619
1620 auto II = Legal->getInductionVars()->find(IV);
1621 assert(II != Legal->getInductionVars()->end() && "IV is not an induction")((II != Legal->getInductionVars()->end() && "IV is not an induction"
) ? static_cast<void> (0) : __assert_fail ("II != Legal->getInductionVars()->end() && \"IV is not an induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1621, __PRETTY_FUNCTION__))
;
1622
1623 auto ID = II->second;
1624 assert(IV->getType() == ID.getStartValue()->getType() && "Types must match")((IV->getType() == ID.getStartValue()->getType() &&
"Types must match") ? static_cast<void> (0) : __assert_fail
("IV->getType() == ID.getStartValue()->getType() && \"Types must match\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1624, __PRETTY_FUNCTION__))
;
1625
1626 // The scalar value to broadcast. This will be derived from the canonical
1627 // induction variable.
1628 Value *ScalarIV = nullptr;
1629
1630 // The value from the original loop to which we are mapping the new induction
1631 // variable.
1632 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
1633
1634 // True if we have vectorized the induction variable.
1635 auto VectorizedIV = false;
1636
1637 // Determine if we want a scalar version of the induction variable. This is
1638 // true if the induction variable itself is not widened, or if it has at
1639 // least one user in the loop that is not widened.
1640 auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
1641
1642 // Generate code for the induction step. Note that induction steps are
1643 // required to be loop-invariant
1644 assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&((PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
"Induction step should be loop invariant") ? static_cast<
void> (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1645, __PRETTY_FUNCTION__))
1645 "Induction step should be loop invariant")((PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
"Induction step should be loop invariant") ? static_cast<
void> (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1645, __PRETTY_FUNCTION__))
;
1646 auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
1647 Value *Step = nullptr;
1648 if (PSE.getSE()->isSCEVable(IV->getType())) {
1649 SCEVExpander Exp(*PSE.getSE(), DL, "induction");
1650 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
1651 LoopVectorPreHeader->getTerminator());
1652 } else {
1653 Step = cast<SCEVUnknown>(ID.getStep())->getValue();
1654 }
1655
1656 // Try to create a new independent vector induction variable. If we can't
1657 // create the phi node, we will splat the scalar induction variable in each
1658 // loop iteration.
1659 if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
1660 createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
1661 VectorizedIV = true;
1662 }
1663
1664 // If we haven't yet vectorized the induction variable, or if we will create
1665 // a scalar one, we need to define the scalar induction variable and step
1666 // values. If we were given a truncation type, truncate the canonical
1667 // induction variable and step. Otherwise, derive these values from the
1668 // induction descriptor.
1669 if (!VectorizedIV || NeedsScalarIV) {
1670 ScalarIV = Induction;
1671 if (IV != OldInduction) {
1672 ScalarIV = IV->getType()->isIntegerTy()
1673 ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
1674 : Builder.CreateCast(Instruction::SIToFP, Induction,
1675 IV->getType());
1676 ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
1677 ScalarIV->setName("offset.idx");
1678 }
1679 if (Trunc) {
1680 auto *TruncType = cast<IntegerType>(Trunc->getType());
1681 assert(Step->getType()->isIntegerTy() &&((Step->getType()->isIntegerTy() && "Truncation requires an integer step"
) ? static_cast<void> (0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1682, __PRETTY_FUNCTION__))
1682 "Truncation requires an integer step")((Step->getType()->isIntegerTy() && "Truncation requires an integer step"
) ? static_cast<void> (0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1682, __PRETTY_FUNCTION__))
;
1683 ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
1684 Step = Builder.CreateTrunc(Step, TruncType);
1685 }
1686 }
1687
1688 // If we haven't yet vectorized the induction variable, splat the scalar
1689 // induction variable, and build the necessary step vectors.
1690 // TODO: Don't do it unless the vectorized IV is really required.
1691 if (!VectorizedIV) {
1692 Value *Broadcasted = getBroadcastInstrs(ScalarIV);
1693 for (unsigned Part = 0; Part < UF; ++Part) {
1694 Value *EntryPart =
1695 getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
1696 VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
1697 if (Trunc)
1698 addMetadata(EntryPart, Trunc);
1699 recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
1700 }
1701 }
1702
1703 // If an induction variable is only used for counting loop iterations or
1704 // calculating addresses, it doesn't need to be widened. Create scalar steps
1705 // that can be used by instructions we will later scalarize. Note that the
1706 // addition of the scalar steps will not increase the number of instructions
1707 // in the loop in the common case prior to InstCombine. We will be trading
1708 // one vector extract for each scalar step.
1709 if (NeedsScalarIV)
1710 buildScalarSteps(ScalarIV, Step, EntryVal, ID);
1711}
1712
1713Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
1714 Instruction::BinaryOps BinOp) {
1715 // Create and check the types.
1716 assert(Val->getType()->isVectorTy() && "Must be a vector")((Val->getType()->isVectorTy() && "Must be a vector"
) ? static_cast<void> (0) : __assert_fail ("Val->getType()->isVectorTy() && \"Must be a vector\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1716, __PRETTY_FUNCTION__))
;
1717 int VLen = Val->getType()->getVectorNumElements();
1718
1719 Type *STy = Val->getType()->getScalarType();
1720 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&(((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
"Induction Step must be an integer or FP") ? static_cast<
void> (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1721, __PRETTY_FUNCTION__))
1721 "Induction Step must be an integer or FP")(((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
"Induction Step must be an integer or FP") ? static_cast<
void> (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1721, __PRETTY_FUNCTION__))
;
1722 assert(Step->getType() == STy && "Step has wrong type")((Step->getType() == STy && "Step has wrong type")
? static_cast<void> (0) : __assert_fail ("Step->getType() == STy && \"Step has wrong type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1722, __PRETTY_FUNCTION__))
;
1723
1724 SmallVector<Constant *, 8> Indices;
1725
1726 if (STy->isIntegerTy()) {
1727 // Create a vector of consecutive numbers from zero to VF.
1728 for (int i = 0; i < VLen; ++i)
1729 Indices.push_back(ConstantInt::get(STy, StartIdx + i));
1730
1731 // Add the consecutive indices to the vector value.
1732 Constant *Cv = ConstantVector::get(Indices);
1733 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec")((Cv->getType() == Val->getType() && "Invalid consecutive vec"
) ? static_cast<void> (0) : __assert_fail ("Cv->getType() == Val->getType() && \"Invalid consecutive vec\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734 Step = Builder.CreateVectorSplat(VLen, Step);
1735 assert(Step->getType() == Val->getType() && "Invalid step vec")((Step->getType() == Val->getType() && "Invalid step vec"
) ? static_cast<void> (0) : __assert_fail ("Step->getType() == Val->getType() && \"Invalid step vec\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1735, __PRETTY_FUNCTION__))
;
1736 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1737 // which can be found from the original scalar operations.
1738 Step = Builder.CreateMul(Cv, Step);
1739 return Builder.CreateAdd(Val, Step, "induction");
1740 }
1741
1742 // Floating point induction.
1743 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&(((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
"Binary Opcode should be specified for FP induction") ? static_cast
<void> (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1744, __PRETTY_FUNCTION__))
1744 "Binary Opcode should be specified for FP induction")(((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
"Binary Opcode should be specified for FP induction") ? static_cast
<void> (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1744, __PRETTY_FUNCTION__))
;
1745 // Create a vector of consecutive numbers from zero to VF.
1746 for (int i = 0; i < VLen; ++i)
1747 Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
1748
1749 // Add the consecutive indices to the vector value.
1750 Constant *Cv = ConstantVector::get(Indices);
1751
1752 Step = Builder.CreateVectorSplat(VLen, Step);
1753
1754 // Floating point operations had to be 'fast' to enable the induction.
1755 FastMathFlags Flags;
1756 Flags.setFast();
1757
1758 Value *MulOp = Builder.CreateFMul(Cv, Step);
1759 if (isa<Instruction>(MulOp))
1760 // Have to check, MulOp may be a constant
1761 cast<Instruction>(MulOp)->setFastMathFlags(Flags);
1762
1763 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
1764 if (isa<Instruction>(BOp))
1765 cast<Instruction>(BOp)->setFastMathFlags(Flags);
1766 return BOp;
1767}
1768
1769void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
1770 Instruction *EntryVal,
1771 const InductionDescriptor &ID) {
1772 // We shouldn't have to build scalar steps if we aren't vectorizing.
1773 assert(VF > 1 && "VF should be greater than one")((VF > 1 && "VF should be greater than one") ? static_cast
<void> (0) : __assert_fail ("VF > 1 && \"VF should be greater than one\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1773, __PRETTY_FUNCTION__))
;
1774
1775 // Get the value type and ensure it and the step have the same integer type.
1776 Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
1777 assert(ScalarIVTy == Step->getType() &&((ScalarIVTy == Step->getType() && "Val and Step should have the same type"
) ? static_cast<void> (0) : __assert_fail ("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1778, __PRETTY_FUNCTION__))
1778 "Val and Step should have the same type")((ScalarIVTy == Step->getType() && "Val and Step should have the same type"
) ? static_cast<void> (0) : __assert_fail ("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1778, __PRETTY_FUNCTION__))
;
1779
1780 // We build scalar steps for both integer and floating-point induction
1781 // variables. Here, we determine the kind of arithmetic we will perform.
1782 Instruction::BinaryOps AddOp;
1783 Instruction::BinaryOps MulOp;
1784 if (ScalarIVTy->isIntegerTy()) {
1785 AddOp = Instruction::Add;
1786 MulOp = Instruction::Mul;
1787 } else {
1788 AddOp = ID.getInductionOpcode();
1789 MulOp = Instruction::FMul;
1790 }
1791
1792 // Determine the number of scalars we need to generate for each unroll
1793 // iteration. If EntryVal is uniform, we only need to generate the first
1794 // lane. Otherwise, we generate all VF values.
1795 unsigned Lanes =
1796 Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
1797 : VF;
1798 // Compute the scalar steps and save the results in VectorLoopValueMap.
1799 for (unsigned Part = 0; Part < UF; ++Part) {
1800 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
1801 auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
1802 auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
1803 auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
1804 VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
1805 recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
1806 }
1807 }
1808}
1809
1810Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
1811 assert(V != Induction && "The new induction variable should not be used.")((V != Induction && "The new induction variable should not be used."
) ? static_cast<void> (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1811, __PRETTY_FUNCTION__))
;
1812 assert(!V->getType()->isVectorTy() && "Can't widen a vector")((!V->getType()->isVectorTy() && "Can't widen a vector"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't widen a vector\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1812, __PRETTY_FUNCTION__))
;
1813 assert(!V->getType()->isVoidTy() && "Type does not produce a value")((!V->getType()->isVoidTy() && "Type does not produce a value"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isVoidTy() && \"Type does not produce a value\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1813, __PRETTY_FUNCTION__))
;
1814
1815 // If we have a stride that is replaced by one, do it here. Defer this for
1816 // the VPlan-native path until we start running Legal checks in that path.
1817 if (!EnableVPlanNativePath && Legal->hasStride(V))
1818 V = ConstantInt::get(V->getType(), 1);
1819
1820 // If we have a vector mapped to this value, return it.
1821 if (VectorLoopValueMap.hasVectorValue(V, Part))
1822 return VectorLoopValueMap.getVectorValue(V, Part);
1823
1824 // If the value has not been vectorized, check if it has been scalarized
1825 // instead. If it has been scalarized, and we actually need the value in
1826 // vector form, we will construct the vector values on demand.
1827 if (VectorLoopValueMap.hasAnyScalarValue(V)) {
1828 Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
1829
1830 // If we've scalarized a value, that value should be an instruction.
1831 auto *I = cast<Instruction>(V);
1832
1833 // If we aren't vectorizing, we can just copy the scalar map values over to
1834 // the vector map.
1835 if (VF == 1) {
1836 VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
1837 return ScalarValue;
1838 }
1839
1840 // Get the last scalar instruction we generated for V and Part. If the value
1841 // is known to be uniform after vectorization, this corresponds to lane zero
1842 // of the Part unroll iteration. Otherwise, the last instruction is the one
1843 // we created for the last vector lane of the Part unroll iteration.
1844 unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
1845 auto *LastInst = cast<Instruction>(
1846 VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
1847
1848 // Set the insert point after the last scalarized instruction. This ensures
1849 // the insertelement sequence will directly follow the scalar definitions.
1850 auto OldIP = Builder.saveIP();
1851 auto NewIP = std::next(BasicBlock::iterator(LastInst));
1852 Builder.SetInsertPoint(&*NewIP);
1853
1854 // However, if we are vectorizing, we need to construct the vector values.
1855 // If the value is known to be uniform after vectorization, we can just
1856 // broadcast the scalar value corresponding to lane zero for each unroll
1857 // iteration. Otherwise, we construct the vector values using insertelement
1858 // instructions. Since the resulting vectors are stored in
1859 // VectorLoopValueMap, we will only generate the insertelements once.
1860 Value *VectorValue = nullptr;
1861 if (Cost->isUniformAfterVectorization(I, VF)) {
1862 VectorValue = getBroadcastInstrs(ScalarValue);
1863 VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
1864 } else {
1865 // Initialize packing with insertelements to start from undef.
1866 Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
1867 VectorLoopValueMap.setVectorValue(V, Part, Undef);
1868 for (unsigned Lane = 0; Lane < VF; ++Lane)
1869 packScalarIntoVectorValue(V, {Part, Lane});
1870 VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
1871 }
1872 Builder.restoreIP(OldIP);
1873 return VectorValue;
1874 }
1875
1876 // If this scalar is unknown, assume that it is a constant or that it is
1877 // loop invariant. Broadcast V and save the value for future uses.
1878 Value *B = getBroadcastInstrs(V);
1879 VectorLoopValueMap.setVectorValue(V, Part, B);
1880 return B;
1881}
1882
1883Value *
1884InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
1885 const VPIteration &Instance) {
1886 // If the value is not an instruction contained in the loop, it should
1887 // already be scalar.
1888 if (OrigLoop->isLoopInvariant(V))
1889 return V;
1890
1891 assert(Instance.Lane > 0((Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? static_cast<void> (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1893, __PRETTY_FUNCTION__))
1892 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)((Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? static_cast<void> (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1893, __PRETTY_FUNCTION__))
1893 : true && "Uniform values only have lane zero")((Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? static_cast<void> (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1893, __PRETTY_FUNCTION__))
;
1894
1895 // If the value from the original loop has not been vectorized, it is
1896 // represented by UF x VF scalar values in the new loop. Return the requested
1897 // scalar value.
1898 if (VectorLoopValueMap.hasScalarValue(V, Instance))
1899 return VectorLoopValueMap.getScalarValue(V, Instance);
1900
1901 // If the value has not been scalarized, get its entry in VectorLoopValueMap
1902 // for the given unroll part. If this entry is not a vector type (i.e., the
1903 // vectorization factor is one), there is no need to generate an
1904 // extractelement instruction.
1905 auto *U = getOrCreateVectorValue(V, Instance.Part);
1906 if (!U->getType()->isVectorTy()) {
1907 assert(VF == 1 && "Value not scalarized has non-vector type")((VF == 1 && "Value not scalarized has non-vector type"
) ? static_cast<void> (0) : __assert_fail ("VF == 1 && \"Value not scalarized has non-vector type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1907, __PRETTY_FUNCTION__))
;
1908 return U;
1909 }
1910
1911 // Otherwise, the value from the original loop has been vectorized and is
1912 // represented by UF vector values. Extract and return the requested scalar
1913 // value from the appropriate vector lane.
1914 return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
1915}
1916
1917void InnerLoopVectorizer::packScalarIntoVectorValue(
1918 Value *V, const VPIteration &Instance) {
1919 assert(V != Induction && "The new induction variable should not be used.")((V != Induction && "The new induction variable should not be used."
) ? static_cast<void> (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1919, __PRETTY_FUNCTION__))
;
1920 assert(!V->getType()->isVectorTy() && "Can't pack a vector")((!V->getType()->isVectorTy() && "Can't pack a vector"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't pack a vector\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1920, __PRETTY_FUNCTION__))
;
1921 assert(!V->getType()->isVoidTy() && "Type does not produce a value")((!V->getType()->isVoidTy() && "Type does not produce a value"
) ? static_cast<void> (0) : __assert_fail ("!V->getType()->isVoidTy() && \"Type does not produce a value\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1921, __PRETTY_FUNCTION__))
;
1922
1923 Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
1924 Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
1925 VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
1926 Builder.getInt32(Instance.Lane));
1927 VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
1928}
1929
1930Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1931 assert(Vec->getType()->isVectorTy() && "Invalid type")((Vec->getType()->isVectorTy() && "Invalid type"
) ? static_cast<void> (0) : __assert_fail ("Vec->getType()->isVectorTy() && \"Invalid type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1931, __PRETTY_FUNCTION__))
;
1932 SmallVector<Constant *, 8> ShuffleMask;
1933 for (unsigned i = 0; i < VF; ++i)
1934 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1935
1936 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1937 ConstantVector::get(ShuffleMask),
1938 "reverse");
1939}
1940
1941// Try to vectorize the interleave group that \p Instr belongs to.
1942//
1943// E.g. Translate following interleaved load group (factor = 3):
1944// for (i = 0; i < N; i+=3) {
1945// R = Pic[i]; // Member of index 0
1946// G = Pic[i+1]; // Member of index 1
1947// B = Pic[i+2]; // Member of index 2
1948// ... // do something to R, G, B
1949// }
1950// To:
1951// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
1952// %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
1953// %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
1954// %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
1955//
1956// Or translate following interleaved store group (factor = 3):
1957// for (i = 0; i < N; i+=3) {
1958// ... do something to R, G, B
1959// Pic[i] = R; // Member of index 0
1960// Pic[i+1] = G; // Member of index 1
1961// Pic[i+2] = B; // Member of index 2
1962// }
1963// To:
1964// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
1965// %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
1966// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
1967// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
1968// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
1969void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr,
1970 VectorParts *BlockInMask) {
1971 const InterleaveGroup *Group = Cost->getInterleavedAccessGroup(Instr);
1972 assert(Group && "Fail to get an interleaved access group.")((Group && "Fail to get an interleaved access group."
) ? static_cast<void> (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1972, __PRETTY_FUNCTION__))
;
1973
1974 // Skip if current instruction is not the insert position.
1975 if (Instr != Group->getInsertPos())
1976 return;
1977
1978 const DataLayout &DL = Instr->getModule()->getDataLayout();
1979 Value *Ptr = getLoadStorePointerOperand(Instr);
1980
1981 // Prepare for the vector type of the interleaved load/store.
1982 Type *ScalarTy = getMemInstValueType(Instr);
1983 unsigned InterleaveFactor = Group->getFactor();
1984 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
1985 Type *PtrTy = VecTy->getPointerTo(getLoadStoreAddressSpace(Instr));
1986
1987 // Prepare for the new pointers.
1988 setDebugLocFromInst(Builder, Ptr);
1989 SmallVector<Value *, 2> NewPtrs;
1990 unsigned Index = Group->getIndex(Instr);
1991
1992 VectorParts Mask;
1993 bool IsMaskRequired = BlockInMask;
1994 if (IsMaskRequired) {
1995 Mask = *BlockInMask;
1996 // TODO: extend the masked interleaved-group support to reversed access.
1997 assert(!Group->isReverse() && "Reversed masked interleave-group "((!Group->isReverse() && "Reversed masked interleave-group "
"not supported.") ? static_cast<void> (0) : __assert_fail
("!Group->isReverse() && \"Reversed masked interleave-group \" \"not supported.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1998, __PRETTY_FUNCTION__))
1998 "not supported.")((!Group->isReverse() && "Reversed masked interleave-group "
"not supported.") ? static_cast<void> (0) : __assert_fail
("!Group->isReverse() && \"Reversed masked interleave-group \" \"not supported.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1998, __PRETTY_FUNCTION__))
;
1999 }
2000
2001 // If the group is reverse, adjust the index to refer to the last vector lane
2002 // instead of the first. We adjust the index from the first vector lane,
2003 // rather than directly getting the pointer for lane VF - 1, because the
2004 // pointer operand of the interleaved access is supposed to be uniform. For
2005 // uniform instructions, we're only required to generate a value for the
2006 // first vector lane in each unroll iteration.
2007 if (Group->isReverse())
2008 Index += (VF - 1) * Group->getFactor();
2009
2010 bool InBounds = false;
2011 if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2012 InBounds = gep->isInBounds();
2013
2014 for (unsigned Part = 0; Part < UF; Part++) {
2015 Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
2016
2017 // Notice current instruction could be any index. Need to adjust the address
2018 // to the member of index 0.
2019 //
2020 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2021 // b = A[i]; // Member of index 0
2022 // Current pointer is pointed to A[i+1], adjust it to A[i].
2023 //
2024 // E.g. A[i+1] = a; // Member of index 1
2025 // A[i] = b; // Member of index 0
2026 // A[i+2] = c; // Member of index 2 (Current instruction)
2027 // Current pointer is pointed to A[i+2], adjust it to A[i].
2028 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2029 if (InBounds)
2030 cast<GetElementPtrInst>(NewPtr)->setIsInBounds(true);
2031
2032 // Cast to the vector pointer type.
2033 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2034 }
2035
2036 setDebugLocFromInst(Builder, Instr);
2037 Value *UndefVec = UndefValue::get(VecTy);
2038
2039 // Vectorize the interleaved load group.
2040 if (isa<LoadInst>(Instr)) {
2041 // For each unroll part, create a wide load for the group.
2042 SmallVector<Value *, 2> NewLoads;
2043 for (unsigned Part = 0; Part < UF; Part++) {
2044 Instruction *NewLoad;
2045 if (IsMaskRequired) {
2046 auto *Undefs = UndefValue::get(Mask[Part]->getType());
2047 auto *RepMask = createReplicatedMask(Builder, InterleaveFactor, VF);
2048 Value *ShuffledMask = Builder.CreateShuffleVector(
2049 Mask[Part], Undefs, RepMask, "interleaved.mask");
2050 NewLoad = Builder.CreateMaskedLoad(NewPtrs[Part], Group->getAlignment(),
2051 ShuffledMask, UndefVec,
2052 "wide.masked.vec");
2053 }
2054 else
2055 NewLoad = Builder.CreateAlignedLoad(NewPtrs[Part],
2056 Group->getAlignment(), "wide.vec");
2057 Group->addMetadata(NewLoad);
2058 NewLoads.push_back(NewLoad);
2059 }
2060
2061 // For each member in the group, shuffle out the appropriate data from the
2062 // wide loads.
2063 for (unsigned I = 0; I < InterleaveFactor; ++I) {
2064 Instruction *Member = Group->getMember(I);
2065
2066 // Skip the gaps in the group.
2067 if (!Member)
2068 continue;
2069
2070 Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2071 for (unsigned Part = 0; Part < UF; Part++) {
2072 Value *StridedVec = Builder.CreateShuffleVector(
2073 NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2074
2075 // If this member has different type, cast the result type.
2076 if (Member->getType() != ScalarTy) {
2077 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2078 StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2079 }
2080
2081 if (Group->isReverse())
2082 StridedVec = reverseVector(StridedVec);
2083
2084 VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2085 }
2086 }
2087 return;
2088 }
2089
2090 // The sub vector type for current instruction.
2091 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2092
2093 // Vectorize the interleaved store group.
2094 for (unsigned Part = 0; Part < UF; Part++) {
2095 // Collect the stored vector from each member.
2096 SmallVector<Value *, 4> StoredVecs;
2097 for (unsigned i = 0; i < InterleaveFactor; i++) {
2098 // Interleaved store group doesn't allow a gap, so each index has a member
2099 Instruction *Member = Group->getMember(i);
2100 assert(Member && "Fail to get a member from an interleaved store group")((Member && "Fail to get a member from an interleaved store group"
) ? static_cast<void> (0) : __assert_fail ("Member && \"Fail to get a member from an interleaved store group\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2100, __PRETTY_FUNCTION__))
;
2101
2102 Value *StoredVec = getOrCreateVectorValue(
2103 cast<StoreInst>(Member)->getValueOperand(), Part);
2104 if (Group->isReverse())
2105 StoredVec = reverseVector(StoredVec);
2106
2107 // If this member has different type, cast it to a unified type.
2108
2109 if (StoredVec->getType() != SubVT)
2110 StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2111
2112 StoredVecs.push_back(StoredVec);
2113 }
2114
2115 // Concatenate all vectors into a wide vector.
2116 Value *WideVec = concatenateVectors(Builder, StoredVecs);
2117
2118 // Interleave the elements in the wide vector.
2119 Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2120 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2121 "interleaved.vec");
2122
2123 Instruction *NewStoreInstr;
2124 if (IsMaskRequired) {
2125 auto *Undefs = UndefValue::get(Mask[Part]->getType());
2126 auto *RepMask = createReplicatedMask(Builder, InterleaveFactor, VF);
2127 Value *ShuffledMask = Builder.CreateShuffleVector(
2128 Mask[Part], Undefs, RepMask, "interleaved.mask");
2129 NewStoreInstr = Builder.CreateMaskedStore(
2130 IVec, NewPtrs[Part], Group->getAlignment(), ShuffledMask);
2131 }
2132 else
2133 NewStoreInstr = Builder.CreateAlignedStore(IVec, NewPtrs[Part],
2134 Group->getAlignment());
2135
2136 Group->addMetadata(NewStoreInstr);
2137 }
2138}
2139
2140void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
2141 VectorParts *BlockInMask) {
2142 // Attempt to issue a wide load.
2143 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2144 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2145
2146 assert((LI || SI) && "Invalid Load/Store instruction")(((LI || SI) && "Invalid Load/Store instruction") ? static_cast
<void> (0) : __assert_fail ("(LI || SI) && \"Invalid Load/Store instruction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2146, __PRETTY_FUNCTION__))
;
2147
2148 LoopVectorizationCostModel::InstWidening Decision =
2149 Cost->getWideningDecision(Instr, VF);
2150 assert(Decision != LoopVectorizationCostModel::CM_Unknown &&((Decision != LoopVectorizationCostModel::CM_Unknown &&
"CM decision should be taken at this point") ? static_cast<
void> (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2151, __PRETTY_FUNCTION__))
2151 "CM decision should be taken at this point")((Decision != LoopVectorizationCostModel::CM_Unknown &&
"CM decision should be taken at this point") ? static_cast<
void> (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2151, __PRETTY_FUNCTION__))
;
2152 if (Decision == LoopVectorizationCostModel::CM_Interleave)
2153 return vectorizeInterleaveGroup(Instr);
2154
2155 Type *ScalarDataTy = getMemInstValueType(Instr);
2156 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2157 Value *Ptr = getLoadStorePointerOperand(Instr);
2158 unsigned Alignment = getLoadStoreAlignment(Instr);
2159 // An alignment of 0 means target abi alignment. We need to use the scalar's
2160 // target abi alignment in such a case.
2161 const DataLayout &DL = Instr->getModule()->getDataLayout();
2162 if (!Alignment)
2163 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2164 unsigned AddressSpace = getLoadStoreAddressSpace(Instr);
2165
2166 // Determine if the pointer operand of the access is either consecutive or
2167 // reverse consecutive.
2168 bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2169 bool ConsecutiveStride =
2170 Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2171 bool CreateGatherScatter =
2172 (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2173
2174 // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2175 // gather/scatter. Otherwise Decision should have been to Scalarize.
2176 assert((ConsecutiveStride || CreateGatherScatter) &&(((ConsecutiveStride || CreateGatherScatter) && "The instruction should be scalarized"
) ? static_cast<void> (0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2177, __PRETTY_FUNCTION__))
2177 "The instruction should be scalarized")(((ConsecutiveStride || CreateGatherScatter) && "The instruction should be scalarized"
) ? static_cast<void> (0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2177, __PRETTY_FUNCTION__))
;
2178
2179 // Handle consecutive loads/stores.
2180 if (ConsecutiveStride)
2181 Ptr = getOrCreateScalarValue(Ptr, {0, 0});
2182
2183 VectorParts Mask;
2184 bool isMaskRequired = BlockInMask;
2185 if (isMaskRequired)
2186 Mask = *BlockInMask;
2187
2188 bool InBounds = false;
2189 if (auto *gep = dyn_cast<GetElementPtrInst>(
2190 getLoadStorePointerOperand(Instr)->stripPointerCasts()))
2191 InBounds = gep->isInBounds();
2192
2193 const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2194 // Calculate the pointer for the specific unroll-part.
2195 GetElementPtrInst *PartPtr = nullptr;
2196
2197 if (Reverse) {
2198 // If the address is consecutive but reversed, then the
2199 // wide store needs to start at the last vector element.
2200 PartPtr = cast<GetElementPtrInst>(
2201 Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)));
2202 PartPtr->setIsInBounds(InBounds);
2203 PartPtr = cast<GetElementPtrInst>(
2204 Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)));
2205 PartPtr->setIsInBounds(InBounds);
2206 if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2207 Mask[Part] = reverseVector(Mask[Part]);
2208 } else {
2209 PartPtr = cast<GetElementPtrInst>(
2210 Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)));
2211 PartPtr->setIsInBounds(InBounds);
2212 }
2213
2214 return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2215 };
2216
2217 // Handle Stores:
2218 if (SI) {
2219 setDebugLocFromInst(Builder, SI);
2220
2221 for (unsigned Part = 0; Part < UF; ++Part) {
2222 Instruction *NewSI = nullptr;
2223 Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
2224 if (CreateGatherScatter) {
2225 Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
2226 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
2227 NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2228 MaskPart);
2229 } else {
2230 if (Reverse) {
2231 // If we store to reverse consecutive memory locations, then we need
2232 // to reverse the order of elements in the stored value.
2233 StoredVal = reverseVector(StoredVal);
2234 // We don't want to update the value in the map as it might be used in
2235 // another expression. So don't call resetVectorValue(StoredVal).
2236 }
2237 auto *VecPtr = CreateVecPtr(Part, Ptr);
2238 if (isMaskRequired)
2239 NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2240 Mask[Part]);
2241 else
2242 NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2243 }
2244 addMetadata(NewSI, SI);
2245 }
2246 return;
2247 }
2248
2249 // Handle loads.
2250 assert(LI && "Must have a load instruction")((LI && "Must have a load instruction") ? static_cast
<void> (0) : __assert_fail ("LI && \"Must have a load instruction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2250, __PRETTY_FUNCTION__))
;
2251 setDebugLocFromInst(Builder, LI);
2252 for (unsigned Part = 0; Part < UF; ++Part) {
2253 Value *NewLI;
2254 if (CreateGatherScatter) {
2255 Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
2256 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
2257 NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2258 nullptr, "wide.masked.gather");
2259 addMetadata(NewLI, LI);
2260 } else {
2261 auto *VecPtr = CreateVecPtr(Part, Ptr);
2262 if (isMaskRequired)
2263 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2264 UndefValue::get(DataTy),
2265 "wide.masked.load");
2266 else
2267 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2268
2269 // Add metadata to the load, but setVectorValue to the reverse shuffle.
2270 addMetadata(NewLI, LI);
2271 if (Reverse)
2272 NewLI = reverseVector(NewLI);
2273 }
2274 VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
2275 }
2276}
2277
2278void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2279 const VPIteration &Instance,
2280 bool IfPredicateInstr) {
2281 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors")((!Instr->getType()->isAggregateType() && "Can't handle vectors"
) ? static_cast<void> (0) : __assert_fail ("!Instr->getType()->isAggregateType() && \"Can't handle vectors\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2281, __PRETTY_FUNCTION__))
;
2282
2283 setDebugLocFromInst(Builder, Instr);
2284
2285 // Does this instruction return a value ?
2286 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2287
2288 Instruction *Cloned = Instr->clone();
2289 if (!IsVoidRetTy)
2290 Cloned->setName(Instr->getName() + ".cloned");
2291
2292 // Replace the operands of the cloned instructions with their scalar
2293 // equivalents in the new loop.
2294 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2295 auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
2296 Cloned->setOperand(op, NewOp);
2297 }
2298 addNewMetadata(Cloned, Instr);
2299
2300 // Place the cloned scalar in the new loop.
2301 Builder.Insert(Cloned);
2302
2303 // Add the cloned scalar to the scalar map entry.
2304 VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
2305
2306 // If we just cloned a new assumption, add it the assumption cache.
2307 if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
2308 if (II->getIntrinsicID() == Intrinsic::assume)
2309 AC->registerAssumption(II);
2310
2311 // End if-block.
2312 if (IfPredicateInstr)
2313 PredicatedInstructions.push_back(Cloned);
2314}
2315
2316PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2317 Value *End, Value *Step,
2318 Instruction *DL) {
2319 BasicBlock *Header = L->getHeader();
2320 BasicBlock *Latch = L->getLoopLatch();
2321 // As we're just creating this loop, it's possible no latch exists
2322 // yet. If so, use the header as this will be a single block loop.
2323 if (!Latch)
2324 Latch = Header;
2325
2326 IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2327 Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
2328 setDebugLocFromInst(Builder, OldInst);
2329 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2330
2331 Builder.SetInsertPoint(Latch->getTerminator());
2332 setDebugLocFromInst(Builder, OldInst);
2333
2334 // Create i+1 and fill the PHINode.
2335 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2336 Induction->addIncoming(Start, L->getLoopPreheader());
2337 Induction->addIncoming(Next, Latch);
2338 // Create the compare.
2339 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2340 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2341
2342 // Now we have two terminators. Remove the old one from the block.
2343 Latch->getTerminator()->eraseFromParent();
2344
2345 return Induction;
2346}
2347
2348Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2349 if (TripCount)
2350 return TripCount;
2351
2352 assert(L && "Create Trip Count for null loop.")((L && "Create Trip Count for null loop.") ? static_cast
<void> (0) : __assert_fail ("L && \"Create Trip Count for null loop.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2352, __PRETTY_FUNCTION__))
;
2353 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2354 // Find the loop boundaries.
2355 ScalarEvolution *SE = PSE.getSE();
2356 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2357 assert(BackedgeTakenCount != SE->getCouldNotCompute() &&((BackedgeTakenCount != SE->getCouldNotCompute() &&
"Invalid loop count") ? static_cast<void> (0) : __assert_fail
("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2358, __PRETTY_FUNCTION__))
2358 "Invalid loop count")((BackedgeTakenCount != SE->getCouldNotCompute() &&
"Invalid loop count") ? static_cast<void> (0) : __assert_fail
("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2358, __PRETTY_FUNCTION__))
;
2359
2360 Type *IdxTy = Legal->getWidestInductionType();
2361 assert(IdxTy && "No type for induction")((IdxTy && "No type for induction") ? static_cast<
void> (0) : __assert_fail ("IdxTy && \"No type for induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2361, __PRETTY_FUNCTION__))
;
2362
2363 // The exit count might have the type of i64 while the phi is i32. This can
2364 // happen if we have an induction variable that is sign extended before the
2365 // compare. The only way that we get a backedge taken count is that the
2366 // induction variable was signed and as such will not overflow. In such a case
2367 // truncation is legal.
2368 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2369 IdxTy->getPrimitiveSizeInBits())
2370 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2371 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2372
2373 // Get the total trip count from the count by adding 1.
2374 const SCEV *ExitCount = SE->getAddExpr(
2375 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2376
2377 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2378
2379 // Expand the trip count and place the new instructions in the preheader.
2380 // Notice that the pre-header does not change, only the loop body.
2381 SCEVExpander Exp(*SE, DL, "induction");
2382
2383 // Count holds the overall loop count (N).
2384 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2385 L->getLoopPreheader()->getTerminator());
2386
2387 if (TripCount->getType()->isPointerTy())
2388 TripCount =
2389 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2390 L->getLoopPreheader()->getTerminator());
2391
2392 return TripCount;
2393}
2394
2395Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2396 if (VectorTripCount)
2397 return VectorTripCount;
2398
2399 Value *TC = getOrCreateTripCount(L);
2400 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2401
2402 Type *Ty = TC->getType();
2403 Constant *Step = ConstantInt::get(Ty, VF * UF);
2404
2405 // If the tail is to be folded by masking, round the number of iterations N
2406 // up to a multiple of Step instead of rounding down. This is done by first
2407 // adding Step-1 and then rounding down. Note that it's ok if this addition
2408 // overflows: the vector induction variable will eventually wrap to zero given
2409 // that it starts at zero and its Step is a power of two; the loop will then
2410 // exit, with the last early-exit vector comparison also producing all-true.
2411 if (Cost->foldTailByMasking()) {
2412 assert(isPowerOf2_32(VF * UF) &&((isPowerOf2_32(VF * UF) && "VF*UF must be a power of 2 when folding tail by masking"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(VF * UF) && \"VF*UF must be a power of 2 when folding tail by masking\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2413, __PRETTY_FUNCTION__))
2413 "VF*UF must be a power of 2 when folding tail by masking")((isPowerOf2_32(VF * UF) && "VF*UF must be a power of 2 when folding tail by masking"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(VF * UF) && \"VF*UF must be a power of 2 when folding tail by masking\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2413, __PRETTY_FUNCTION__))
;
2414 TC = Builder.CreateAdd(TC, ConstantInt::get(Ty, VF * UF - 1), "n.rnd.up");
2415 }
2416
2417 // Now we need to generate the expression for the part of the loop that the
2418 // vectorized body will execute. This is equal to N - (N % Step) if scalar
2419 // iterations are not required for correctness, or N - Step, otherwise. Step
2420 // is equal to the vectorization factor (number of SIMD elements) times the
2421 // unroll factor (number of SIMD instructions).
2422 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2423
2424 // If there is a non-reversed interleaved group that may speculatively access
2425 // memory out-of-bounds, we need to ensure that there will be at least one
2426 // iteration of the scalar epilogue loop. Thus, if the step evenly divides
2427 // the trip count, we set the remainder to be equal to the step. If the step
2428 // does not evenly divide the trip count, no adjustment is necessary since
2429 // there will already be scalar iterations. Note that the minimum iterations
2430 // check ensures that N >= Step.
2431 if (VF > 1 && Cost->requiresScalarEpilogue()) {
2432 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2433 R = Builder.CreateSelect(IsZero, Step, R);
2434 }
2435
2436 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2437
2438 return VectorTripCount;
2439}
2440
2441Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2442 const DataLayout &DL) {
2443 // Verify that V is a vector type with same number of elements as DstVTy.
2444 unsigned VF = DstVTy->getNumElements();
2445 VectorType *SrcVecTy = cast<VectorType>(V->getType());
2446 assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match")(((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match"
) ? static_cast<void> (0) : __assert_fail ("(VF == SrcVecTy->getNumElements()) && \"Vector dimensions do not match\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2446, __PRETTY_FUNCTION__))
;
2447 Type *SrcElemTy = SrcVecTy->getElementType();
2448 Type *DstElemTy = DstVTy->getElementType();
2449 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&(((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy
)) && "Vector elements must have same size") ? static_cast
<void> (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2450, __PRETTY_FUNCTION__))
2450 "Vector elements must have same size")(((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy
)) && "Vector elements must have same size") ? static_cast
<void> (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2450, __PRETTY_FUNCTION__))
;
2451
2452 // Do a direct cast if element types are castable.
2453 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2454 return Builder.CreateBitOrPointerCast(V, DstVTy);
2455 }
2456 // V cannot be directly casted to desired vector type.
2457 // May happen when V is a floating point vector but DstVTy is a vector of
2458 // pointers or vice-versa. Handle this using a two-step bitcast using an
2459 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2460 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&(((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()
) && "Only one type should be a pointer type") ? static_cast
<void> (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2461, __PRETTY_FUNCTION__))
2461 "Only one type should be a pointer type")(((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()
) && "Only one type should be a pointer type") ? static_cast
<void> (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2461, __PRETTY_FUNCTION__))
;
2462 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&(((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy
()) && "Only one type should be a floating point type"
) ? static_cast<void> (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2463, __PRETTY_FUNCTION__))
2463 "Only one type should be a floating point type")(((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy
()) && "Only one type should be a floating point type"
) ? static_cast<void> (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2463, __PRETTY_FUNCTION__))
;
2464 Type *IntTy =
2465 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2466 VectorType *VecIntTy = VectorType::get(IntTy, VF);
2467 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2468 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
2469}
2470
2471void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2472 BasicBlock *Bypass) {
2473 Value *Count = getOrCreateTripCount(L);
2474 BasicBlock *BB = L->getLoopPreheader();
2475 IRBuilder<> Builder(BB->getTerminator());
2476
2477 // Generate code to check if the loop's trip count is less than VF * UF, or
2478 // equal to it in case a scalar epilogue is required; this implies that the
2479 // vector trip count is zero. This check also covers the case where adding one
2480 // to the backedge-taken count overflowed leading to an incorrect trip count
2481 // of zero. In this case we will also jump to the scalar loop.
2482 auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
2483 : ICmpInst::ICMP_ULT;
2484
2485 // If tail is to be folded, vector loop takes care of all iterations.
2486 Value *CheckMinIters = Builder.getFalse();
2487 if (!Cost->foldTailByMasking())
2488 CheckMinIters = Builder.CreateICmp(
2489 P, Count, ConstantInt::get(Count->getType(), VF * UF),
2490 "min.iters.check");
2491
2492 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2493 // Update dominator tree immediately if the generated block is a
2494 // LoopBypassBlock because SCEV expansions to generate loop bypass
2495 // checks may query it before the current function is finished.
2496 DT->addNewBlock(NewBB, BB);
2497 if (L->getParentLoop())
2498 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2499 ReplaceInstWithInst(BB->getTerminator(),
2500 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2501 LoopBypassBlocks.push_back(BB);
2502}
2503
2504void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
2505 BasicBlock *BB = L->getLoopPreheader();
2506
2507 // Generate the code to check that the SCEV assumptions that we made.
2508 // We want the new basic block to start at the first instruction in a
2509 // sequence of instructions that form a check.
2510 SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
2511 "scev.check");
2512 Value *SCEVCheck =
2513 Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
2514
2515 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2516 if (C->isZero())
2517 return;
2518
2519 assert(!Cost->foldTailByMasking() && "Cannot check stride when folding tail")((!Cost->foldTailByMasking() && "Cannot check stride when folding tail"
) ? static_cast<void> (0) : __assert_fail ("!Cost->foldTailByMasking() && \"Cannot check stride when folding tail\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2519, __PRETTY_FUNCTION__))
;
2520 // Create a new block containing the stride check.
2521 BB->setName("vector.scevcheck");
2522 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2523 // Update dominator tree immediately if the generated block is a
2524 // LoopBypassBlock because SCEV expansions to generate loop bypass
2525 // checks may query it before the current function is finished.
2526 DT->addNewBlock(NewBB, BB);
2527 if (L->getParentLoop())
2528 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2529 ReplaceInstWithInst(BB->getTerminator(),
2530 BranchInst::Create(Bypass, NewBB, SCEVCheck));
2531 LoopBypassBlocks.push_back(BB);
2532 AddedSafetyChecks = true;
2533}
2534
2535void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
2536 // VPlan-native path does not do any analysis for runtime checks currently.
2537 if (EnableVPlanNativePath)
2538 return;
2539
2540 BasicBlock *BB = L->getLoopPreheader();
2541
2542 // Generate the code that checks in runtime if arrays overlap. We put the
2543 // checks into a separate block to make the more common case of few elements
2544 // faster.
2545 Instruction *FirstCheckInst;
2546 Instruction *MemRuntimeCheck;
2547 std::tie(FirstCheckInst, MemRuntimeCheck) =
2548 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2549 if (!MemRuntimeCheck)
2550 return;
2551
2552 assert(!Cost->foldTailByMasking() && "Cannot check memory when folding tail")((!Cost->foldTailByMasking() && "Cannot check memory when folding tail"
) ? static_cast<void> (0) : __assert_fail ("!Cost->foldTailByMasking() && \"Cannot check memory when folding tail\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2552, __PRETTY_FUNCTION__))
;
2553 // Create a new block containing the memory check.
2554 BB->setName("vector.memcheck");
2555 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2556 // Update dominator tree immediately if the generated block is a
2557 // LoopBypassBlock because SCEV expansions to generate loop bypass
2558 // checks may query it before the current function is finished.
2559 DT->addNewBlock(NewBB, BB);
2560 if (L->getParentLoop())
2561 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2562 ReplaceInstWithInst(BB->getTerminator(),
2563 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2564 LoopBypassBlocks.push_back(BB);
2565 AddedSafetyChecks = true;
2566
2567 // We currently don't use LoopVersioning for the actual loop cloning but we
2568 // still use it to add the noalias metadata.
2569 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
2570 PSE.getSE());
2571 LVer->prepareNoAliasMetadata();
2572}
2573
2574Value *InnerLoopVectorizer::emitTransformedIndex(
2575 IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
2576 const InductionDescriptor &ID) const {
2577
2578 SCEVExpander Exp(*SE, DL, "induction");
2579 auto Step = ID.getStep();
2580 auto StartValue = ID.getStartValue();
2581 assert(Index->getType() == Step->getType() &&((Index->getType() == Step->getType() && "Index type does not match StepValue type"
) ? static_cast<void> (0) : __assert_fail ("Index->getType() == Step->getType() && \"Index type does not match StepValue type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2582, __PRETTY_FUNCTION__))
2582 "Index type does not match StepValue type")((Index->getType() == Step->getType() && "Index type does not match StepValue type"
) ? static_cast<void> (0) : __assert_fail ("Index->getType() == Step->getType() && \"Index type does not match StepValue type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2582, __PRETTY_FUNCTION__))
;
2583
2584 // Note: the IR at this point is broken. We cannot use SE to create any new
2585 // SCEV and then expand it, hoping that SCEV's simplification will give us
2586 // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2587 // lead to various SCEV crashes. So all we can do is to use builder and rely
2588 // on InstCombine for future simplifications. Here we handle some trivial
2589 // cases only.
2590 auto CreateAdd = [&B](Value *X, Value *Y) {
2591 assert(X->getType() == Y->getType() && "Types don't match!")((X->getType() == Y->getType() && "Types don't match!"
) ? static_cast<void> (0) : __assert_fail ("X->getType() == Y->getType() && \"Types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2591, __PRETTY_FUNCTION__))
;
2592 if (auto *CX = dyn_cast<ConstantInt>(X))
2593 if (CX->isZero())
2594 return Y;
2595 if (auto *CY = dyn_cast<ConstantInt>(Y))
2596 if (CY->isZero())
2597 return X;
2598 return B.CreateAdd(X, Y);
2599 };
2600
2601 auto CreateMul = [&B](Value *X, Value *Y) {
2602 assert(X->getType() == Y->getType() && "Types don't match!")((X->getType() == Y->getType() && "Types don't match!"
) ? static_cast<void> (0) : __assert_fail ("X->getType() == Y->getType() && \"Types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2602, __PRETTY_FUNCTION__))
;
2603 if (auto *CX = dyn_cast<ConstantInt>(X))
2604 if (CX->isOne())
2605 return Y;
2606 if (auto *CY = dyn_cast<ConstantInt>(Y))
2607 if (CY->isOne())
2608 return X;
2609 return B.CreateMul(X, Y);
2610 };
2611
2612 switch (ID.getKind()) {
2613 case InductionDescriptor::IK_IntInduction: {
2614 assert(Index->getType() == StartValue->getType() &&((Index->getType() == StartValue->getType() && "Index type does not match StartValue type"
) ? static_cast<void> (0) : __assert_fail ("Index->getType() == StartValue->getType() && \"Index type does not match StartValue type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2615, __PRETTY_FUNCTION__))
2615 "Index type does not match StartValue type")((Index->getType() == StartValue->getType() && "Index type does not match StartValue type"
) ? static_cast<void> (0) : __assert_fail ("Index->getType() == StartValue->getType() && \"Index type does not match StartValue type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2615, __PRETTY_FUNCTION__))
;
2616 if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
2617 return B.CreateSub(StartValue, Index);
2618 auto *Offset = CreateMul(
2619 Index, Exp.expandCodeFor(Step, Index->getType(), &*B.GetInsertPoint()));
2620 return CreateAdd(StartValue, Offset);
2621 }
2622 case InductionDescriptor::IK_PtrInduction: {
2623 assert(isa<SCEVConstant>(Step) &&((isa<SCEVConstant>(Step) && "Expected constant step for pointer induction"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Step) && \"Expected constant step for pointer induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2624, __PRETTY_FUNCTION__))
2624 "Expected constant step for pointer induction")((isa<SCEVConstant>(Step) && "Expected constant step for pointer induction"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Step) && \"Expected constant step for pointer induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2624, __PRETTY_FUNCTION__))
;
2625 return B.CreateGEP(
2626 nullptr, StartValue,
2627 CreateMul(Index, Exp.expandCodeFor(Step, Index->getType(),
2628 &*B.GetInsertPoint())));
2629 }
2630 case InductionDescriptor::IK_FpInduction: {
2631 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value")((Step->getType()->isFloatingPointTy() && "Expected FP Step value"
) ? static_cast<void> (0) : __assert_fail ("Step->getType()->isFloatingPointTy() && \"Expected FP Step value\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2631, __PRETTY_FUNCTION__))
;
2632 auto InductionBinOp = ID.getInductionBinOp();
2633 assert(InductionBinOp &&((InductionBinOp && (InductionBinOp->getOpcode() ==
Instruction::FAdd || InductionBinOp->getOpcode() == Instruction
::FSub) && "Original bin op should be defined for FP induction"
) ? static_cast<void> (0) : __assert_fail ("InductionBinOp && (InductionBinOp->getOpcode() == Instruction::FAdd || InductionBinOp->getOpcode() == Instruction::FSub) && \"Original bin op should be defined for FP induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2636, __PRETTY_FUNCTION__))
2634 (InductionBinOp->getOpcode() == Instruction::FAdd ||((InductionBinOp && (InductionBinOp->getOpcode() ==
Instruction::FAdd || InductionBinOp->getOpcode() == Instruction
::FSub) && "Original bin op should be defined for FP induction"
) ? static_cast<void> (0) : __assert_fail ("InductionBinOp && (InductionBinOp->getOpcode() == Instruction::FAdd || InductionBinOp->getOpcode() == Instruction::FSub) && \"Original bin op should be defined for FP induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2636, __PRETTY_FUNCTION__))
2635 InductionBinOp->getOpcode() == Instruction::FSub) &&((InductionBinOp && (InductionBinOp->getOpcode() ==
Instruction::FAdd || InductionBinOp->getOpcode() == Instruction
::FSub) && "Original bin op should be defined for FP induction"
) ? static_cast<void> (0) : __assert_fail ("InductionBinOp && (InductionBinOp->getOpcode() == Instruction::FAdd || InductionBinOp->getOpcode() == Instruction::FSub) && \"Original bin op should be defined for FP induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2636, __PRETTY_FUNCTION__))
2636 "Original bin op should be defined for FP induction")((InductionBinOp && (InductionBinOp->getOpcode() ==
Instruction::FAdd || InductionBinOp->getOpcode() == Instruction
::FSub) && "Original bin op should be defined for FP induction"
) ? static_cast<void> (0) : __assert_fail ("InductionBinOp && (InductionBinOp->getOpcode() == Instruction::FAdd || InductionBinOp->getOpcode() == Instruction::FSub) && \"Original bin op should be defined for FP induction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2636, __PRETTY_FUNCTION__))
;
2637
2638 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
2639
2640 // Floating point operations had to be 'fast' to enable the induction.
2641 FastMathFlags Flags;
2642 Flags.setFast();
2643
2644 Value *MulExp = B.CreateFMul(StepValue, Index);
2645 if (isa<Instruction>(MulExp))
2646 // We have to check, the MulExp may be a constant.
2647 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
2648
2649 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2650 "induction");
2651 if (isa<Instruction>(BOp))
2652 cast<Instruction>(BOp)->setFastMathFlags(Flags);
2653
2654 return BOp;
2655 }
2656 case InductionDescriptor::IK_NoInduction:
2657 return nullptr;
2658 }
2659 llvm_unreachable("invalid enum")::llvm::llvm_unreachable_internal("invalid enum", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2659)
;
2660}
2661
2662BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
2663 /*
2664 In this function we generate a new loop. The new loop will contain
2665 the vectorized instructions while the old loop will continue to run the
2666 scalar remainder.
2667
2668 [ ] <-- loop iteration number check.
2669 / |
2670 / v
2671 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2672 | / |
2673 | / v
2674 || [ ] <-- vector pre header.
2675 |/ |
2676 | v
2677 | [ ] \
2678 | [ ]_| <-- vector loop.
2679 | |
2680 | v
2681 | -[ ] <--- middle-block.
2682 | / |
2683 | / v
2684 -|- >[ ] <--- new preheader.
2685 | |
2686 | v
2687 | [ ] \
2688 | [ ]_| <-- old scalar loop to handle remainder.
2689 \ |
2690 \ v
2691 >[ ] <-- exit block.
2692 ...
2693 */
2694
2695 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2696 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2697 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2698 assert(VectorPH && "Invalid loop structure")((VectorPH && "Invalid loop structure") ? static_cast
<void> (0) : __assert_fail ("VectorPH && \"Invalid loop structure\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2698, __PRETTY_FUNCTION__))
;
2699 assert(ExitBlock && "Must have an exit block")((ExitBlock && "Must have an exit block") ? static_cast
<void> (0) : __assert_fail ("ExitBlock && \"Must have an exit block\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2699, __PRETTY_FUNCTION__))
;
2700
2701 // Some loops have a single integer induction variable, while other loops
2702 // don't. One example is c++ iterators that often have multiple pointer
2703 // induction variables. In the code below we also support a case where we
2704 // don't have a single induction variable.
2705 //
2706 // We try to obtain an induction variable from the original loop as hard
2707 // as possible. However if we don't find one that:
2708 // - is an integer
2709 // - counts from zero, stepping by one
2710 // - is the size of the widest induction variable type
2711 // then we create a new one.
2712 OldInduction = Legal->getPrimaryInduction();
2713 Type *IdxTy = Legal->getWidestInductionType();
2714
2715 // Split the single block loop into the two loop structure described above.
2716 BasicBlock *VecBody =
2717 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2718 BasicBlock *MiddleBlock =
2719 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2720 BasicBlock *ScalarPH =
2721 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2722
2723 // Create and register the new vector loop.
2724 Loop *Lp = LI->AllocateLoop();
2725 Loop *ParentLoop = OrigLoop->getParentLoop();
2726
2727 // Insert the new loop into the loop nest and register the new basic blocks
2728 // before calling any utilities such as SCEV that require valid LoopInfo.
2729 if (ParentLoop) {
2730 ParentLoop->addChildLoop(Lp);
2731 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2732 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2733 } else {
2734 LI->addTopLevelLoop(Lp);
2735 }
2736 Lp->addBasicBlockToLoop(VecBody, *LI);
2737
2738 // Find the loop boundaries.
2739 Value *Count = getOrCreateTripCount(Lp);
2740
2741 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2742
2743 // Now, compare the new count to zero. If it is zero skip the vector loop and
2744 // jump to the scalar loop. This check also covers the case where the
2745 // backedge-taken count is uint##_max: adding one to it will overflow leading
2746 // to an incorrect trip count of zero. In this (rare) case we will also jump
2747 // to the scalar loop.
2748 emitMinimumIterationCountCheck(Lp, ScalarPH);
2749
2750 // Generate the code to check any assumptions that we've made for SCEV
2751 // expressions.
2752 emitSCEVChecks(Lp, ScalarPH);
2753
2754 // Generate the code that checks in runtime if arrays overlap. We put the
2755 // checks into a separate block to make the more common case of few elements
2756 // faster.
2757 emitMemRuntimeChecks(Lp, ScalarPH);
2758
2759 // Generate the induction variable.
2760 // The loop step is equal to the vectorization factor (num of SIMD elements)
2761 // times the unroll factor (num of SIMD instructions).
2762 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2763 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2764 Induction =
2765 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2766 getDebugLocFromInstOrOperands(OldInduction));
2767
2768 // We are going to resume the execution of the scalar loop.
2769 // Go over all of the induction variables that we found and fix the
2770 // PHIs that are left in the scalar version of the loop.
2771 // The starting values of PHI nodes depend on the counter of the last
2772 // iteration in the vectorized loop.
2773 // If we come from a bypass edge then we need to start from the original
2774 // start value.
2775
2776 // This variable saves the new starting index for the scalar loop. It is used
2777 // to test if there are any tail iterations left once the vector loop has
2778 // completed.
2779 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2780 for (auto &InductionEntry : *List) {
2781 PHINode *OrigPhi = InductionEntry.first;
2782 InductionDescriptor II = InductionEntry.second;
2783
2784 // Create phi nodes to merge from the backedge-taken check block.
2785 PHINode *BCResumeVal = PHINode::Create(
2786 OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
2787 // Copy original phi DL over to the new one.
2788 BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
2789 Value *&EndValue = IVEndValues[OrigPhi];
2790 if (OrigPhi == OldInduction) {
2791 // We know what the end value is.
2792 EndValue = CountRoundDown;
2793 } else {
2794 IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
2795 Type *StepType = II.getStep()->getType();
2796 Instruction::CastOps CastOp =
2797 CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
2798 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
2799 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2800 EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
2801 EndValue->setName("ind.end");
2802 }
2803
2804 // The new PHI merges the original incoming value, in case of a bypass,
2805 // or the value at the end of the vectorized loop.
2806 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2807
2808 // Fix the scalar body counter (PHI node).
2809 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2810
2811 // The old induction's phi node in the scalar body needs the truncated
2812 // value.
2813 for (BasicBlock *BB : LoopBypassBlocks)
2814 BCResumeVal->addIncoming(II.getStartValue(), BB);
2815 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2816 }
2817
2818 // Add a check in the middle block to see if we have completed
2819 // all of the iterations in the first vector loop.
2820 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2821 // If tail is to be folded, we know we don't need to run the remainder.
2822 Value *CmpN = Builder.getTrue();
2823 if (!Cost->foldTailByMasking())
2824 CmpN =
2825 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2826 CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
2827 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2828 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2829
2830 // Get ready to start creating new instructions into the vectorized body.
2831 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
2832
2833 // Save the state.
2834 LoopVectorPreHeader = Lp->getLoopPreheader();
2835 LoopScalarPreHeader = ScalarPH;
2836 LoopMiddleBlock = MiddleBlock;
2837 LoopExitBlock = ExitBlock;
2838 LoopVectorBody = VecBody;
2839 LoopScalarBody = OldBasicBlock;
2840
2841 // Keep all loop hints from the original loop on the vector loop (we'll
2842 // replace the vectorizer-specific hints below).
2843 if (MDNode *LID = OrigLoop->getLoopID())
2844 Lp->setLoopID(LID);
2845
2846 LoopVectorizeHints Hints(Lp, true, *ORE);
2847 Hints.setAlreadyVectorized();
2848
2849 return LoopVectorPreHeader;
2850}
2851
2852// Fix up external users of the induction variable. At this point, we are
2853// in LCSSA form, with all external PHIs that use the IV having one input value,
2854// coming from the remainder loop. We need those PHIs to also have a correct
2855// value for the IV when arriving directly from the middle block.
2856void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
2857 const InductionDescriptor &II,
2858 Value *CountRoundDown, Value *EndValue,
2859 BasicBlock *MiddleBlock) {
2860 // There are two kinds of external IV usages - those that use the value
2861 // computed in the last iteration (the PHI) and those that use the penultimate
2862 // value (the value that feeds into the phi from the loop latch).
2863 // We allow both, but they, obviously, have different values.
2864
2865 assert(OrigLoop->getExitBlock() && "Expected a single exit block")((OrigLoop->getExitBlock() && "Expected a single exit block"
) ? static_cast<void> (0) : __assert_fail ("OrigLoop->getExitBlock() && \"Expected a single exit block\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2865, __PRETTY_FUNCTION__))
;
2866
2867 DenseMap<Value *, Value *> MissingVals;
2868
2869 // An external user of the last iteration's value should see the value that
2870 // the remainder loop uses to initialize its own IV.
2871 Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
2872 for (User *U : PostInc->users()) {
2873 Instruction *UI = cast<Instruction>(U);
2874 if (!OrigLoop->contains(UI)) {
2875 assert(isa<PHINode>(UI) && "Expected LCSSA form")((isa<PHINode>(UI) && "Expected LCSSA form") ? static_cast
<void> (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2875, __PRETTY_FUNCTION__))
;
2876 MissingVals[UI] = EndValue;
2877 }
2878 }
2879
2880 // An external user of the penultimate value need to see EndValue - Step.
2881 // The simplest way to get this is to recompute it from the constituent SCEVs,
2882 // that is Start + (Step * (CRD - 1)).
2883 for (User *U : OrigPhi->users()) {
2884 auto *UI = cast<Instruction>(U);
2885 if (!OrigLoop->contains(UI)) {
2886 const DataLayout &DL =
2887 OrigLoop->getHeader()->getModule()->getDataLayout();
2888 assert(isa<PHINode>(UI) && "Expected LCSSA form")((isa<PHINode>(UI) && "Expected LCSSA form") ? static_cast
<void> (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2888, __PRETTY_FUNCTION__))
;
2889
2890 IRBuilder<> B(MiddleBlock->getTerminator());
2891 Value *CountMinusOne = B.CreateSub(
2892 CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
2893 Value *CMO =
2894 !II.getStep()->getType()->isIntegerTy()
2895 ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
2896 II.getStep()->getType())
2897 : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
2898 CMO->setName("cast.cmo");
2899 Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
2900 Escape->setName("ind.escape");
2901 MissingVals[UI] = Escape;
2902 }
2903 }
2904
2905 for (auto &I : MissingVals) {
2906 PHINode *PHI = cast<PHINode>(I.first);
2907 // One corner case we have to handle is two IVs "chasing" each-other,
2908 // that is %IV2 = phi [...], [ %IV1, %latch ]
2909 // In this case, if IV1 has an external use, we need to avoid adding both
2910 // "last value of IV1" and "penultimate value of IV2". So, verify that we
2911 // don't already have an incoming value for the middle block.
2912 if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
2913 PHI->addIncoming(I.second, MiddleBlock);
2914 }
2915}
2916
2917namespace {
2918
2919struct CSEDenseMapInfo {
2920 static bool canHandle(const Instruction *I) {
2921 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2922 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2923 }
2924
2925 static inline Instruction *getEmptyKey() {
2926 return DenseMapInfo<Instruction *>::getEmptyKey();
2927 }
2928
2929 static inline Instruction *getTombstoneKey() {
2930 return DenseMapInfo<Instruction *>::getTombstoneKey();
2931 }
2932
2933 static unsigned getHashValue(const Instruction *I) {
2934 assert(canHandle(I) && "Unknown instruction!")((canHandle(I) && "Unknown instruction!") ? static_cast
<void> (0) : __assert_fail ("canHandle(I) && \"Unknown instruction!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2934, __PRETTY_FUNCTION__))
;
2935 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2936 I->value_op_end()));
2937 }
2938
2939 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
2940 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2941 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2942 return LHS == RHS;
2943 return LHS->isIdenticalTo(RHS);
2944 }
2945};
2946
2947} // end anonymous namespace
2948
2949///Perform cse of induction variable instructions.
2950static void cse(BasicBlock *BB) {
2951 // Perform simple cse.
2952 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2953 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2954 Instruction *In = &*I++;
2955
2956 if (!CSEDenseMapInfo::canHandle(In))
2957 continue;
2958
2959 // Check if we can replace this instruction with any of the
2960 // visited instructions.
2961 if (Instruction *V = CSEMap.lookup(In)) {
2962 In->replaceAllUsesWith(V);
2963 In->eraseFromParent();
2964 continue;
2965 }
2966
2967 CSEMap[In] = In;
2968 }
2969}
2970
2971/// Estimate the overhead of scalarizing an instruction. This is a
2972/// convenience wrapper for the type-based getScalarizationOverhead API.
2973static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
2974 const TargetTransformInfo &TTI) {
2975 if (VF == 1)
2976 return 0;
2977
2978 unsigned Cost = 0;
2979 Type *RetTy = ToVectorTy(I->getType(), VF);
2980 if (!RetTy->isVoidTy() &&
2981 (!isa<LoadInst>(I) ||
2982 !TTI.supportsEfficientVectorElementLoadStore()))
2983 Cost += TTI.getScalarizationOverhead(RetTy, true, false);
2984
2985 if (CallInst *CI = dyn_cast<CallInst>(I)) {
2986 SmallVector<const Value *, 4> Operands(CI->arg_operands());
2987 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
2988 }
2989 else if (!isa<StoreInst>(I) ||
2990 !TTI.supportsEfficientVectorElementLoadStore()) {
2991 SmallVector<const Value *, 4> Operands(I->operand_values());
2992 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
2993 }
2994
2995 return Cost;
2996}
2997
2998// Estimate cost of a call instruction CI if it were vectorized with factor VF.
2999// Return the cost of the instruction, including scalarization overhead if it's
3000// needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3001// i.e. either vector version isn't available, or is too expensive.
3002static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3003 const TargetTransformInfo &TTI,
3004 const TargetLibraryInfo *TLI,
3005 bool &NeedToScalarize) {
3006 Function *F = CI->getCalledFunction();
3007 StringRef FnName = CI->getCalledFunction()->getName();
3008 Type *ScalarRetTy = CI->getType();
3009 SmallVector<Type *, 4> Tys, ScalarTys;
3010 for (auto &ArgOp : CI->arg_operands())
3011 ScalarTys.push_back(ArgOp->getType());
3012
3013 // Estimate cost of scalarized vector call. The source operands are assumed
3014 // to be vectors, so we need to extract individual elements from there,
3015 // execute VF scalar calls, and then gather the result into the vector return
3016 // value.
3017 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3018 if (VF == 1)
3019 return ScalarCallCost;
3020
3021 // Compute corresponding vector type for return value and arguments.
3022 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3023 for (Type *ScalarTy : ScalarTys)
3024 Tys.push_back(ToVectorTy(ScalarTy, VF));
3025
3026 // Compute costs of unpacking argument values for the scalar calls and
3027 // packing the return values to a vector.
3028 unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3029
3030 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3031
3032 // If we can't emit a vector call for this function, then the currently found
3033 // cost is the cost we need to return.
3034 NeedToScalarize = true;
3035 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3036 return Cost;
3037
3038 // If the corresponding vector cost is cheaper, return its cost.
3039 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3040 if (VectorCallCost < Cost) {
3041 NeedToScalarize = false;
3042 return VectorCallCost;
3043 }
3044 return Cost;
3045}
3046
3047// Estimate cost of an intrinsic call instruction CI if it were vectorized with
3048// factor VF. Return the cost of the instruction, including scalarization
3049// overhead if it's needed.
3050static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3051 const TargetTransformInfo &TTI,
3052 const TargetLibraryInfo *TLI) {
3053 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3054 assert(ID && "Expected intrinsic call!")((ID && "Expected intrinsic call!") ? static_cast<
void> (0) : __assert_fail ("ID && \"Expected intrinsic call!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3054, __PRETTY_FUNCTION__))
;
3055
3056 FastMathFlags FMF;
3057 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3058 FMF = FPMO->getFastMathFlags();
3059
3060 SmallVector<Value *, 4> Operands(CI->arg_operands());
3061 return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3062}
3063
3064static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3065 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3066 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3067 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3068}
3069static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3070 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3071 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3072 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3073}
3074
3075void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3076 // For every instruction `I` in MinBWs, truncate the operands, create a
3077 // truncated version of `I` and reextend its result. InstCombine runs
3078 // later and will remove any ext/trunc pairs.
3079 SmallPtrSet<Value *, 4> Erased;
3080 for (const auto &KV : Cost->getMinimalBitwidths()) {
3081 // If the value wasn't vectorized, we must maintain the original scalar
3082 // type. The absence of the value from VectorLoopValueMap indicates that it
3083 // wasn't vectorized.
3084 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3085 continue;
3086 for (unsigned Part = 0; Part < UF; ++Part) {
3087 Value *I = getOrCreateVectorValue(KV.first, Part);
3088 if (Erased.find(I) != Erased.end() || I->use_empty() ||
3089 !isa<Instruction>(I))
3090 continue;
3091 Type *OriginalTy = I->getType();
3092 Type *ScalarTruncatedTy =
3093 IntegerType::get(OriginalTy->getContext(), KV.second);
3094 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3095 OriginalTy->getVectorNumElements());
3096 if (TruncatedTy == OriginalTy)
3097 continue;
3098
3099 IRBuilder<> B(cast<Instruction>(I));
3100 auto ShrinkOperand = [&](Value *V) -> Value * {
3101 if (auto *ZI = dyn_cast<ZExtInst>(V))
3102 if (ZI->getSrcTy() == TruncatedTy)
3103 return ZI->getOperand(0);
3104 return B.CreateZExtOrTrunc(V, TruncatedTy);
3105 };
3106
3107 // The actual instruction modification depends on the instruction type,
3108 // unfortunately.
3109 Value *NewI = nullptr;
3110 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3111 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3112 ShrinkOperand(BO->getOperand(1)));
3113
3114 // Any wrapping introduced by shrinking this operation shouldn't be
3115 // considered undefined behavior. So, we can't unconditionally copy
3116 // arithmetic wrapping flags to NewI.
3117 cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3118 } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3119 NewI =
3120 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3121 ShrinkOperand(CI->getOperand(1)));
3122 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3123 NewI = B.CreateSelect(SI->getCondition(),
3124 ShrinkOperand(SI->getTrueValue()),
3125 ShrinkOperand(SI->getFalseValue()));
3126 } else if (auto *CI = dyn_cast<CastInst>(I)) {
3127 switch (CI->getOpcode()) {
3128 default:
3129 llvm_unreachable("Unhandled cast!")::llvm::llvm_unreachable_internal("Unhandled cast!", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3129)
;
3130 case Instruction::Trunc:
3131 NewI = ShrinkOperand(CI->getOperand(0));
3132 break;
3133 case Instruction::SExt:
3134 NewI = B.CreateSExtOrTrunc(
3135 CI->getOperand(0),
3136 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3137 break;
3138 case Instruction::ZExt:
3139 NewI = B.CreateZExtOrTrunc(
3140 CI->getOperand(0),
3141 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3142 break;
3143 }
3144 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3145 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3146 auto *O0 = B.CreateZExtOrTrunc(
3147 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3148 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3149 auto *O1 = B.CreateZExtOrTrunc(
3150 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3151
3152 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3153 } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3154 // Don't do anything with the operands, just extend the result.
3155 continue;
3156 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3157 auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3158 auto *O0 = B.CreateZExtOrTrunc(
3159 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3160 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3161 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3162 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3163 auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3164 auto *O0 = B.CreateZExtOrTrunc(
3165 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3166 NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3167 } else {
3168 // If we don't know what to do, be conservative and don't do anything.
3169 continue;
3170 }
3171
3172 // Lastly, extend the result.
3173 NewI->takeName(cast<Instruction>(I));
3174 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3175 I->replaceAllUsesWith(Res);
3176 cast<Instruction>(I)->eraseFromParent();
3177 Erased.insert(I);
3178 VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3179 }
3180 }
3181
3182 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3183 for (const auto &KV : Cost->getMinimalBitwidths()) {
3184 // If the value wasn't vectorized, we must maintain the original scalar
3185 // type. The absence of the value from VectorLoopValueMap indicates that it
3186 // wasn't vectorized.
3187 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3188 continue;
3189 for (unsigned Part = 0; Part < UF; ++Part) {
3190 Value *I = getOrCreateVectorValue(KV.first, Part);
3191 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3192 if (Inst && Inst->use_empty()) {
3193 Value *NewI = Inst->getOperand(0);
3194 Inst->eraseFromParent();
3195 VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3196 }
3197 }
3198 }
3199}
3200
3201void InnerLoopVectorizer::fixVectorizedLoop() {
3202 // Insert truncates and extends for any truncated instructions as hints to
3203 // InstCombine.
3204 if (VF > 1)
3205 truncateToMinimalBitwidths();
3206
3207 // Fix widened non-induction PHIs by setting up the PHI operands.
3208 if (OrigPHIsToFix.size()) {
3209 assert(EnableVPlanNativePath &&((EnableVPlanNativePath && "Unexpected non-induction PHIs for fixup in non VPlan-native path"
) ? static_cast<void> (0) : __assert_fail ("EnableVPlanNativePath && \"Unexpected non-induction PHIs for fixup in non VPlan-native path\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3210, __PRETTY_FUNCTION__))
3210 "Unexpected non-induction PHIs for fixup in non VPlan-native path")((EnableVPlanNativePath && "Unexpected non-induction PHIs for fixup in non VPlan-native path"
) ? static_cast<void> (0) : __assert_fail ("EnableVPlanNativePath && \"Unexpected non-induction PHIs for fixup in non VPlan-native path\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3210, __PRETTY_FUNCTION__))
;
3211 fixNonInductionPHIs();
3212 }
3213
3214 // At this point every instruction in the original loop is widened to a
3215 // vector form. Now we need to fix the recurrences in the loop. These PHI
3216 // nodes are currently empty because we did not want to introduce cycles.
3217 // This is the second stage of vectorizing recurrences.
3218 fixCrossIterationPHIs();
3219
3220 // Update the dominator tree.
3221 //
3222 // FIXME: After creating the structure of the new loop, the dominator tree is
3223 // no longer up-to-date, and it remains that way until we update it
3224 // here. An out-of-date dominator tree is problematic for SCEV,
3225 // because SCEVExpander uses it to guide code generation. The
3226 // vectorizer use SCEVExpanders in several places. Instead, we should
3227 // keep the dominator tree up-to-date as we go.
3228 updateAnalysis();
3229
3230 // Fix-up external users of the induction variables.
3231 for (auto &Entry : *Legal->getInductionVars())
3232 fixupIVUsers(Entry.first, Entry.second,
3233 getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3234 IVEndValues[Entry.first], LoopMiddleBlock);
3235
3236 fixLCSSAPHIs();
3237 for (Instruction *PI : PredicatedInstructions)
3238 sinkScalarOperands(&*PI);
3239
3240 // Remove redundant induction instructions.
3241 cse(LoopVectorBody);
3242}
3243
3244void InnerLoopVectorizer::fixCrossIterationPHIs() {
3245 // In order to support recurrences we need to be able to vectorize Phi nodes.
3246 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3247 // stage #2: We now need to fix the recurrences by adding incoming edges to
3248 // the currently empty PHI nodes. At this point every instruction in the
3249 // original loop is widened to a vector form so we can use them to construct
3250 // the incoming edges.
3251 for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
3252 // Handle first-order recurrences and reductions that need to be fixed.
3253 if (Legal->isFirstOrderRecurrence(&Phi))
3254 fixFirstOrderRecurrence(&Phi);
3255 else if (Legal->isReductionVariable(&Phi))
3256 fixReduction(&Phi);
3257 }
3258}
3259
3260void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3261 // This is the second phase of vectorizing first-order recurrences. An
3262 // overview of the transformation is described below. Suppose we have the
3263 // following loop.
3264 //
3265 // for (int i = 0; i < n; ++i)
3266 // b[i] = a[i] - a[i - 1];
3267 //
3268 // There is a first-order recurrence on "a". For this loop, the shorthand
3269 // scalar IR looks like:
3270 //
3271 // scalar.ph:
3272 // s_init = a[-1]
3273 // br scalar.body
3274 //
3275 // scalar.body:
3276 // i = phi [0, scalar.ph], [i+1, scalar.body]
3277 // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3278 // s2 = a[i]
3279 // b[i] = s2 - s1
3280 // br cond, scalar.body, ...
3281 //
3282 // In this example, s1 is a recurrence because it's value depends on the
3283 // previous iteration. In the first phase of vectorization, we created a
3284 // temporary value for s1. We now complete the vectorization and produce the
3285 // shorthand vector IR shown below (for VF = 4, UF = 1).
3286 //
3287 // vector.ph:
3288 // v_init = vector(..., ..., ..., a[-1])
3289 // br vector.body
3290 //
3291 // vector.body
3292 // i = phi [0, vector.ph], [i+4, vector.body]
3293 // v1 = phi [v_init, vector.ph], [v2, vector.body]
3294 // v2 = a[i, i+1, i+2, i+3];
3295 // v3 = vector(v1(3), v2(0, 1, 2))
3296 // b[i, i+1, i+2, i+3] = v2 - v3
3297 // br cond, vector.body, middle.block
3298 //
3299 // middle.block:
3300 // x = v2(3)
3301 // br scalar.ph
3302 //
3303 // scalar.ph:
3304 // s_init = phi [x, middle.block], [a[-1], otherwise]
3305 // br scalar.body
3306 //
3307 // After execution completes the vector loop, we extract the next value of
3308 // the recurrence (x) to use as the initial value in the scalar loop.
3309
3310 // Get the original loop preheader and single loop latch.
3311 auto *Preheader = OrigLoop->getLoopPreheader();
3312 auto *Latch = OrigLoop->getLoopLatch();
3313
3314 // Get the initial and previous values of the scalar recurrence.
3315 auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
3316 auto *Previous = Phi->getIncomingValueForBlock(Latch);
3317
3318 // Create a vector from the initial value.
3319 auto *VectorInit = ScalarInit;
3320 if (VF > 1) {
3321 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3322 VectorInit = Builder.CreateInsertElement(
3323 UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
3324 Builder.getInt32(VF - 1), "vector.recur.init");
3325 }
3326
3327 // We constructed a temporary phi node in the first phase of vectorization.
3328 // This phi node will eventually be deleted.
3329 Builder.SetInsertPoint(
3330 cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
3331
3332 // Create a phi node for the new recurrence. The current value will either be
3333 // the initial value inserted into a vector or loop-varying vector value.
3334 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
3335 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
3336
3337 // Get the vectorized previous value of the last part UF - 1. It appears last
3338 // among all unrolled iterations, due to the order of their construction.
3339 Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
3340
3341 // Set the insertion point after the previous value if it is an instruction.
3342 // Note that the previous value may have been constant-folded so it is not
3343 // guaranteed to be an instruction in the vector loop. Also, if the previous
3344 // value is a phi node, we should insert after all the phi nodes to avoid
3345 // breaking basic block verification.
3346 if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
3347 isa<PHINode>(PreviousLastPart))
3348 Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3349 else
3350 Builder.SetInsertPoint(
3351 &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
3352
3353 // We will construct a vector for the recurrence by combining the values for
3354 // the current and previous iterations. This is the required shuffle mask.
3355 SmallVector<Constant *, 8> ShuffleMask(VF);
3356 ShuffleMask[0] = Builder.getInt32(VF - 1);
3357 for (unsigned I = 1; I < VF; ++I)
3358 ShuffleMask[I] = Builder.getInt32(I + VF - 1);
3359
3360 // The vector from which to take the initial value for the current iteration
3361 // (actual or unrolled). Initially, this is the vector phi node.
3362 Value *Incoming = VecPhi;
3363
3364 // Shuffle the current and previous vector and update the vector parts.
3365 for (unsigned Part = 0; Part < UF; ++Part) {
3366 Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
3367 Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
3368 auto *Shuffle =
3369 VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
3370 ConstantVector::get(ShuffleMask))
3371 : Incoming;
3372 PhiPart->replaceAllUsesWith(Shuffle);
3373 cast<Instruction>(PhiPart)->eraseFromParent();
3374 VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
3375 Incoming = PreviousPart;
3376 }
3377
3378 // Fix the latch value of the new recurrence in the vector loop.
3379 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3380
3381 // Extract the last vector element in the middle block. This will be the
3382 // initial value for the recurrence when jumping to the scalar loop.
3383 auto *ExtractForScalar = Incoming;
3384 if (VF > 1) {
3385 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3386 ExtractForScalar = Builder.CreateExtractElement(
3387 ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
3388 }
3389 // Extract the second last element in the middle block if the
3390 // Phi is used outside the loop. We need to extract the phi itself
3391 // and not the last element (the phi update in the current iteration). This
3392 // will be the value when jumping to the exit block from the LoopMiddleBlock,
3393 // when the scalar loop is not run at all.
3394 Value *ExtractForPhiUsedOutsideLoop = nullptr;
3395 if (VF > 1)
3396 ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3397 Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
3398 // When loop is unrolled without vectorizing, initialize
3399 // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
3400 // `Incoming`. This is analogous to the vectorized case above: extracting the
3401 // second last element when VF > 1.
3402 else if (UF > 1)
3403 ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
3404
3405 // Fix the initial value of the original recurrence in the scalar loop.
3406 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3407 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3408 for (auto *BB : predecessors(LoopScalarPreHeader)) {
3409 auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3410 Start->addIncoming(Incoming, BB);
3411 }
3412
3413 Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
3414 Phi->setName("scalar.recur");
3415
3416 // Finally, fix users of the recurrence outside the loop. The users will need
3417 // either the last value of the scalar recurrence or the last value of the
3418 // vector recurrence we extracted in the middle block. Since the loop is in
3419 // LCSSA form, we just need to find all the phi nodes for the original scalar
3420 // recurrence in the exit block, and then add an edge for the middle block.
3421 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3422 if (LCSSAPhi.getIncomingValue(0) == Phi) {
3423 LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3424 }
3425 }
3426}
3427
3428void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
3429 Constant *Zero = Builder.getInt32(0);
3430
3431 // Get it's reduction variable descriptor.
3432 assert(Legal->isReductionVariable(Phi) &&((Legal->isReductionVariable(Phi) && "Unable to find the reduction variable"
) ? static_cast<void> (0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3433, __PRETTY_FUNCTION__))
3433 "Unable to find the reduction variable")((Legal->isReductionVariable(Phi) && "Unable to find the reduction variable"
) ? static_cast<void> (0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3433, __PRETTY_FUNCTION__))
;
3434 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
3435
3436 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3437 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3438 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3439 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3440 RdxDesc.getMinMaxRecurrenceKind();
3441 setDebugLocFromInst(Builder, ReductionStartValue);
3442
3443 // We need to generate a reduction vector from the incoming scalar.
3444 // To do so, we need to generate the 'identity' vector and override
3445 // one of the elements with the incoming scalar reduction. We need
3446 // to do it in the vector-loop preheader.
3447 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3448
3449 // This is the vector-clone of the value that leaves the loop.
3450 Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
3451
3452 // Find the reduction identity variable. Zero for addition, or, xor,
3453 // one for multiplication, -1 for And.
3454 Value *Identity;
3455 Value *VectorStart;
3456 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3457 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3458 // MinMax reduction have the start value as their identify.
3459 if (VF == 1) {
3460 VectorStart = Identity = ReductionStartValue;
3461 } else {
3462 VectorStart = Identity =
3463 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3464 }
3465 } else {
3466 // Handle other reduction kinds:
3467 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3468 RK, VecTy->getScalarType());
3469 if (VF == 1) {
3470 Identity = Iden;
3471 // This vector is the Identity vector where the first element is the
3472 // incoming scalar reduction.
3473 VectorStart = ReductionStartValue;
3474 } else {
3475 Identity = ConstantVector::getSplat(VF, Iden);
3476
3477 // This vector is the Identity vector where the first element is the
3478 // incoming scalar reduction.
3479 VectorStart =
3480 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3481 }
3482 }
3483
3484 // Fix the vector-loop phi.
3485
3486 // Reductions do not have to start at zero. They can start with
3487 // any loop invariant values.
3488 BasicBlock *Latch = OrigLoop->getLoopLatch();
3489 Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
3490 for (unsigned Part = 0; Part < UF; ++Part) {
3491 Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
3492 Value *Val = getOrCreateVectorValue(LoopVal, Part);
3493 // Make sure to add the reduction stat value only to the
3494 // first unroll part.
3495 Value *StartVal = (Part == 0) ? VectorStart : Identity;
3496 cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
3497 cast<PHINode>(VecRdxPhi)
3498 ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3499 }
3500
3501 // Before each round, move the insertion point right between
3502 // the PHIs and the values we are going to write.
3503 // This allows us to write both PHINodes and the extractelement
3504 // instructions.
3505 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3506
3507 setDebugLocFromInst(Builder, LoopExitInst);
3508
3509 // If the vector reduction can be performed in a smaller type, we truncate
3510 // then extend the loop exit value to enable InstCombine to evaluate the
3511 // entire expression in the smaller type.
3512 if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
3513 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3514 Builder.SetInsertPoint(
3515 LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
3516 VectorParts RdxParts(UF);
3517 for (unsigned Part = 0; Part < UF; ++Part) {
3518 RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
3519 Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3520 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3521 : Builder.CreateZExt(Trunc, VecTy);
3522 for (Value::user_iterator UI = RdxParts[Part]->user_begin();
3523 UI != RdxParts[Part]->user_end();)
3524 if (*UI != Trunc) {
3525 (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
3526 RdxParts[Part] = Extnd;
3527 } else {
3528 ++UI;
3529 }
3530 }
3531 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3532 for (unsigned Part = 0; Part < UF; ++Part) {
3533 RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3534 VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
3535 }
3536 }
3537
3538 // Reduce all of the unrolled parts into a single vector.
3539 Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
3540 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3541 setDebugLocFromInst(Builder, ReducedPartRdx);
3542 for (unsigned Part = 1; Part < UF; ++Part) {
3543 Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
3544 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3545 // Floating point operations had to be 'fast' to enable the reduction.
3546 ReducedPartRdx = addFastMathFlag(
3547 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
3548 ReducedPartRdx, "bin.rdx"));
3549 else
3550 ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
3551 RdxPart);
3552 }
3553
3554 if (VF > 1) {
3555 bool NoNaN = Legal->hasFunNoNaNAttr();
3556 ReducedPartRdx =
3557 createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
3558 // If the reduction can be performed in a smaller type, we need to extend
3559 // the reduction to the wider type before we branch to the original loop.
3560 if (Phi->getType() != RdxDesc.getRecurrenceType())
3561 ReducedPartRdx =
3562 RdxDesc.isSigned()
3563 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
3564 : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
3565 }
3566
3567 // Create a phi node that merges control-flow from the backedge-taken check
3568 // block and the middle block.
3569 PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
3570 LoopScalarPreHeader->getTerminator());
3571 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3572 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3573 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3574
3575 // Now, we need to fix the users of the reduction variable
3576 // inside and outside of the scalar remainder loop.
3577 // We know that the loop is in LCSSA form. We need to update the
3578 // PHI nodes in the exit blocks.
3579 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3580 // All PHINodes need to have a single entry edge, or two if
3581 // we already fixed them.
3582 assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI")((LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI"
) ? static_cast<void> (0) : __assert_fail ("LCSSAPhi.getNumIncomingValues() < 3 && \"Invalid LCSSA PHI\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3582, __PRETTY_FUNCTION__))
;
3583
3584 // We found a reduction value exit-PHI. Update it with the
3585 // incoming bypass edge.
3586 if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
3587 LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
3588 } // end of the LCSSA phi scan.
3589
3590 // Fix the scalar loop reduction variable with the incoming reduction sum
3591 // from the vector body and from the backedge value.
3592 int IncomingEdgeBlockIdx =
3593 Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
3594 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index")((IncomingEdgeBlockIdx >= 0 && "Invalid block index"
) ? static_cast<void> (0) : __assert_fail ("IncomingEdgeBlockIdx >= 0 && \"Invalid block index\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3594, __PRETTY_FUNCTION__))
;
3595 // Pick the other block.
3596 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3597 Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3598 Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3599}
3600
3601void InnerLoopVectorizer::fixLCSSAPHIs() {
3602 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3603 if (LCSSAPhi.getNumIncomingValues() == 1) {
3604 auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
3605 // Non-instruction incoming values will have only one value.
3606 unsigned LastLane = 0;
3607 if (isa<Instruction>(IncomingValue))
3608 LastLane = Cost->isUniformAfterVectorization(
3609 cast<Instruction>(IncomingValue), VF)
3610 ? 0
3611 : VF - 1;
3612 // Can be a loop invariant incoming value or the last scalar value to be
3613 // extracted from the vectorized loop.
3614 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3615 Value *lastIncomingValue =
3616 getOrCreateScalarValue(IncomingValue, { UF - 1, LastLane });
3617 LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
3618 }
3619 }
3620}
3621
3622void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
3623 // The basic block and loop containing the predicated instruction.
3624 auto *PredBB = PredInst->getParent();
3625 auto *VectorLoop = LI->getLoopFor(PredBB);
3626
3627 // Initialize a worklist with the operands of the predicated instruction.
3628 SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
3629
3630 // Holds instructions that we need to analyze again. An instruction may be
3631 // reanalyzed if we don't yet know if we can sink it or not.
3632 SmallVector<Instruction *, 8> InstsToReanalyze;
3633
3634 // Returns true if a given use occurs in the predicated block. Phi nodes use
3635 // their operands in their corresponding predecessor blocks.
3636 auto isBlockOfUsePredicated = [&](Use &U) -> bool {
3637 auto *I = cast<Instruction>(U.getUser());
3638 BasicBlock *BB = I->getParent();
3639 if (auto *Phi = dyn_cast<PHINode>(I))
3640 BB = Phi->getIncomingBlock(
3641 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3642 return BB == PredBB;
3643 };
3644
3645 // Iteratively sink the scalarized operands of the predicated instruction
3646 // into the block we created for it. When an instruction is sunk, it's
3647 // operands are then added to the worklist. The algorithm ends after one pass
3648 // through the worklist doesn't sink a single instruction.
3649 bool Changed;
3650 do {
3651 // Add the instructions that need to be reanalyzed to the worklist, and
3652 // reset the changed indicator.
3653 Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
3654 InstsToReanalyze.clear();
3655 Changed = false;
3656
3657 while (!Worklist.empty()) {
3658 auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
3659
3660 // We can't sink an instruction if it is a phi node, is already in the
3661 // predicated block, is not in the loop, or may have side effects.
3662 if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
3663 !VectorLoop->contains(I) || I->mayHaveSideEffects())
3664 continue;
3665
3666 // It's legal to sink the instruction if all its uses occur in the
3667 // predicated block. Otherwise, there's nothing to do yet, and we may
3668 // need to reanalyze the instruction.
3669 if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
3670 InstsToReanalyze.push_back(I);
3671 continue;
3672 }
3673
3674 // Move the instruction to the beginning of the predicated block, and add
3675 // it's operands to the worklist.
3676 I->moveBefore(&*PredBB->getFirstInsertionPt());
3677 Worklist.insert(I->op_begin(), I->op_end());
3678
3679 // The sinking may have enabled other instructions to be sunk, so we will
3680 // need to iterate.
3681 Changed = true;
3682 }
3683 } while (Changed);
3684}
3685
3686void InnerLoopVectorizer::fixNonInductionPHIs() {
3687 for (PHINode *OrigPhi : OrigPHIsToFix) {
3688 PHINode *NewPhi =
3689 cast<PHINode>(VectorLoopValueMap.getVectorValue(OrigPhi, 0));
3690 unsigned NumIncomingValues = OrigPhi->getNumIncomingValues();
3691
3692 SmallVector<BasicBlock *, 2> ScalarBBPredecessors(
3693 predecessors(OrigPhi->getParent()));
3694 SmallVector<BasicBlock *, 2> VectorBBPredecessors(
3695 predecessors(NewPhi->getParent()));
3696 assert(ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&((ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&
"Scalar and Vector BB should have the same number of predecessors"
) ? static_cast<void> (0) : __assert_fail ("ScalarBBPredecessors.size() == VectorBBPredecessors.size() && \"Scalar and Vector BB should have the same number of predecessors\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3697, __PRETTY_FUNCTION__))
3697 "Scalar and Vector BB should have the same number of predecessors")((ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&
"Scalar and Vector BB should have the same number of predecessors"
) ? static_cast<void> (0) : __assert_fail ("ScalarBBPredecessors.size() == VectorBBPredecessors.size() && \"Scalar and Vector BB should have the same number of predecessors\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3697, __PRETTY_FUNCTION__))
;
3698
3699 // The insertion point in Builder may be invalidated by the time we get
3700 // here. Force the Builder insertion point to something valid so that we do
3701 // not run into issues during insertion point restore in
3702 // getOrCreateVectorValue calls below.
3703 Builder.SetInsertPoint(NewPhi);
3704
3705 // The predecessor order is preserved and we can rely on mapping between
3706 // scalar and vector block predecessors.
3707 for (unsigned i = 0; i < NumIncomingValues; ++i) {
3708 BasicBlock *NewPredBB = VectorBBPredecessors[i];
3709
3710 // When looking up the new scalar/vector values to fix up, use incoming
3711 // values from original phi.
3712 Value *ScIncV =
3713 OrigPhi->getIncomingValueForBlock(ScalarBBPredecessors[i]);
3714
3715 // Scalar incoming value may need a broadcast
3716 Value *NewIncV = getOrCreateVectorValue(ScIncV, 0);
3717 NewPhi->addIncoming(NewIncV, NewPredBB);
3718 }
3719 }
3720}
3721
3722void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
3723 unsigned VF) {
3724 PHINode *P = cast<PHINode>(PN);
3725 if (EnableVPlanNativePath) {
3726 // Currently we enter here in the VPlan-native path for non-induction
3727 // PHIs where all control flow is uniform. We simply widen these PHIs.
3728 // Create a vector phi with no operands - the vector phi operands will be
3729 // set at the end of vector code generation.
3730 Type *VecTy =
3731 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
3732 Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
3733 VectorLoopValueMap.setVectorValue(P, 0, VecPhi);
3734 OrigPHIsToFix.push_back(P);
3735
3736 return;
3737 }
3738
3739 assert(PN->getParent() == OrigLoop->getHeader() &&((PN->getParent() == OrigLoop->getHeader() && "Non-header phis should have been handled elsewhere"
) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3740, __PRETTY_FUNCTION__))
3740 "Non-header phis should have been handled elsewhere")((PN->getParent() == OrigLoop->getHeader() && "Non-header phis should have been handled elsewhere"
) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3740, __PRETTY_FUNCTION__))
;
3741
3742 // In order to support recurrences we need to be able to vectorize Phi nodes.
3743 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3744 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
3745 // this value when we vectorize all of the instructions that use the PHI.
3746 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
3747 for (unsigned Part = 0; Part < UF; ++Part) {
3748 // This is phase one of vectorizing PHIs.
3749 Type *VecTy =
3750 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
3751 Value *EntryPart = PHINode::Create(
3752 VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
3753 VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
3754 }
3755 return;
3756 }
3757
3758 setDebugLocFromInst(Builder, P);
3759
3760 // This PHINode must be an induction variable.
3761 // Make sure that we know about it.
3762 assert(Legal->getInductionVars()->count(P) && "Not an induction variable")((Legal->getInductionVars()->count(P) && "Not an induction variable"
) ? static_cast<void> (0) : __assert_fail ("Legal->getInductionVars()->count(P) && \"Not an induction variable\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3762, __PRETTY_FUNCTION__))
;
3763
3764 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3765 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3766
3767 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3768 // which can be found from the original scalar operations.
3769 switch (II.getKind()) {
3770 case InductionDescriptor::IK_NoInduction:
3771 llvm_unreachable("Unknown induction")::llvm::llvm_unreachable_internal("Unknown induction", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3771)
;
3772 case InductionDescriptor::IK_IntInduction:
3773 case InductionDescriptor::IK_FpInduction:
3774 llvm_unreachable("Integer/fp induction is handled elsewhere.")::llvm::llvm_unreachable_internal("Integer/fp induction is handled elsewhere."
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3774)
;
3775 case InductionDescriptor::IK_PtrInduction: {
3776 // Handle the pointer induction variable case.
3777 assert(P->getType()->isPointerTy() && "Unexpected type.")((P->getType()->isPointerTy() && "Unexpected type."
) ? static_cast<void> (0) : __assert_fail ("P->getType()->isPointerTy() && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3777, __PRETTY_FUNCTION__))
;
3778 // This is the normalized GEP that starts counting at zero.
3779 Value *PtrInd = Induction;
3780 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
3781 // Determine the number of scalars we need to generate for each unroll
3782 // iteration. If the instruction is uniform, we only need to generate the
3783 // first lane. Otherwise, we generate all VF values.
3784 unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
3785 // These are the scalar results. Notice that we don't generate vector GEPs
3786 // because scalar GEPs result in better code.
3787 for (unsigned Part = 0; Part < UF; ++Part) {
3788 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
3789 Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
3790 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3791 Value *SclrGep =
3792 emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
3793 SclrGep->setName("next.gep");
3794 VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
3795 }
3796 }
3797 return;
3798 }
3799 }
3800}
3801
3802/// A helper function for checking whether an integer division-related
3803/// instruction may divide by zero (in which case it must be predicated if
3804/// executed conditionally in the scalar code).
3805/// TODO: It may be worthwhile to generalize and check isKnownNonZero().
3806/// Non-zero divisors that are non compile-time constants will not be
3807/// converted into multiplication, so we will still end up scalarizing
3808/// the division, but can do so w/o predication.
3809static bool mayDivideByZero(Instruction &I) {
3810 assert((I.getOpcode() == Instruction::UDiv ||(((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction
::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode()
== Instruction::SRem) && "Unexpected instruction") ?
static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3814, __PRETTY_FUNCTION__))
3811 I.getOpcode() == Instruction::SDiv ||(((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction
::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode()
== Instruction::SRem) && "Unexpected instruction") ?
static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3814, __PRETTY_FUNCTION__))
3812 I.getOpcode() == Instruction::URem ||(((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction
::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode()
== Instruction::SRem) && "Unexpected instruction") ?
static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3814, __PRETTY_FUNCTION__))
3813 I.getOpcode() == Instruction::SRem) &&(((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction
::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode()
== Instruction::SRem) && "Unexpected instruction") ?
static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3814, __PRETTY_FUNCTION__))
3814 "Unexpected instruction")(((I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction
::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode()
== Instruction::SRem) && "Unexpected instruction") ?
static_cast<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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3814, __PRETTY_FUNCTION__))
;
3815 Value *Divisor = I.getOperand(1);
3816 auto *CInt = dyn_cast<ConstantInt>(Divisor);
3817 return !CInt || CInt->isZero();
3818}
3819
3820void InnerLoopVectorizer::widenInstruction(Instruction &I) {
3821 switch (I.getOpcode()) {
3822 case Instruction::Br:
3823 case Instruction::PHI:
3824 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-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3824)
;
3825 case Instruction::GetElementPtr: {
3826 // Construct a vector GEP by widening the operands of the scalar GEP as
3827 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
3828 // results in a vector of pointers when at least one operand of the GEP
3829 // is vector-typed. Thus, to keep the representation compact, we only use
3830 // vector-typed operands for loop-varying values.
3831 auto *GEP = cast<GetElementPtrInst>(&I);
3832
3833 if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
3834 // If we are vectorizing, but the GEP has only loop-invariant operands,
3835 // the GEP we build (by only using vector-typed operands for
3836 // loop-varying values) would be a scalar pointer. Thus, to ensure we
3837 // produce a vector of pointers, we need to either arbitrarily pick an
3838 // operand to broadcast, or broadcast a clone of the original GEP.
3839 // Here, we broadcast a clone of the original.
3840 //
3841 // TODO: If at some point we decide to scalarize instructions having
3842 // loop-invariant operands, this special case will no longer be
3843 // required. We would add the scalarization decision to
3844 // collectLoopScalars() and teach getVectorValue() to broadcast
3845 // the lane-zero scalar value.
3846 auto *Clone = Builder.Insert(GEP->clone());
3847 for (unsigned Part = 0; Part < UF; ++Part) {
3848 Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
3849 VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
3850 addMetadata(EntryPart, GEP);
3851 }
3852 } else {
3853 // If the GEP has at least one loop-varying operand, we are sure to
3854 // produce a vector of pointers. But if we are only unrolling, we want
3855 // to produce a scalar GEP for each unroll part. Thus, the GEP we
3856 // produce with the code below will be scalar (if VF == 1) or vector
3857 // (otherwise). Note that for the unroll-only case, we still maintain
3858 // values in the vector mapping with initVector, as we do for other
3859 // instructions.
3860 for (unsigned Part = 0; Part < UF; ++Part) {
3861 // The pointer operand of the new GEP. If it's loop-invariant, we
3862 // won't broadcast it.
3863 auto *Ptr =
3864 OrigLoop->isLoopInvariant(GEP->getPointerOperand())
3865 ? GEP->getPointerOperand()
3866 : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
3867
3868 // Collect all the indices for the new GEP. If any index is
3869 // loop-invariant, we won't broadcast it.
3870 SmallVector<Value *, 4> Indices;
3871 for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
3872 if (OrigLoop->isLoopInvariant(U.get()))
3873 Indices.push_back(U.get());
3874 else
3875 Indices.push_back(getOrCreateVectorValue(U.get(), Part));
3876 }
3877
3878 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
3879 // but it should be a vector, otherwise.
3880 auto *NewGEP = GEP->isInBounds()
3881 ? Builder.CreateInBoundsGEP(Ptr, Indices)
3882 : Builder.CreateGEP(Ptr, Indices);
3883 assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&(((VF == 1 || NewGEP->getType()->isVectorTy()) &&
"NewGEP is not a pointer vector") ? static_cast<void> (
0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3884, __PRETTY_FUNCTION__))
3884 "NewGEP is not a pointer vector")(((VF == 1 || NewGEP->getType()->isVectorTy()) &&
"NewGEP is not a pointer vector") ? static_cast<void> (
0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3884, __PRETTY_FUNCTION__))
;
3885 VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
3886 addMetadata(NewGEP, GEP);
3887 }
3888 }
3889
3890 break;
3891 }
3892 case Instruction::UDiv:
3893 case Instruction::SDiv:
3894 case Instruction::SRem:
3895 case Instruction::URem:
3896 case Instruction::Add:
3897 case Instruction::FAdd:
3898 case Instruction::Sub:
3899 case Instruction::FSub:
3900 case Instruction::Mul:
3901 case Instruction::FMul:
3902 case Instruction::FDiv:
3903 case Instruction::FRem:
3904 case Instruction::Shl:
3905 case Instruction::LShr:
3906 case Instruction::AShr:
3907 case Instruction::And:
3908 case Instruction::Or:
3909 case Instruction::Xor: {
3910 // Just widen binops.
3911 auto *BinOp = cast<BinaryOperator>(&I);
3912 setDebugLocFromInst(Builder, BinOp);
3913
3914 for (unsigned Part = 0; Part < UF; ++Part) {
3915 Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
3916 Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
3917 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
3918
3919 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3920 VecOp->copyIRFlags(BinOp);
3921
3922 // Use this vector value for all users of the original instruction.
3923 VectorLoopValueMap.setVectorValue(&I, Part, V);
3924 addMetadata(V, BinOp);
3925 }
3926
3927 break;
3928 }
3929 case Instruction::Select: {
3930 // Widen selects.
3931 // If the selector is loop invariant we can create a select
3932 // instruction with a scalar condition. Otherwise, use vector-select.
3933 auto *SE = PSE.getSE();
3934 bool InvariantCond =
3935 SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
3936 setDebugLocFromInst(Builder, &I);
3937
3938 // The condition can be loop invariant but still defined inside the
3939 // loop. This means that we can't just use the original 'cond' value.
3940 // We have to take the 'vectorized' value and pick the first lane.
3941 // Instcombine will make this a no-op.
3942
3943 auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
3944
3945 for (unsigned Part = 0; Part < UF; ++Part) {
3946 Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
3947 Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
3948 Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
3949 Value *Sel =
3950 Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
3951 VectorLoopValueMap.setVectorValue(&I, Part, Sel);
3952 addMetadata(Sel, &I);
3953 }
3954
3955 break;
3956 }
3957
3958 case Instruction::ICmp:
3959 case Instruction::FCmp: {
3960 // Widen compares. Generate vector compares.
3961 bool FCmp = (I.getOpcode() == Instruction::FCmp);
3962 auto *Cmp = dyn_cast<CmpInst>(&I);
3963 setDebugLocFromInst(Builder, Cmp);
3964 for (unsigned Part = 0; Part < UF; ++Part) {
3965 Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
3966 Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
3967 Value *C = nullptr;
3968 if (FCmp) {
3969 // Propagate fast math flags.
3970 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3971 Builder.setFastMathFlags(Cmp->getFastMathFlags());
3972 C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
3973 } else {
3974 C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
3975 }
3976 VectorLoopValueMap.setVectorValue(&I, Part, C);
3977 addMetadata(C, &I);
3978 }
3979
3980 break;
3981 }
3982
3983 case Instruction::ZExt:
3984 case Instruction::SExt:
3985 case Instruction::FPToUI:
3986 case Instruction::FPToSI:
3987 case Instruction::FPExt:
3988 case Instruction::PtrToInt:
3989 case Instruction::IntToPtr:
3990 case Instruction::SIToFP:
3991 case Instruction::UIToFP:
3992 case Instruction::Trunc:
3993 case Instruction::FPTrunc:
3994 case Instruction::BitCast: {
3995 auto *CI = dyn_cast<CastInst>(&I);
3996 setDebugLocFromInst(Builder, CI);
3997
3998 /// Vectorize casts.
3999 Type *DestTy =
4000 (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4001
4002 for (unsigned Part = 0; Part < UF; ++Part) {
4003 Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4004 Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4005 VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4006 addMetadata(Cast, &I);
4007 }
4008 break;
4009 }
4010
4011 case Instruction::Call: {
4012 // Ignore dbg intrinsics.
4013 if (isa<DbgInfoIntrinsic>(I))
4014 break;
4015 setDebugLocFromInst(Builder, &I);
4016
4017 Module *M = I.getParent()->getParent()->getParent();
4018 auto *CI = cast<CallInst>(&I);
4019
4020 StringRef FnName = CI->getCalledFunction()->getName();
4021 Function *F = CI->getCalledFunction();
4022 Type *RetTy = ToVectorTy(CI->getType(), VF);
4023 SmallVector<Type *, 4> Tys;
4024 for (Value *ArgOperand : CI->arg_operands())
4025 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4026
4027 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4028
4029 // The flag shows whether we use Intrinsic or a usual Call for vectorized
4030 // version of the instruction.
4031 // Is it beneficial to perform intrinsic call compared to lib call?
4032 bool NeedToScalarize;
4033 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4034 bool UseVectorIntrinsic =
4035 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4036 assert((UseVectorIntrinsic || !NeedToScalarize) &&(((UseVectorIntrinsic || !NeedToScalarize) && "Instruction should be scalarized elsewhere."
) ? static_cast<void> (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4037, __PRETTY_FUNCTION__))
4037 "Instruction should be scalarized elsewhere.")(((UseVectorIntrinsic || !NeedToScalarize) && "Instruction should be scalarized elsewhere."
) ? static_cast<void> (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4037, __PRETTY_FUNCTION__))
;
4038
4039 for (unsigned Part = 0; Part < UF; ++Part) {
4040 SmallVector<Value *, 4> Args;
4041 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4042 Value *Arg = CI->getArgOperand(i);
4043 // Some intrinsics have a scalar argument - don't replace it with a
4044 // vector.
4045 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
4046 Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4047 Args.push_back(Arg);
4048 }
4049
4050 Function *VectorF;
4051 if (UseVectorIntrinsic) {
4052 // Use vector version of the intrinsic.
4053 Type *TysForDecl[] = {CI->getType()};
4054 if (VF > 1)
4055 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4056 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4057 } else {
4058 // Use vector version of the library call.
4059 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4060 assert(!VFnName.empty() && "Vector function name is empty.")((!VFnName.empty() && "Vector function name is empty."
) ? static_cast<void> (0) : __assert_fail ("!VFnName.empty() && \"Vector function name is empty.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4060, __PRETTY_FUNCTION__))
;
4061 VectorF = M->getFunction(VFnName);
4062 if (!VectorF) {
4063 // Generate a declaration
4064 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4065 VectorF =
4066 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4067 VectorF->copyAttributesFrom(F);
4068 }
4069 }
4070 assert(VectorF && "Can't create vector function.")((VectorF && "Can't create vector function.") ? static_cast
<void> (0) : __assert_fail ("VectorF && \"Can't create vector function.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4070, __PRETTY_FUNCTION__))
;
4071
4072 SmallVector<OperandBundleDef, 1> OpBundles;
4073 CI->getOperandBundlesAsDefs(OpBundles);
4074 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4075
4076 if (isa<FPMathOperator>(V))
4077 V->copyFastMathFlags(CI);
4078
4079 VectorLoopValueMap.setVectorValue(&I, Part, V);
4080 addMetadata(V, &I);
4081 }
4082
4083 break;
4084 }
4085
4086 default:
4087 // This instruction is not vectorized by simple widening.
4088 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)
;
4089 llvm_unreachable("Unhandled instruction!")::llvm::llvm_unreachable_internal("Unhandled instruction!", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4089)
;
4090 } // end of switch.
4091}
4092
4093void InnerLoopVectorizer::updateAnalysis() {
4094 // Forget the original basic block.
4095 PSE.getSE()->forgetLoop(OrigLoop);
4096
4097 // DT is not kept up-to-date for outer loop vectorization
4098 if (EnableVPlanNativePath)
4099 return;
4100
4101 // Update the dominator tree information.
4102 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&((DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock
) && "Entry does not dominate exit.") ? static_cast<
void> (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4103, __PRETTY_FUNCTION__))
4103 "Entry does not dominate exit.")((DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock
) && "Entry does not dominate exit.") ? static_cast<
void> (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4103, __PRETTY_FUNCTION__))
;
4104
4105 DT->addNewBlock(LoopMiddleBlock,
4106 LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4107 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4108 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4109 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4110 assert(DT->verify(DominatorTree::VerificationLevel::Fast))((DT->verify(DominatorTree::VerificationLevel::Fast)) ? static_cast
<void> (0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast)"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4110, __PRETTY_FUNCTION__))
;
4111}
4112
4113void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
4114 // We should not collect Scalars more than once per VF. Right now, this
4115 // function is called from collectUniformsAndScalars(), which already does
4116 // this check. Collecting Scalars for VF=1 does not make any sense.
4117 assert(VF >= 2 && Scalars.find(VF) == Scalars.end() &&((VF >= 2 && Scalars.find(VF) == Scalars.end() &&
"This function should not be visited twice for the same VF")
? static_cast<void> (0) : __assert_fail ("VF >= 2 && Scalars.find(VF) == Scalars.end() && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4118, __PRETTY_FUNCTION__))
4118 "This function should not be visited twice for the same VF")((VF >= 2 && Scalars.find(VF) == Scalars.end() &&
"This function should not be visited twice for the same VF")
? static_cast<void> (0) : __assert_fail ("VF >= 2 && Scalars.find(VF) == Scalars.end() && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4118, __PRETTY_FUNCTION__))
;
4119
4120 SmallSetVector<Instruction *, 8> Worklist;
4121
4122 // These sets are used to seed the analysis with pointers used by memory
4123 // accesses that will remain scalar.
4124 SmallSetVector<Instruction *, 8> ScalarPtrs;
4125 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4126
4127 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4128 // The pointer operands of loads and stores will be scalar as long as the
4129 // memory access is not a gather or scatter operation. The value operand of a
4130 // store will remain scalar if the store is scalarized.
4131 auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4132 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4133 assert(WideningDecision != CM_Unknown &&((WideningDecision != CM_Unknown && "Widening decision should be ready at this moment"
) ? static_cast<void> (0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4134, __PRETTY_FUNCTION__))
4134 "Widening decision should be ready at this moment")((WideningDecision != CM_Unknown && "Widening decision should be ready at this moment"
) ? static_cast<void> (0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4134, __PRETTY_FUNCTION__))
;
4135 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4136 if (Ptr == Store->getValueOperand())
4137 return WideningDecision == CM_Scalarize;
4138 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&((Ptr == getLoadStorePointerOperand(MemAccess) && "Ptr is neither a value or pointer operand"
) ? static_cast<void> (0) : __assert_fail ("Ptr == getLoadStorePointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4139, __PRETTY_FUNCTION__))
4139 "Ptr is neither a value or pointer operand")((Ptr == getLoadStorePointerOperand(MemAccess) && "Ptr is neither a value or pointer operand"
) ? static_cast<void> (0) : __assert_fail ("Ptr == getLoadStorePointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4139, __PRETTY_FUNCTION__))
;
4140 return WideningDecision != CM_GatherScatter;
4141 };
4142
4143 // A helper that returns true if the given value is a bitcast or
4144 // getelementptr instruction contained in the loop.
4145 auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4146 return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4147 isa<GetElementPtrInst>(V)) &&
4148 !TheLoop->isLoopInvariant(V);
4149 };
4150
4151 // A helper that evaluates a memory access's use of a pointer. If the use
4152 // will be a scalar use, and the pointer is only used by memory accesses, we
4153 // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4154 // PossibleNonScalarPtrs.
4155 auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4156 // We only care about bitcast and getelementptr instructions contained in
4157 // the loop.
4158 if (!isLoopVaryingBitCastOrGEP(Ptr))
4159 return;
4160
4161 // If the pointer has already been identified as scalar (e.g., if it was
4162 // also identified as uniform), there's nothing to do.
4163 auto *I = cast<Instruction>(Ptr);
4164 if (Worklist.count(I))
4165 return;
4166
4167 // If the use of the pointer will be a scalar use, and all users of the
4168 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4169 // place the pointer in PossibleNonScalarPtrs.
4170 if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4171 return isa<LoadInst>(U) || isa<StoreInst>(U);
4172 }))
4173 ScalarPtrs.insert(I);
4174 else
4175 PossibleNonScalarPtrs.insert(I);
4176 };
4177
4178 // We seed the scalars analysis with three classes of instructions: (1)
4179 // instructions marked uniform-after-vectorization, (2) bitcast and
4180 // getelementptr instructions used by memory accesses requiring a scalar use,
4181 // and (3) pointer induction variables and their update instructions (we
4182 // currently only scalarize these).
4183 //
4184 // (1) Add to the worklist all instructions that have been identified as
4185 // uniform-after-vectorization.
4186 Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4187
4188 // (2) Add to the worklist all bitcast and getelementptr instructions used by
4189 // memory accesses requiring a scalar use. The pointer operands of loads and
4190 // stores will be scalar as long as the memory accesses is not a gather or
4191 // scatter operation. The value operand of a store will remain scalar if the
4192 // store is scalarized.
4193 for (auto *BB : TheLoop->blocks())
4194 for (auto &I : *BB) {
4195 if (auto *Load = dyn_cast<LoadInst>(&I)) {
4196 evaluatePtrUse(Load, Load->getPointerOperand());
4197 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4198 evaluatePtrUse(Store, Store->getPointerOperand());
4199 evaluatePtrUse(Store, Store->getValueOperand());
4200 }
4201 }
4202 for (auto *I : ScalarPtrs)
4203 if (PossibleNonScalarPtrs.find(I) == PossibleNonScalarPtrs.end()) {
4204 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)
;
4205 Worklist.insert(I);
4206 }
4207
4208 // (3) Add to the worklist all pointer induction variables and their update
4209 // instructions.
4210 //
4211 // TODO: Once we are able to vectorize pointer induction variables we should
4212 // no longer insert them into the worklist here.
4213 auto *Latch = TheLoop->getLoopLatch();
4214 for (auto &Induction : *Legal->getInductionVars()) {
4215 auto *Ind = Induction.first;
4216 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4217 if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
4218 continue;
4219 Worklist.insert(Ind);
4220 Worklist.insert(IndUpdate);
4221 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)
;
4222 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdatedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
4223 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
4224 }
4225
4226 // Insert the forced scalars.
4227 // FIXME: Currently widenPHIInstruction() often creates a dead vector
4228 // induction variable when the PHI user is scalarized.
4229 auto ForcedScalar = ForcedScalars.find(VF);
4230 if (ForcedScalar != ForcedScalars.end())
4231 for (auto *I : ForcedScalar->second)
4232 Worklist.insert(I);
4233
4234 // Expand the worklist by looking through any bitcasts and getelementptr
4235 // instructions we've already identified as scalar. This is similar to the
4236 // expansion step in collectLoopUniforms(); however, here we're only
4237 // expanding to include additional bitcasts and getelementptr instructions.
4238 unsigned Idx = 0;
4239 while (Idx != Worklist.size()) {
4240 Instruction *Dst = Worklist[Idx++];
4241 if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4242 continue;
4243 auto *Src = cast<Instruction>(Dst->getOperand(0));
4244 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4245 auto *J = cast<Instruction>(U);
4246 return !TheLoop->contains(J) || Worklist.count(J) ||
4247 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4248 isScalarUse(J, Src));
4249 })) {
4250 Worklist.insert(Src);
4251 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)
;
4252 }
4253 }
4254
4255 // An induction variable will remain scalar if all users of the induction
4256 // variable and induction variable update remain scalar.
4257 for (auto &Induction : *Legal->getInductionVars()) {
4258 auto *Ind = Induction.first;
4259 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4260
4261 // We already considered pointer induction variables, so there's no reason
4262 // to look at their users again.
4263 //
4264 // TODO: Once we are able to vectorize pointer induction variables we
4265 // should no longer skip over them here.
4266 if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
4267 continue;
4268
4269 // Determine if all users of the induction variable are scalar after
4270 // vectorization.
4271 auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4272 auto *I = cast<Instruction>(U);
4273 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
4274 });
4275 if (!ScalarInd)
4276 continue;
4277
4278 // Determine if all users of the induction variable update instruction are
4279 // scalar after vectorization.
4280 auto ScalarIndUpdate =
4281 llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4282 auto *I = cast<Instruction>(U);
4283 return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
4284 });
4285 if (!ScalarIndUpdate)
4286 continue;
4287
4288 // The induction variable and its update instruction will remain scalar.
4289 Worklist.insert(Ind);
4290 Worklist.insert(IndUpdate);
4291 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)
;
4292 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdatedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
4293 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
4294 }
4295
4296 Scalars[VF].insert(Worklist.begin(), Worklist.end());
4297}
4298
4299bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I, unsigned VF) {
4300 if (!blockNeedsPredication(I->getParent()))
4301 return false;
4302 switch(I->getOpcode()) {
4303 default:
4304 break;
4305 case Instruction::Load:
4306 case Instruction::Store: {
4307 if (!Legal->isMaskRequired(I))
4308 return false;
4309 auto *Ptr = getLoadStorePointerOperand(I);
4310 auto *Ty = getMemInstValueType(I);
4311 // We have already decided how to vectorize this instruction, get that
4312 // result.
4313 if (VF > 1) {
4314 InstWidening WideningDecision = getWideningDecision(I, VF);
4315 assert(WideningDecision != CM_Unknown &&((WideningDecision != CM_Unknown && "Widening decision should be ready at this moment"
) ? static_cast<void> (0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4316, __PRETTY_FUNCTION__))
4316 "Widening decision should be ready at this moment")((WideningDecision != CM_Unknown && "Widening decision should be ready at this moment"
) ? static_cast<void> (0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4316, __PRETTY_FUNCTION__))
;
4317 return WideningDecision == CM_Scalarize;
4318 }
4319 return isa<LoadInst>(I) ?
4320 !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty))
4321 : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
4322 }
4323 case Instruction::UDiv:
4324 case Instruction::SDiv:
4325 case Instruction::SRem:
4326 case Instruction::URem:
4327 return mayDivideByZero(*I);
4328 }
4329 return false;
4330}
4331
4332static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
4333 if (!(EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0))
4334 return TTI.enableMaskedInterleavedAccessVectorization();
4335
4336 // If an override option has been passed in for interleaved accesses, use it.
4337 return EnableMaskedInterleavedMemAccesses;
4338}
4339
4340bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(Instruction *I,
4341 unsigned VF) {
4342 assert(isAccessInterleaved(I) && "Expecting interleaved access.")((isAccessInterleaved(I) && "Expecting interleaved access."
) ? static_cast<void> (0) : __assert_fail ("isAccessInterleaved(I) && \"Expecting interleaved access.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4342, __PRETTY_FUNCTION__))
;
4343 assert(getWideningDecision(I, VF) == CM_Unknown &&((getWideningDecision(I, VF) == CM_Unknown && "Decision should not be set yet."
) ? static_cast<void> (0) : __assert_fail ("getWideningDecision(I, VF) == CM_Unknown && \"Decision should not be set yet.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4344, __PRETTY_FUNCTION__))
4344 "Decision should not be set yet.")((getWideningDecision(I, VF) == CM_Unknown && "Decision should not be set yet."
) ? static_cast<void> (0) : __assert_fail ("getWideningDecision(I, VF) == CM_Unknown && \"Decision should not be set yet.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4344, __PRETTY_FUNCTION__))
;
4345
4346 if (!Legal->blockNeedsPredication(I->getParent()) ||
4347 !Legal->isMaskRequired(I))
4348 return true;
4349
4350 if (!useMaskedInterleavedAccesses(TTI))
4351 return false;
4352
4353 auto *Ty = getMemInstValueType(I);
4354 return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty)
4355 : TTI.isLegalMaskedStore(Ty);
4356}
4357
4358bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I,
4359 unsigned VF) {
4360 // Get and ensure we have a valid memory instruction.
4361 LoadInst *LI = dyn_cast<LoadInst>(I);
4362 StoreInst *SI = dyn_cast<StoreInst>(I);
4363 assert((LI || SI) && "Invalid memory instruction")(((LI || SI) && "Invalid memory instruction") ? static_cast
<void> (0) : __assert_fail ("(LI || SI) && \"Invalid memory instruction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4363, __PRETTY_FUNCTION__))
;
4364
4365 auto *Ptr = getLoadStorePointerOperand(I);
4366
4367 // In order to be widened, the pointer should be consecutive, first of all.
4368 if (!Legal->isConsecutivePtr(Ptr))
4369 return false;
4370
4371 // If the instruction is a store located in a predicated block, it will be
4372 // scalarized.
4373 if (isScalarWithPredication(I))
4374 return false;
4375
4376 // If the instruction's allocated size doesn't equal it's type size, it
4377 // requires padding and will be scalarized.
4378 auto &DL = I->getModule()->getDataLayout();
4379 auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
4380 if (hasIrregularType(ScalarTy, DL, VF))
4381 return false;
4382
4383 return true;
4384}
4385
4386void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
4387 // We should not collect Uniforms more than once per VF. Right now,
4388 // this function is called from collectUniformsAndScalars(), which
4389 // already does this check. Collecting Uniforms for VF=1 does not make any
4390 // sense.
4391
4392 assert(VF >= 2 && Uniforms.find(VF) == Uniforms.end() &&((VF >= 2 && Uniforms.find(VF) == Uniforms.end() &&
"This function should not be visited twice for the same VF")
? static_cast<void> (0) : __assert_fail ("VF >= 2 && Uniforms.find(VF) == Uniforms.end() && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4393, __PRETTY_FUNCTION__))
4393 "This function should not be visited twice for the same VF")((VF >= 2 && Uniforms.find(VF) == Uniforms.end() &&
"This function should not be visited twice for the same VF")
? static_cast<void> (0) : __assert_fail ("VF >= 2 && Uniforms.find(VF) == Uniforms.end() && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4393, __PRETTY_FUNCTION__))
;
4394
4395 // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4396 // not analyze again. Uniforms.count(VF) will return 1.
4397 Uniforms[VF].clear();
4398
4399 // We now know that the loop is vectorizable!
4400 // Collect instructions inside the loop that will remain uniform after
4401 // vectorization.
4402
4403 // Global values, params and instructions outside of current loop are out of
4404 // scope.
4405 auto isOutOfScope = [&](Value *V) -> bool {
4406 Instruction *I = dyn_cast<Instruction>(V);
4407 return (!I || !TheLoop->contains(I));
4408 };
4409
4410 SetVector<Instruction *> Worklist;
4411 BasicBlock *Latch = TheLoop->getLoopLatch();
4412
4413 // Start with the conditional branch. If the branch condition is an
4414 // instruction contained in the loop that is only used by the branch, it is
4415 // uniform.
4416 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4417 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
4418 Worklist.insert(Cmp);
4419 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)
;
4420 }
4421
4422 // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
4423 // are pointers that are treated like consecutive pointers during
4424 // vectorization. The pointer operands of interleaved accesses are an
4425 // example.
4426 SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
4427
4428 // Holds pointer operands of instructions that are possibly non-uniform.
4429 SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
4430
4431 auto isUniformDecision = [&](Instruction *I, unsigned VF) {
4432 InstWidening WideningDecision = getWideningDecision(I, VF);
4433 assert(WideningDecision != CM_Unknown &&((WideningDecision != CM_Unknown && "Widening decision should be ready at this moment"
) ? static_cast<void> (0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4434, __PRETTY_FUNCTION__))
4434 "Widening decision should be ready at this moment")((WideningDecision != CM_Unknown && "Widening decision should be ready at this moment"
) ? static_cast<void> (0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4434, __PRETTY_FUNCTION__))
;
4435
4436 return (WideningDecision == CM_Widen ||
4437 WideningDecision == CM_Widen_Reverse ||
4438 WideningDecision == CM_Interleave);
4439 };
4440 // Iterate over the instructions in the loop, and collect all
4441 // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
4442 // that a consecutive-like pointer operand will be scalarized, we collect it
4443 // in PossibleNonUniformPtrs instead. We use two sets here because a single
4444 // getelementptr instruction can be used by both vectorized and scalarized
4445 // memory instructions. For example, if a loop loads and stores from the same
4446 // location, but the store is conditional, the store will be scalarized, and
4447 // the getelementptr won't remain uniform.
4448 for (auto *BB : TheLoop->blocks())
4449 for (auto &I : *BB) {
4450 // If there's no pointer operand, there's nothing to do.
4451 auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
4452 if (!Ptr)
4453 continue;
4454
4455 // True if all users of Ptr are memory accesses that have Ptr as their
4456 // pointer operand.
4457 auto UsersAreMemAccesses =
4458 llvm::all_of(Ptr->users(), [&](User *U) -> bool {
4459 return getLoadStorePointerOperand(U) == Ptr;
4460 });
4461
4462 // Ensure the memory instruction will not be scalarized or used by
4463 // gather/scatter, making its pointer operand non-uniform. If the pointer
4464 // operand is used by any instruction other than a memory access, we
4465 // conservatively assume the pointer operand may be non-uniform.
4466 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
4467 PossibleNonUniformPtrs.insert(Ptr);
4468
4469 // If the memory instruction will be vectorized and its pointer operand
4470 // is consecutive-like, or interleaving - the pointer operand should
4471 // remain uniform.
4472 else
4473 ConsecutiveLikePtrs.insert(Ptr);
4474 }
4475
4476 // Add to the Worklist all consecutive and consecutive-like pointers that
4477 // aren't also identified as possibly non-uniform.
4478 for (auto *V : ConsecutiveLikePtrs)
4479 if (PossibleNonUniformPtrs.find(V) == PossibleNonUniformPtrs.end()) {
4480 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)
;
4481 Worklist.insert(V);
4482 }
4483
4484 // Expand Worklist in topological order: whenever a new instruction
4485 // is added , its users should be already inside Worklist. It ensures
4486 // a uniform instruction will only be used by uniform instructions.
4487 unsigned idx = 0;
4488 while (idx != Worklist.size()) {
4489 Instruction *I = Worklist[idx++];
4490
4491 for (auto OV : I->operand_values()) {
4492 // isOutOfScope operands cannot be uniform instructions.
4493 if (isOutOfScope(OV))
4494 continue;
4495 // First order recurrence Phi's should typically be considered
4496 // non-uniform.
4497 auto *OP = dyn_cast<PHINode>(OV);
4498 if (OP && Legal->isFirstOrderRecurrence(OP))
4499 continue;
4500 // If all the users of the operand are uniform, then add the
4501 // operand into the uniform worklist.
4502 auto *OI = cast<Instruction>(OV);
4503 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4504 auto *J = cast<Instruction>(U);
4505 return Worklist.count(J) ||
4506 (OI == getLoadStorePointerOperand(J) &&
4507 isUniformDecision(J, VF));
4508 })) {
4509 Worklist.insert(OI);
4510 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)
;
4511 }
4512 }
4513 }
4514
4515 // Returns true if Ptr is the pointer operand of a memory access instruction
4516 // I, and I is known to not require scalarization.
4517 auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4518 return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4519 };
4520
4521 // For an instruction to be added into Worklist above, all its users inside
4522 // the loop should also be in Worklist. However, this condition cannot be
4523 // true for phi nodes that form a cyclic dependence. We must process phi
4524 // nodes separately. An induction variable will remain uniform if all users
4525 // of the induction variable and induction variable update remain uniform.
4526 // The code below handles both pointer and non-pointer induction variables.
4527 for (auto &Induction : *Legal->getInductionVars()) {
4528 auto *Ind = Induction.first;
4529 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4530
4531 // Determine if all users of the induction variable are uniform after
4532 // vectorization.
4533 auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4534 auto *I = cast<Instruction>(U);
4535 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4536 isVectorizedMemAccessUse(I, Ind);
4537 });
4538 if (!UniformInd)
4539 continue;
4540
4541 // Determine if all users of the induction variable update instruction are
4542 // uniform after vectorization.
4543 auto UniformIndUpdate =
4544 llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4545 auto *I = cast<Instruction>(U);
4546 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4547 isVectorizedMemAccessUse(I, IndUpdate);
4548 });
4549 if (!UniformIndUpdate)
4550 continue;
4551
4552 // The induction variable and its update instruction will remain uniform.
4553 Worklist.insert(Ind);
4554 Worklist.insert(IndUpdate);
4555 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)
;
4556 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdatedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *IndUpdate << "\n"; } } while (false)
4557 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
4558 }
4559
4560 Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4561}
4562
4563Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
4564 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
4565 // TODO: It may by useful to do since it's still likely to be dynamically
4566 // uniform if the target can skip.
4567 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not inserting runtime ptr check for divergent target"
; } } while (false)
4568 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)
;
4569
4570 ORE->emit(
4571 createMissedAnalysis("CantVersionLoopWithDivergentTarget")
4572 << "runtime pointer checks needed. Not enabled for divergent target");
4573
4574 return None;
4575 }
4576
4577 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
4578 if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
4579 return computeFeasibleMaxVF(OptForSize, TC);
4580
4581 if (Legal->getRuntimePointerChecking()->Need) {
4582 ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
4583 << "runtime pointer checks needed. Enable vectorization of this "
4584 "loop with '#pragma clang loop vectorize(enable)' when "
4585 "compiling with -Os/-Oz");
4586 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n"
; } } while (false)
4587 dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n"
; } } while (false)
4588 << "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)
;
4589 return None;
4590 }
4591
4592 // If we optimize the program for size, avoid creating the tail loop.
4593 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)
;
4594
4595 if (TC == 1) {
4596 ORE->emit(createMissedAnalysis("SingleIterationLoop")
4597 << "loop trip count is one, irrelevant for vectorization");
4598 LLVM_DEBUG(dbgs() << "LV: Aborting, single iteration (non) loop.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Aborting, single iteration (non) loop.\n"
; } } while (false)
;
4599 return None;
4600 }
4601
4602 // Record that scalar epilogue is not allowed.
4603 LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n"
; } } while (false)
;
4604
4605 // We don't create an epilogue when optimizing for size.
4606 // Invalidate interleave groups that require an epilogue.
4607 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
4608
4609 unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
4610
4611 if (TC > 0 && TC % MaxVF == 0) {
4612 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: No tail will remain for any chosen VF.\n"
; } } while (false)
;
4613 return MaxVF;
4614 }
4615
4616 // If we don't know the precise trip count, or if the trip count that we
4617 // found modulo the vectorization factor is not zero, try to fold the tail
4618 // by masking.
4619 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
4620 if (Legal->canFoldTailByMasking()) {
4621 FoldTailByMasking = true;
4622 return MaxVF;
4623 }
4624
4625 if (TC == 0) {
4626 ORE->emit(
4627 createMissedAnalysis("UnknownLoopCountComplexCFG")
4628 << "unable to calculate the loop count due to complex control flow");
4629 return None;
4630 }
4631
4632 ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
4633 << "cannot optimize for size and vectorize at the same time. "
4634 "Enable vectorization of this loop with '#pragma clang loop "
4635 "vectorize(enable)' when compiling with -Os/-Oz");
4636 return None;
4637}
4638
4639unsigned
4640LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
4641 unsigned ConstTripCount) {
4642 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4643 unsigned SmallestType, WidestType;
4644 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4645 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4646
4647 // Get the maximum safe dependence distance in bits computed by LAA.
4648 // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4649 // the memory accesses that is most restrictive (involved in the smallest
4650 // dependence distance).
4651 unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
4652
4653 WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
4654
4655 unsigned MaxVectorSize = WidestRegister / WidestType;
4656
4657 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)
4658 << " / " << WidestType << " bits.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The Smallest and Widest types: "
<< SmallestType << " / " << WidestType <<
" bits.\n"; } } while (false)
;
4659 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
)
4660 << 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
)
;
4661
4662 assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"((MaxVectorSize <= 256 && "Did not expect to pack so many elements"
" into one vector!") ? static_cast<void> (0) : __assert_fail
("MaxVectorSize <= 256 && \"Did not expect to pack so many elements\" \" into one vector!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4663, __PRETTY_FUNCTION__))
4663 " into one vector!")((MaxVectorSize <= 256 && "Did not expect to pack so many elements"
" into one vector!") ? static_cast<void> (0) : __assert_fail
("MaxVectorSize <= 256 && \"Did not expect to pack so many elements\" \" into one vector!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4663, __PRETTY_FUNCTION__))
;
4664 if (MaxVectorSize == 0) {
4665 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)
;
4666 MaxVectorSize = 1;
4667 return MaxVectorSize;
4668 } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
4669 isPowerOf2_32(ConstTripCount)) {
4670 // We need to clamp the VF to be the ConstTripCount. There is no point in
4671 // choosing a higher viable VF as done in the loop below.
4672 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)
4673 << ConstTripCount << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
<< ConstTripCount << "\n"; } } while (false)
;
4674 MaxVectorSize = ConstTripCount;
4675 return MaxVectorSize;
4676 }
4677
4678 unsigned MaxVF = MaxVectorSize;
4679 if (TTI.shouldMaximizeVectorBandwidth(OptForSize) ||
4680 (MaximizeBandwidth && !OptForSize)) {
4681 // Collect all viable vectorization factors larger than the default MaxVF
4682 // (i.e. MaxVectorSize).
4683 SmallVector<unsigned, 8> VFs;
4684 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
4685 for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
4686 VFs.push_back(VS);
4687
4688 // For each VF calculate its register usage.
4689 auto RUs = calculateRegisterUsage(VFs);
4690
4691 // Select the largest VF which doesn't require more registers than existing
4692 // ones.
4693 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
4694 for (int i = RUs.size() - 1; i >= 0; --i) {
4695 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
4696 MaxVF = VFs[i];
4697 break;
4698 }
4699 }
4700 if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
4701 if (MaxVF < MinVF) {
4702 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)
4703 << ") 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)
;
4704 MaxVF = MinVF;
4705 }
4706 }
4707 }
4708 return MaxVF;
4709}
4710
4711VectorizationFactor
4712LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
4713 float Cost = expectedCost(1).first;
4714 const float ScalarCost = Cost;
4715 unsigned Width = 1;
4716 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)
;
4717
4718 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4719 if (ForceVectorization && MaxVF > 1) {
4720 // Ignore scalar width, because the user explicitly wants vectorization.
4721 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
4722 // evaluation.
4723 Cost = std::numeric_limits<float>::max();
4724 }
4725
4726 for (unsigned i = 2; i <= MaxVF; i *= 2) {
4727 // Notice that the vector loop needs to be executed less times, so
4728 // we need to divide the cost of the vector loops by the width of
4729 // the vector elements.
4730 VectorizationCostTy C = expectedCost(i);
4731 float VectorCost = C.first / (float)i;
4732 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)
4733 << " 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)
;
4734 if (!C.second && !ForceVectorization) {
4735 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)
4736 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)
4737 << " 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)
;
4738 continue;
4739 }
4740 if (VectorCost < Cost) {
4741 Cost = VectorCost;
4742 Width = i;
4743 }
4744 }
4745
4746 if (!EnableCondStoresVectorization && NumPredStores) {
4747 ORE->emit(createMissedAnalysis("ConditionalStore")
4748 << "store that is conditionally executed prevents vectorization");
4749 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: No vectorization. There are conditional stores.\n"
; } } while (false)
4750 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)
;
4751 Width = 1;
4752 Cost = ScalarCost;
4753 }
4754
4755 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)
4756 << "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)
4757 << "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)
;
4758 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Selecting VF: " <<
Width << ".\n"; } } while (false)
;
4759 VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
4760 return Factor;
4761}
4762
4763std::pair<unsigned, unsigned>
4764LoopVectorizationCostModel::getSmallestAndWidestTypes() {
4765 unsigned MinWidth = -1U;
4766 unsigned MaxWidth = 8;
4767 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4768
4769 // For each block.
4770 for (BasicBlock *BB : TheLoop->blocks()) {
4771 // For each instruction in the loop.
4772 for (Instruction &I : BB->instructionsWithoutDebug()) {
4773 Type *T = I.getType();
4774
4775 // Skip ignored values.
4776 if (ValuesToIgnore.find(&I) != ValuesToIgnore.end())
4777 continue;
4778
4779 // Only examine Loads, Stores and PHINodes.
4780 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
4781 continue;
4782
4783 // Examine PHI nodes that are reduction variables. Update the type to
4784 // account for the recurrence type.
4785 if (auto *PN = dyn_cast<PHINode>(&I)) {
4786 if (!Legal->isReductionVariable(PN))
4787 continue;
4788 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4789 T = RdxDesc.getRecurrenceType();
4790 }
4791
4792 // Examine the stored values.
4793 if (auto *ST = dyn_cast<StoreInst>(&I))
4794 T = ST->getValueOperand()->getType();
4795
4796 // Ignore loaded pointer types and stored pointer types that are not
4797 // vectorizable.
4798 //
4799 // FIXME: The check here attempts to predict whether a load or store will
4800 // be vectorized. We only know this for certain after a VF has
4801 // been selected. Here, we assume that if an access can be
4802 // vectorized, it will be. We should also look at extending this
4803 // optimization to non-pointer types.
4804 //
4805 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
4806 !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
4807 continue;
4808
4809 MinWidth = std::min(MinWidth,
4810 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4811 MaxWidth = std::max(MaxWidth,
4812 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4813 }
4814 }
4815
4816 return {MinWidth, MaxWidth};
4817}
4818
4819unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4820 unsigned VF,
4821 unsigned LoopCost) {
4822 // -- The interleave heuristics --
4823 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4824 // There are many micro-architectural considerations that we can't predict
4825 // at this level. For example, frontend pressure (on decode or fetch) due to
4826 // code size, or the number and capabilities of the execution ports.
4827 //
4828 // We use the following heuristics to select the interleave count:
4829 // 1. If the code has reductions, then we interleave to break the cross
4830 // iteration dependency.
4831 // 2. If the loop is really small, then we interleave to reduce the loop
4832 // overhead.
4833 // 3. We don't interleave if we think that we will spill registers to memory
4834 // due to the increased register pressure.
4835
4836 // When we optimize for size, we don't interleave.
4837 if (OptForSize)
20
Taking false branch
4838 return 1;
4839
4840 // We used the distance for the interleave count.
4841 if (Legal->getMaxSafeDepDistBytes() != -1U)
21
Assuming the condition is false
22
Taking false branch
4842 return 1;
4843
4844 // Do not interleave loops with a relatively small trip count.
4845 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
4846 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
23
Assuming 'TC' is <= 1
4847 return 1;
4848
4849 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4850 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
)
4851 << " registers\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The target has " <<
TargetNumRegisters << " registers\n"; } } while (false
)
;
4852
4853 if (VF == 1) {
24
Taking true branch
4854 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
25
Assuming the condition is false
26
Taking false branch
4855 TargetNumRegisters = ForceTargetNumScalarRegs;
4856 } else {
4857 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4858 TargetNumRegisters = ForceTargetNumVectorRegs;
4859 }
4860
4861 RegisterUsage R = calculateRegisterUsage({VF})[0];
4862 // We divide by these constants so assume that we have at least one
4863 // instruction that uses at least one register.
4864 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4865
4866 // We calculate the interleave count using the following formula.
4867 // Subtract the number of loop invariants from the number of available
4868 // registers. These registers are used by all of the interleaved instances.
4869 // Next, divide the remaining registers by the number of registers that is
4870 // required by the loop, in order to estimate how many parallel instances
4871 // fit without causing spills. All of this is rounded down if necessary to be
4872 // a power of two. We want power of two interleave count to simplify any
4873 // addressing operations or alignment considerations.
4874 // We also want power of two interleave counts to ensure that the induction
4875 // variable of the vector loop wraps to zero, when tail is folded by masking;
4876 // this currently happens when OptForSize, in which case IC is set to 1 above.
4877 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4878 R.MaxLocalUsers);
4879
4880 // Don't count the induction variable as interleaved.
4881 if (EnableIndVarRegisterHeur)
27
Assuming the condition is false
28
Taking false branch
4882 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4883 std::max(1U, (R.MaxLocalUsers - 1)));
4884
4885 // Clamp the interleave ranges to reasonable counts.
4886 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4887
4888 // Check if the user has overridden the max.
4889 if (VF == 1) {
29
Taking true branch
4890 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
30
Assuming the condition is false
31
Taking false branch
4891 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4892 } else {
4893 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4894 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4895 }
4896
4897 // If we did not calculate the cost for VF (because the user selected the VF)
4898 // then we calculate the cost of VF here.
4899 if (LoopCost == 0)
32
Taking true branch
4900 LoopCost = expectedCost(VF).first;
33
The value 0 is assigned to 'LoopCost'
4901
4902 // Clamp the calculated IC to be between the 1 and the max interleave count
4903 // that the target allows.
4904 if (IC > MaxInterleaveCount)
34
Assuming 'IC' is <= 'MaxInterleaveCount'
35
Taking false branch
4905 IC = MaxInterleaveCount;
4906 else if (IC < 1)
36
Assuming 'IC' is >= 1
37
Taking false branch
4907 IC = 1;
4908
4909 // Interleave if we vectorized this loop and there is a reduction that could
4910 // benefit from interleaving.
4911 if (VF > 1 && !Legal->getReductionVars()->empty()) {
4912 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)
;
4913 return IC;
4914 }
4915
4916 // Note that if we've already vectorized the loop we will have done the
4917 // runtime check and so interleaving won't require further checks.
4918 bool InterleavingRequiresRuntimePointerCheck =
4919 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4920
4921 // We want to interleave small loops in order to reduce the loop overhead and
4922 // potentially expose ILP opportunities.
4923 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)
;
4924 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
38
Assuming 'InterleavingRequiresRuntimePointerCheck' is 0
39
Assuming the condition is true
40
Taking true branch
4925 // We assume that the cost overhead is 1 and we use the cost model
4926 // to estimate the cost of the loop and interleave until the cost of the
4927 // loop overhead is about 5% of the cost of the loop.
4928 unsigned SmallIC =
4929 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
41
Division by zero
4930
4931 // Interleave until store/load ports (estimated by max interleave count) are
4932 // saturated.
4933 unsigned NumStores = Legal->getNumStores();
4934 unsigned NumLoads = Legal->getNumLoads();
4935 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4936 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4937
4938 // If we have a scalar reduction (vector reductions are already dealt with
4939 // by this point), we can increase the critical path length if the loop
4940 // we're interleaving is inside another loop. Limit, by default to 2, so the
4941 // critical path only gets increased by one reduction operation.
4942 if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) {
4943 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4944 SmallIC = std::min(SmallIC, F);
4945 StoresIC = std::min(StoresIC, F);
4946 LoadsIC = std::min(LoadsIC, F);
4947 }
4948
4949 if (EnableLoadStoreRuntimeInterleave &&
4950 std::max(StoresIC, LoadsIC) > SmallIC) {
4951 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Interleaving to saturate store or load ports.\n"
; } } while (false)
4952 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)
;
4953 return std::max(StoresIC, LoadsIC);
4954 }
4955
4956 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)
;
4957 return SmallIC;
4958 }
4959
4960 // Interleave if this is a large loop (small loops are already dealt with by
4961 // this point) that could benefit from interleaving.
4962 bool HasReductions = !Legal->getReductionVars()->empty();
4963 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4964 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)
;
4965 return IC;
4966 }
4967
4968 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not Interleaving.\n"
; } } while (false)
;
4969 return 1;
4970}
4971
4972SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
4973LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
4974 // This function calculates the register usage by measuring the highest number
4975 // of values that are alive at a single location. Obviously, this is a very
4976 // rough estimation. We scan the loop in a topological order in order and
4977 // assign a number to each instruction. We use RPO to ensure that defs are
4978 // met before their users. We assume that each instruction that has in-loop
4979 // users starts an interval. We record every time that an in-loop value is
4980 // used, so we have a list of the first and last occurrences of each
4981 // instruction. Next, we transpose this data structure into a multi map that
4982 // holds the list of intervals that *end* at a specific location. This multi
4983 // map allows us to perform a linear search. We scan the instructions linearly
4984 // and record each time that a new interval starts, by placing it in a set.
4985 // If we find this value in the multi-map then we remove it from the set.
4986 // The max register usage is the maximum size of the set.
4987 // We also search for instructions that are defined outside the loop, but are
4988 // used inside the loop. We need this number separately from the max-interval
4989 // usage number because when we unroll, loop-invariant values do not take
4990 // more register.
4991 LoopBlocksDFS DFS(TheLoop);
4992 DFS.perform(LI);
4993
4994 RegisterUsage RU;
4995
4996 // Each 'key' in the map opens a new interval. The values
4997 // of the map are the index of the 'last seen' usage of the
4998 // instruction that is the key.
4999 using IntervalMap = DenseMap<Instruction *, unsigned>;
5000
5001 // Maps instruction to its index.
5002 SmallVector<Instruction *, 64> IdxToInstr;
5003 // Marks the end of each interval.
5004 IntervalMap EndPoint;
5005 // Saves the list of instruction indices that are used in the loop.
5006 SmallPtrSet<Instruction *, 8> Ends;
5007 // Saves the list of values that are used in the loop but are
5008 // defined outside the loop, such as arguments and constants.
5009 SmallPtrSet<Value *, 8> LoopInvariants;
5010
5011 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5012 for (Instruction &I : BB->instructionsWithoutDebug()) {
5013 IdxToInstr.push_back(&I);
5014
5015 // Save the end location of each USE.
5016 for (Value *U : I.operands()) {
5017 auto *Instr = dyn_cast<Instruction>(U);
5018
5019 // Ignore non-instruction values such as arguments, constants, etc.
5020 if (!Instr)
5021 continue;
5022
5023 // If this instruction is outside the loop then record it and continue.
5024 if (!TheLoop->contains(Instr)) {
5025 LoopInvariants.insert(Instr);
5026 continue;
5027 }
5028
5029 // Overwrite previous end points.
5030 EndPoint[Instr] = IdxToInstr.size();
5031 Ends.insert(Instr);
5032 }
5033 }
5034 }
5035
5036 // Saves the list of intervals that end with the index in 'key'.
5037 using InstrList = SmallVector<Instruction *, 2>;
5038 DenseMap<unsigned, InstrList> TransposeEnds;
5039
5040 // Transpose the EndPoints to a list of values that end at each index.
5041 for (auto &Interval : EndPoint)
5042 TransposeEnds[Interval.second].push_back(Interval.first);
5043
5044 SmallPtrSet<Instruction *, 8> OpenIntervals;
5045
5046 // Get the size of the widest register.
5047 unsigned MaxSafeDepDist = -1U;
5048 if (Legal->getMaxSafeDepDistBytes() != -1U)
5049 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5050 unsigned WidestRegister =
5051 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
5052 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5053
5054 SmallVector<RegisterUsage, 8> RUs(VFs.size());
5055 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
5056
5057 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)
;
5058
5059 // A lambda that gets the register usage for the given type and VF.
5060 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
5061 if (Ty->isTokenTy())
5062 return 0U;
5063 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5064 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5065 };
5066
5067 for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
5068 Instruction *I = IdxToInstr[i];
5069
5070 // Remove all of the instructions that end at this location.
5071 InstrList &List = TransposeEnds[i];
5072 for (Instruction *ToRemove : List)
5073 OpenIntervals.erase(ToRemove);
5074
5075 // Ignore instructions that are never used within the loop.
5076 if (Ends.find(I) == Ends.end())
5077 continue;
5078
5079 // Skip ignored values.
5080 if (ValuesToIgnore.find(I) != ValuesToIgnore.end())
5081 continue;
5082
5083 // For each VF find the maximum usage of registers.
5084 for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5085 if (VFs[j] == 1) {
5086 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
5087 continue;
5088 }
5089 collectUniformsAndScalars(VFs[j]);
5090 // Count the number of live intervals.
5091 unsigned RegUsage = 0;
5092 for (auto Inst : OpenIntervals) {
5093 // Skip ignored values for VF > 1.
5094 if (VecValuesToIgnore.find(Inst) != VecValuesToIgnore.end() ||
5095 isScalarAfterVectorization(Inst, VFs[j]))
5096 continue;
5097 RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
5098 }
5099 MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
5100 }
5101
5102 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)
5103 << OpenIntervals.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV(REG): At #" <<
i << " Interval # " << OpenIntervals.size() <<
'\n'; } } while (false)
;
5104
5105 // Add the current instruction to the list of open intervals.
5106 OpenIntervals.insert(I);
5107 }
5108
5109 for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
5110 unsigned Invariant = 0;
5111 if (VFs[i] == 1)
5112 Invariant = LoopInvariants.size();
5113 else {
5114 for (auto Inst : LoopInvariants)
5115 Invariant += GetRegUsage(Inst->getType(), VFs[i]);
5116 }
5117
5118 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)
;
5119 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)
;
5120 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)
5121 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV(REG): Found invariant usage: "
<< Invariant << '\n'; } } while (false)
;
5122
5123 RU.LoopInvariantRegs = Invariant;
5124 RU.MaxLocalUsers = MaxUsages[i];
5125 RUs[i] = RU;
5126 }
5127
5128 return RUs;
5129}
5130
5131bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
5132 // TODO: Cost model for emulated masked load/store is completely
5133 // broken. This hack guides the cost model to use an artificially
5134 // high enough value to practically disable vectorization with such
5135 // operations, except where previously deployed legality hack allowed
5136 // using very low cost values. This is to avoid regressions coming simply
5137 // from moving "masked load/store" check from legality to cost model.
5138 // Masked Load/Gather emulation was previously never allowed.
5139 // Limited number of Masked Store/Scatter emulation was allowed.
5140 assert(isPredicatedInst(I) && "Expecting a scalar emulated instruction")((isPredicatedInst(I) && "Expecting a scalar emulated instruction"
) ? static_cast<void> (0) : __assert_fail ("isPredicatedInst(I) && \"Expecting a scalar emulated instruction\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5140, __PRETTY_FUNCTION__))
;
5141 return isa<LoadInst>(I) ||
5142 (isa<StoreInst>(I) &&
5143 NumPredStores > NumberOfStoresToPredicate);
5144}
5145
5146void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
5147 // If we aren't vectorizing the loop, or if we've already collected the
5148 // instructions to scalarize, there's nothing to do. Collection may already
5149 // have occurred if we have a user-selected VF and are now computing the
5150 // expected cost for interleaving.
5151 if (VF < 2 || InstsToScalarize.find(VF) != InstsToScalarize.end())
5152 return;
5153
5154 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
5155 // not profitable to scalarize any instructions, the presence of VF in the
5156 // map will indicate that we've analyzed it already.
5157 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
5158
5159 // Find all the instructions that are scalar with predication in the loop and
5160 // determine if it would be better to not if-convert the blocks they are in.
5161 // If so, we also record the instructions to scalarize.
5162 for (BasicBlock *BB : TheLoop->blocks()) {
5163 if (!blockNeedsPredication(BB))
5164 continue;
5165 for (Instruction &I : *BB)
5166 if (isScalarWithPredication(&I)) {
5167 ScalarCostsTy ScalarCosts;
5168 // Do not apply discount logic if hacked cost is needed
5169 // for emulated masked memrefs.
5170 if (!useEmulatedMaskMemRefHack(&I) &&
5171 computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
5172 ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
5173 // Remember that BB will remain after vectorization.
5174 PredicatedBBsAfterVectorization.insert(BB);
5175 }
5176 }
5177}
5178
5179int LoopVectorizationCostModel::computePredInstDiscount(
5180 Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
5181 unsigned VF) {
5182 assert(!isUniformAfterVectorization(PredInst, VF) &&((!isUniformAfterVectorization(PredInst, VF) && "Instruction marked uniform-after-vectorization will be predicated"
) ? static_cast<void> (0) : __assert_fail ("!isUniformAfterVectorization(PredInst, VF) && \"Instruction marked uniform-after-vectorization will be predicated\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5183, __PRETTY_FUNCTION__))
5183 "Instruction marked uniform-after-vectorization will be predicated")((!isUniformAfterVectorization(PredInst, VF) && "Instruction marked uniform-after-vectorization will be predicated"
) ? static_cast<void> (0) : __assert_fail ("!isUniformAfterVectorization(PredInst, VF) && \"Instruction marked uniform-after-vectorization will be predicated\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5183, __PRETTY_FUNCTION__))
;
5184
5185 // Initialize the discount to zero, meaning that the scalar version and the
5186 // vector version cost the same.
5187 int Discount = 0;
5188
5189 // Holds instructions to analyze. The instructions we visit are mapped in
5190 // ScalarCosts. Those instructions are the ones that would be scalarized if
5191 // we find that the scalar version costs less.
5192 SmallVector<Instruction *, 8> Worklist;
5193
5194 // Returns true if the given instruction can be scalarized.
5195 auto canBeScalarized = [&](Instruction *I) -> bool {
5196 // We only attempt to scalarize instructions forming a single-use chain
5197 // from the original predicated block that would otherwise be vectorized.
5198 // Although not strictly necessary, we give up on instructions we know will
5199 // already be scalar to avoid traversing chains that are unlikely to be
5200 // beneficial.
5201 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
5202 isScalarAfterVectorization(I, VF))
5203 return false;
5204
5205 // If the instruction is scalar with predication, it will be analyzed
5206 // separately. We ignore it within the context of PredInst.
5207 if (isScalarWithPredication(I))
5208 return false;
5209
5210 // If any of the instruction's operands are uniform after vectorization,
5211 // the instruction cannot be scalarized. This prevents, for example, a
5212 // masked load from being scalarized.
5213 //
5214 // We assume we will only emit a value for lane zero of an instruction
5215 // marked uniform after vectorization, rather than VF identical values.
5216 // Thus, if we scalarize an instruction that uses a uniform, we would
5217 // create uses of values corresponding to the lanes we aren't emitting code
5218 // for. This behavior can be changed by allowing getScalarValue to clone
5219 // the lane zero values for uniforms rather than asserting.
5220 for (Use &U : I->operands())
5221 if (auto *J = dyn_cast<Instruction>(U.get()))
5222 if (isUniformAfterVectorization(J, VF))
5223 return false;
5224
5225 // Otherwise, we can scalarize the instruction.
5226 return true;
5227 };
5228
5229 // Returns true if an operand that cannot be scalarized must be extracted
5230 // from a vector. We will account for this scalarization overhead below. Note
5231 // that the non-void predicated instructions are placed in their own blocks,
5232 // and their return values are inserted into vectors. Thus, an extract would
5233 // still be required.
5234 auto needsExtract = [&](Instruction *I) -> bool {
5235 return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
5236 };
5237
5238 // Compute the expected cost discount from scalarizing the entire expression
5239 // feeding the predicated instruction. We currently only consider expressions
5240 // that are single-use instruction chains.
5241 Worklist.push_back(PredInst);
5242 while (!Worklist.empty()) {
5243 Instruction *I = Worklist.pop_back_val();
5244
5245 // If we've already analyzed the instruction, there's nothing to do.
5246 if (ScalarCosts.find(I) != ScalarCosts.end())
5247 continue;
5248
5249 // Compute the cost of the vector instruction. Note that this cost already
5250 // includes the scalarization overhead of the predicated instruction.
5251 unsigned VectorCost = getInstructionCost(I, VF).first;
5252
5253 // Compute the cost of the scalarized instruction. This cost is the cost of
5254 // the instruction as if it wasn't if-converted and instead remained in the
5255 // predicated block. We will scale this cost by block probability after
5256 // computing the scalarization overhead.
5257 unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
5258
5259 // Compute the scalarization overhead of needed insertelement instructions
5260 // and phi nodes.
5261 if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
5262 ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
5263 true, false);
5264 ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
5265 }
5266
5267 // Compute the scalarization overhead of needed extractelement
5268 // instructions. For each of the instruction's operands, if the operand can
5269 // be scalarized, add it to the worklist; otherwise, account for the
5270 // overhead.
5271 for (Use &U : I->operands())
5272 if (auto *J = dyn_cast<Instruction>(U.get())) {
5273 assert(VectorType::isValidElementType(J->getType()) &&((VectorType::isValidElementType(J->getType()) && "Instruction has non-scalar type"
) ? static_cast<void> (0) : __assert_fail ("VectorType::isValidElementType(J->getType()) && \"Instruction has non-scalar type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5274, __PRETTY_FUNCTION__))
5274 "Instruction has non-scalar type")((VectorType::isValidElementType(J->getType()) && "Instruction has non-scalar type"
) ? static_cast<void> (0) : __assert_fail ("VectorType::isValidElementType(J->getType()) && \"Instruction has non-scalar type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5274, __PRETTY_FUNCTION__))
;
5275 if (canBeScalarized(J))
5276 Worklist.push_back(J);
5277 else if (needsExtract(J))
5278 ScalarCost += TTI.getScalarizationOverhead(
5279 ToVectorTy(J->getType(),VF), false, true);
5280 }
5281
5282 // Scale the total scalar cost by block probability.
5283 ScalarCost /= getReciprocalPredBlockProb();
5284
5285 // Compute the discount. A non-negative discount means the vector version
5286 // of the instruction costs more, and scalarizing would be beneficial.
5287 Discount += VectorCost - ScalarCost;
5288 ScalarCosts[I] = ScalarCost;
5289 }
5290
5291 return Discount;
5292}
5293
5294LoopVectorizationCostModel::VectorizationCostTy
5295LoopVectorizationCostModel::expectedCost(unsigned VF) {
5296 VectorizationCostTy Cost;
5297
5298 // For each block.
5299 for (BasicBlock *BB : TheLoop->blocks()) {
5300 VectorizationCostTy BlockCost;
5301
5302 // For each instruction in the old loop.
5303 for (Instruction &I : BB->instructionsWithoutDebug()) {
5304 // Skip ignored values.
5305 if (ValuesToIgnore.find(&I) != ValuesToIgnore.end() ||
5306 (VF > 1 && VecValuesToIgnore.find(&I) != VecValuesToIgnore.end()))
5307 continue;
5308
5309 VectorizationCostTy C = getInstructionCost(&I, VF);
5310
5311 // Check if we should override the cost.
5312 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5313 C.first = ForceTargetInstructionCost;
5314
5315 BlockCost.first += C.first;
5316 BlockCost.second |= C.second;
5317 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)
5318 << " 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)
5319 << '\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)
;
5320 }
5321
5322 // If we are vectorizing a predicated block, it will have been
5323 // if-converted. This means that the block's instructions (aside from
5324 // stores and instructions that may divide by zero) will now be
5325 // unconditionally executed. For the scalar case, we may not always execute
5326 // the predicated block. Thus, scale the block's cost by the probability of
5327 // executing it.
5328 if (VF == 1 && blockNeedsPredication(BB))
5329 BlockCost.first /= getReciprocalPredBlockProb();
5330
5331 Cost.first += BlockCost.first;
5332 Cost.second |= BlockCost.second;
5333 }
5334
5335 return Cost;
5336}
5337
5338/// Gets Address Access SCEV after verifying that the access pattern
5339/// is loop invariant except the induction variable dependence.
5340///
5341/// This SCEV can be sent to the Target in order to estimate the address
5342/// calculation cost.
5343static const SCEV *getAddressAccessSCEV(
5344 Value *Ptr,
5345 LoopVectorizationLegality *Legal,
5346 PredicatedScalarEvolution &PSE,
5347 const Loop *TheLoop) {
5348
5349 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5350 if (!Gep)
5351 return nullptr;
5352
5353 // We are looking for a gep with all loop invariant indices except for one
5354 // which should be an induction variable.
5355 auto SE = PSE.getSE();
5356 unsigned NumOperands = Gep->getNumOperands();
5357 for (unsigned i = 1; i < NumOperands; ++i) {
5358 Value *Opd = Gep->getOperand(i);
5359 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5360 !Legal->isInductionVariable(Opd))
5361 return nullptr;
5362 }
5363
5364 // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
5365 return PSE.getSCEV(Ptr);
5366}
5367
5368static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5369 return Legal->hasStride(I->getOperand(0)) ||
5370 Legal->hasStride(I->getOperand(1));
5371}
5372
5373unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
5374 unsigned VF) {
5375 Type *ValTy = getMemInstValueType(I);
5376 auto SE = PSE.getSE();
5377
5378 unsigned Alignment = getLoadStoreAlignment(I);
5379 unsigned AS = getLoadStoreAddressSpace(I);
5380 Value *Ptr = getLoadStorePointerOperand(I);
5381 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5382
5383 // Figure out whether the access is strided and get the stride value
5384 // if it's known in compile time
5385 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
5386
5387 // Get the cost of the scalar memory instruction and address computation.
5388 unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
5389
5390 Cost += VF *
5391 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
5392 AS, I);
5393
5394 // Get the overhead of the extractelement and insertelement instructions
5395 // we might create due to scalarization.
5396 Cost += getScalarizationOverhead(I, VF, TTI);
5397
5398 // If we have a predicated store, it may not be executed for each vector
5399 // lane. Scale the cost by the probability of executing the predicated
5400 // block.
5401 if (isPredicatedInst(I)) {
5402 Cost /= getReciprocalPredBlockProb();
5403
5404 if (useEmulatedMaskMemRefHack(I))
5405 // Artificially setting to a high enough value to practically disable
5406 // vectorization with such operations.
5407 Cost = 3000000;
5408 }
5409
5410 return Cost;
5411}
5412
5413unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
5414 unsigned VF) {
5415 Type *ValTy = getMemInstValueType(I);
5416 Type *VectorTy = ToVectorTy(ValTy, VF);
5417 unsigned Alignment = getLoadStoreAlignment(I);
5418 Value *Ptr = getLoadStorePointerOperand(I);
5419 unsigned AS = getLoadStoreAddressSpace(I);
5420 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5421
5422 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&(((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
"Stride should be 1 or -1 for consecutive memory access") ? static_cast
<void> (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Stride should be 1 or -1 for consecutive memory access\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5423, __PRETTY_FUNCTION__))
5423 "Stride should be 1 or -1 for consecutive memory access")(((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
"Stride should be 1 or -1 for consecutive memory access") ? static_cast
<void> (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Stride should be 1 or -1 for consecutive memory access\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5423, __PRETTY_FUNCTION__))
;
5424 unsigned Cost = 0;
5425 if (Legal->isMaskRequired(I))
5426 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5427 else
5428 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
5429
5430 bool Reverse = ConsecutiveStride < 0;
5431 if (Reverse)
5432 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5433 return Cost;
5434}
5435
5436unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
5437 unsigned VF) {
5438 Type *ValTy = getMemInstValueType(I);
5439 Type *VectorTy = ToVectorTy(ValTy, VF);
5440 unsigned Alignment = getLoadStoreAlignment(I);
5441 unsigned AS = getLoadStoreAddressSpace(I);
5442 if (isa<LoadInst>(I)) {
5443 return TTI.getAddressComputationCost(ValTy) +
5444 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
5445 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
5446 }
5447 StoreInst *SI = cast<StoreInst>(I);
5448
5449 bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
5450 return TTI.getAddressComputationCost(ValTy) +
5451 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS) +
5452 (isLoopInvariantStoreValue ? 0 : TTI.getVectorInstrCost(
5453 Instruction::ExtractElement,
5454 VectorTy, VF - 1));
5455}
5456
5457unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
5458 unsigned VF) {
5459 Type *ValTy = getMemInstValueType(I);
5460 Type *VectorTy = ToVectorTy(ValTy, VF);
5461 unsigned Alignment = getLoadStoreAlignment(I);
5462 Value *Ptr = getLoadStorePointerOperand(I);
5463
5464 return TTI.getAddressComputationCost(VectorTy) +
5465 TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
5466 Legal->isMaskRequired(I), Alignment);
5467}
5468
5469unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
5470 unsigned VF) {
5471 Type *ValTy = getMemInstValueType(I);
5472 Type *VectorTy = ToVectorTy(ValTy, VF);
5473 unsigned AS = getLoadStoreAddressSpace(I);
5474
5475 auto Group = getInterleavedAccessGroup(I);
5476 assert(Group && "Fail to get an interleaved access group.")((Group && "Fail to get an interleaved access group."
) ? static_cast<void> (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5476, __PRETTY_FUNCTION__))
;
5477
5478 unsigned InterleaveFactor = Group->getFactor();
5479 Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5480
5481 // Holds the indices of existing members in an interleaved load group.
5482 // An interleaved store group doesn't need this as it doesn't allow gaps.
5483 SmallVector<unsigned, 4> Indices;
5484 if (isa<LoadInst>(I)) {
5485 for (unsigned i = 0; i < InterleaveFactor; i++)
5486 if (Group->getMember(i))
5487 Indices.push_back(i);
5488 }
5489
5490 // Calculate the cost of the whole interleaved group.
5491 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5492 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5493 Group->getAlignment(), AS, Legal->isMaskRequired(I));
5494
5495 if (Group->isReverse()) {
5496 // TODO: Add support for reversed masked interleaved access.
5497 assert(!Legal->isMaskRequired(I) &&((!Legal->isMaskRequired(I) && "Reverse masked interleaved access not supported."
) ? static_cast<void> (0) : __assert_fail ("!Legal->isMaskRequired(I) && \"Reverse masked interleaved access not supported.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5498, __PRETTY_FUNCTION__))
5498