Bug Summary

File:lib/Transforms/Vectorize/LoopVectorize.cpp
Warning:line 6387, 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-eagerly-assume -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.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-7~svn326551/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-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp
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//===----------------------------------------------------------------------===//
30//
31// The reduction-variable vectorization is based on the paper:
32// D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33//
34// Variable uniformity checks are inspired by:
35// Karrenberg, R. and Hack, S. Whole Function Vectorization.
36//
37// The interleaved access vectorization is based on the paper:
38// Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
39// Data for SIMD
40//
41// Other ideas/concepts are from:
42// A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
43//
44// S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
45// Vectorizing Compilers.
46//
47//===----------------------------------------------------------------------===//
48
49#include "llvm/Transforms/Vectorize/LoopVectorize.h"
50#include "LoopVectorizationPlanner.h"
51#include "llvm/ADT/APInt.h"
52#include "llvm/ADT/ArrayRef.h"
53#include "llvm/ADT/DenseMap.h"
54#include "llvm/ADT/DenseMapInfo.h"
55#include "llvm/ADT/Hashing.h"
56#include "llvm/ADT/MapVector.h"
57#include "llvm/ADT/None.h"
58#include "llvm/ADT/Optional.h"
59#include "llvm/ADT/SCCIterator.h"
60#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallSet.h"
64#include "llvm/ADT/SmallVector.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/ADT/StringRef.h"
67#include "llvm/ADT/Twine.h"
68#include "llvm/ADT/iterator_range.h"
69#include "llvm/Analysis/AssumptionCache.h"
70#include "llvm/Analysis/BasicAliasAnalysis.h"
71#include "llvm/Analysis/BlockFrequencyInfo.h"
72#include "llvm/Analysis/CodeMetrics.h"
73#include "llvm/Analysis/DemandedBits.h"
74#include "llvm/Analysis/GlobalsModRef.h"
75#include "llvm/Analysis/LoopAccessAnalysis.h"
76#include "llvm/Analysis/LoopAnalysisManager.h"
77#include "llvm/Analysis/LoopInfo.h"
78#include "llvm/Analysis/LoopIterator.h"
79#include "llvm/Analysis/OptimizationRemarkEmitter.h"
80#include "llvm/Analysis/ScalarEvolution.h"
81#include "llvm/Analysis/ScalarEvolutionExpander.h"
82#include "llvm/Analysis/ScalarEvolutionExpressions.h"
83#include "llvm/Analysis/TargetLibraryInfo.h"
84#include "llvm/Analysis/TargetTransformInfo.h"
85#include "llvm/Analysis/VectorUtils.h"
86#include "llvm/IR/Attributes.h"
87#include "llvm/IR/BasicBlock.h"
88#include "llvm/IR/CFG.h"
89#include "llvm/IR/Constant.h"
90#include "llvm/IR/Constants.h"
91#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/DebugInfoMetadata.h"
93#include "llvm/IR/DebugLoc.h"
94#include "llvm/IR/DerivedTypes.h"
95#include "llvm/IR/DiagnosticInfo.h"
96#include "llvm/IR/Dominators.h"
97#include "llvm/IR/Function.h"
98#include "llvm/IR/IRBuilder.h"
99#include "llvm/IR/InstrTypes.h"
100#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Instructions.h"
102#include "llvm/IR/IntrinsicInst.h"
103#include "llvm/IR/Intrinsics.h"
104#include "llvm/IR/LLVMContext.h"
105#include "llvm/IR/Metadata.h"
106#include "llvm/IR/Module.h"
107#include "llvm/IR/Operator.h"
108#include "llvm/IR/Type.h"
109#include "llvm/IR/Use.h"
110#include "llvm/IR/User.h"
111#include "llvm/IR/Value.h"
112#include "llvm/IR/ValueHandle.h"
113#include "llvm/IR/Verifier.h"
114#include "llvm/Pass.h"
115#include "llvm/Support/Casting.h"
116#include "llvm/Support/CommandLine.h"
117#include "llvm/Support/Compiler.h"
118#include "llvm/Support/Debug.h"
119#include "llvm/Support/ErrorHandling.h"
120#include "llvm/Support/MathExtras.h"
121#include "llvm/Support/raw_ostream.h"
122#include "llvm/Transforms/Utils/BasicBlockUtils.h"
123#include "llvm/Transforms/Utils/LoopSimplify.h"
124#include "llvm/Transforms/Utils/LoopUtils.h"
125#include "llvm/Transforms/Utils/LoopVersioning.h"
126#include <algorithm>
127#include <cassert>
128#include <cstdint>
129#include <cstdlib>
130#include <functional>
131#include <iterator>
132#include <limits>
133#include <memory>
134#include <string>
135#include <tuple>
136#include <utility>
137#include <vector>
138
139using namespace llvm;
140
141#define LV_NAME"loop-vectorize" "loop-vectorize"
142#define DEBUG_TYPE"loop-vectorize" LV_NAME"loop-vectorize"
143
144STATISTIC(LoopsVectorized, "Number of loops vectorized")static llvm::Statistic LoopsVectorized = {"loop-vectorize", "LoopsVectorized"
, "Number of loops vectorized", {0}, {false}}
;
145STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization")static llvm::Statistic LoopsAnalyzed = {"loop-vectorize", "LoopsAnalyzed"
, "Number of loops analyzed for vectorization", {0}, {false}}
;
146
147static cl::opt<bool>
148 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
149 cl::desc("Enable if-conversion during vectorization."));
150
151/// Loops with a known constant trip count below this number are vectorized only
152/// if no scalar iteration overheads are incurred.
153static cl::opt<unsigned> TinyTripCountVectorThreshold(
154 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
155 cl::desc("Loops with a constant trip count that is smaller than this "
156 "value are vectorized only if no scalar iteration overheads "
157 "are incurred."));
158
159static cl::opt<bool> MaximizeBandwidth(
160 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
161 cl::desc("Maximize bandwidth when selecting vectorization factor which "
162 "will be determined by the smallest type in loop."));
163
164static cl::opt<bool> EnableInterleavedMemAccesses(
165 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
166 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
167
168/// Maximum factor for an interleaved memory access.
169static cl::opt<unsigned> MaxInterleaveGroupFactor(
170 "max-interleave-group-factor", cl::Hidden,
171 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
172 cl::init(8));
173
174/// We don't interleave loops with a known constant trip count below this
175/// number.
176static const unsigned TinyTripCountInterleaveThreshold = 128;
177
178static cl::opt<unsigned> ForceTargetNumScalarRegs(
179 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
180 cl::desc("A flag that overrides the target's number of scalar registers."));
181
182static cl::opt<unsigned> ForceTargetNumVectorRegs(
183 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
184 cl::desc("A flag that overrides the target's number of vector registers."));
185
186/// Maximum vectorization interleave count.
187static const unsigned MaxInterleaveFactor = 16;
188
189static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
190 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
191 cl::desc("A flag that overrides the target's max interleave factor for "
192 "scalar loops."));
193
194static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
195 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
196 cl::desc("A flag that overrides the target's max interleave factor for "
197 "vectorized loops."));
198
199static cl::opt<unsigned> ForceTargetInstructionCost(
200 "force-target-instruction-cost", cl::init(0), cl::Hidden,
201 cl::desc("A flag that overrides the target's expected cost for "
202 "an instruction to a single constant value. Mostly "
203 "useful for getting consistent testing."));
204
205static cl::opt<unsigned> SmallLoopCost(
206 "small-loop-cost", cl::init(20), cl::Hidden,
207 cl::desc(
208 "The cost of a loop that is considered 'small' by the interleaver."));
209
210static cl::opt<bool> LoopVectorizeWithBlockFrequency(
211 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
212 cl::desc("Enable the use of the block frequency analysis to access PGO "
213 "heuristics minimizing code growth in cold regions and being more "
214 "aggressive in hot regions."));
215
216// Runtime interleave loops for load/store throughput.
217static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
218 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
219 cl::desc(
220 "Enable runtime interleaving until load/store ports are saturated"));
221
222/// The number of stores in a loop that are allowed to need predication.
223static cl::opt<unsigned> NumberOfStoresToPredicate(
224 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
225 cl::desc("Max number of stores to be predicated behind an if."));
226
227static cl::opt<bool> EnableIndVarRegisterHeur(
228 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
229 cl::desc("Count the induction variable only once when interleaving"));
230
231static cl::opt<bool> EnableCondStoresVectorization(
232 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
233 cl::desc("Enable if predication of stores during vectorization."));
234
235static cl::opt<unsigned> MaxNestedScalarReductionIC(
236 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
237 cl::desc("The maximum interleave count to use when interleaving a scalar "
238 "reduction in a nested loop."));
239
240static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
241 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
242 cl::desc("The maximum allowed number of runtime memory checks with a "
243 "vectorize(enable) pragma."));
244
245static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
246 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
247 cl::desc("The maximum number of SCEV checks allowed."));
248
249static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
250 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
251 cl::desc("The maximum number of SCEV checks allowed with a "
252 "vectorize(enable) pragma"));
253
254/// Create an analysis remark that explains why vectorization failed
255///
256/// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
257/// RemarkName is the identifier for the remark. If \p I is passed it is an
258/// instruction that prevents vectorization. Otherwise \p TheLoop is used for
259/// the location of the remark. \return the remark object that can be
260/// streamed to.
261static OptimizationRemarkAnalysis
262createMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
263 Instruction *I = nullptr) {
264 Value *CodeRegion = TheLoop->getHeader();
265 DebugLoc DL = TheLoop->getStartLoc();
266
267 if (I) {
268 CodeRegion = I->getParent();
269 // If there is no debug location attached to the instruction, revert back to
270 // using the loop's.
271 if (I->getDebugLoc())
272 DL = I->getDebugLoc();
273 }
274
275 OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
276 R << "loop not vectorized: ";
277 return R;
278}
279
280namespace {
281
282class LoopVectorizationRequirements;
283
284} // end anonymous namespace
285
286/// Returns true if the given loop body has a cycle, excluding the loop
287/// itself.
288static bool hasCyclesInLoopBody(const Loop &L) {
289 if (!L.empty())
290 return true;
291
292 for (const auto &SCC :
293 make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L),
294 scc_iterator<Loop, LoopBodyTraits>::end(L))) {
295 if (SCC.size() > 1) {
296 DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LVL: Detected a cycle in the loop body:\n"
; } } while (false)
;
297 DEBUG(L.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { L.dump(); } } while (false)
;
298 return true;
299 }
300 }
301 return false;
302}
303
304/// A helper function for converting Scalar types to vector types.
305/// If the incoming type is void, we return void. If the VF is 1, we return
306/// the scalar type.
307static Type *ToVectorTy(Type *Scalar, unsigned VF) {
308 if (Scalar->isVoidTy() || VF == 1)
309 return Scalar;
310 return VectorType::get(Scalar, VF);
311}
312
313// FIXME: The following helper functions have multiple implementations
314// in the project. They can be effectively organized in a common Load/Store
315// utilities unit.
316
317/// A helper function that returns the pointer operand of a load or store
318/// instruction.
319static Value *getPointerOperand(Value *I) {
320 if (auto *LI = dyn_cast<LoadInst>(I))
321 return LI->getPointerOperand();
322 if (auto *SI = dyn_cast<StoreInst>(I))
323 return SI->getPointerOperand();
324 return nullptr;
325}
326
327/// A helper function that returns the type of loaded or stored value.
328static Type *getMemInstValueType(Value *I) {
329 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 330, __extension__ __PRETTY_FUNCTION__))
330 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 330, __extension__ __PRETTY_FUNCTION__))
;
331 if (auto *LI = dyn_cast<LoadInst>(I))
332 return LI->getType();
333 return cast<StoreInst>(I)->getValueOperand()->getType();
334}
335
336/// A helper function that returns the alignment of load or store instruction.
337static unsigned getMemInstAlignment(Value *I) {
338 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 339, __extension__ __PRETTY_FUNCTION__))
339 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 339, __extension__ __PRETTY_FUNCTION__))
;
340 if (auto *LI = dyn_cast<LoadInst>(I))
341 return LI->getAlignment();
342 return cast<StoreInst>(I)->getAlignment();
343}
344
345/// A helper function that returns the address space of the pointer operand of
346/// load or store instruction.
347static unsigned getMemInstAddressSpace(Value *I) {
348 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 349, __extension__ __PRETTY_FUNCTION__))
349 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 if (auto *LI = dyn_cast<LoadInst>(I))
351 return LI->getPointerAddressSpace();
352 return cast<StoreInst>(I)->getPointerAddressSpace();
353}
354
355/// A helper function that returns true if the given type is irregular. The
356/// type is irregular if its allocated size doesn't equal the store size of an
357/// element of the corresponding vector type at the given vectorization factor.
358static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
359 // Determine if an array of VF elements of type Ty is "bitcast compatible"
360 // with a <VF x Ty> vector.
361 if (VF > 1) {
362 auto *VectorTy = VectorType::get(Ty, VF);
363 return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
364 }
365
366 // If the vectorization factor is one, we just check if an array of type Ty
367 // requires padding between elements.
368 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
369}
370
371/// A helper function that returns the reciprocal of the block probability of
372/// predicated blocks. If we return X, we are assuming the predicated block
373/// will execute once for every X iterations of the loop header.
374///
375/// TODO: We should use actual block probability here, if available. Currently,
376/// we always assume predicated blocks have a 50% chance of executing.
377static unsigned getReciprocalPredBlockProb() { return 2; }
378
379/// A helper function that adds a 'fast' flag to floating-point operations.
380static Value *addFastMathFlag(Value *V) {
381 if (isa<FPMathOperator>(V)) {
382 FastMathFlags Flags;
383 Flags.setFast();
384 cast<Instruction>(V)->setFastMathFlags(Flags);
385 }
386 return V;
387}
388
389/// A helper function that returns an integer or floating-point constant with
390/// value C.
391static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
392 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
393 : ConstantFP::get(Ty, C);
394}
395
396namespace llvm {
397
398/// InnerLoopVectorizer vectorizes loops which contain only one basic
399/// block to a specified vectorization factor (VF).
400/// This class performs the widening of scalars into vectors, or multiple
401/// scalars. This class also implements the following features:
402/// * It inserts an epilogue loop for handling loops that don't have iteration
403/// counts that are known to be a multiple of the vectorization factor.
404/// * It handles the code generation for reduction variables.
405/// * Scalarization (implementation using scalars) of un-vectorizable
406/// instructions.
407/// InnerLoopVectorizer does not perform any vectorization-legality
408/// checks, and relies on the caller to check for the different legality
409/// aspects. The InnerLoopVectorizer relies on the
410/// LoopVectorizationLegality class to provide information about the induction
411/// and reduction variables that were found to a given vectorization factor.
412class InnerLoopVectorizer {
413public:
414 InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
415 LoopInfo *LI, DominatorTree *DT,
416 const TargetLibraryInfo *TLI,
417 const TargetTransformInfo *TTI, AssumptionCache *AC,
418 OptimizationRemarkEmitter *ORE, unsigned VecWidth,
419 unsigned UnrollFactor, LoopVectorizationLegality *LVL,
420 LoopVectorizationCostModel *CM)
421 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
422 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
423 Builder(PSE.getSE()->getContext()),
424 VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
425 virtual ~InnerLoopVectorizer() = default;
426
427 /// Create a new empty loop. Unlink the old loop and connect the new one.
428 /// Return the pre-header block of the new loop.
429 BasicBlock *createVectorizedLoopSkeleton();
430
431 /// Widen a single instruction within the innermost loop.
432 void widenInstruction(Instruction &I);
433
434 /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
435 void fixVectorizedLoop();
436
437 // Return true if any runtime check is added.
438 bool areSafetyChecksAdded() { return AddedSafetyChecks; }
439
440 /// A type for vectorized values in the new loop. Each value from the
441 /// original loop, when vectorized, is represented by UF vector values in the
442 /// new unrolled loop, where UF is the unroll factor.
443 using VectorParts = SmallVector<Value *, 2>;
444
445 /// Vectorize a single PHINode in a block. This method handles the induction
446 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
447 /// arbitrary length vectors.
448 void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
449
450 /// A helper function to scalarize a single Instruction in the innermost loop.
451 /// Generates a sequence of scalar instances for each lane between \p MinLane
452 /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
453 /// inclusive..
454 void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
455 bool IfPredicateInstr);
456
457 /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
458 /// is provided, the integer induction variable will first be truncated to
459 /// the corresponding type.
460 void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
461
462 /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
463 /// vector or scalar value on-demand if one is not yet available. When
464 /// vectorizing a loop, we visit the definition of an instruction before its
465 /// uses. When visiting the definition, we either vectorize or scalarize the
466 /// instruction, creating an entry for it in the corresponding map. (In some
467 /// cases, such as induction variables, we will create both vector and scalar
468 /// entries.) Then, as we encounter uses of the definition, we derive values
469 /// for each scalar or vector use unless such a value is already available.
470 /// For example, if we scalarize a definition and one of its uses is vector,
471 /// we build the required vector on-demand with an insertelement sequence
472 /// when visiting the use. Otherwise, if the use is scalar, we can use the
473 /// existing scalar definition.
474 ///
475 /// Return a value in the new loop corresponding to \p V from the original
476 /// loop at unroll index \p Part. If the value has already been vectorized,
477 /// the corresponding vector entry in VectorLoopValueMap is returned. If,
478 /// however, the value has a scalar entry in VectorLoopValueMap, we construct
479 /// a new vector value on-demand by inserting the scalar values into a vector
480 /// with an insertelement sequence. If the value has been neither vectorized
481 /// nor scalarized, it must be loop invariant, so we simply broadcast the
482 /// value into a vector.
483 Value *getOrCreateVectorValue(Value *V, unsigned Part);
484
485 /// Return a value in the new loop corresponding to \p V from the original
486 /// loop at unroll and vector indices \p Instance. If the value has been
487 /// vectorized but not scalarized, the necessary extractelement instruction
488 /// will be generated.
489 Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
490
491 /// Construct the vector value of a scalarized value \p V one lane at a time.
492 void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
493
494 /// Try to vectorize the interleaved access group that \p Instr belongs to.
495 void vectorizeInterleaveGroup(Instruction *Instr);
496
497 /// Vectorize Load and Store instructions, optionally masking the vector
498 /// operations if \p BlockInMask is non-null.
499 void vectorizeMemoryInstruction(Instruction *Instr,
500 VectorParts *BlockInMask = nullptr);
501
502 /// \brief Set the debug location in the builder using the debug location in
503 /// the instruction.
504 void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
505
506protected:
507 friend class LoopVectorizationPlanner;
508
509 /// A small list of PHINodes.
510 using PhiVector = SmallVector<PHINode *, 4>;
511
512 /// A type for scalarized values in the new loop. Each value from the
513 /// original loop, when scalarized, is represented by UF x VF scalar values
514 /// in the new unrolled loop, where UF is the unroll factor and VF is the
515 /// vectorization factor.
516 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
517
518 /// Set up the values of the IVs correctly when exiting the vector loop.
519 void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
520 Value *CountRoundDown, Value *EndValue,
521 BasicBlock *MiddleBlock);
522
523 /// Create a new induction variable inside L.
524 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
525 Value *Step, Instruction *DL);
526
527 /// Handle all cross-iteration phis in the header.
528 void fixCrossIterationPHIs();
529
530 /// Fix a first-order recurrence. This is the second phase of vectorizing
531 /// this phi node.
532 void fixFirstOrderRecurrence(PHINode *Phi);
533
534 /// Fix a reduction cross-iteration phi. This is the second phase of
535 /// vectorizing this phi node.
536 void fixReduction(PHINode *Phi);
537
538 /// \brief The Loop exit block may have single value PHI nodes with some
539 /// incoming value. While vectorizing we only handled real values
540 /// that were defined inside the loop and we should have one value for
541 /// each predecessor of its parent basic block. See PR14725.
542 void fixLCSSAPHIs();
543
544 /// Iteratively sink the scalarized operands of a predicated instruction into
545 /// the block that was created for it.
546 void sinkScalarOperands(Instruction *PredInst);
547
548 /// Shrinks vector element sizes to the smallest bitwidth they can be legally
549 /// represented as.
550 void truncateToMinimalBitwidths();
551
552 /// Insert the new loop to the loop hierarchy and pass manager
553 /// and update the analysis passes.
554 void updateAnalysis();
555
556 /// Create a broadcast instruction. This method generates a broadcast
557 /// instruction (shuffle) for loop invariant values and for the induction
558 /// value. If this is the induction variable then we extend it to N, N+1, ...
559 /// this is needed because each iteration in the loop corresponds to a SIMD
560 /// element.
561 virtual Value *getBroadcastInstrs(Value *V);
562
563 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
564 /// to each vector element of Val. The sequence starts at StartIndex.
565 /// \p Opcode is relevant for FP induction variable.
566 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
567 Instruction::BinaryOps Opcode =
568 Instruction::BinaryOpsEnd);
569
570 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
571 /// variable on which to base the steps, \p Step is the size of the step, and
572 /// \p EntryVal is the value from the original loop that maps to the steps.
573 /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it
574 /// can be a truncate instruction).
575 void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal,
576 const InductionDescriptor &ID);
577
578 /// Create a vector induction phi node based on an existing scalar one. \p
579 /// EntryVal is the value from the original loop that maps to the vector phi
580 /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
581 /// truncate instruction, instead of widening the original IV, we widen a
582 /// version of the IV truncated to \p EntryVal's type.
583 void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
584 Value *Step, Instruction *EntryVal);
585
586 /// Returns true if an instruction \p I should be scalarized instead of
587 /// vectorized for the chosen vectorization factor.
588 bool shouldScalarizeInstruction(Instruction *I) const;
589
590 /// Returns true if we should generate a scalar version of \p IV.
591 bool needsScalarInduction(Instruction *IV) const;
592
593 /// If there is a cast involved in the induction variable \p ID, which should
594 /// be ignored in the vectorized loop body, this function records the
595 /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
596 /// cast. We had already proved that the casted Phi is equal to the uncasted
597 /// Phi in the vectorized loop (under a runtime guard), and therefore
598 /// there is no need to vectorize the cast - the same value can be used in the
599 /// vector loop for both the Phi and the cast.
600 /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
601 /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
602 void recordVectorLoopValueForInductionCast (const InductionDescriptor &ID,
603 Value *VectorLoopValue,
604 unsigned Part,
605 unsigned Lane = UINT_MAX(2147483647 *2U +1U));
606
607 /// Generate a shuffle sequence that will reverse the vector Vec.
608 virtual Value *reverseVector(Value *Vec);
609
610 /// Returns (and creates if needed) the original loop trip count.
611 Value *getOrCreateTripCount(Loop *NewLoop);
612
613 /// Returns (and creates if needed) the trip count of the widened loop.
614 Value *getOrCreateVectorTripCount(Loop *NewLoop);
615
616 /// Returns a bitcasted value to the requested vector type.
617 /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
618 Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
619 const DataLayout &DL);
620
621 /// Emit a bypass check to see if the vector trip count is zero, including if
622 /// it overflows.
623 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
624
625 /// Emit a bypass check to see if all of the SCEV assumptions we've
626 /// had to make are correct.
627 void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
628
629 /// Emit bypass checks to check any memory assumptions we may have made.
630 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
631
632 /// Add additional metadata to \p To that was not present on \p Orig.
633 ///
634 /// Currently this is used to add the noalias annotations based on the
635 /// inserted memchecks. Use this for instructions that are *cloned* into the
636 /// vector loop.
637 void addNewMetadata(Instruction *To, const Instruction *Orig);
638
639 /// Add metadata from one instruction to another.
640 ///
641 /// This includes both the original MDs from \p From and additional ones (\see
642 /// addNewMetadata). Use this for *newly created* instructions in the vector
643 /// loop.
644 void addMetadata(Instruction *To, Instruction *From);
645
646 /// \brief Similar to the previous function but it adds the metadata to a
647 /// vector of instructions.
648 void addMetadata(ArrayRef<Value *> To, Instruction *From);
649
650 /// The original loop.
651 Loop *OrigLoop;
652
653 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
654 /// dynamic knowledge to simplify SCEV expressions and converts them to a
655 /// more usable form.
656 PredicatedScalarEvolution &PSE;
657
658 /// Loop Info.
659 LoopInfo *LI;
660
661 /// Dominator Tree.
662 DominatorTree *DT;
663
664 /// Alias Analysis.
665 AliasAnalysis *AA;
666
667 /// Target Library Info.
668 const TargetLibraryInfo *TLI;
669
670 /// Target Transform Info.
671 const TargetTransformInfo *TTI;
672
673 /// Assumption Cache.
674 AssumptionCache *AC;
675
676 /// Interface to emit optimization remarks.
677 OptimizationRemarkEmitter *ORE;
678
679 /// \brief LoopVersioning. It's only set up (non-null) if memchecks were
680 /// used.
681 ///
682 /// This is currently only used to add no-alias metadata based on the
683 /// memchecks. The actually versioning is performed manually.
684 std::unique_ptr<LoopVersioning> LVer;
685
686 /// The vectorization SIMD factor to use. Each vector will have this many
687 /// vector elements.
688 unsigned VF;
689
690 /// The vectorization unroll factor to use. Each scalar is vectorized to this
691 /// many different vector instructions.
692 unsigned UF;
693
694 /// The builder that we use
695 IRBuilder<> Builder;
696
697 // --- Vectorization state ---
698
699 /// The vector-loop preheader.
700 BasicBlock *LoopVectorPreHeader;
701
702 /// The scalar-loop preheader.
703 BasicBlock *LoopScalarPreHeader;
704
705 /// Middle Block between the vector and the scalar.
706 BasicBlock *LoopMiddleBlock;
707
708 /// The ExitBlock of the scalar loop.
709 BasicBlock *LoopExitBlock;
710
711 /// The vector loop body.
712 BasicBlock *LoopVectorBody;
713
714 /// The scalar loop body.
715 BasicBlock *LoopScalarBody;
716
717 /// A list of all bypass blocks. The first block is the entry of the loop.
718 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
719
720 /// The new Induction variable which was added to the new block.
721 PHINode *Induction = nullptr;
722
723 /// The induction variable of the old basic block.
724 PHINode *OldInduction = nullptr;
725
726 /// Maps values from the original loop to their corresponding values in the
727 /// vectorized loop. A key value can map to either vector values, scalar
728 /// values or both kinds of values, depending on whether the key was
729 /// vectorized and scalarized.
730 VectorizerValueMap VectorLoopValueMap;
731
732 /// Store instructions that were predicated.
733 SmallVector<Instruction *, 4> PredicatedInstructions;
734
735 /// Trip count of the original loop.
736 Value *TripCount = nullptr;
737
738 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
739 Value *VectorTripCount = nullptr;
740
741 /// The legality analysis.
742 LoopVectorizationLegality *Legal;
743
744 /// The profitablity analysis.
745 LoopVectorizationCostModel *Cost;
746
747 // Record whether runtime checks are added.
748 bool AddedSafetyChecks = false;
749
750 // Holds the end values for each induction variable. We save the end values
751 // so we can later fix-up the external users of the induction variables.
752 DenseMap<PHINode *, Value *> IVEndValues;
753};
754
755class InnerLoopUnroller : public InnerLoopVectorizer {
756public:
757 InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
758 LoopInfo *LI, DominatorTree *DT,
759 const TargetLibraryInfo *TLI,
760 const TargetTransformInfo *TTI, AssumptionCache *AC,
761 OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
762 LoopVectorizationLegality *LVL,
763 LoopVectorizationCostModel *CM)
764 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
765 UnrollFactor, LVL, CM) {}
766
767private:
768 Value *getBroadcastInstrs(Value *V) override;
769 Value *getStepVector(Value *Val, int StartIdx, Value *Step,
770 Instruction::BinaryOps Opcode =
771 Instruction::BinaryOpsEnd) override;
772 Value *reverseVector(Value *Vec) override;
773};
774
775} // end namespace llvm
776
777/// \brief Look for a meaningful debug location on the instruction or it's
778/// operands.
779static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
780 if (!I)
781 return I;
782
783 DebugLoc Empty;
784 if (I->getDebugLoc() != Empty)
785 return I;
786
787 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
788 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
789 if (OpInst->getDebugLoc() != Empty)
790 return OpInst;
791 }
792
793 return I;
794}
795
796void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
797 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
798 const DILocation *DIL = Inst->getDebugLoc();
799 if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
800 !isa<DbgInfoIntrinsic>(Inst))
801 B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
802 else
803 B.SetCurrentDebugLocation(DIL);
804 } else
805 B.SetCurrentDebugLocation(DebugLoc());
806}
807
808#ifndef NDEBUG
809/// \return string containing a file name and a line # for the given loop.
810static std::string getDebugLocString(const Loop *L) {
811 std::string Result;
812 if (L) {
813 raw_string_ostream OS(Result);
814 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
815 LoopDbgLoc.print(OS);
816 else
817 // Just print the module name.
818 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
819 OS.flush();
820 }
821 return Result;
822}
823#endif
824
825void InnerLoopVectorizer::addNewMetadata(Instruction *To,
826 const Instruction *Orig) {
827 // If the loop was versioned with memchecks, add the corresponding no-alias
828 // metadata.
829 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
830 LVer->annotateInstWithNoAlias(To, Orig);
831}
832
833void InnerLoopVectorizer::addMetadata(Instruction *To,
834 Instruction *From) {
835 propagateMetadata(To, From);
836 addNewMetadata(To, From);
837}
838
839void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
840 Instruction *From) {
841 for (Value *V : To) {
842 if (Instruction *I = dyn_cast<Instruction>(V))
843 addMetadata(I, From);
844 }
845}
846
847namespace llvm {
848
849/// \brief The group of interleaved loads/stores sharing the same stride and
850/// close to each other.
851///
852/// Each member in this group has an index starting from 0, and the largest
853/// index should be less than interleaved factor, which is equal to the absolute
854/// value of the access's stride.
855///
856/// E.g. An interleaved load group of factor 4:
857/// for (unsigned i = 0; i < 1024; i+=4) {
858/// a = A[i]; // Member of index 0
859/// b = A[i+1]; // Member of index 1
860/// d = A[i+3]; // Member of index 3
861/// ...
862/// }
863///
864/// An interleaved store group of factor 4:
865/// for (unsigned i = 0; i < 1024; i+=4) {
866/// ...
867/// A[i] = a; // Member of index 0
868/// A[i+1] = b; // Member of index 1
869/// A[i+2] = c; // Member of index 2
870/// A[i+3] = d; // Member of index 3
871/// }
872///
873/// Note: the interleaved load group could have gaps (missing members), but
874/// the interleaved store group doesn't allow gaps.
875class InterleaveGroup {
876public:
877 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
878 : Align(Align), InsertPos(Instr) {
879 assert(Align && "The alignment should be non-zero")(static_cast <bool> (Align && "The alignment should be non-zero"
) ? void (0) : __assert_fail ("Align && \"The alignment should be non-zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 879, __extension__ __PRETTY_FUNCTION__))
;
880
881 Factor = std::abs(Stride);
882 assert(Factor > 1 && "Invalid interleave factor")(static_cast <bool> (Factor > 1 && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor > 1 && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 882, __extension__ __PRETTY_FUNCTION__))
;
883
884 Reverse = Stride < 0;
885 Members[0] = Instr;
886 }
887
888 bool isReverse() const { return Reverse; }
889 unsigned getFactor() const { return Factor; }
890 unsigned getAlignment() const { return Align; }
891 unsigned getNumMembers() const { return Members.size(); }
892
893 /// \brief Try to insert a new member \p Instr with index \p Index and
894 /// alignment \p NewAlign. The index is related to the leader and it could be
895 /// negative if it is the new leader.
896 ///
897 /// \returns false if the instruction doesn't belong to the group.
898 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
899 assert(NewAlign && "The new member's alignment should be non-zero")(static_cast <bool> (NewAlign && "The new member's alignment should be non-zero"
) ? void (0) : __assert_fail ("NewAlign && \"The new member's alignment should be non-zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 899, __extension__ __PRETTY_FUNCTION__))
;
900
901 int Key = Index + SmallestKey;
902
903 // Skip if there is already a member with the same index.
904 if (Members.count(Key))
905 return false;
906
907 if (Key > LargestKey) {
908 // The largest index is always less than the interleave factor.
909 if (Index >= static_cast<int>(Factor))
910 return false;
911
912 LargestKey = Key;
913 } else if (Key < SmallestKey) {
914 // The largest index is always less than the interleave factor.
915 if (LargestKey - Key >= static_cast<int>(Factor))
916 return false;
917
918 SmallestKey = Key;
919 }
920
921 // It's always safe to select the minimum alignment.
922 Align = std::min(Align, NewAlign);
923 Members[Key] = Instr;
924 return true;
925 }
926
927 /// \brief Get the member with the given index \p Index
928 ///
929 /// \returns nullptr if contains no such member.
930 Instruction *getMember(unsigned Index) const {
931 int Key = SmallestKey + Index;
932 if (!Members.count(Key))
933 return nullptr;
934
935 return Members.find(Key)->second;
936 }
937
938 /// \brief Get the index for the given member. Unlike the key in the member
939 /// map, the index starts from 0.
940 unsigned getIndex(Instruction *Instr) const {
941 for (auto I : Members)
942 if (I.second == Instr)
943 return I.first - SmallestKey;
944
945 llvm_unreachable("InterleaveGroup contains no such member")::llvm::llvm_unreachable_internal("InterleaveGroup contains no such member"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 945)
;
946 }
947
948 Instruction *getInsertPos() const { return InsertPos; }
949 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
950
951 /// Add metadata (e.g. alias info) from the instructions in this group to \p
952 /// NewInst.
953 ///
954 /// FIXME: this function currently does not add noalias metadata a'la
955 /// addNewMedata. To do that we need to compute the intersection of the
956 /// noalias info from all members.
957 void addMetadata(Instruction *NewInst) const {
958 SmallVector<Value *, 4> VL;
959 std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
960 [](std::pair<int, Instruction *> p) { return p.second; });
961 propagateMetadata(NewInst, VL);
962 }
963
964private:
965 unsigned Factor; // Interleave Factor.
966 bool Reverse;
967 unsigned Align;
968 DenseMap<int, Instruction *> Members;
969 int SmallestKey = 0;
970 int LargestKey = 0;
971
972 // To avoid breaking dependences, vectorized instructions of an interleave
973 // group should be inserted at either the first load or the last store in
974 // program order.
975 //
976 // E.g. %even = load i32 // Insert Position
977 // %add = add i32 %even // Use of %even
978 // %odd = load i32
979 //
980 // store i32 %even
981 // %odd = add i32 // Def of %odd
982 // store i32 %odd // Insert Position
983 Instruction *InsertPos;
984};
985} // end namespace llvm
986
987namespace {
988
989/// \brief Drive the analysis of interleaved memory accesses in the loop.
990///
991/// Use this class to analyze interleaved accesses only when we can vectorize
992/// a loop. Otherwise it's meaningless to do analysis as the vectorization
993/// on interleaved accesses is unsafe.
994///
995/// The analysis collects interleave groups and records the relationships
996/// between the member and the group in a map.
997class InterleavedAccessInfo {
998public:
999 InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
1000 DominatorTree *DT, LoopInfo *LI)
1001 : PSE(PSE), TheLoop(L), DT(DT), LI(LI) {}
1002
1003 ~InterleavedAccessInfo() {
1004 SmallSet<InterleaveGroup *, 4> DelSet;
1005 // Avoid releasing a pointer twice.
1006 for (auto &I : InterleaveGroupMap)
1007 DelSet.insert(I.second);
1008 for (auto *Ptr : DelSet)
1009 delete Ptr;
1010 }
1011
1012 /// \brief Analyze the interleaved accesses and collect them in interleave
1013 /// groups. Substitute symbolic strides using \p Strides.
1014 void analyzeInterleaving(const ValueToValueMap &Strides);
1015
1016 /// \brief Check if \p Instr belongs to any interleave group.
1017 bool isInterleaved(Instruction *Instr) const {
1018 return InterleaveGroupMap.count(Instr);
1019 }
1020
1021 /// \brief Get the interleave group that \p Instr belongs to.
1022 ///
1023 /// \returns nullptr if doesn't have such group.
1024 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
1025 if (InterleaveGroupMap.count(Instr))
1026 return InterleaveGroupMap.find(Instr)->second;
1027 return nullptr;
1028 }
1029
1030 /// \brief Returns true if an interleaved group that may access memory
1031 /// out-of-bounds requires a scalar epilogue iteration for correctness.
1032 bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
1033
1034 /// \brief Initialize the LoopAccessInfo used for dependence checking.
1035 void setLAI(const LoopAccessInfo *Info) { LAI = Info; }
1036
1037private:
1038 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
1039 /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
1040 /// The interleaved access analysis can also add new predicates (for example
1041 /// by versioning strides of pointers).
1042 PredicatedScalarEvolution &PSE;
1043
1044 Loop *TheLoop;
1045 DominatorTree *DT;
1046 LoopInfo *LI;
1047 const LoopAccessInfo *LAI = nullptr;
1048
1049 /// True if the loop may contain non-reversed interleaved groups with
1050 /// out-of-bounds accesses. We ensure we don't speculatively access memory
1051 /// out-of-bounds by executing at least one scalar epilogue iteration.
1052 bool RequiresScalarEpilogue = false;
1053
1054 /// Holds the relationships between the members and the interleave group.
1055 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
1056
1057 /// Holds dependences among the memory accesses in the loop. It maps a source
1058 /// access to a set of dependent sink accesses.
1059 DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
1060
1061 /// \brief The descriptor for a strided memory access.
1062 struct StrideDescriptor {
1063 StrideDescriptor() = default;
1064 StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
1065 unsigned Align)
1066 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
1067
1068 // The access's stride. It is negative for a reverse access.
1069 int64_t Stride = 0;
1070
1071 // The scalar expression of this access.
1072 const SCEV *Scev = nullptr;
1073
1074 // The size of the memory object.
1075 uint64_t Size = 0;
1076
1077 // The alignment of this access.
1078 unsigned Align = 0;
1079 };
1080
1081 /// \brief A type for holding instructions and their stride descriptors.
1082 using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
1083
1084 /// \brief Create a new interleave group with the given instruction \p Instr,
1085 /// stride \p Stride and alignment \p Align.
1086 ///
1087 /// \returns the newly created interleave group.
1088 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
1089 unsigned Align) {
1090 assert(!InterleaveGroupMap.count(Instr) &&(static_cast <bool> (!InterleaveGroupMap.count(Instr) &&
"Already in an interleaved access group") ? void (0) : __assert_fail
("!InterleaveGroupMap.count(Instr) && \"Already in an interleaved access group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1091, __extension__ __PRETTY_FUNCTION__))
1091 "Already in an interleaved access group")(static_cast <bool> (!InterleaveGroupMap.count(Instr) &&
"Already in an interleaved access group") ? void (0) : __assert_fail
("!InterleaveGroupMap.count(Instr) && \"Already in an interleaved access group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1091, __extension__ __PRETTY_FUNCTION__))
;
1092 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
1093 return InterleaveGroupMap[Instr];
1094 }
1095
1096 /// \brief Release the group and remove all the relationships.
1097 void releaseGroup(InterleaveGroup *Group) {
1098 for (unsigned i = 0; i < Group->getFactor(); i++)
1099 if (Instruction *Member = Group->getMember(i))
1100 InterleaveGroupMap.erase(Member);
1101
1102 delete Group;
1103 }
1104
1105 /// \brief Collect all the accesses with a constant stride in program order.
1106 void collectConstStrideAccesses(
1107 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
1108 const ValueToValueMap &Strides);
1109
1110 /// \brief Returns true if \p Stride is allowed in an interleaved group.
1111 static bool isStrided(int Stride) {
1112 unsigned Factor = std::abs(Stride);
1113 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1114 }
1115
1116 /// \brief Returns true if \p BB is a predicated block.
1117 bool isPredicated(BasicBlock *BB) const {
1118 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1119 }
1120
1121 /// \brief Returns true if LoopAccessInfo can be used for dependence queries.
1122 bool areDependencesValid() const {
1123 return LAI && LAI->getDepChecker().getDependences();
1124 }
1125
1126 /// \brief Returns true if memory accesses \p A and \p B can be reordered, if
1127 /// necessary, when constructing interleaved groups.
1128 ///
1129 /// \p A must precede \p B in program order. We return false if reordering is
1130 /// not necessary or is prevented because \p A and \p B may be dependent.
1131 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1132 StrideEntry *B) const {
1133 // Code motion for interleaved accesses can potentially hoist strided loads
1134 // and sink strided stores. The code below checks the legality of the
1135 // following two conditions:
1136 //
1137 // 1. Potentially moving a strided load (B) before any store (A) that
1138 // precedes B, or
1139 //
1140 // 2. Potentially moving a strided store (A) after any load or store (B)
1141 // that A precedes.
1142 //
1143 // It's legal to reorder A and B if we know there isn't a dependence from A
1144 // to B. Note that this determination is conservative since some
1145 // dependences could potentially be reordered safely.
1146
1147 // A is potentially the source of a dependence.
1148 auto *Src = A->first;
1149 auto SrcDes = A->second;
1150
1151 // B is potentially the sink of a dependence.
1152 auto *Sink = B->first;
1153 auto SinkDes = B->second;
1154
1155 // Code motion for interleaved accesses can't violate WAR dependences.
1156 // Thus, reordering is legal if the source isn't a write.
1157 if (!Src->mayWriteToMemory())
1158 return true;
1159
1160 // At least one of the accesses must be strided.
1161 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1162 return true;
1163
1164 // If dependence information is not available from LoopAccessInfo,
1165 // conservatively assume the instructions can't be reordered.
1166 if (!areDependencesValid())
1167 return false;
1168
1169 // If we know there is a dependence from source to sink, assume the
1170 // instructions can't be reordered. Otherwise, reordering is legal.
1171 return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
1172 }
1173
1174 /// \brief Collect the dependences from LoopAccessInfo.
1175 ///
1176 /// We process the dependences once during the interleaved access analysis to
1177 /// enable constant-time dependence queries.
1178 void collectDependences() {
1179 if (!areDependencesValid())
1180 return;
1181 auto *Deps = LAI->getDepChecker().getDependences();
1182 for (auto Dep : *Deps)
1183 Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1184 }
1185};
1186
1187/// Utility class for getting and setting loop vectorizer hints in the form
1188/// of loop metadata.
1189/// This class keeps a number of loop annotations locally (as member variables)
1190/// and can, upon request, write them back as metadata on the loop. It will
1191/// initially scan the loop for existing metadata, and will update the local
1192/// values based on information in the loop.
1193/// We cannot write all values to metadata, as the mere presence of some info,
1194/// for example 'force', means a decision has been made. So, we need to be
1195/// careful NOT to add them if the user hasn't specifically asked so.
1196class LoopVectorizeHints {
1197 enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE, HK_ISVECTORIZED };
1198
1199 /// Hint - associates name and validation with the hint value.
1200 struct Hint {
1201 const char *Name;
1202 unsigned Value; // This may have to change for non-numeric values.
1203 HintKind Kind;
1204
1205 Hint(const char *Name, unsigned Value, HintKind Kind)
1206 : Name(Name), Value(Value), Kind(Kind) {}
1207
1208 bool validate(unsigned Val) {
1209 switch (Kind) {
1210 case HK_WIDTH:
1211 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1212 case HK_UNROLL:
1213 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1214 case HK_FORCE:
1215 return (Val <= 1);
1216 case HK_ISVECTORIZED:
1217 return (Val==0 || Val==1);
1218 }
1219 return false;
1220 }
1221 };
1222
1223 /// Vectorization width.
1224 Hint Width;
1225
1226 /// Vectorization interleave factor.
1227 Hint Interleave;
1228
1229 /// Vectorization forced
1230 Hint Force;
1231
1232 /// Already Vectorized
1233 Hint IsVectorized;
1234
1235 /// Return the loop metadata prefix.
1236 static StringRef Prefix() { return "llvm.loop."; }
1237
1238 /// True if there is any unsafe math in the loop.
1239 bool PotentiallyUnsafe = false;
1240
1241public:
1242 enum ForceKind {
1243 FK_Undefined = -1, ///< Not selected.
1244 FK_Disabled = 0, ///< Forcing disabled.
1245 FK_Enabled = 1, ///< Forcing enabled.
1246 };
1247
1248 LoopVectorizeHints(const Loop *L, bool DisableInterleaving,
1249 OptimizationRemarkEmitter &ORE)
1250 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1251 HK_WIDTH),
1252 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1253 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1254 IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) {
1255 // Populate values with existing loop metadata.
1256 getHintsFromMetadata();
1257
1258 // force-vector-interleave overrides DisableInterleaving.
1259 if (VectorizerParams::isInterleaveForced())
1260 Interleave.Value = VectorizerParams::VectorizationInterleave;
1261
1262 if (IsVectorized.Value != 1)
1263 // If the vectorization width and interleaving count are both 1 then
1264 // consider the loop to have been already vectorized because there's
1265 // nothing more that we can do.
1266 IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
1267 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { if (DisableInterleaving && Interleave
.Value == 1) dbgs() << "LV: Interleaving disabled by the pass manager\n"
; } } while (false)
1268 << "LV: Interleaving disabled by the pass manager\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { if (DisableInterleaving && Interleave
.Value == 1) dbgs() << "LV: Interleaving disabled by the pass manager\n"
; } } while (false)
;
1269 }
1270
1271 /// Mark the loop L as already vectorized by setting the width to 1.
1272 void setAlreadyVectorized() {
1273 IsVectorized.Value = 1;
1274 Hint Hints[] = {IsVectorized};
1275 writeHintsToMetadata(Hints);
1276 }
1277
1278 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
1279 if (getForce() == LoopVectorizeHints::FK_Disabled) {
1280 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"
; } } while (false)
;
1281 emitRemarkWithHints();
1282 return false;
1283 }
1284
1285 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1286 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"
; } } while (false)
;
1287 emitRemarkWithHints();
1288 return false;
1289 }
1290
1291 if (getIsVectorized() == 1) {
1292 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"
; } } while (false)
;
1293 // FIXME: Add interleave.disable metadata. This will allow
1294 // vectorize.disable to be used without disabling the pass and errors
1295 // to differentiate between disabled vectorization and a width of 1.
1296 ORE.emit([&]() {
1297 return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
1298 "AllDisabled", L->getStartLoc(),
1299 L->getHeader())
1300 << "loop not vectorized: vectorization and interleaving are "
1301 "explicitly disabled, or the loop has already been "
1302 "vectorized";
1303 });
1304 return false;
1305 }
1306
1307 return true;
1308 }
1309
1310 /// Dumps all the hint information.
1311 void emitRemarkWithHints() const {
1312 using namespace ore;
1313
1314 ORE.emit([&]() {
1315 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1316 return OptimizationRemarkMissed(LV_NAME"loop-vectorize", "MissedExplicitlyDisabled",
1317 TheLoop->getStartLoc(),
1318 TheLoop->getHeader())
1319 << "loop not vectorized: vectorization is explicitly disabled";
1320 else {
1321 OptimizationRemarkMissed R(LV_NAME"loop-vectorize", "MissedDetails",
1322 TheLoop->getStartLoc(),
1323 TheLoop->getHeader());
1324 R << "loop not vectorized";
1325 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1326 R << " (Force=" << NV("Force", true);
1327 if (Width.Value != 0)
1328 R << ", Vector Width=" << NV("VectorWidth", Width.Value);
1329 if (Interleave.Value != 0)
1330 R << ", Interleave Count="
1331 << NV("InterleaveCount", Interleave.Value);
1332 R << ")";
1333 }
1334 return R;
1335 }
1336 });
1337 }
1338
1339 unsigned getWidth() const { return Width.Value; }
1340 unsigned getInterleave() const { return Interleave.Value; }
1341 unsigned getIsVectorized() const { return IsVectorized.Value; }
1342 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1343
1344 /// \brief If hints are provided that force vectorization, use the AlwaysPrint
1345 /// pass name to force the frontend to print the diagnostic.
1346 const char *vectorizeAnalysisPassName() const {
1347 if (getWidth() == 1)
1348 return LV_NAME"loop-vectorize";
1349 if (getForce() == LoopVectorizeHints::FK_Disabled)
1350 return LV_NAME"loop-vectorize";
1351 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1352 return LV_NAME"loop-vectorize";
1353 return OptimizationRemarkAnalysis::AlwaysPrint;
1354 }
1355
1356 bool allowReordering() const {
1357 // When enabling loop hints are provided we allow the vectorizer to change
1358 // the order of operations that is given by the scalar loop. This is not
1359 // enabled by default because can be unsafe or inefficient. For example,
1360 // reordering floating-point operations will change the way round-off
1361 // error accumulates in the loop.
1362 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1363 }
1364
1365 bool isPotentiallyUnsafe() const {
1366 // Avoid FP vectorization if the target is unsure about proper support.
1367 // This may be related to the SIMD unit in the target not handling
1368 // IEEE 754 FP ops properly, or bad single-to-double promotions.
1369 // Otherwise, a sequence of vectorized loops, even without reduction,
1370 // could lead to different end results on the destination vectors.
1371 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1372 }
1373
1374 void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
1375
1376private:
1377 /// Find hints specified in the loop metadata and update local values.
1378 void getHintsFromMetadata() {
1379 MDNode *LoopID = TheLoop->getLoopID();
1380 if (!LoopID)
1381 return;
1382
1383 // First operand should refer to the loop id itself.
1384 assert(LoopID->getNumOperands() > 0 && "requires at least one operand")(static_cast <bool> (LoopID->getNumOperands() > 0
&& "requires at least one operand") ? void (0) : __assert_fail
("LoopID->getNumOperands() > 0 && \"requires at least one operand\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1384, __extension__ __PRETTY_FUNCTION__))
;
1385 assert(LoopID->getOperand(0) == LoopID && "invalid loop id")(static_cast <bool> (LoopID->getOperand(0) == LoopID
&& "invalid loop id") ? void (0) : __assert_fail ("LoopID->getOperand(0) == LoopID && \"invalid loop id\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1385, __extension__ __PRETTY_FUNCTION__))
;
1386
1387 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1388 const MDString *S = nullptr;
1389 SmallVector<Metadata *, 4> Args;
1390
1391 // The expected hint is either a MDString or a MDNode with the first
1392 // operand a MDString.
1393 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1394 if (!MD || MD->getNumOperands() == 0)
1395 continue;
1396 S = dyn_cast<MDString>(MD->getOperand(0));
1397 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1398 Args.push_back(MD->getOperand(i));
1399 } else {
1400 S = dyn_cast<MDString>(LoopID->getOperand(i));
1401 assert(Args.size() == 0 && "too many arguments for MDString")(static_cast <bool> (Args.size() == 0 && "too many arguments for MDString"
) ? void (0) : __assert_fail ("Args.size() == 0 && \"too many arguments for MDString\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1401, __extension__ __PRETTY_FUNCTION__))
;
1402 }
1403
1404 if (!S)
1405 continue;
1406
1407 // Check if the hint starts with the loop metadata prefix.
1408 StringRef Name = S->getString();
1409 if (Args.size() == 1)
1410 setHint(Name, Args[0]);
1411 }
1412 }
1413
1414 /// Checks string hint with one operand and set value if valid.
1415 void setHint(StringRef Name, Metadata *Arg) {
1416 if (!Name.startswith(Prefix()))
1417 return;
1418 Name = Name.substr(Prefix().size(), StringRef::npos);
1419
1420 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1421 if (!C)
1422 return;
1423 unsigned Val = C->getZExtValue();
1424
1425 Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
1426 for (auto H : Hints) {
1427 if (Name == H->Name) {
1428 if (H->validate(Val))
1429 H->Value = Val;
1430 else
1431 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: ignoring invalid hint '"
<< Name << "'\n"; } } while (false)
;
1432 break;
1433 }
1434 }
1435 }
1436
1437 /// Create a new hint from name / value pair.
1438 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1439 LLVMContext &Context = TheLoop->getHeader()->getContext();
1440 Metadata *MDs[] = {MDString::get(Context, Name),
1441 ConstantAsMetadata::get(
1442 ConstantInt::get(Type::getInt32Ty(Context), V))};
1443 return MDNode::get(Context, MDs);
1444 }
1445
1446 /// Matches metadata with hint name.
1447 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1448 MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
1449 if (!Name)
1450 return false;
1451
1452 for (auto H : HintTypes)
1453 if (Name->getString().endswith(H.Name))
1454 return true;
1455 return false;
1456 }
1457
1458 /// Sets current hints into loop metadata, keeping other values intact.
1459 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1460 if (HintTypes.empty())
1461 return;
1462
1463 // Reserve the first element to LoopID (see below).
1464 SmallVector<Metadata *, 4> MDs(1);
1465 // If the loop already has metadata, then ignore the existing operands.
1466 MDNode *LoopID = TheLoop->getLoopID();
1467 if (LoopID) {
1468 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1469 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1470 // If node in update list, ignore old value.
1471 if (!matchesHintMetadataName(Node, HintTypes))
1472 MDs.push_back(Node);
1473 }
1474 }
1475
1476 // Now, add the missing hints.
1477 for (auto H : HintTypes)
1478 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1479
1480 // Replace current metadata node with new one.
1481 LLVMContext &Context = TheLoop->getHeader()->getContext();
1482 MDNode *NewLoopID = MDNode::get(Context, MDs);
1483 // Set operand 0 to refer to the loop id itself.
1484 NewLoopID->replaceOperandWith(0, NewLoopID);
1485
1486 TheLoop->setLoopID(NewLoopID);
1487 }
1488
1489 /// The loop these hints belong to.
1490 const Loop *TheLoop;
1491
1492 /// Interface to emit optimization remarks.
1493 OptimizationRemarkEmitter &ORE;
1494};
1495
1496} // end anonymous namespace
1497
1498static void emitMissedWarning(Function *F, Loop *L,
1499 const LoopVectorizeHints &LH,
1500 OptimizationRemarkEmitter *ORE) {
1501 LH.emitRemarkWithHints();
1502
1503 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1504 if (LH.getWidth() != 1)
1505 ORE->emit(DiagnosticInfoOptimizationFailure(
1506 DEBUG_TYPE"loop-vectorize", "FailedRequestedVectorization",
1507 L->getStartLoc(), L->getHeader())
1508 << "loop not vectorized: "
1509 << "failed explicitly specified loop vectorization");
1510 else if (LH.getInterleave() != 1)
1511 ORE->emit(DiagnosticInfoOptimizationFailure(
1512 DEBUG_TYPE"loop-vectorize", "FailedRequestedInterleaving", L->getStartLoc(),
1513 L->getHeader())
1514 << "loop not interleaved: "
1515 << "failed explicitly specified loop interleaving");
1516 }
1517}
1518
1519namespace llvm {
1520
1521/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1522/// to what vectorization factor.
1523/// This class does not look at the profitability of vectorization, only the
1524/// legality. This class has two main kinds of checks:
1525/// * Memory checks - The code in canVectorizeMemory checks if vectorization
1526/// will change the order of memory accesses in a way that will change the
1527/// correctness of the program.
1528/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1529/// checks for a number of different conditions, such as the availability of a
1530/// single induction variable, that all types are supported and vectorize-able,
1531/// etc. This code reflects the capabilities of InnerLoopVectorizer.
1532/// This class is also used by InnerLoopVectorizer for identifying
1533/// induction variable and the different reduction variables.
1534class LoopVectorizationLegality {
1535public:
1536 LoopVectorizationLegality(
1537 Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT,
1538 TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F,
1539 const TargetTransformInfo *TTI,
1540 std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
1541 OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R,
1542 LoopVectorizeHints *H, DemandedBits *DB, AssumptionCache *AC)
1543 : TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT), GetLAA(GetLAA),
1544 ORE(ORE), InterleaveInfo(PSE, L, DT, LI), Requirements(R), Hints(H),
1545 DB(DB), AC(AC) {}
1546
1547 /// ReductionList contains the reduction descriptors for all
1548 /// of the reductions that were found in the loop.
1549 using ReductionList = DenseMap<PHINode *, RecurrenceDescriptor>;
1550
1551 /// InductionList saves induction variables and maps them to the
1552 /// induction descriptor.
1553 using InductionList = MapVector<PHINode *, InductionDescriptor>;
1554
1555 /// RecurrenceSet contains the phi nodes that are recurrences other than
1556 /// inductions and reductions.
1557 using RecurrenceSet = SmallPtrSet<const PHINode *, 8>;
1558
1559 /// Returns true if it is legal to vectorize this loop.
1560 /// This does not mean that it is profitable to vectorize this
1561 /// loop, only that it is legal to do so.
1562 bool canVectorize();
1563
1564 /// Returns the primary induction variable.
1565 PHINode *getPrimaryInduction() { return PrimaryInduction; }
1566
1567 /// Returns the reduction variables found in the loop.
1568 ReductionList *getReductionVars() { return &Reductions; }
1569
1570 /// Returns the induction variables found in the loop.
1571 InductionList *getInductionVars() { return &Inductions; }
1572
1573 /// Return the first-order recurrences found in the loop.
1574 RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
1575
1576 /// Return the set of instructions to sink to handle first-order recurrences.
1577 DenseMap<Instruction *, Instruction *> &getSinkAfter() { return SinkAfter; }
1578
1579 /// Returns the widest induction type.
1580 Type *getWidestInductionType() { return WidestIndTy; }
1581
1582 /// Returns True if V is a Phi node of an induction variable in this loop.
1583 bool isInductionPhi(const Value *V);
1584
1585 /// Returns True if V is a cast that is part of an induction def-use chain,
1586 /// and had been proven to be redundant under a runtime guard (in other
1587 /// words, the cast has the same SCEV expression as the induction phi).
1588 bool isCastedInductionVariable(const Value *V);
1589
1590 /// Returns True if V can be considered as an induction variable in this
1591 /// loop. V can be the induction phi, or some redundant cast in the def-use
1592 /// chain of the inducion phi.
1593 bool isInductionVariable(const Value *V);
1594
1595 /// Returns True if PN is a reduction variable in this loop.
1596 bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
1597
1598 /// Returns True if Phi is a first-order recurrence in this loop.
1599 bool isFirstOrderRecurrence(const PHINode *Phi);
1600
1601 /// Return true if the block BB needs to be predicated in order for the loop
1602 /// to be vectorized.
1603 bool blockNeedsPredication(BasicBlock *BB);
1604
1605 /// Check if this pointer is consecutive when vectorizing. This happens
1606 /// when the last index of the GEP is the induction variable, or that the
1607 /// pointer itself is an induction variable.
1608 /// This check allows us to vectorize A[idx] into a wide load/store.
1609 /// Returns:
1610 /// 0 - Stride is unknown or non-consecutive.
1611 /// 1 - Address is consecutive.
1612 /// -1 - Address is consecutive, and decreasing.
1613 /// NOTE: This method must only be used before modifying the original scalar
1614 /// loop. Do not use after invoking 'createVectorizedLoopSkeleton' (PR34965).
1615 int isConsecutivePtr(Value *Ptr);
1616
1617 /// Returns true if the value V is uniform within the loop.
1618 bool isUniform(Value *V);
1619
1620 /// Returns the information that we collected about runtime memory check.
1621 const RuntimePointerChecking *getRuntimePointerChecking() const {
1622 return LAI->getRuntimePointerChecking();
1623 }
1624
1625 const LoopAccessInfo *getLAI() const { return LAI; }
1626
1627 /// \brief Check if \p Instr belongs to any interleaved access group.
1628 bool isAccessInterleaved(Instruction *Instr) {
1629 return InterleaveInfo.isInterleaved(Instr);
1630 }
1631
1632 /// \brief Get the interleaved access group that \p Instr belongs to.
1633 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1634 return InterleaveInfo.getInterleaveGroup(Instr);
1635 }
1636
1637 /// \brief Returns true if an interleaved group requires a scalar iteration
1638 /// to handle accesses with gaps.
1639 bool requiresScalarEpilogue() const {
1640 return InterleaveInfo.requiresScalarEpilogue();
1641 }
1642
1643 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1644
1645 uint64_t getMaxSafeRegisterWidth() const {
1646 return LAI->getDepChecker().getMaxSafeRegisterWidth();
1647 }
1648
1649 bool hasStride(Value *V) { return LAI->hasStride(V); }
1650
1651 /// Returns true if vector representation of the instruction \p I
1652 /// requires mask.
1653 bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
1654
1655 unsigned getNumStores() const { return LAI->getNumStores(); }
1656 unsigned getNumLoads() const { return LAI->getNumLoads(); }
1657
1658 // Returns true if the NoNaN attribute is set on the function.
1659 bool hasFunNoNaNAttr() const { return HasFunNoNaNAttr; }
1660
1661private:
1662 /// Check if a single basic block loop is vectorizable.
1663 /// At this point we know that this is a loop with a constant trip count
1664 /// and we only need to check individual instructions.
1665 bool canVectorizeInstrs();
1666
1667 /// When we vectorize loops we may change the order in which
1668 /// we read and write from memory. This method checks if it is
1669 /// legal to vectorize the code, considering only memory constrains.
1670 /// Returns true if the loop is vectorizable
1671 bool canVectorizeMemory();
1672
1673 /// Return true if we can vectorize this loop using the IF-conversion
1674 /// transformation.
1675 bool canVectorizeWithIfConvert();
1676
1677 /// Return true if all of the instructions in the block can be speculatively
1678 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1679 /// and we know that we can read from them without segfault.
1680 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1681
1682 /// Updates the vectorization state by adding \p Phi to the inductions list.
1683 /// This can set \p Phi as the main induction of the loop if \p Phi is a
1684 /// better choice for the main induction than the existing one.
1685 void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
1686 SmallPtrSetImpl<Value *> &AllowedExit);
1687
1688 /// Create an analysis remark that explains why vectorization failed
1689 ///
1690 /// \p RemarkName is the identifier for the remark. If \p I is passed it is
1691 /// an instruction that prevents vectorization. Otherwise the loop is used
1692 /// for the location of the remark. \return the remark object that can be
1693 /// streamed to.
1694 OptimizationRemarkAnalysis
1695 createMissedAnalysis(StringRef RemarkName, Instruction *I = nullptr) const {
1696 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1697 RemarkName, TheLoop, I);
1698 }
1699
1700 /// \brief If an access has a symbolic strides, this maps the pointer value to
1701 /// the stride symbol.
1702 const ValueToValueMap *getSymbolicStrides() {
1703 // FIXME: Currently, the set of symbolic strides is sometimes queried before
1704 // it's collected. This happens from canVectorizeWithIfConvert, when the
1705 // pointer is checked to reference consecutive elements suitable for a
1706 // masked access.
1707 return LAI ? &LAI->getSymbolicStrides() : nullptr;
1708 }
1709
1710 /// The loop that we evaluate.
1711 Loop *TheLoop;
1712
1713 /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
1714 /// Applies dynamic knowledge to simplify SCEV expressions in the context
1715 /// of existing SCEV assumptions. The analysis will also add a minimal set
1716 /// of new predicates if this is required to enable vectorization and
1717 /// unrolling.
1718 PredicatedScalarEvolution &PSE;
1719
1720 /// Target Library Info.
1721 TargetLibraryInfo *TLI;
1722
1723 /// Target Transform Info
1724 const TargetTransformInfo *TTI;
1725
1726 /// Dominator Tree.
1727 DominatorTree *DT;
1728
1729 // LoopAccess analysis.
1730 std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1731
1732 // And the loop-accesses info corresponding to this loop. This pointer is
1733 // null until canVectorizeMemory sets it up.
1734 const LoopAccessInfo *LAI = nullptr;
1735
1736 /// Interface to emit optimization remarks.
1737 OptimizationRemarkEmitter *ORE;
1738
1739 /// The interleave access information contains groups of interleaved accesses
1740 /// with the same stride and close to each other.
1741 InterleavedAccessInfo InterleaveInfo;
1742
1743 // --- vectorization state --- //
1744
1745 /// Holds the primary induction variable. This is the counter of the
1746 /// loop.
1747 PHINode *PrimaryInduction = nullptr;
1748
1749 /// Holds the reduction variables.
1750 ReductionList Reductions;
1751
1752 /// Holds all of the induction variables that we found in the loop.
1753 /// Notice that inductions don't need to start at zero and that induction
1754 /// variables can be pointers.
1755 InductionList Inductions;
1756
1757 /// Holds all the casts that participate in the update chain of the induction
1758 /// variables, and that have been proven to be redundant (possibly under a
1759 /// runtime guard). These casts can be ignored when creating the vectorized
1760 /// loop body.
1761 SmallPtrSet<Instruction *, 4> InductionCastsToIgnore;
1762
1763 /// Holds the phi nodes that are first-order recurrences.
1764 RecurrenceSet FirstOrderRecurrences;
1765
1766 /// Holds instructions that need to sink past other instructions to handle
1767 /// first-order recurrences.
1768 DenseMap<Instruction *, Instruction *> SinkAfter;
1769
1770 /// Holds the widest induction type encountered.
1771 Type *WidestIndTy = nullptr;
1772
1773 /// Allowed outside users. This holds the induction and reduction
1774 /// vars which can be accessed from outside the loop.
1775 SmallPtrSet<Value *, 4> AllowedExit;
1776
1777 /// Can we assume the absence of NaNs.
1778 bool HasFunNoNaNAttr = false;
1779
1780 /// Vectorization requirements that will go through late-evaluation.
1781 LoopVectorizationRequirements *Requirements;
1782
1783 /// Used to emit an analysis of any legality issues.
1784 LoopVectorizeHints *Hints;
1785
1786 /// The demanded bits analsyis is used to compute the minimum type size in
1787 /// which a reduction can be computed.
1788 DemandedBits *DB;
1789
1790 /// The assumption cache analysis is used to compute the minimum type size in
1791 /// which a reduction can be computed.
1792 AssumptionCache *AC;
1793
1794 /// While vectorizing these instructions we have to generate a
1795 /// call to the appropriate masked intrinsic
1796 SmallPtrSet<const Instruction *, 8> MaskedOp;
1797};
1798
1799/// LoopVectorizationCostModel - estimates the expected speedups due to
1800/// vectorization.
1801/// In many cases vectorization is not profitable. This can happen because of
1802/// a number of reasons. In this class we mainly attempt to predict the
1803/// expected speedup/slowdowns due to the supported instruction set. We use the
1804/// TargetTransformInfo to query the different backends for the cost of
1805/// different operations.
1806class LoopVectorizationCostModel {
1807public:
1808 LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1809 LoopInfo *LI, LoopVectorizationLegality *Legal,
1810 const TargetTransformInfo &TTI,
1811 const TargetLibraryInfo *TLI, DemandedBits *DB,
1812 AssumptionCache *AC,
1813 OptimizationRemarkEmitter *ORE, const Function *F,
1814 const LoopVectorizeHints *Hints)
1815 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1816 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {}
1817
1818 /// \return An upper bound for the vectorization factor, or None if
1819 /// vectorization should be avoided up front.
1820 Optional<unsigned> computeMaxVF(bool OptForSize);
1821
1822 /// \return The most profitable vectorization factor and the cost of that VF.
1823 /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1824 /// then this vectorization factor will be selected if vectorization is
1825 /// possible.
1826 VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
1827
1828 /// Setup cost-based decisions for user vectorization factor.
1829 void selectUserVectorizationFactor(unsigned UserVF) {
1830 collectUniformsAndScalars(UserVF);
1831 collectInstsToScalarize(UserVF);
1832 }
1833
1834 /// \return The size (in bits) of the smallest and widest types in the code
1835 /// that needs to be vectorized. We ignore values that remain scalar such as
1836 /// 64 bit loop indices.
1837 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1838
1839 /// \return The desired interleave count.
1840 /// If interleave count has been specified by metadata it will be returned.
1841 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1842 /// are the selected vectorization factor and the cost of the selected VF.
1843 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1844 unsigned LoopCost);
1845
1846 /// Memory access instruction may be vectorized in more than one way.
1847 /// Form of instruction after vectorization depends on cost.
1848 /// This function takes cost-based decisions for Load/Store instructions
1849 /// and collects them in a map. This decisions map is used for building
1850 /// the lists of loop-uniform and loop-scalar instructions.
1851 /// The calculated cost is saved with widening decision in order to
1852 /// avoid redundant calculations.
1853 void setCostBasedWideningDecision(unsigned VF);
1854
1855 /// \brief A struct that represents some properties of the register usage
1856 /// of a loop.
1857 struct RegisterUsage {
1858 /// Holds the number of loop invariant values that are used in the loop.
1859 unsigned LoopInvariantRegs;
1860
1861 /// Holds the maximum number of concurrent live intervals in the loop.
1862 unsigned MaxLocalUsers;
1863
1864 /// Holds the number of instructions in the loop.
1865 unsigned NumInstructions;
1866 };
1867
1868 /// \return Returns information about the register usages of the loop for the
1869 /// given vectorization factors.
1870 SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1871
1872 /// Collect values we want to ignore in the cost model.
1873 void collectValuesToIgnore();
1874
1875 /// \returns The smallest bitwidth each instruction can be represented with.
1876 /// The vector equivalents of these instructions should be truncated to this
1877 /// type.
1878 const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1879 return MinBWs;
1880 }
1881
1882 /// \returns True if it is more profitable to scalarize instruction \p I for
1883 /// vectorization factor \p VF.
1884 bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
1885 assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.")(static_cast <bool> (VF > 1 && "Profitable to scalarize relevant only for VF > 1."
) ? void (0) : __assert_fail ("VF > 1 && \"Profitable to scalarize relevant only for VF > 1.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1885, __extension__ __PRETTY_FUNCTION__))
;
1886 auto Scalars = InstsToScalarize.find(VF);
1887 assert(Scalars != InstsToScalarize.end() &&(static_cast <bool> (Scalars != InstsToScalarize.end() &&
"VF not yet analyzed for scalarization profitability") ? void
(0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1888, __extension__ __PRETTY_FUNCTION__))
1888 "VF not yet analyzed for scalarization profitability")(static_cast <bool> (Scalars != InstsToScalarize.end() &&
"VF not yet analyzed for scalarization profitability") ? void
(0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1888, __extension__ __PRETTY_FUNCTION__))
;
1889 return Scalars->second.count(I);
1890 }
1891
1892 /// Returns true if \p I is known to be uniform after vectorization.
1893 bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
1894 if (VF == 1)
1895 return true;
1896 assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity")(static_cast <bool> (Uniforms.count(VF) && "VF not yet analyzed for uniformity"
) ? void (0) : __assert_fail ("Uniforms.count(VF) && \"VF not yet analyzed for uniformity\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1896, __extension__ __PRETTY_FUNCTION__))
;
1897 auto UniformsPerVF = Uniforms.find(VF);
1898 return UniformsPerVF->second.count(I);
1899 }
1900
1901 /// Returns true if \p I is known to be scalar after vectorization.
1902 bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
1903 if (VF == 1)
1904 return true;
1905 assert(Scalars.count(VF) && "Scalar values are not calculated for VF")(static_cast <bool> (Scalars.count(VF) && "Scalar values are not calculated for VF"
) ? void (0) : __assert_fail ("Scalars.count(VF) && \"Scalar values are not calculated for VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1905, __extension__ __PRETTY_FUNCTION__))
;
1906 auto ScalarsPerVF = Scalars.find(VF);
1907 return ScalarsPerVF->second.count(I);
1908 }
1909
1910 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1911 /// for vectorization factor \p VF.
1912 bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
1913 return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1914 !isScalarAfterVectorization(I, VF);
1915 }
1916
1917 /// Decision that was taken during cost calculation for memory instruction.
1918 enum InstWidening {
1919 CM_Unknown,
1920 CM_Widen, // For consecutive accesses with stride +1.
1921 CM_Widen_Reverse, // For consecutive accesses with stride -1.
1922 CM_Interleave,
1923 CM_GatherScatter,
1924 CM_Scalarize
1925 };
1926
1927 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1928 /// instruction \p I and vector width \p VF.
1929 void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
1930 unsigned Cost) {
1931 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1931, __extension__ __PRETTY_FUNCTION__))
;
1932 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1933 }
1934
1935 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1936 /// interleaving group \p Grp and vector width \p VF.
1937 void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
1938 InstWidening W, unsigned Cost) {
1939 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1939, __extension__ __PRETTY_FUNCTION__))
;
1940 /// Broadcast this decicion to all instructions inside the group.
1941 /// But the cost will be assigned to one instruction only.
1942 for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1943 if (auto *I = Grp->getMember(i)) {
1944 if (Grp->getInsertPos() == I)
1945 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1946 else
1947 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1948 }
1949 }
1950 }
1951
1952 /// Return the cost model decision for the given instruction \p I and vector
1953 /// width \p VF. Return CM_Unknown if this instruction did not pass
1954 /// through the cost modeling.
1955 InstWidening getWideningDecision(Instruction *I, unsigned VF) {
1956 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1956, __extension__ __PRETTY_FUNCTION__))
;
1957 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1958 auto Itr = WideningDecisions.find(InstOnVF);
1959 if (Itr == WideningDecisions.end())
1960 return CM_Unknown;
1961 return Itr->second.first;
1962 }
1963
1964 /// Return the vectorization cost for the given instruction \p I and vector
1965 /// width \p VF.
1966 unsigned getWideningCost(Instruction *I, unsigned VF) {
1967 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1967, __extension__ __PRETTY_FUNCTION__))
;
1968 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1969 assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated")(static_cast <bool> (WideningDecisions.count(InstOnVF) &&
"The cost is not calculated") ? void (0) : __assert_fail ("WideningDecisions.count(InstOnVF) && \"The cost is not calculated\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1969, __extension__ __PRETTY_FUNCTION__))
;
1970 return WideningDecisions[InstOnVF].second;
1971 }
1972
1973 /// Return True if instruction \p I is an optimizable truncate whose operand
1974 /// is an induction variable. Such a truncate will be removed by adding a new
1975 /// induction variable with the destination type.
1976 bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
1977 // If the instruction is not a truncate, return false.
1978 auto *Trunc = dyn_cast<TruncInst>(I);
1979 if (!Trunc)
1980 return false;
1981
1982 // Get the source and destination types of the truncate.
1983 Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1984 Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1985
1986 // If the truncate is free for the given types, return false. Replacing a
1987 // free truncate with an induction variable would add an induction variable
1988 // update instruction to each iteration of the loop. We exclude from this
1989 // check the primary induction variable since it will need an update
1990 // instruction regardless.
1991 Value *Op = Trunc->getOperand(0);
1992 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1993 return false;
1994
1995 // If the truncated value is not an induction variable, return false.
1996 return Legal->isInductionPhi(Op);
1997 }
1998
1999 /// Collects the instructions to scalarize for each predicated instruction in
2000 /// the loop.
2001 void collectInstsToScalarize(unsigned VF);
2002
2003 /// Collect Uniform and Scalar values for the given \p VF.
2004 /// The sets depend on CM decision for Load/Store instructions
2005 /// that may be vectorized as interleave, gather-scatter or scalarized.
2006 void collectUniformsAndScalars(unsigned VF) {
2007 // Do the analysis once.
2008 if (VF == 1 || Uniforms.count(VF))
2009 return;
2010 setCostBasedWideningDecision(VF);
2011 collectLoopUniforms(VF);
2012 collectLoopScalars(VF);
2013 }
2014
2015 /// Returns true if the target machine supports masked store operation
2016 /// for the given \p DataType and kind of access to \p Ptr.
2017 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
2018 return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType);
2019 }
2020
2021 /// Returns true if the target machine supports masked load operation
2022 /// for the given \p DataType and kind of access to \p Ptr.
2023 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
2024 return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType);
2025 }
2026
2027 /// Returns true if the target machine supports masked scatter operation
2028 /// for the given \p DataType.
2029 bool isLegalMaskedScatter(Type *DataType) {
2030 return TTI.isLegalMaskedScatter(DataType);
2031 }
2032
2033 /// Returns true if the target machine supports masked gather operation
2034 /// for the given \p DataType.
2035 bool isLegalMaskedGather(Type *DataType) {
2036 return TTI.isLegalMaskedGather(DataType);
2037 }
2038
2039 /// Returns true if the target machine can represent \p V as a masked gather
2040 /// or scatter operation.
2041 bool isLegalGatherOrScatter(Value *V) {
2042 bool LI = isa<LoadInst>(V);
2043 bool SI = isa<StoreInst>(V);
2044 if (!LI && !SI)
2045 return false;
2046 auto *Ty = getMemInstValueType(V);
2047 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
2048 }
2049
2050 /// Returns true if \p I is an instruction that will be scalarized with
2051 /// predication. Such instructions include conditional stores and
2052 /// instructions that may divide by zero.
2053 bool isScalarWithPredication(Instruction *I);
2054
2055 /// Returns true if \p I is a memory instruction with consecutive memory
2056 /// access that can be widened.
2057 bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
2058
2059private:
2060 unsigned NumPredStores = 0;
2061
2062 /// \return An upper bound for the vectorization factor, larger than zero.
2063 /// One is returned if vectorization should best be avoided due to cost.
2064 unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
2065
2066 /// The vectorization cost is a combination of the cost itself and a boolean
2067 /// indicating whether any of the contributing operations will actually
2068 /// operate on
2069 /// vector values after type legalization in the backend. If this latter value
2070 /// is
2071 /// false, then all operations will be scalarized (i.e. no vectorization has
2072 /// actually taken place).
2073 using VectorizationCostTy = std::pair<unsigned, bool>;
2074
2075 /// Returns the expected execution cost. The unit of the cost does
2076 /// not matter because we use the 'cost' units to compare different
2077 /// vector widths. The cost that is returned is *not* normalized by
2078 /// the factor width.
2079 VectorizationCostTy expectedCost(unsigned VF);
2080
2081 /// Returns the execution time cost of an instruction for a given vector
2082 /// width. Vector width of one means scalar.
2083 VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
2084
2085 /// The cost-computation logic from getInstructionCost which provides
2086 /// the vector type as an output parameter.
2087 unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
2088
2089 /// Calculate vectorization cost of memory instruction \p I.
2090 unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
2091
2092 /// The cost computation for scalarized memory instruction.
2093 unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
2094
2095 /// The cost computation for interleaving group of memory instructions.
2096 unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
2097
2098 /// The cost computation for Gather/Scatter instruction.
2099 unsigned getGatherScatterCost(Instruction *I, unsigned VF);
2100
2101 /// The cost computation for widening instruction \p I with consecutive
2102 /// memory access.
2103 unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
2104
2105 /// The cost calculation for Load instruction \p I with uniform pointer -
2106 /// scalar load + broadcast.
2107 unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
2108
2109 /// Returns whether the instruction is a load or store and will be a emitted
2110 /// as a vector operation.
2111 bool isConsecutiveLoadOrStore(Instruction *I);
2112
2113 /// Returns true if an artificially high cost for emulated masked memrefs
2114 /// should be used.
2115 bool useEmulatedMaskMemRefHack(Instruction *I);
2116
2117 /// Create an analysis remark that explains why vectorization failed
2118 ///
2119 /// \p RemarkName is the identifier for the remark. \return the remark object
2120 /// that can be streamed to.
2121 OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
2122 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
2123 RemarkName, TheLoop);
2124 }
2125
2126 /// Map of scalar integer values to the smallest bitwidth they can be legally
2127 /// represented as. The vector equivalents of these values should be truncated
2128 /// to this type.
2129 MapVector<Instruction *, uint64_t> MinBWs;
2130
2131 /// A type representing the costs for instructions if they were to be
2132 /// scalarized rather than vectorized. The entries are Instruction-Cost
2133 /// pairs.
2134 using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
2135
2136 /// A set containing all BasicBlocks that are known to present after
2137 /// vectorization as a predicated block.
2138 SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
2139
2140 /// A map holding scalar costs for different vectorization factors. The
2141 /// presence of a cost for an instruction in the mapping indicates that the
2142 /// instruction will be scalarized when vectorizing with the associated
2143 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
2144 DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
2145
2146 /// Holds the instructions known to be uniform after vectorization.
2147 /// The data is collected per VF.
2148 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
2149
2150 /// Holds the instructions known to be scalar after vectorization.
2151 /// The data is collected per VF.
2152 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
2153
2154 /// Holds the instructions (address computations) that are forced to be
2155 /// scalarized.
2156 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
2157
2158 /// Returns the expected difference in cost from scalarizing the expression
2159 /// feeding a predicated instruction \p PredInst. The instructions to
2160 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
2161 /// non-negative return value implies the expression will be scalarized.
2162 /// Currently, only single-use chains are considered for scalarization.
2163 int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
2164 unsigned VF);
2165
2166 /// Collect the instructions that are uniform after vectorization. An
2167 /// instruction is uniform if we represent it with a single scalar value in
2168 /// the vectorized loop corresponding to each vector iteration. Examples of
2169 /// uniform instructions include pointer operands of consecutive or
2170 /// interleaved memory accesses. Note that although uniformity implies an
2171 /// instruction will be scalar, the reverse is not true. In general, a
2172 /// scalarized instruction will be represented by VF scalar values in the
2173 /// vectorized loop, each corresponding to an iteration of the original
2174 /// scalar loop.
2175 void collectLoopUniforms(unsigned VF);
2176
2177 /// Collect the instructions that are scalar after vectorization. An
2178 /// instruction is scalar if it is known to be uniform or will be scalarized
2179 /// during vectorization. Non-uniform scalarized instructions will be
2180 /// represented by VF values in the vectorized loop, each corresponding to an
2181 /// iteration of the original scalar loop.
2182 void collectLoopScalars(unsigned VF);
2183
2184 /// Keeps cost model vectorization decision and cost for instructions.
2185 /// Right now it is used for memory instructions only.
2186 using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
2187 std::pair<InstWidening, unsigned>>;
2188
2189 DecisionList WideningDecisions;
2190
2191public:
2192 /// The loop that we evaluate.
2193 Loop *TheLoop;
2194
2195 /// Predicated scalar evolution analysis.
2196 PredicatedScalarEvolution &PSE;
2197
2198 /// Loop Info analysis.
2199 LoopInfo *LI;
2200
2201 /// Vectorization legality.
2202 LoopVectorizationLegality *Legal;
2203
2204 /// Vector target information.
2205 const TargetTransformInfo &TTI;
2206
2207 /// Target Library Info.
2208 const TargetLibraryInfo *TLI;
2209
2210 /// Demanded bits analysis.
2211 DemandedBits *DB;
2212
2213 /// Assumption cache.
2214 AssumptionCache *AC;
2215
2216 /// Interface to emit optimization remarks.
2217 OptimizationRemarkEmitter *ORE;
2218
2219 const Function *TheFunction;
2220
2221 /// Loop Vectorize Hint.
2222 const LoopVectorizeHints *Hints;
2223
2224 /// Values to ignore in the cost model.
2225 SmallPtrSet<const Value *, 16> ValuesToIgnore;
2226
2227 /// Values to ignore in the cost model when VF > 1.
2228 SmallPtrSet<const Value *, 16> VecValuesToIgnore;
2229};
2230
2231} // end namespace llvm
2232
2233namespace {
2234
2235/// \brief This holds vectorization requirements that must be verified late in
2236/// the process. The requirements are set by legalize and costmodel. Once
2237/// vectorization has been determined to be possible and profitable the
2238/// requirements can be verified by looking for metadata or compiler options.
2239/// For example, some loops require FP commutativity which is only allowed if
2240/// vectorization is explicitly specified or if the fast-math compiler option
2241/// has been provided.
2242/// Late evaluation of these requirements allows helpful diagnostics to be
2243/// composed that tells the user what need to be done to vectorize the loop. For
2244/// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
2245/// evaluation should be used only when diagnostics can generated that can be
2246/// followed by a non-expert user.
2247class LoopVectorizationRequirements {
2248public:
2249 LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE) : ORE(ORE) {}
2250
2251 void addUnsafeAlgebraInst(Instruction *I) {
2252 // First unsafe algebra instruction.
2253 if (!UnsafeAlgebraInst)
2254 UnsafeAlgebraInst = I;
2255 }
2256
2257 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
2258
2259 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
2260 const char *PassName = Hints.vectorizeAnalysisPassName();
2261 bool Failed = false;
2262 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
2263 ORE.emit([&]() {
2264 return OptimizationRemarkAnalysisFPCommute(
2265 PassName, "CantReorderFPOps",
2266 UnsafeAlgebraInst->getDebugLoc(),
2267 UnsafeAlgebraInst->getParent())
2268 << "loop not vectorized: cannot prove it is safe to reorder "
2269 "floating-point operations";
2270 });
2271 Failed = true;
2272 }
2273
2274 // Test if runtime memcheck thresholds are exceeded.
2275 bool PragmaThresholdReached =
2276 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
2277 bool ThresholdReached =
2278 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
2279 if ((ThresholdReached && !Hints.allowReordering()) ||
2280 PragmaThresholdReached) {
2281 ORE.emit([&]() {
2282 return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
2283 L->getStartLoc(),
2284 L->getHeader())
2285 << "loop not vectorized: cannot prove it is safe to reorder "
2286 "memory operations";
2287 });
2288 DEBUG(dbgs() << "LV: Too many memory checks needed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Too many memory checks needed.\n"
; } } while (false)
;
2289 Failed = true;
2290 }
2291
2292 return Failed;
2293 }
2294
2295private:
2296 unsigned NumRuntimePointerChecks = 0;
2297 Instruction *UnsafeAlgebraInst = nullptr;
2298
2299 /// Interface to emit optimization remarks.
2300 OptimizationRemarkEmitter &ORE;
2301};
2302
2303} // end anonymous namespace
2304
2305static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
2306 if (L.empty()) {
2307 if (!hasCyclesInLoopBody(L))
2308 V.push_back(&L);
2309 return;
2310 }
2311 for (Loop *InnerL : L)
2312 addAcyclicInnerLoop(*InnerL, V);
2313}
2314
2315namespace {
2316
2317/// The LoopVectorize Pass.
2318struct LoopVectorize : public FunctionPass {
2319 /// Pass identification, replacement for typeid
2320 static char ID;
2321
2322 LoopVectorizePass Impl;
2323
2324 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
2325 : FunctionPass(ID) {
2326 Impl.DisableUnrolling = NoUnrolling;
2327 Impl.AlwaysVectorize = AlwaysVectorize;
2328 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2329 }
2330
2331 bool runOnFunction(Function &F) override {
2332 if (skipFunction(F))
2333 return false;
2334
2335 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2336 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2337 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2338 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2339 auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2340 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2341 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2342 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2343 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2344 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2345 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2346 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2347
2348 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2349 [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2350
2351 return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2352 GetLAA, *ORE);
2353 }
2354
2355 void getAnalysisUsage(AnalysisUsage &AU) const override {
2356 AU.addRequired<AssumptionCacheTracker>();
2357 AU.addRequired<BlockFrequencyInfoWrapperPass>();
2358 AU.addRequired<DominatorTreeWrapperPass>();
2359 AU.addRequired<LoopInfoWrapperPass>();
2360 AU.addRequired<ScalarEvolutionWrapperPass>();
2361 AU.addRequired<TargetTransformInfoWrapperPass>();
2362 AU.addRequired<AAResultsWrapperPass>();
2363 AU.addRequired<LoopAccessLegacyAnalysis>();
2364 AU.addRequired<DemandedBitsWrapperPass>();
2365 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2366 AU.addPreserved<LoopInfoWrapperPass>();
2367 AU.addPreserved<DominatorTreeWrapperPass>();
2368 AU.addPreserved<BasicAAWrapperPass>();
2369 AU.addPreserved<GlobalsAAWrapperPass>();
2370 }
2371};
2372
2373} // end anonymous namespace
2374
2375//===----------------------------------------------------------------------===//
2376// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2377// LoopVectorizationCostModel and LoopVectorizationPlanner.
2378//===----------------------------------------------------------------------===//
2379
2380Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2381 // We need to place the broadcast of invariant variables outside the loop.
2382 Instruction *Instr = dyn_cast<Instruction>(V);
2383 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
2384 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
2385
2386 // Place the code for broadcasting invariant variables in the new preheader.
2387 IRBuilder<>::InsertPointGuard Guard(Builder);
2388 if (Invariant)
2389 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2390
2391 // Broadcast the scalar into all locations in the vector.
2392 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2393
2394 return Shuf;
2395}
2396
2397void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2398 const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
2399 Value *Start = II.getStartValue();
2400
2401 // Construct the initial value of the vector IV in the vector loop preheader
2402 auto CurrIP = Builder.saveIP();
2403 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2404 if (isa<TruncInst>(EntryVal)) {
2405 assert(Start->getType()->isIntegerTy() &&(static_cast <bool> (Start->getType()->isIntegerTy
() && "Truncation requires an integer type") ? void (
0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2406, __extension__ __PRETTY_FUNCTION__))
2406 "Truncation requires an integer type")(static_cast <bool> (Start->getType()->isIntegerTy
() && "Truncation requires an integer type") ? void (
0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2406, __extension__ __PRETTY_FUNCTION__))
;
2407 auto *TruncType = cast<IntegerType>(EntryVal->getType());
2408 Step = Builder.CreateTrunc(Step, TruncType);
2409 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2410 }
2411 Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2412 Value *SteppedStart =
2413 getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2414
2415 // We create vector phi nodes for both integer and floating-point induction
2416 // variables. Here, we determine the kind of arithmetic we will perform.
2417 Instruction::BinaryOps AddOp;
2418 Instruction::BinaryOps MulOp;
2419 if (Step->getType()->isIntegerTy()) {
2420 AddOp = Instruction::Add;
2421 MulOp = Instruction::Mul;
2422 } else {
2423 AddOp = II.getInductionOpcode();
2424 MulOp = Instruction::FMul;
2425 }
2426
2427 // Multiply the vectorization factor by the step using integer or
2428 // floating-point arithmetic as appropriate.
2429 Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
2430 Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
2431
2432 // Create a vector splat to use in the induction update.
2433 //
2434 // FIXME: If the step is non-constant, we create the vector splat with
2435 // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2436 // handle a constant vector splat.
2437 Value *SplatVF = isa<Constant>(Mul)
2438 ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2439 : Builder.CreateVectorSplat(VF, Mul);
2440 Builder.restoreIP(CurrIP);
2441
2442 // We may need to add the step a number of times, depending on the unroll
2443 // factor. The last of those goes into the PHI.
2444 PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2445 &*LoopVectorBody->getFirstInsertionPt());
2446 Instruction *LastInduction = VecInd;
2447 for (unsigned Part = 0; Part < UF; ++Part) {
2448 VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
2449
2450 if (isa<TruncInst>(EntryVal))
2451 addMetadata(LastInduction, EntryVal);
2452 else
2453 recordVectorLoopValueForInductionCast(II, LastInduction, Part);
2454
2455 LastInduction = cast<Instruction>(addFastMathFlag(
2456 Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
2457 }
2458
2459 // Move the last step to the end of the latch block. This ensures consistent
2460 // placement of all induction updates.
2461 auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2462 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2463 auto *ICmp = cast<Instruction>(Br->getCondition());
2464 LastInduction->moveBefore(ICmp);
2465 LastInduction->setName("vec.ind.next");
2466
2467 VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2468 VecInd->addIncoming(LastInduction, LoopVectorLatch);
2469}
2470
2471bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2472 return Cost->isScalarAfterVectorization(I, VF) ||
2473 Cost->isProfitableToScalarize(I, VF);
2474}
2475
2476bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2477 if (shouldScalarizeInstruction(IV))
2478 return true;
2479 auto isScalarInst = [&](User *U) -> bool {
2480 auto *I = cast<Instruction>(U);
2481 return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2482 };
2483 return llvm::any_of(IV->users(), isScalarInst);
2484}
2485
2486void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2487 const InductionDescriptor &ID, Value *VectorLoopVal, unsigned Part,
2488 unsigned Lane) {
2489 const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2490 if (Casts.empty())
2491 return;
2492 // Only the first Cast instruction in the Casts vector is of interest.
2493 // The rest of the Casts (if exist) have no uses outside the
2494 // induction update chain itself.
2495 Instruction *CastInst = *Casts.begin();
2496 if (Lane < UINT_MAX(2147483647 *2U +1U))
2497 VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
2498 else
2499 VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
2500}
2501
2502void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
2503 assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&(static_cast <bool> ((IV->getType()->isIntegerTy(
) || IV != OldInduction) && "Primary induction variable must have an integer type"
) ? void (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2504, __extension__ __PRETTY_FUNCTION__))
2504 "Primary induction variable must have an integer type")(static_cast <bool> ((IV->getType()->isIntegerTy(
) || IV != OldInduction) && "Primary induction variable must have an integer type"
) ? void (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2504, __extension__ __PRETTY_FUNCTION__))
;
2505
2506 auto II = Legal->getInductionVars()->find(IV);
2507 assert(II != Legal->getInductionVars()->end() && "IV is not an induction")(static_cast <bool> (II != Legal->getInductionVars()
->end() && "IV is not an induction") ? void (0) : __assert_fail
("II != Legal->getInductionVars()->end() && \"IV is not an induction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2507, __extension__ __PRETTY_FUNCTION__))
;
2508
2509 auto ID = II->second;
2510 assert(IV->getType() == ID.getStartValue()->getType() && "Types must match")(static_cast <bool> (IV->getType() == ID.getStartValue
()->getType() && "Types must match") ? void (0) : __assert_fail
("IV->getType() == ID.getStartValue()->getType() && \"Types must match\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2510, __extension__ __PRETTY_FUNCTION__))
;
2511
2512 // The scalar value to broadcast. This will be derived from the canonical
2513 // induction variable.
2514 Value *ScalarIV = nullptr;
2515
2516 // The value from the original loop to which we are mapping the new induction
2517 // variable.
2518 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2519
2520 // True if we have vectorized the induction variable.
2521 auto VectorizedIV = false;
2522
2523 // Determine if we want a scalar version of the induction variable. This is
2524 // true if the induction variable itself is not widened, or if it has at
2525 // least one user in the loop that is not widened.
2526 auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
2527
2528 // Generate code for the induction step. Note that induction steps are
2529 // required to be loop-invariant
2530 assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&(static_cast <bool> (PSE.getSE()->isLoopInvariant(ID
.getStep(), OrigLoop) && "Induction step should be loop invariant"
) ? void (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2531, __extension__ __PRETTY_FUNCTION__))
2531 "Induction step should be loop invariant")(static_cast <bool> (PSE.getSE()->isLoopInvariant(ID
.getStep(), OrigLoop) && "Induction step should be loop invariant"
) ? void (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2531, __extension__ __PRETTY_FUNCTION__))
;
2532 auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2533 Value *Step = nullptr;
2534 if (PSE.getSE()->isSCEVable(IV->getType())) {
2535 SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2536 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2537 LoopVectorPreHeader->getTerminator());
2538 } else {
2539 Step = cast<SCEVUnknown>(ID.getStep())->getValue();
2540 }
2541
2542 // Try to create a new independent vector induction variable. If we can't
2543 // create the phi node, we will splat the scalar induction variable in each
2544 // loop iteration.
2545 if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
2546 createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2547 VectorizedIV = true;
2548 }
2549
2550 // If we haven't yet vectorized the induction variable, or if we will create
2551 // a scalar one, we need to define the scalar induction variable and step
2552 // values. If we were given a truncation type, truncate the canonical
2553 // induction variable and step. Otherwise, derive these values from the
2554 // induction descriptor.
2555 if (!VectorizedIV || NeedsScalarIV) {
2556 ScalarIV = Induction;
2557 if (IV != OldInduction) {
2558 ScalarIV = IV->getType()->isIntegerTy()
2559 ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2560 : Builder.CreateCast(Instruction::SIToFP, Induction,
2561 IV->getType());
2562 ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
2563 ScalarIV->setName("offset.idx");
2564 }
2565 if (Trunc) {
2566 auto *TruncType = cast<IntegerType>(Trunc->getType());
2567 assert(Step->getType()->isIntegerTy() &&(static_cast <bool> (Step->getType()->isIntegerTy
() && "Truncation requires an integer step") ? void (
0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2568, __extension__ __PRETTY_FUNCTION__))
2568 "Truncation requires an integer step")(static_cast <bool> (Step->getType()->isIntegerTy
() && "Truncation requires an integer step") ? void (
0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2568, __extension__ __PRETTY_FUNCTION__))
;
2569 ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2570 Step = Builder.CreateTrunc(Step, TruncType);
2571 }
2572 }
2573
2574 // If we haven't yet vectorized the induction variable, splat the scalar
2575 // induction variable, and build the necessary step vectors.
2576 // TODO: Don't do it unless the vectorized IV is really required.
2577 if (!VectorizedIV) {
2578 Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2579 for (unsigned Part = 0; Part < UF; ++Part) {
2580 Value *EntryPart =
2581 getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
2582 VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
2583 if (Trunc)
2584 addMetadata(EntryPart, Trunc);
2585 else
2586 recordVectorLoopValueForInductionCast(ID, EntryPart, Part);
2587 }
2588 }
2589
2590 // If an induction variable is only used for counting loop iterations or
2591 // calculating addresses, it doesn't need to be widened. Create scalar steps
2592 // that can be used by instructions we will later scalarize. Note that the
2593 // addition of the scalar steps will not increase the number of instructions
2594 // in the loop in the common case prior to InstCombine. We will be trading
2595 // one vector extract for each scalar step.
2596 if (NeedsScalarIV)
2597 buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2598}
2599
2600Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2601 Instruction::BinaryOps BinOp) {
2602 // Create and check the types.
2603 assert(Val->getType()->isVectorTy() && "Must be a vector")(static_cast <bool> (Val->getType()->isVectorTy()
&& "Must be a vector") ? void (0) : __assert_fail ("Val->getType()->isVectorTy() && \"Must be a vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2603, __extension__ __PRETTY_FUNCTION__))
;
2604 int VLen = Val->getType()->getVectorNumElements();
2605
2606 Type *STy = Val->getType()->getScalarType();
2607 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&(static_cast <bool> ((STy->isIntegerTy() || STy->
isFloatingPointTy()) && "Induction Step must be an integer or FP"
) ? void (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2608, __extension__ __PRETTY_FUNCTION__))
2608 "Induction Step must be an integer or FP")(static_cast <bool> ((STy->isIntegerTy() || STy->
isFloatingPointTy()) && "Induction Step must be an integer or FP"
) ? void (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2608, __extension__ __PRETTY_FUNCTION__))
;
2609 assert(Step->getType() == STy && "Step has wrong type")(static_cast <bool> (Step->getType() == STy &&
"Step has wrong type") ? void (0) : __assert_fail ("Step->getType() == STy && \"Step has wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2609, __extension__ __PRETTY_FUNCTION__))
;
2610
2611 SmallVector<Constant *, 8> Indices;
2612
2613 if (STy->isIntegerTy()) {
2614 // Create a vector of consecutive numbers from zero to VF.
2615 for (int i = 0; i < VLen; ++i)
2616 Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2617
2618 // Add the consecutive indices to the vector value.
2619 Constant *Cv = ConstantVector::get(Indices);
2620 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec")(static_cast <bool> (Cv->getType() == Val->getType
() && "Invalid consecutive vec") ? void (0) : __assert_fail
("Cv->getType() == Val->getType() && \"Invalid consecutive vec\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2620, __extension__ __PRETTY_FUNCTION__))
;
2621 Step = Builder.CreateVectorSplat(VLen, Step);
2622 assert(Step->getType() == Val->getType() && "Invalid step vec")(static_cast <bool> (Step->getType() == Val->getType
() && "Invalid step vec") ? void (0) : __assert_fail (
"Step->getType() == Val->getType() && \"Invalid step vec\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2622, __extension__ __PRETTY_FUNCTION__))
;
2623 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2624 // which can be found from the original scalar operations.
2625 Step = Builder.CreateMul(Cv, Step);
2626 return Builder.CreateAdd(Val, Step, "induction");
2627 }
2628
2629 // Floating point induction.
2630 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&(static_cast <bool> ((BinOp == Instruction::FAdd || BinOp
== Instruction::FSub) && "Binary Opcode should be specified for FP induction"
) ? void (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2631, __extension__ __PRETTY_FUNCTION__))
2631 "Binary Opcode should be specified for FP induction")(static_cast <bool> ((BinOp == Instruction::FAdd || BinOp
== Instruction::FSub) && "Binary Opcode should be specified for FP induction"
) ? void (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2631, __extension__ __PRETTY_FUNCTION__))
;
2632 // Create a vector of consecutive numbers from zero to VF.
2633 for (int i = 0; i < VLen; ++i)
2634 Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2635
2636 // Add the consecutive indices to the vector value.
2637 Constant *Cv = ConstantVector::get(Indices);
2638
2639 Step = Builder.CreateVectorSplat(VLen, Step);
2640
2641 // Floating point operations had to be 'fast' to enable the induction.
2642 FastMathFlags Flags;
2643 Flags.setFast();
2644
2645 Value *MulOp = Builder.CreateFMul(Cv, Step);
2646 if (isa<Instruction>(MulOp))
2647 // Have to check, MulOp may be a constant
2648 cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2649
2650 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2651 if (isa<Instruction>(BOp))
2652 cast<Instruction>(BOp)->setFastMathFlags(Flags);
2653 return BOp;
2654}
2655
2656void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2657 Value *EntryVal,
2658 const InductionDescriptor &ID) {
2659 // We shouldn't have to build scalar steps if we aren't vectorizing.
2660 assert(VF > 1 && "VF should be greater than one")(static_cast <bool> (VF > 1 && "VF should be greater than one"
) ? void (0) : __assert_fail ("VF > 1 && \"VF should be greater than one\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2660, __extension__ __PRETTY_FUNCTION__))
;
2661
2662 // Get the value type and ensure it and the step have the same integer type.
2663 Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2664 assert(ScalarIVTy == Step->getType() &&(static_cast <bool> (ScalarIVTy == Step->getType() &&
"Val and Step should have the same type") ? void (0) : __assert_fail
("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2665, __extension__ __PRETTY_FUNCTION__))
2665 "Val and Step should have the same type")(static_cast <bool> (ScalarIVTy == Step->getType() &&
"Val and Step should have the same type") ? void (0) : __assert_fail
("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2665, __extension__ __PRETTY_FUNCTION__))
;
2666
2667 // We build scalar steps for both integer and floating-point induction
2668 // variables. Here, we determine the kind of arithmetic we will perform.
2669 Instruction::BinaryOps AddOp;
2670 Instruction::BinaryOps MulOp;
2671 if (ScalarIVTy->isIntegerTy()) {
2672 AddOp = Instruction::Add;
2673 MulOp = Instruction::Mul;
2674 } else {
2675 AddOp = ID.getInductionOpcode();
2676 MulOp = Instruction::FMul;
2677 }
2678
2679 // Determine the number of scalars we need to generate for each unroll
2680 // iteration. If EntryVal is uniform, we only need to generate the first
2681 // lane. Otherwise, we generate all VF values.
2682 unsigned Lanes =
2683 Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
2684 : VF;
2685 // Compute the scalar steps and save the results in VectorLoopValueMap.
2686 for (unsigned Part = 0; Part < UF; ++Part) {
2687 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2688 auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2689 auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2690 auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2691 VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
2692 recordVectorLoopValueForInductionCast(ID, Add, Part, Lane);
2693 }
2694 }
2695}
2696
2697int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2698 const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() :
2699 ValueToValueMap();
2700
2701 int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
2702 if (Stride == 1 || Stride == -1)
2703 return Stride;
2704 return 0;
2705}
2706
2707bool LoopVectorizationLegality::isUniform(Value *V) {
2708 return LAI->isUniform(V);
2709}
2710
2711Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
2712 assert(V != Induction && "The new induction variable should not be used.")(static_cast <bool> (V != Induction && "The new induction variable should not be used."
) ? void (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2712, __extension__ __PRETTY_FUNCTION__))
;
2713 assert(!V->getType()->isVectorTy() && "Can't widen a vector")(static_cast <bool> (!V->getType()->isVectorTy() &&
"Can't widen a vector") ? void (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't widen a vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
;
2714 assert(!V->getType()->isVoidTy() && "Type does not produce a value")(static_cast <bool> (!V->getType()->isVoidTy() &&
"Type does not produce a value") ? void (0) : __assert_fail (
"!V->getType()->isVoidTy() && \"Type does not produce a value\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2714, __extension__ __PRETTY_FUNCTION__))
;
2715
2716 // If we have a stride that is replaced by one, do it here.
2717 if (Legal->hasStride(V))
2718 V = ConstantInt::get(V->getType(), 1);
2719
2720 // If we have a vector mapped to this value, return it.
2721 if (VectorLoopValueMap.hasVectorValue(V, Part))
2722 return VectorLoopValueMap.getVectorValue(V, Part);
2723
2724 // If the value has not been vectorized, check if it has been scalarized
2725 // instead. If it has been scalarized, and we actually need the value in
2726 // vector form, we will construct the vector values on demand.
2727 if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2728 Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
2729
2730 // If we've scalarized a value, that value should be an instruction.
2731 auto *I = cast<Instruction>(V);
2732
2733 // If we aren't vectorizing, we can just copy the scalar map values over to
2734 // the vector map.
2735 if (VF == 1) {
2736 VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2737 return ScalarValue;
2738 }
2739
2740 // Get the last scalar instruction we generated for V and Part. If the value
2741 // is known to be uniform after vectorization, this corresponds to lane zero
2742 // of the Part unroll iteration. Otherwise, the last instruction is the one
2743 // we created for the last vector lane of the Part unroll iteration.
2744 unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2745 auto *LastInst = cast<Instruction>(
2746 VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
2747
2748 // Set the insert point after the last scalarized instruction. This ensures
2749 // the insertelement sequence will directly follow the scalar definitions.
2750 auto OldIP = Builder.saveIP();
2751 auto NewIP = std::next(BasicBlock::iterator(LastInst));
2752 Builder.SetInsertPoint(&*NewIP);
2753
2754 // However, if we are vectorizing, we need to construct the vector values.
2755 // If the value is known to be uniform after vectorization, we can just
2756 // broadcast the scalar value corresponding to lane zero for each unroll
2757 // iteration. Otherwise, we construct the vector values using insertelement
2758 // instructions. Since the resulting vectors are stored in
2759 // VectorLoopValueMap, we will only generate the insertelements once.
2760 Value *VectorValue = nullptr;
2761 if (Cost->isUniformAfterVectorization(I, VF)) {
2762 VectorValue = getBroadcastInstrs(ScalarValue);
2763 VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2764 } else {
2765 // Initialize packing with insertelements to start from undef.
2766 Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
2767 VectorLoopValueMap.setVectorValue(V, Part, Undef);
2768 for (unsigned Lane = 0; Lane < VF; ++Lane)
2769 packScalarIntoVectorValue(V, {Part, Lane});
2770 VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2771 }
2772 Builder.restoreIP(OldIP);
2773 return VectorValue;
2774 }
2775
2776 // If this scalar is unknown, assume that it is a constant or that it is
2777 // loop invariant. Broadcast V and save the value for future uses.
2778 Value *B = getBroadcastInstrs(V);
2779 VectorLoopValueMap.setVectorValue(V, Part, B);
2780 return B;
2781}
2782
2783Value *
2784InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
2785 const VPIteration &Instance) {
2786 // If the value is not an instruction contained in the loop, it should
2787 // already be scalar.
2788 if (OrigLoop->isLoopInvariant(V))
2789 return V;
2790
2791 assert(Instance.Lane > 0(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2793, __extension__ __PRETTY_FUNCTION__))
2792 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2793, __extension__ __PRETTY_FUNCTION__))
2793 : true && "Uniform values only have lane zero")(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2793, __extension__ __PRETTY_FUNCTION__))
;
2794
2795 // If the value from the original loop has not been vectorized, it is
2796 // represented by UF x VF scalar values in the new loop. Return the requested
2797 // scalar value.
2798 if (VectorLoopValueMap.hasScalarValue(V, Instance))
2799 return VectorLoopValueMap.getScalarValue(V, Instance);
2800
2801 // If the value has not been scalarized, get its entry in VectorLoopValueMap
2802 // for the given unroll part. If this entry is not a vector type (i.e., the
2803 // vectorization factor is one), there is no need to generate an
2804 // extractelement instruction.
2805 auto *U = getOrCreateVectorValue(V, Instance.Part);
2806 if (!U->getType()->isVectorTy()) {
2807 assert(VF == 1 && "Value not scalarized has non-vector type")(static_cast <bool> (VF == 1 && "Value not scalarized has non-vector type"
) ? void (0) : __assert_fail ("VF == 1 && \"Value not scalarized has non-vector type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2807, __extension__ __PRETTY_FUNCTION__))
;
2808 return U;
2809 }
2810
2811 // Otherwise, the value from the original loop has been vectorized and is
2812 // represented by UF vector values. Extract and return the requested scalar
2813 // value from the appropriate vector lane.
2814 return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2815}
2816
2817void InnerLoopVectorizer::packScalarIntoVectorValue(
2818 Value *V, const VPIteration &Instance) {
2819 assert(V != Induction && "The new induction variable should not be used.")(static_cast <bool> (V != Induction && "The new induction variable should not be used."
) ? void (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2819, __extension__ __PRETTY_FUNCTION__))
;
2820 assert(!V->getType()->isVectorTy() && "Can't pack a vector")(static_cast <bool> (!V->getType()->isVectorTy() &&
"Can't pack a vector") ? void (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't pack a vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2820, __extension__ __PRETTY_FUNCTION__))
;
2821 assert(!V->getType()->isVoidTy() && "Type does not produce a value")(static_cast <bool> (!V->getType()->isVoidTy() &&
"Type does not produce a value") ? void (0) : __assert_fail (
"!V->getType()->isVoidTy() && \"Type does not produce a value\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2821, __extension__ __PRETTY_FUNCTION__))
;
2822
2823 Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2824 Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2825 VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2826 Builder.getInt32(Instance.Lane));
2827 VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2828}
2829
2830Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2831 assert(Vec->getType()->isVectorTy() && "Invalid type")(static_cast <bool> (Vec->getType()->isVectorTy()
&& "Invalid type") ? void (0) : __assert_fail ("Vec->getType()->isVectorTy() && \"Invalid type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2831, __extension__ __PRETTY_FUNCTION__))
;
2832 SmallVector<Constant *, 8> ShuffleMask;
2833 for (unsigned i = 0; i < VF; ++i)
2834 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2835
2836 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2837 ConstantVector::get(ShuffleMask),
2838 "reverse");
2839}
2840
2841// Try to vectorize the interleave group that \p Instr belongs to.
2842//
2843// E.g. Translate following interleaved load group (factor = 3):
2844// for (i = 0; i < N; i+=3) {
2845// R = Pic[i]; // Member of index 0
2846// G = Pic[i+1]; // Member of index 1
2847// B = Pic[i+2]; // Member of index 2
2848// ... // do something to R, G, B
2849// }
2850// To:
2851// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2852// %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2853// %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2854// %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2855//
2856// Or translate following interleaved store group (factor = 3):
2857// for (i = 0; i < N; i+=3) {
2858// ... do something to R, G, B
2859// Pic[i] = R; // Member of index 0
2860// Pic[i+1] = G; // Member of index 1
2861// Pic[i+2] = B; // Member of index 2
2862// }
2863// To:
2864// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2865// %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2866// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2867// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2868// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2869void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2870 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2871 assert(Group && "Fail to get an interleaved access group.")(static_cast <bool> (Group && "Fail to get an interleaved access group."
) ? void (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2871, __extension__ __PRETTY_FUNCTION__))
;
2872
2873 // Skip if current instruction is not the insert position.
2874 if (Instr != Group->getInsertPos())
2875 return;
2876
2877 const DataLayout &DL = Instr->getModule()->getDataLayout();
2878 Value *Ptr = getPointerOperand(Instr);
2879
2880 // Prepare for the vector type of the interleaved load/store.
2881 Type *ScalarTy = getMemInstValueType(Instr);
2882 unsigned InterleaveFactor = Group->getFactor();
2883 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2884 Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2885
2886 // Prepare for the new pointers.
2887 setDebugLocFromInst(Builder, Ptr);
2888 SmallVector<Value *, 2> NewPtrs;
2889 unsigned Index = Group->getIndex(Instr);
2890
2891 // If the group is reverse, adjust the index to refer to the last vector lane
2892 // instead of the first. We adjust the index from the first vector lane,
2893 // rather than directly getting the pointer for lane VF - 1, because the
2894 // pointer operand of the interleaved access is supposed to be uniform. For
2895 // uniform instructions, we're only required to generate a value for the
2896 // first vector lane in each unroll iteration.
2897 if (Group->isReverse())
2898 Index += (VF - 1) * Group->getFactor();
2899
2900 for (unsigned Part = 0; Part < UF; Part++) {
2901 Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
2902
2903 // Notice current instruction could be any index. Need to adjust the address
2904 // to the member of index 0.
2905 //
2906 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2907 // b = A[i]; // Member of index 0
2908 // Current pointer is pointed to A[i+1], adjust it to A[i].
2909 //
2910 // E.g. A[i+1] = a; // Member of index 1
2911 // A[i] = b; // Member of index 0
2912 // A[i+2] = c; // Member of index 2 (Current instruction)
2913 // Current pointer is pointed to A[i+2], adjust it to A[i].
2914 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2915
2916 // Cast to the vector pointer type.
2917 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2918 }
2919
2920 setDebugLocFromInst(Builder, Instr);
2921 Value *UndefVec = UndefValue::get(VecTy);
2922
2923 // Vectorize the interleaved load group.
2924 if (isa<LoadInst>(Instr)) {
2925 // For each unroll part, create a wide load for the group.
2926 SmallVector<Value *, 2> NewLoads;
2927 for (unsigned Part = 0; Part < UF; Part++) {
2928 auto *NewLoad = Builder.CreateAlignedLoad(
2929 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2930 Group->addMetadata(NewLoad);
2931 NewLoads.push_back(NewLoad);
2932 }
2933
2934 // For each member in the group, shuffle out the appropriate data from the
2935 // wide loads.
2936 for (unsigned I = 0; I < InterleaveFactor; ++I) {
2937 Instruction *Member = Group->getMember(I);
2938
2939 // Skip the gaps in the group.
2940 if (!Member)
2941 continue;
2942
2943 Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2944 for (unsigned Part = 0; Part < UF; Part++) {
2945 Value *StridedVec = Builder.CreateShuffleVector(
2946 NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2947
2948 // If this member has different type, cast the result type.
2949 if (Member->getType() != ScalarTy) {
2950 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2951 StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2952 }
2953
2954 if (Group->isReverse())
2955 StridedVec = reverseVector(StridedVec);
2956
2957 VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2958 }
2959 }
2960 return;
2961 }
2962
2963 // The sub vector type for current instruction.
2964 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2965
2966 // Vectorize the interleaved store group.
2967 for (unsigned Part = 0; Part < UF; Part++) {
2968 // Collect the stored vector from each member.
2969 SmallVector<Value *, 4> StoredVecs;
2970 for (unsigned i = 0; i < InterleaveFactor; i++) {
2971 // Interleaved store group doesn't allow a gap, so each index has a member
2972 Instruction *Member = Group->getMember(i);
2973 assert(Member && "Fail to get a member from an interleaved store group")(static_cast <bool> (Member && "Fail to get a member from an interleaved store group"
) ? void (0) : __assert_fail ("Member && \"Fail to get a member from an interleaved store group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2973, __extension__ __PRETTY_FUNCTION__))
;
2974
2975 Value *StoredVec = getOrCreateVectorValue(
2976 cast<StoreInst>(Member)->getValueOperand(), Part);
2977 if (Group->isReverse())
2978 StoredVec = reverseVector(StoredVec);
2979
2980 // If this member has different type, cast it to a unified type.
2981
2982 if (StoredVec->getType() != SubVT)
2983 StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2984
2985 StoredVecs.push_back(StoredVec);
2986 }
2987
2988 // Concatenate all vectors into a wide vector.
2989 Value *WideVec = concatenateVectors(Builder, StoredVecs);
2990
2991 // Interleave the elements in the wide vector.
2992 Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2993 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2994 "interleaved.vec");
2995
2996 Instruction *NewStoreInstr =
2997 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2998
2999 Group->addMetadata(NewStoreInstr);
3000 }
3001}
3002
3003void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
3004 VectorParts *BlockInMask) {
3005 // Attempt to issue a wide load.
3006 LoadInst *LI = dyn_cast<LoadInst>(Instr);
3007 StoreInst *SI = dyn_cast<StoreInst>(Instr);
3008
3009 assert((LI || SI) && "Invalid Load/Store instruction")(static_cast <bool> ((LI || SI) && "Invalid Load/Store instruction"
) ? void (0) : __assert_fail ("(LI || SI) && \"Invalid Load/Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3009, __extension__ __PRETTY_FUNCTION__))
;
3010
3011 LoopVectorizationCostModel::InstWidening Decision =
3012 Cost->getWideningDecision(Instr, VF);
3013 assert(Decision != LoopVectorizationCostModel::CM_Unknown &&(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Unknown && "CM decision should be taken at this point"
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3014, __extension__ __PRETTY_FUNCTION__))
3014 "CM decision should be taken at this point")(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Unknown && "CM decision should be taken at this point"
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3014, __extension__ __PRETTY_FUNCTION__))
;
3015 if (Decision == LoopVectorizationCostModel::CM_Interleave)
3016 return vectorizeInterleaveGroup(Instr);
3017
3018 Type *ScalarDataTy = getMemInstValueType(Instr);
3019 Type *DataTy = VectorType::get(ScalarDataTy, VF);
3020 Value *Ptr = getPointerOperand(Instr);
3021 unsigned Alignment = getMemInstAlignment(Instr);
3022 // An alignment of 0 means target abi alignment. We need to use the scalar's
3023 // target abi alignment in such a case.
3024 const DataLayout &DL = Instr->getModule()->getDataLayout();
3025 if (!Alignment)
3026 Alignment = DL.getABITypeAlignment(ScalarDataTy);
3027 unsigned AddressSpace = getMemInstAddressSpace(Instr);
3028
3029 // Determine if the pointer operand of the access is either consecutive or
3030 // reverse consecutive.
3031 bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
3032 bool ConsecutiveStride =
3033 Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
3034 bool CreateGatherScatter =
3035 (Decision == LoopVectorizationCostModel::CM_GatherScatter);
3036
3037 // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
3038 // gather/scatter. Otherwise Decision should have been to Scalarize.
3039 assert((ConsecutiveStride || CreateGatherScatter) &&(static_cast <bool> ((ConsecutiveStride || CreateGatherScatter
) && "The instruction should be scalarized") ? void (
0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3040, __extension__ __PRETTY_FUNCTION__))
3040 "The instruction should be scalarized")(static_cast <bool> ((ConsecutiveStride || CreateGatherScatter
) && "The instruction should be scalarized") ? void (
0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3040, __extension__ __PRETTY_FUNCTION__))
;
3041
3042 // Handle consecutive loads/stores.
3043 if (ConsecutiveStride)
3044 Ptr = getOrCreateScalarValue(Ptr, {0, 0});
3045
3046 VectorParts Mask;
3047 bool isMaskRequired = BlockInMask;
3048 if (isMaskRequired)
3049 Mask = *BlockInMask;
3050
3051 // Handle Stores:
3052 if (SI) {
3053 assert(!Legal->isUniform(SI->getPointerOperand()) &&(static_cast <bool> (!Legal->isUniform(SI->getPointerOperand
()) && "We do not allow storing to uniform addresses"
) ? void (0) : __assert_fail ("!Legal->isUniform(SI->getPointerOperand()) && \"We do not allow storing to uniform addresses\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3054, __extension__ __PRETTY_FUNCTION__))
3054 "We do not allow storing to uniform addresses")(static_cast <bool> (!Legal->isUniform(SI->getPointerOperand
()) && "We do not allow storing to uniform addresses"
) ? void (0) : __assert_fail ("!Legal->isUniform(SI->getPointerOperand()) && \"We do not allow storing to uniform addresses\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3054, __extension__ __PRETTY_FUNCTION__))
;
3055 setDebugLocFromInst(Builder, SI);
3056
3057 for (unsigned Part = 0; Part < UF; ++Part) {
3058 Instruction *NewSI = nullptr;
3059 Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
3060 if (CreateGatherScatter) {
3061 Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
3062 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3063 NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
3064 MaskPart);
3065 } else {
3066 // Calculate the pointer for the specific unroll-part.
3067 Value *PartPtr =
3068 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3069
3070 if (Reverse) {
3071 // If we store to reverse consecutive memory locations, then we need
3072 // to reverse the order of elements in the stored value.
3073 StoredVal = reverseVector(StoredVal);
3074 // We don't want to update the value in the map as it might be used in
3075 // another expression. So don't call resetVectorValue(StoredVal).
3076
3077 // If the address is consecutive but reversed, then the
3078 // wide store needs to start at the last vector element.
3079 PartPtr =
3080 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3081 PartPtr =
3082 Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3083 if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
3084 Mask[Part] = reverseVector(Mask[Part]);
3085 }
3086
3087 Value *VecPtr =
3088 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3089
3090 if (isMaskRequired)
3091 NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
3092 Mask[Part]);
3093 else
3094 NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
3095 }
3096 addMetadata(NewSI, SI);
3097 }
3098 return;
3099 }
3100
3101 // Handle loads.
3102 assert(LI && "Must have a load instruction")(static_cast <bool> (LI && "Must have a load instruction"
) ? void (0) : __assert_fail ("LI && \"Must have a load instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3102, __extension__ __PRETTY_FUNCTION__))
;
3103 setDebugLocFromInst(Builder, LI);
3104 for (unsigned Part = 0; Part < UF; ++Part) {
3105 Value *NewLI;
3106 if (CreateGatherScatter) {
3107 Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
3108 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3109 NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
3110 nullptr, "wide.masked.gather");
3111 addMetadata(NewLI, LI);
3112 } else {
3113 // Calculate the pointer for the specific unroll-part.
3114 Value *PartPtr =
3115 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3116
3117 if (Reverse) {
3118 // If the address is consecutive but reversed, then the
3119 // wide load needs to start at the last vector element.
3120 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3121 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3122 if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
3123 Mask[Part] = reverseVector(Mask[Part]);
3124 }
3125
3126 Value *VecPtr =
3127 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3128 if (isMaskRequired)
3129 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
3130 UndefValue::get(DataTy),
3131 "wide.masked.load");
3132 else
3133 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
3134
3135 // Add metadata to the load, but setVectorValue to the reverse shuffle.
3136 addMetadata(NewLI, LI);
3137 if (Reverse)
3138 NewLI = reverseVector(NewLI);
3139 }
3140 VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
3141 }
3142}
3143
3144void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
3145 const VPIteration &Instance,
3146 bool IfPredicateInstr) {
3147 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors")(static_cast <bool> (!Instr->getType()->isAggregateType
() && "Can't handle vectors") ? void (0) : __assert_fail
("!Instr->getType()->isAggregateType() && \"Can't handle vectors\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3147, __extension__ __PRETTY_FUNCTION__))
;
3148
3149 setDebugLocFromInst(Builder, Instr);
3150
3151 // Does this instruction return a value ?
3152 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3153
3154 Instruction *Cloned = Instr->clone();
3155 if (!IsVoidRetTy)
3156 Cloned->setName(Instr->getName() + ".cloned");
3157
3158 // Replace the operands of the cloned instructions with their scalar
3159 // equivalents in the new loop.
3160 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
3161 auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
3162 Cloned->setOperand(op, NewOp);
3163 }
3164 addNewMetadata(Cloned, Instr);
3165
3166 // Place the cloned scalar in the new loop.
3167 Builder.Insert(Cloned);
3168
3169 // Add the cloned scalar to the scalar map entry.
3170 VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
3171
3172 // If we just cloned a new assumption, add it the assumption cache.
3173 if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
3174 if (II->getIntrinsicID() == Intrinsic::assume)
3175 AC->registerAssumption(II);
3176
3177 // End if-block.
3178 if (IfPredicateInstr)
3179 PredicatedInstructions.push_back(Cloned);
3180}
3181
3182PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3183 Value *End, Value *Step,
3184 Instruction *DL) {
3185 BasicBlock *Header = L->getHeader();
3186 BasicBlock *Latch = L->getLoopLatch();
3187 // As we're just creating this loop, it's possible no latch exists
3188 // yet. If so, use the header as this will be a single block loop.
3189 if (!Latch)
3190 Latch = Header;
3191
3192 IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3193 Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3194 setDebugLocFromInst(Builder, OldInst);
3195 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3196
3197 Builder.SetInsertPoint(Latch->getTerminator());
3198 setDebugLocFromInst(Builder, OldInst);
3199
3200 // Create i+1 and fill the PHINode.
3201 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3202 Induction->addIncoming(Start, L->getLoopPreheader());
3203 Induction->addIncoming(Next, Latch);
3204 // Create the compare.
3205 Value *ICmp = Builder.CreateICmpEQ(Next, End);
3206 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
3207
3208 // Now we have two terminators. Remove the old one from the block.
3209 Latch->getTerminator()->eraseFromParent();
3210
3211 return Induction;
3212}
3213
3214Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3215 if (TripCount)
3216 return TripCount;
3217
3218 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3219 // Find the loop boundaries.
3220 ScalarEvolution *SE = PSE.getSE();
3221 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3222 assert(BackedgeTakenCount != SE->getCouldNotCompute() &&(static_cast <bool> (BackedgeTakenCount != SE->getCouldNotCompute
() && "Invalid loop count") ? void (0) : __assert_fail
("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3223, __extension__ __PRETTY_FUNCTION__))
3223 "Invalid loop count")(static_cast <bool> (BackedgeTakenCount != SE->getCouldNotCompute
() && "Invalid loop count") ? void (0) : __assert_fail
("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3223, __extension__ __PRETTY_FUNCTION__))
;
3224
3225 Type *IdxTy = Legal->getWidestInductionType();
3226
3227 // The exit count might have the type of i64 while the phi is i32. This can
3228 // happen if we have an induction variable that is sign extended before the
3229 // compare. The only way that we get a backedge taken count is that the
3230 // induction variable was signed and as such will not overflow. In such a case
3231 // truncation is legal.
3232 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
3233 IdxTy->getPrimitiveSizeInBits())
3234 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3235 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3236
3237 // Get the total trip count from the count by adding 1.
3238 const SCEV *ExitCount = SE->getAddExpr(
3239 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3240
3241 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3242
3243 // Expand the trip count and place the new instructions in the preheader.
3244 // Notice that the pre-header does not change, only the loop body.
3245 SCEVExpander Exp(*SE, DL, "induction");
3246
3247 // Count holds the overall loop count (N).
3248 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3249 L->getLoopPreheader()->getTerminator());
3250
3251 if (TripCount->getType()->isPointerTy())
3252 TripCount =
3253 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3254 L->getLoopPreheader()->getTerminator());
3255
3256 return TripCount;
3257}
3258
3259Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3260 if (VectorTripCount)
3261 return VectorTripCount;
3262
3263 Value *TC = getOrCreateTripCount(L);
3264 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3265
3266 // Now we need to generate the expression for the part of the loop that the
3267 // vectorized body will execute. This is equal to N - (N % Step) if scalar
3268 // iterations are not required for correctness, or N - Step, otherwise. Step
3269 // is equal to the vectorization factor (number of SIMD elements) times the
3270 // unroll factor (number of SIMD instructions).
3271 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
3272 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3273
3274 // If there is a non-reversed interleaved group that may speculatively access
3275 // memory out-of-bounds, we need to ensure that there will be at least one
3276 // iteration of the scalar epilogue loop. Thus, if the step evenly divides
3277 // the trip count, we set the remainder to be equal to the step. If the step
3278 // does not evenly divide the trip count, no adjustment is necessary since
3279 // there will already be scalar iterations. Note that the minimum iterations
3280 // check ensures that N >= Step.
3281 if (VF > 1 && Legal->requiresScalarEpilogue()) {
3282 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3283 R = Builder.CreateSelect(IsZero, Step, R);
3284 }
3285
3286 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3287
3288 return VectorTripCount;
3289}
3290
3291Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3292 const DataLayout &DL) {
3293 // Verify that V is a vector type with same number of elements as DstVTy.
3294 unsigned VF = DstVTy->getNumElements();
3295 VectorType *SrcVecTy = cast<VectorType>(V->getType());
3296 assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match")(static_cast <bool> ((VF == SrcVecTy->getNumElements
()) && "Vector dimensions do not match") ? void (0) :
__assert_fail ("(VF == SrcVecTy->getNumElements()) && \"Vector dimensions do not match\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3296, __extension__ __PRETTY_FUNCTION__))
;
3297 Type *SrcElemTy = SrcVecTy->getElementType();
3298 Type *DstElemTy = DstVTy->getElementType();
3299 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&(static_cast <bool> ((DL.getTypeSizeInBits(SrcElemTy) ==
DL.getTypeSizeInBits(DstElemTy)) && "Vector elements must have same size"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3300, __extension__ __PRETTY_FUNCTION__))
3300 "Vector elements must have same size")(static_cast <bool> ((DL.getTypeSizeInBits(SrcElemTy) ==
DL.getTypeSizeInBits(DstElemTy)) && "Vector elements must have same size"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3300, __extension__ __PRETTY_FUNCTION__))
;
3301
3302 // Do a direct cast if element types are castable.
3303 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3304 return Builder.CreateBitOrPointerCast(V, DstVTy);
3305 }
3306 // V cannot be directly casted to desired vector type.
3307 // May happen when V is a floating point vector but DstVTy is a vector of
3308 // pointers or vice-versa. Handle this using a two-step bitcast using an
3309 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3310 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&(static_cast <bool> ((DstElemTy->isPointerTy() != SrcElemTy
->isPointerTy()) && "Only one type should be a pointer type"
) ? void (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3311, __extension__ __PRETTY_FUNCTION__))
3311 "Only one type should be a pointer type")(static_cast <bool> ((DstElemTy->isPointerTy() != SrcElemTy
->isPointerTy()) && "Only one type should be a pointer type"
) ? void (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3311, __extension__ __PRETTY_FUNCTION__))
;
3312 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&(static_cast <bool> ((DstElemTy->isFloatingPointTy()
!= SrcElemTy->isFloatingPointTy()) && "Only one type should be a floating point type"
) ? void (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3313, __extension__ __PRETTY_FUNCTION__))
3313 "Only one type should be a floating point type")(static_cast <bool> ((DstElemTy->isFloatingPointTy()
!= SrcElemTy->isFloatingPointTy()) && "Only one type should be a floating point type"
) ? void (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3313, __extension__ __PRETTY_FUNCTION__))
;
3314 Type *IntTy =
3315 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3316 VectorType *VecIntTy = VectorType::get(IntTy, VF);
3317 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3318 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3319}
3320
3321void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3322 BasicBlock *Bypass) {
3323 Value *Count = getOrCreateTripCount(L);
3324 BasicBlock *BB = L->getLoopPreheader();
3325 IRBuilder<> Builder(BB->getTerminator());
3326
3327 // Generate code to check if the loop's trip count is less than VF * UF, or
3328 // equal to it in case a scalar epilogue is required; this implies that the
3329 // vector trip count is zero. This check also covers the case where adding one
3330 // to the backedge-taken count overflowed leading to an incorrect trip count
3331 // of zero. In this case we will also jump to the scalar loop.
3332 auto P = Legal->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
3333 : ICmpInst::ICMP_ULT;
3334 Value *CheckMinIters = Builder.CreateICmp(
3335 P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
3336
3337 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3338 // Update dominator tree immediately if the generated block is a
3339 // LoopBypassBlock because SCEV expansions to generate loop bypass
3340 // checks may query it before the current function is finished.
3341 DT->addNewBlock(NewBB, BB);
3342 if (L->getParentLoop())
3343 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3344 ReplaceInstWithInst(BB->getTerminator(),
3345 BranchInst::Create(Bypass, NewBB, CheckMinIters));
3346 LoopBypassBlocks.push_back(BB);
3347}
3348
3349void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3350 BasicBlock *BB = L->getLoopPreheader();
3351
3352 // Generate the code to check that the SCEV assumptions that we made.
3353 // We want the new basic block to start at the first instruction in a
3354 // sequence of instructions that form a check.
3355 SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
3356 "scev.check");
3357 Value *SCEVCheck =
3358 Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
3359
3360 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3361 if (C->isZero())
3362 return;
3363
3364 // Create a new block containing the stride check.
3365 BB->setName("vector.scevcheck");
3366 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3367 // Update dominator tree immediately if the generated block is a
3368 // LoopBypassBlock because SCEV expansions to generate loop bypass
3369 // checks may query it before the current function is finished.
3370 DT->addNewBlock(NewBB, BB);
3371 if (L->getParentLoop())
3372 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3373 ReplaceInstWithInst(BB->getTerminator(),
3374 BranchInst::Create(Bypass, NewBB, SCEVCheck));
3375 LoopBypassBlocks.push_back(BB);
3376 AddedSafetyChecks = true;
3377}
3378
3379void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
3380 BasicBlock *BB = L->getLoopPreheader();
3381
3382 // Generate the code that checks in runtime if arrays overlap. We put the
3383 // checks into a separate block to make the more common case of few elements
3384 // faster.
3385 Instruction *FirstCheckInst;
3386 Instruction *MemRuntimeCheck;
3387 std::tie(FirstCheckInst, MemRuntimeCheck) =
3388 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
3389 if (!MemRuntimeCheck)
3390 return;
3391
3392 // Create a new block containing the memory check.
3393 BB->setName("vector.memcheck");
3394 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3395 // Update dominator tree immediately if the generated block is a
3396 // LoopBypassBlock because SCEV expansions to generate loop bypass
3397 // checks may query it before the current function is finished.
3398 DT->addNewBlock(NewBB, BB);
3399 if (L->getParentLoop())
3400 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3401 ReplaceInstWithInst(BB->getTerminator(),
3402 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
3403 LoopBypassBlocks.push_back(BB);
3404 AddedSafetyChecks = true;
3405
3406 // We currently don't use LoopVersioning for the actual loop cloning but we
3407 // still use it to add the noalias metadata.
3408 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3409 PSE.getSE());
3410 LVer->prepareNoAliasMetadata();
3411}
3412
3413BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3414 /*
3415 In this function we generate a new loop. The new loop will contain
3416 the vectorized instructions while the old loop will continue to run the
3417 scalar remainder.
3418
3419 [ ] <-- loop iteration number check.
3420 / |
3421 / v
3422 | [ ] <-- vector loop bypass (may consist of multiple blocks).
3423 | / |
3424 | / v
3425 || [ ] <-- vector pre header.
3426 |/ |
3427 | v
3428 | [ ] \
3429 | [ ]_| <-- vector loop.
3430 | |
3431 | v
3432 | -[ ] <--- middle-block.
3433 | / |
3434 | / v
3435 -|- >[ ] <--- new preheader.
3436 | |
3437 | v
3438 | [ ] \
3439 | [ ]_| <-- old scalar loop to handle remainder.
3440 \ |
3441 \ v
3442 >[ ] <-- exit block.
3443 ...
3444 */
3445
3446 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3447 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3448 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3449 assert(VectorPH && "Invalid loop structure")(static_cast <bool> (VectorPH && "Invalid loop structure"
) ? void (0) : __assert_fail ("VectorPH && \"Invalid loop structure\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3449, __extension__ __PRETTY_FUNCTION__))
;
3450 assert(ExitBlock && "Must have an exit block")(static_cast <bool> (ExitBlock && "Must have an exit block"
) ? void (0) : __assert_fail ("ExitBlock && \"Must have an exit block\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3450, __extension__ __PRETTY_FUNCTION__))
;
3451
3452 // Some loops have a single integer induction variable, while other loops
3453 // don't. One example is c++ iterators that often have multiple pointer
3454 // induction variables. In the code below we also support a case where we
3455 // don't have a single induction variable.
3456 //
3457 // We try to obtain an induction variable from the original loop as hard
3458 // as possible. However if we don't find one that:
3459 // - is an integer
3460 // - counts from zero, stepping by one
3461 // - is the size of the widest induction variable type
3462 // then we create a new one.
3463 OldInduction = Legal->getPrimaryInduction();
3464 Type *IdxTy = Legal->getWidestInductionType();
3465
3466 // Split the single block loop into the two loop structure described above.
3467 BasicBlock *VecBody =
3468 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
3469 BasicBlock *MiddleBlock =
3470 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
3471 BasicBlock *ScalarPH =
3472 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
3473
3474 // Create and register the new vector loop.
3475 Loop *Lp = LI->AllocateLoop();
3476 Loop *ParentLoop = OrigLoop->getParentLoop();
3477
3478 // Insert the new loop into the loop nest and register the new basic blocks
3479 // before calling any utilities such as SCEV that require valid LoopInfo.
3480 if (ParentLoop) {
3481 ParentLoop->addChildLoop(Lp);
3482 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
3483 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
3484 } else {
3485 LI->addTopLevelLoop(Lp);
3486 }
3487 Lp->addBasicBlockToLoop(VecBody, *LI);
3488
3489 // Find the loop boundaries.
3490 Value *Count = getOrCreateTripCount(Lp);
3491
3492 Value *StartIdx = ConstantInt::get(IdxTy, 0);
3493
3494 // Now, compare the new count to zero. If it is zero skip the vector loop and
3495 // jump to the scalar loop. This check also covers the case where the
3496 // backedge-taken count is uint##_max: adding one to it will overflow leading
3497 // to an incorrect trip count of zero. In this (rare) case we will also jump
3498 // to the scalar loop.
3499 emitMinimumIterationCountCheck(Lp, ScalarPH);
3500
3501 // Generate the code to check any assumptions that we've made for SCEV
3502 // expressions.
3503 emitSCEVChecks(Lp, ScalarPH);
3504
3505 // Generate the code that checks in runtime if arrays overlap. We put the
3506 // checks into a separate block to make the more common case of few elements
3507 // faster.
3508 emitMemRuntimeChecks(Lp, ScalarPH);
3509
3510 // Generate the induction variable.
3511 // The loop step is equal to the vectorization factor (num of SIMD elements)
3512 // times the unroll factor (num of SIMD instructions).
3513 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3514 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
3515 Induction =
3516 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3517 getDebugLocFromInstOrOperands(OldInduction));
3518
3519 // We are going to resume the execution of the scalar loop.
3520 // Go over all of the induction variables that we found and fix the
3521 // PHIs that are left in the scalar version of the loop.
3522 // The starting values of PHI nodes depend on the counter of the last
3523 // iteration in the vectorized loop.
3524 // If we come from a bypass edge then we need to start from the original
3525 // start value.
3526
3527 // This variable saves the new starting index for the scalar loop. It is used
3528 // to test if there are any tail iterations left once the vector loop has
3529 // completed.
3530 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
3531 for (auto &InductionEntry : *List) {
3532 PHINode *OrigPhi = InductionEntry.first;
3533 InductionDescriptor II = InductionEntry.second;
3534
3535 // Create phi nodes to merge from the backedge-taken check block.
3536 PHINode *BCResumeVal = PHINode::Create(
3537 OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
3538 Value *&EndValue = IVEndValues[OrigPhi];
3539 if (OrigPhi == OldInduction) {
3540 // We know what the end value is.
3541 EndValue = CountRoundDown;
3542 } else {
3543 IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
3544 Type *StepType = II.getStep()->getType();
3545 Instruction::CastOps CastOp =
3546 CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
3547 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
3548 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3549 EndValue = II.transform(B, CRD, PSE.getSE(), DL);
3550 EndValue->setName("ind.end");
3551 }
3552
3553 // The new PHI merges the original incoming value, in case of a bypass,
3554 // or the value at the end of the vectorized loop.
3555 BCResumeVal->addIncoming(EndValue, MiddleBlock);
3556
3557 // Fix the scalar body counter (PHI node).
3558 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
3559
3560 // The old induction's phi node in the scalar body needs the truncated
3561 // value.
3562 for (BasicBlock *BB : LoopBypassBlocks)
3563 BCResumeVal->addIncoming(II.getStartValue(), BB);
3564 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
3565 }
3566
3567 // Add a check in the middle block to see if we have completed
3568 // all of the iterations in the first vector loop.
3569 // If (N - N%VF) == N, then we *don't* need to run the remainder.
3570 Value *CmpN =
3571 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3572 CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
3573 ReplaceInstWithInst(MiddleBlock->getTerminator(),
3574 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
3575
3576 // Get ready to start creating new instructions into the vectorized body.
3577 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
3578
3579 // Save the state.
3580 LoopVectorPreHeader = Lp->getLoopPreheader();
3581 LoopScalarPreHeader = ScalarPH;
3582 LoopMiddleBlock = MiddleBlock;
3583 LoopExitBlock = ExitBlock;
3584 LoopVectorBody = VecBody;
3585 LoopScalarBody = OldBasicBlock;
3586
3587 // Keep all loop hints from the original loop on the vector loop (we'll
3588 // replace the vectorizer-specific hints below).
3589 if (MDNode *LID = OrigLoop->getLoopID())
3590 Lp->setLoopID(LID);
3591
3592 LoopVectorizeHints Hints(Lp, true, *ORE);
3593 Hints.setAlreadyVectorized();
3594
3595 return LoopVectorPreHeader;
3596}
3597
3598// Fix up external users of the induction variable. At this point, we are
3599// in LCSSA form, with all external PHIs that use the IV having one input value,
3600// coming from the remainder loop. We need those PHIs to also have a correct
3601// value for the IV when arriving directly from the middle block.
3602void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3603 const InductionDescriptor &II,
3604 Value *CountRoundDown, Value *EndValue,
3605 BasicBlock *MiddleBlock) {
3606 // There are two kinds of external IV usages - those that use the value
3607 // computed in the last iteration (the PHI) and those that use the penultimate
3608 // value (the value that feeds into the phi from the loop latch).
3609 // We allow both, but they, obviously, have different values.
3610
3611 assert(OrigLoop->getExitBlock() && "Expected a single exit block")(static_cast <bool> (OrigLoop->getExitBlock() &&
"Expected a single exit block") ? void (0) : __assert_fail (
"OrigLoop->getExitBlock() && \"Expected a single exit block\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3611, __extension__ __PRETTY_FUNCTION__))
;
3612
3613 DenseMap<Value *, Value *> MissingVals;
3614
3615 // An external user of the last iteration's value should see the value that
3616 // the remainder loop uses to initialize its own IV.
3617 Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3618 for (User *U : PostInc->users()) {
3619 Instruction *UI = cast<Instruction>(U);
3620 if (!OrigLoop->contains(UI)) {
3621 assert(isa<PHINode>(UI) && "Expected LCSSA form")(static_cast <bool> (isa<PHINode>(UI) && "Expected LCSSA form"
) ? void (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3621, __extension__ __PRETTY_FUNCTION__))
;
3622 MissingVals[UI] = EndValue;
3623 }
3624 }
3625
3626 // An external user of the penultimate value need to see EndValue - Step.
3627 // The simplest way to get this is to recompute it from the constituent SCEVs,
3628 // that is Start + (Step * (CRD - 1)).
3629 for (User *U : OrigPhi->users()) {
3630 auto *UI = cast<Instruction>(U);
3631 if (!OrigLoop->contains(UI)) {
3632 const DataLayout &DL =
3633 OrigLoop->getHeader()->getModule()->getDataLayout();
3634 assert(isa<PHINode>(UI) && "Expected LCSSA form")(static_cast <bool> (isa<PHINode>(UI) && "Expected LCSSA form"
) ? void (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3634, __extension__ __PRETTY_FUNCTION__))
;
3635
3636 IRBuilder<> B(MiddleBlock->getTerminator());
3637 Value *CountMinusOne = B.CreateSub(
3638 CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3639 Value *CMO =
3640 !II.getStep()->getType()->isIntegerTy()
3641 ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3642 II.getStep()->getType())
3643 : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3644 CMO->setName("cast.cmo");
3645 Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3646 Escape->setName("ind.escape");
3647 MissingVals[UI] = Escape;
3648 }
3649 }
3650
3651 for (auto &I : MissingVals) {
3652 PHINode *PHI = cast<PHINode>(I.first);
3653 // One corner case we have to handle is two IVs "chasing" each-other,
3654 // that is %IV2 = phi [...], [ %IV1, %latch ]
3655 // In this case, if IV1 has an external use, we need to avoid adding both
3656 // "last value of IV1" and "penultimate value of IV2". So, verify that we
3657 // don't already have an incoming value for the middle block.
3658 if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3659 PHI->addIncoming(I.second, MiddleBlock);
3660 }
3661}
3662
3663namespace {
3664
3665struct CSEDenseMapInfo {
3666 static bool canHandle(const Instruction *I) {
3667 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3668 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3669 }
3670
3671 static inline Instruction *getEmptyKey() {
3672 return DenseMapInfo<Instruction *>::getEmptyKey();
3673 }
3674
3675 static inline Instruction *getTombstoneKey() {
3676 return DenseMapInfo<Instruction *>::getTombstoneKey();
3677 }
3678
3679 static unsigned getHashValue(const Instruction *I) {
3680 assert(canHandle(I) && "Unknown instruction!")(static_cast <bool> (canHandle(I) && "Unknown instruction!"
) ? void (0) : __assert_fail ("canHandle(I) && \"Unknown instruction!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3680, __extension__ __PRETTY_FUNCTION__))
;
3681 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3682 I->value_op_end()));
3683 }
3684
3685 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3686 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3687 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3688 return LHS == RHS;
3689 return LHS->isIdenticalTo(RHS);
3690 }
3691};
3692
3693} // end anonymous namespace
3694
3695///\brief Perform cse of induction variable instructions.
3696static void cse(BasicBlock *BB) {
3697 // Perform simple cse.
3698 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3699 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3700 Instruction *In = &*I++;
3701
3702 if (!CSEDenseMapInfo::canHandle(In))
3703 continue;
3704
3705 // Check if we can replace this instruction with any of the
3706 // visited instructions.
3707 if (Instruction *V = CSEMap.lookup(In)) {
3708 In->replaceAllUsesWith(V);
3709 In->eraseFromParent();
3710 continue;
3711 }
3712
3713 CSEMap[In] = In;
3714 }
3715}
3716
3717/// \brief Estimate the overhead of scalarizing an instruction. This is a
3718/// convenience wrapper for the type-based getScalarizationOverhead API.
3719static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3720 const TargetTransformInfo &TTI) {
3721 if (VF == 1)
3722 return 0;
3723
3724 unsigned Cost = 0;
3725 Type *RetTy = ToVectorTy(I->getType(), VF);
3726 if (!RetTy->isVoidTy() &&
3727 (!isa<LoadInst>(I) ||
3728 !TTI.supportsEfficientVectorElementLoadStore()))
3729 Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3730
3731 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3732 SmallVector<const Value *, 4> Operands(CI->arg_operands());
3733 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3734 }
3735 else if (!isa<StoreInst>(I) ||
3736 !TTI.supportsEfficientVectorElementLoadStore()) {
3737 SmallVector<const Value *, 4> Operands(I->operand_values());
3738 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3739 }
3740
3741 return Cost;
3742}
3743
3744// Estimate cost of a call instruction CI if it were vectorized with factor VF.
3745// Return the cost of the instruction, including scalarization overhead if it's
3746// needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3747// i.e. either vector version isn't available, or is too expensive.
3748static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3749 const TargetTransformInfo &TTI,
3750 const TargetLibraryInfo *TLI,
3751 bool &NeedToScalarize) {
3752 Function *F = CI->getCalledFunction();
3753 StringRef FnName = CI->getCalledFunction()->getName();
3754 Type *ScalarRetTy = CI->getType();
3755 SmallVector<Type *, 4> Tys, ScalarTys;
3756 for (auto &ArgOp : CI->arg_operands())
3757 ScalarTys.push_back(ArgOp->getType());
3758
3759 // Estimate cost of scalarized vector call. The source operands are assumed
3760 // to be vectors, so we need to extract individual elements from there,
3761 // execute VF scalar calls, and then gather the result into the vector return
3762 // value.
3763 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3764 if (VF == 1)
3765 return ScalarCallCost;
3766
3767 // Compute corresponding vector type for return value and arguments.
3768 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3769 for (Type *ScalarTy : ScalarTys)
3770 Tys.push_back(ToVectorTy(ScalarTy, VF));
3771
3772 // Compute costs of unpacking argument values for the scalar calls and
3773 // packing the return values to a vector.
3774 unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3775
3776 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3777
3778 // If we can't emit a vector call for this function, then the currently found
3779 // cost is the cost we need to return.
3780 NeedToScalarize = true;
3781 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3782 return Cost;
3783
3784 // If the corresponding vector cost is cheaper, return its cost.
3785 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3786 if (VectorCallCost < Cost) {
3787 NeedToScalarize = false;
3788 return VectorCallCost;
3789 }
3790 return Cost;
3791}
3792
3793// Estimate cost of an intrinsic call instruction CI if it were vectorized with
3794// factor VF. Return the cost of the instruction, including scalarization
3795// overhead if it's needed.
3796static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3797 const TargetTransformInfo &TTI,
3798 const TargetLibraryInfo *TLI) {
3799 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3800 assert(ID && "Expected intrinsic call!")(static_cast <bool> (ID && "Expected intrinsic call!"
) ? void (0) : __assert_fail ("ID && \"Expected intrinsic call!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3800, __extension__ __PRETTY_FUNCTION__))
;
3801
3802 FastMathFlags FMF;
3803 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3804 FMF = FPMO->getFastMathFlags();
3805
3806 SmallVector<Value *, 4> Operands(CI->arg_operands());
3807 return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3808}
3809
3810static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3811 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3812 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3813 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3814}
3815static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3816 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3817 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3818 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3819}
3820
3821void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3822 // For every instruction `I` in MinBWs, truncate the operands, create a
3823 // truncated version of `I` and reextend its result. InstCombine runs
3824 // later and will remove any ext/trunc pairs.
3825 SmallPtrSet<Value *, 4> Erased;
3826 for (const auto &KV : Cost->getMinimalBitwidths()) {
3827 // If the value wasn't vectorized, we must maintain the original scalar
3828 // type. The absence of the value from VectorLoopValueMap indicates that it
3829 // wasn't vectorized.
3830 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3831 continue;
3832 for (unsigned Part = 0; Part < UF; ++Part) {
3833 Value *I = getOrCreateVectorValue(KV.first, Part);
3834 if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3835 continue;
3836 Type *OriginalTy = I->getType();
3837 Type *ScalarTruncatedTy =
3838 IntegerType::get(OriginalTy->getContext(), KV.second);
3839 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3840 OriginalTy->getVectorNumElements());
3841 if (TruncatedTy == OriginalTy)
3842 continue;
3843
3844 IRBuilder<> B(cast<Instruction>(I));
3845 auto ShrinkOperand = [&](Value *V) -> Value * {
3846 if (auto *ZI = dyn_cast<ZExtInst>(V))
3847 if (ZI->getSrcTy() == TruncatedTy)
3848 return ZI->getOperand(0);
3849 return B.CreateZExtOrTrunc(V, TruncatedTy);
3850 };
3851
3852 // The actual instruction modification depends on the instruction type,
3853 // unfortunately.
3854 Value *NewI = nullptr;
3855 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3856 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3857 ShrinkOperand(BO->getOperand(1)));
3858
3859 // Any wrapping introduced by shrinking this operation shouldn't be
3860 // considered undefined behavior. So, we can't unconditionally copy
3861 // arithmetic wrapping flags to NewI.
3862 cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3863 } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3864 NewI =
3865 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3866 ShrinkOperand(CI->getOperand(1)));
3867 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3868 NewI = B.CreateSelect(SI->getCondition(),
3869 ShrinkOperand(SI->getTrueValue()),
3870 ShrinkOperand(SI->getFalseValue()));
3871 } else if (auto *CI = dyn_cast<CastInst>(I)) {
3872 switch (CI->getOpcode()) {
3873 default:
3874 llvm_unreachable("Unhandled cast!")::llvm::llvm_unreachable_internal("Unhandled cast!", "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3874)
;
3875 case Instruction::Trunc:
3876 NewI = ShrinkOperand(CI->getOperand(0));
3877 break;
3878 case Instruction::SExt:
3879 NewI = B.CreateSExtOrTrunc(
3880 CI->getOperand(0),
3881 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3882 break;
3883 case Instruction::ZExt:
3884 NewI = B.CreateZExtOrTrunc(
3885 CI->getOperand(0),
3886 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3887 break;
3888 }
3889 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3890 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3891 auto *O0 = B.CreateZExtOrTrunc(
3892 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3893 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3894 auto *O1 = B.CreateZExtOrTrunc(
3895 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3896
3897 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3898 } else if (isa<LoadInst>(I)) {
3899 // Don't do anything with the operands, just extend the result.
3900 continue;
3901 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3902 auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3903 auto *O0 = B.CreateZExtOrTrunc(
3904 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3905 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3906 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3907 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3908 auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3909 auto *O0 = B.CreateZExtOrTrunc(
3910 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3911 NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3912 } else {
3913 llvm_unreachable("Unhandled instruction type!")::llvm::llvm_unreachable_internal("Unhandled instruction type!"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3913)
;
3914 }
3915
3916 // Lastly, extend the result.
3917 NewI->takeName(cast<Instruction>(I));
3918 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3919 I->replaceAllUsesWith(Res);
3920 cast<Instruction>(I)->eraseFromParent();
3921 Erased.insert(I);
3922 VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3923 }
3924 }
3925
3926 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3927 for (const auto &KV : Cost->getMinimalBitwidths()) {
3928 // If the value wasn't vectorized, we must maintain the original scalar
3929 // type. The absence of the value from VectorLoopValueMap indicates that it
3930 // wasn't vectorized.
3931 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3932 continue;
3933 for (unsigned Part = 0; Part < UF; ++Part) {
3934 Value *I = getOrCreateVectorValue(KV.first, Part);
3935 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3936 if (Inst && Inst->use_empty()) {
3937 Value *NewI = Inst->getOperand(0);
3938 Inst->eraseFromParent();
3939 VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3940 }
3941 }
3942 }
3943}
3944
3945void InnerLoopVectorizer::fixVectorizedLoop() {
3946 // Insert truncates and extends for any truncated instructions as hints to
3947 // InstCombine.
3948 if (VF > 1)
3949 truncateToMinimalBitwidths();
3950
3951 // At this point every instruction in the original loop is widened to a
3952 // vector form. Now we need to fix the recurrences in the loop. These PHI
3953 // nodes are currently empty because we did not want to introduce cycles.
3954 // This is the second stage of vectorizing recurrences.
3955 fixCrossIterationPHIs();
3956
3957 // Update the dominator tree.
3958 //
3959 // FIXME: After creating the structure of the new loop, the dominator tree is
3960 // no longer up-to-date, and it remains that way until we update it
3961 // here. An out-of-date dominator tree is problematic for SCEV,
3962 // because SCEVExpander uses it to guide code generation. The
3963 // vectorizer use SCEVExpanders in several places. Instead, we should
3964 // keep the dominator tree up-to-date as we go.
3965 updateAnalysis();
3966
3967 // Fix-up external users of the induction variables.
3968 for (auto &Entry : *Legal->getInductionVars())
3969 fixupIVUsers(Entry.first, Entry.second,
3970 getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3971 IVEndValues[Entry.first], LoopMiddleBlock);
3972
3973 fixLCSSAPHIs();
3974 for (Instruction *PI : PredicatedInstructions)
3975 sinkScalarOperands(&*PI);
3976
3977 // Remove redundant induction instructions.
3978 cse(LoopVectorBody);
3979}
3980
3981void InnerLoopVectorizer::fixCrossIterationPHIs() {
3982 // In order to support recurrences we need to be able to vectorize Phi nodes.
3983 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3984 // stage #2: We now need to fix the recurrences by adding incoming edges to
3985 // the currently empty PHI nodes. At this point every instruction in the
3986 // original loop is widened to a vector form so we can use them to construct
3987 // the incoming edges.
3988 for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
3989 // Handle first-order recurrences and reductions that need to be fixed.
3990 if (Legal->isFirstOrderRecurrence(&Phi))
3991 fixFirstOrderRecurrence(&Phi);
3992 else if (Legal->isReductionVariable(&Phi))
3993 fixReduction(&Phi);
3994 }
3995}
3996
3997void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3998 // This is the second phase of vectorizing first-order recurrences. An
3999 // overview of the transformation is described below. Suppose we have the
4000 // following loop.
4001 //
4002 // for (int i = 0; i < n; ++i)
4003 // b[i] = a[i] - a[i - 1];
4004 //
4005 // There is a first-order recurrence on "a". For this loop, the shorthand
4006 // scalar IR looks like:
4007 //
4008 // scalar.ph:
4009 // s_init = a[-1]
4010 // br scalar.body
4011 //
4012 // scalar.body:
4013 // i = phi [0, scalar.ph], [i+1, scalar.body]
4014 // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4015 // s2 = a[i]
4016 // b[i] = s2 - s1
4017 // br cond, scalar.body, ...
4018 //
4019 // In this example, s1 is a recurrence because it's value depends on the
4020 // previous iteration. In the first phase of vectorization, we created a
4021 // temporary value for s1. We now complete the vectorization and produce the
4022 // shorthand vector IR shown below (for VF = 4, UF = 1).
4023 //
4024 // vector.ph:
4025 // v_init = vector(..., ..., ..., a[-1])
4026 // br vector.body
4027 //
4028 // vector.body
4029 // i = phi [0, vector.ph], [i+4, vector.body]
4030 // v1 = phi [v_init, vector.ph], [v2, vector.body]
4031 // v2 = a[i, i+1, i+2, i+3];
4032 // v3 = vector(v1(3), v2(0, 1, 2))
4033 // b[i, i+1, i+2, i+3] = v2 - v3
4034 // br cond, vector.body, middle.block
4035 //
4036 // middle.block:
4037 // x = v2(3)
4038 // br scalar.ph
4039 //
4040 // scalar.ph:
4041 // s_init = phi [x, middle.block], [a[-1], otherwise]
4042 // br scalar.body
4043 //
4044 // After execution completes the vector loop, we extract the next value of
4045 // the recurrence (x) to use as the initial value in the scalar loop.
4046
4047 // Get the original loop preheader and single loop latch.
4048 auto *Preheader = OrigLoop->getLoopPreheader();
4049 auto *Latch = OrigLoop->getLoopLatch();
4050
4051 // Get the initial and previous values of the scalar recurrence.
4052 auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4053 auto *Previous = Phi->getIncomingValueForBlock(Latch);
4054
4055 // Create a vector from the initial value.
4056 auto *VectorInit = ScalarInit;
4057 if (VF > 1) {
4058 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4059 VectorInit = Builder.CreateInsertElement(
4060 UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4061 Builder.getInt32(VF - 1), "vector.recur.init");
4062 }
4063
4064 // We constructed a temporary phi node in the first phase of vectorization.
4065 // This phi node will eventually be deleted.
4066 Builder.SetInsertPoint(
4067 cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
4068
4069 // Create a phi node for the new recurrence. The current value will either be
4070 // the initial value inserted into a vector or loop-varying vector value.
4071 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4072 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4073
4074 // Get the vectorized previous value of the last part UF - 1. It appears last
4075 // among all unrolled iterations, due to the order of their construction.
4076 Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
4077
4078 // Set the insertion point after the previous value if it is an instruction.
4079 // Note that the previous value may have been constant-folded so it is not
4080 // guaranteed to be an instruction in the vector loop. Also, if the previous
4081 // value is a phi node, we should insert after all the phi nodes to avoid
4082 // breaking basic block verification.
4083 if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
4084 isa<PHINode>(PreviousLastPart))
4085 Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4086 else
4087 Builder.SetInsertPoint(
4088 &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
4089
4090 // We will construct a vector for the recurrence by combining the values for
4091 // the current and previous iterations. This is the required shuffle mask.
4092 SmallVector<Constant *, 8> ShuffleMask(VF);
4093 ShuffleMask[0] = Builder.getInt32(VF - 1);
4094 for (unsigned I = 1; I < VF; ++I)
4095 ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4096
4097 // The vector from which to take the initial value for the current iteration
4098 // (actual or unrolled). Initially, this is the vector phi node.
4099 Value *Incoming = VecPhi;
4100
4101 // Shuffle the current and previous vector and update the vector parts.
4102 for (unsigned Part = 0; Part < UF; ++Part) {
4103 Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
4104 Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
4105 auto *Shuffle =
4106 VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
4107 ConstantVector::get(ShuffleMask))
4108 : Incoming;
4109 PhiPart->replaceAllUsesWith(Shuffle);
4110 cast<Instruction>(PhiPart)->eraseFromParent();
4111 VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
4112 Incoming = PreviousPart;
4113 }
4114
4115 // Fix the latch value of the new recurrence in the vector loop.
4116 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4117
4118 // Extract the last vector element in the middle block. This will be the
4119 // initial value for the recurrence when jumping to the scalar loop.
4120 auto *ExtractForScalar = Incoming;
4121 if (VF > 1) {
4122 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4123 ExtractForScalar = Builder.CreateExtractElement(
4124 ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
4125 }
4126 // Extract the second last element in the middle block if the
4127 // Phi is used outside the loop. We need to extract the phi itself
4128 // and not the last element (the phi update in the current iteration). This
4129 // will be the value when jumping to the exit block from the LoopMiddleBlock,
4130 // when the scalar loop is not run at all.
4131 Value *ExtractForPhiUsedOutsideLoop = nullptr;
4132 if (VF > 1)
4133 ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4134 Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
4135 // When loop is unrolled without vectorizing, initialize
4136 // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4137 // `Incoming`. This is analogous to the vectorized case above: extracting the
4138 // second last element when VF > 1.
4139 else if (UF > 1)
4140 ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
4141
4142 // Fix the initial value of the original recurrence in the scalar loop.
4143 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4144 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4145 for (auto *BB : predecessors(LoopScalarPreHeader)) {
4146 auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4147 Start->addIncoming(Incoming, BB);
4148 }
4149
4150 Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4151 Phi->setName("scalar.recur");
4152
4153 // Finally, fix users of the recurrence outside the loop. The users will need
4154 // either the last value of the scalar recurrence or the last value of the
4155 // vector recurrence we extracted in the middle block. Since the loop is in
4156 // LCSSA form, we just need to find the phi node for the original scalar
4157 // recurrence in the exit block, and then add an edge for the middle block.
4158 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4159 if (LCSSAPhi.getIncomingValue(0) == Phi) {
4160 LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4161 break;
4162 }
4163 }
4164}
4165
4166void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
4167 Constant *Zero = Builder.getInt32(0);
4168
4169 // Get it's reduction variable descriptor.
4170 assert(Legal->isReductionVariable(Phi) &&(static_cast <bool> (Legal->isReductionVariable(Phi)
&& "Unable to find the reduction variable") ? void (
0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4171, __extension__ __PRETTY_FUNCTION__))
4171 "Unable to find the reduction variable")(static_cast <bool> (Legal->isReductionVariable(Phi)
&& "Unable to find the reduction variable") ? void (
0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4171, __extension__ __PRETTY_FUNCTION__))
;
4172 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
4173
4174 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
4175 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4176 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4177 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
4178 RdxDesc.getMinMaxRecurrenceKind();
4179 setDebugLocFromInst(Builder, ReductionStartValue);
4180
4181 // We need to generate a reduction vector from the incoming scalar.
4182 // To do so, we need to generate the 'identity' vector and override
4183 // one of the elements with the incoming scalar reduction. We need
4184 // to do it in the vector-loop preheader.
4185 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4186
4187 // This is the vector-clone of the value that leaves the loop.
4188 Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
4189
4190 // Find the reduction identity variable. Zero for addition, or, xor,
4191 // one for multiplication, -1 for And.
4192 Value *Identity;
4193 Value *VectorStart;
4194 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
4195 RK == RecurrenceDescriptor::RK_FloatMinMax) {
4196 // MinMax reduction have the start value as their identify.
4197 if (VF == 1) {
4198 VectorStart = Identity = ReductionStartValue;
4199 } else {
4200 VectorStart = Identity =
4201 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
4202 }
4203 } else {
4204 // Handle other reduction kinds:
4205 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
4206 RK, VecTy->getScalarType());
4207 if (VF == 1) {
4208 Identity = Iden;
4209 // This vector is the Identity vector where the first element is the
4210 // incoming scalar reduction.
4211 VectorStart = ReductionStartValue;
4212 } else {
4213 Identity = ConstantVector::getSplat(VF, Iden);
4214
4215 // This vector is the Identity vector where the first element is the
4216 // incoming scalar reduction.
4217 VectorStart =
4218 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
4219 }
4220 }
4221
4222 // Fix the vector-loop phi.
4223
4224 // Reductions do not have to start at zero. They can start with
4225 // any loop invariant values.
4226 BasicBlock *Latch = OrigLoop->getLoopLatch();
4227 Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
4228 for (unsigned Part = 0; Part < UF; ++Part) {
4229 Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
4230 Value *Val = getOrCreateVectorValue(LoopVal, Part);
4231 // Make sure to add the reduction stat value only to the
4232 // first unroll part.
4233 Value *StartVal = (Part == 0) ? VectorStart : Identity;
4234 cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
4235 cast<PHINode>(VecRdxPhi)
4236 ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4237 }
4238
4239 // Before each round, move the insertion point right between
4240 // the PHIs and the values we are going to write.
4241 // This allows us to write both PHINodes and the extractelement
4242 // instructions.
4243 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4244
4245 setDebugLocFromInst(Builder, LoopExitInst);
4246
4247 // If the vector reduction can be performed in a smaller type, we truncate
4248 // then extend the loop exit value to enable InstCombine to evaluate the
4249 // entire expression in the smaller type.
4250 if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
4251 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4252 Builder.SetInsertPoint(
4253 LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4254 VectorParts RdxParts(UF);
4255 for (unsigned Part = 0; Part < UF; ++Part) {
4256 RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4257 Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4258 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4259 : Builder.CreateZExt(Trunc, VecTy);
4260 for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4261 UI != RdxParts[Part]->user_end();)
4262 if (*UI != Trunc) {
4263 (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4264 RdxParts[Part] = Extnd;
4265 } else {
4266 ++UI;
4267 }
4268 }
4269 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4270 for (unsigned Part = 0; Part < UF; ++Part) {
4271 RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4272 VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
4273 }
4274 }
4275
4276 // Reduce all of the unrolled parts into a single vector.
4277 Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
4278 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
4279 setDebugLocFromInst(Builder, ReducedPartRdx);
4280 for (unsigned Part = 1; Part < UF; ++Part) {
4281 Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4282 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4283 // Floating point operations had to be 'fast' to enable the reduction.
4284 ReducedPartRdx = addFastMathFlag(
4285 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
4286 ReducedPartRdx, "bin.rdx"));
4287 else
4288 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
4289 Builder, MinMaxKind, ReducedPartRdx, RdxPart);
4290 }
4291
4292 if (VF > 1) {
4293 bool NoNaN = Legal->hasFunNoNaNAttr();
4294 ReducedPartRdx =
4295 createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
4296 // If the reduction can be performed in a smaller type, we need to extend
4297 // the reduction to the wider type before we branch to the original loop.
4298 if (Phi->getType() != RdxDesc.getRecurrenceType())
4299 ReducedPartRdx =
4300 RdxDesc.isSigned()
4301 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4302 : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4303 }
4304
4305 // Create a phi node that merges control-flow from the backedge-taken check
4306 // block and the middle block.
4307 PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4308 LoopScalarPreHeader->getTerminator());
4309 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4310 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4311 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4312
4313 // Now, we need to fix the users of the reduction variable
4314 // inside and outside of the scalar remainder loop.
4315 // We know that the loop is in LCSSA form. We need to update the
4316 // PHI nodes in the exit blocks.
4317 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4318 // All PHINodes need to have a single entry edge, or two if
4319 // we already fixed them.
4320 assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI")(static_cast <bool> (LCSSAPhi.getNumIncomingValues() <
3 && "Invalid LCSSA PHI") ? void (0) : __assert_fail
("LCSSAPhi.getNumIncomingValues() < 3 && \"Invalid LCSSA PHI\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4320, __extension__ __PRETTY_FUNCTION__))
;
4321
4322 // We found a reduction value exit-PHI. Update it with the
4323 // incoming bypass edge.
4324 if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
4325 LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4326 } // end of the LCSSA phi scan.
4327
4328 // Fix the scalar loop reduction variable with the incoming reduction sum
4329 // from the vector body and from the backedge value.
4330 int IncomingEdgeBlockIdx =
4331 Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4332 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index")(static_cast <bool> (IncomingEdgeBlockIdx >= 0 &&
"Invalid block index") ? void (0) : __assert_fail ("IncomingEdgeBlockIdx >= 0 && \"Invalid block index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4332, __extension__ __PRETTY_FUNCTION__))
;
4333 // Pick the other block.
4334 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4335 Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4336 Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4337}
4338
4339void InnerLoopVectorizer::fixLCSSAPHIs() {
4340 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4341 if (LCSSAPhi.getNumIncomingValues() == 1) {
4342 assert(OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) &&(static_cast <bool> (OrigLoop->isLoopInvariant(LCSSAPhi
.getIncomingValue(0)) && "Incoming value isn't loop invariant"
) ? void (0) : __assert_fail ("OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) && \"Incoming value isn't loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4343, __extension__ __PRETTY_FUNCTION__))
4343 "Incoming value isn't loop invariant")(static_cast <bool> (OrigLoop->isLoopInvariant(LCSSAPhi
.getIncomingValue(0)) && "Incoming value isn't loop invariant"
) ? void (0) : __assert_fail ("OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) && \"Incoming value isn't loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4343, __extension__ __PRETTY_FUNCTION__))
;
4344 LCSSAPhi.addIncoming(LCSSAPhi.getIncomingValue(0), LoopMiddleBlock);
4345 }
4346 }
4347}
4348
4349void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4350 // The basic block and loop containing the predicated instruction.
4351 auto *PredBB = PredInst->getParent();
4352 auto *VectorLoop = LI->getLoopFor(PredBB);
4353
4354 // Initialize a worklist with the operands of the predicated instruction.
4355 SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4356
4357 // Holds instructions that we need to analyze again. An instruction may be
4358 // reanalyzed if we don't yet know if we can sink it or not.
4359 SmallVector<Instruction *, 8> InstsToReanalyze;
4360
4361 // Returns true if a given use occurs in the predicated block. Phi nodes use
4362 // their operands in their corresponding predecessor blocks.
4363 auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4364 auto *I = cast<Instruction>(U.getUser());
4365 BasicBlock *BB = I->getParent();
4366 if (auto *Phi = dyn_cast<PHINode>(I))
4367 BB = Phi->getIncomingBlock(
4368 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4369 return BB == PredBB;
4370 };
4371
4372 // Iteratively sink the scalarized operands of the predicated instruction
4373 // into the block we created for it. When an instruction is sunk, it's
4374 // operands are then added to the worklist. The algorithm ends after one pass
4375 // through the worklist doesn't sink a single instruction.
4376 bool Changed;
4377 do {
4378 // Add the instructions that need to be reanalyzed to the worklist, and
4379 // reset the changed indicator.
4380 Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4381 InstsToReanalyze.clear();
4382 Changed = false;
4383
4384 while (!Worklist.empty()) {
4385 auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4386
4387 // We can't sink an instruction if it is a phi node, is already in the
4388 // predicated block, is not in the loop, or may have side effects.
4389 if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4390 !VectorLoop->contains(I) || I->mayHaveSideEffects())
4391 continue;
4392
4393 // It's legal to sink the instruction if all its uses occur in the
4394 // predicated block. Otherwise, there's nothing to do yet, and we may
4395 // need to reanalyze the instruction.
4396 if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4397 InstsToReanalyze.push_back(I);
4398 continue;
4399 }
4400
4401 // Move the instruction to the beginning of the predicated block, and add
4402 // it's operands to the worklist.
4403 I->moveBefore(&*PredBB->getFirstInsertionPt());
4404 Worklist.insert(I->op_begin(), I->op_end());
4405
4406 // The sinking may have enabled other instructions to be sunk, so we will
4407 // need to iterate.
4408 Changed = true;
4409 }
4410 } while (Changed);
4411}
4412
4413void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
4414 unsigned VF) {
4415 assert(PN->getParent() == OrigLoop->getHeader() &&(static_cast <bool> (PN->getParent() == OrigLoop->
getHeader() && "Non-header phis should have been handled elsewhere"
) ? void (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4416, __extension__ __PRETTY_FUNCTION__))
4416 "Non-header phis should have been handled elsewhere")(static_cast <bool> (PN->getParent() == OrigLoop->
getHeader() && "Non-header phis should have been handled elsewhere"
) ? void (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4416, __extension__ __PRETTY_FUNCTION__))
;
4417
4418 PHINode *P = cast<PHINode>(PN);
4419 // In order to support recurrences we need to be able to vectorize Phi nodes.
4420 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4421 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4422 // this value when we vectorize all of the instructions that use the PHI.
4423 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4424 for (unsigned Part = 0; Part < UF; ++Part) {
4425 // This is phase one of vectorizing PHIs.
4426 Type *VecTy =
4427 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4428 Value *EntryPart = PHINode::Create(
4429 VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4430 VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
4431 }
4432 return;
4433 }
4434
4435 setDebugLocFromInst(Builder, P);
4436
4437 // This PHINode must be an induction variable.
4438 // Make sure that we know about it.
4439 assert(Legal->getInductionVars()->count(P) && "Not an induction variable")(static_cast <bool> (Legal->getInductionVars()->count
(P) && "Not an induction variable") ? void (0) : __assert_fail
("Legal->getInductionVars()->count(P) && \"Not an induction variable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
;
4440
4441 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4442 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4443
4444 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4445 // which can be found from the original scalar operations.
4446 switch (II.getKind()) {
4447 case InductionDescriptor::IK_NoInduction:
4448 llvm_unreachable("Unknown induction")::llvm::llvm_unreachable_internal("Unknown induction", "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4448)
;
4449 case InductionDescriptor::IK_IntInduction:
4450 case InductionDescriptor::IK_FpInduction:
4451 llvm_unreachable("Integer/fp induction is handled elsewhere.")::llvm::llvm_unreachable_internal("Integer/fp induction is handled elsewhere."
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4451)
;
4452 case InductionDescriptor::IK_PtrInduction: {
4453 // Handle the pointer induction variable case.
4454 assert(P->getType()->isPointerTy() && "Unexpected type.")(static_cast <bool> (P->getType()->isPointerTy() &&
"Unexpected type.") ? void (0) : __assert_fail ("P->getType()->isPointerTy() && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4454, __extension__ __PRETTY_FUNCTION__))
;
4455 // This is the normalized GEP that starts counting at zero.
4456 Value *PtrInd = Induction;
4457 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4458 // Determine the number of scalars we need to generate for each unroll
4459 // iteration. If the instruction is uniform, we only need to generate the
4460 // first lane. Otherwise, we generate all VF values.
4461 unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4462 // These are the scalar results. Notice that we don't generate vector GEPs
4463 // because scalar GEPs result in better code.
4464 for (unsigned Part = 0; Part < UF; ++Part) {
4465 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4466 Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
4467 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4468 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4469 SclrGep->setName("next.gep");
4470 VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
4471 }
4472 }
4473 return;
4474 }
4475 }
4476}
4477
4478/// A helper function for checking whether an integer division-related
4479/// instruction may divide by zero (in which case it must be predicated if
4480/// executed conditionally in the scalar code).
4481/// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4482/// Non-zero divisors that are non compile-time constants will not be
4483/// converted into multiplication, so we will still end up scalarizing
4484/// the division, but can do so w/o predication.
4485static bool mayDivideByZero(Instruction &I) {
4486 assert((I.getOpcode() == Instruction::UDiv ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4487 I.getOpcode() == Instruction::SDiv ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4488 I.getOpcode() == Instruction::URem ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4489 I.getOpcode() == Instruction::SRem) &&(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4490 "Unexpected instruction")(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
;
4491 Value *Divisor = I.getOperand(1);
4492 auto *CInt = dyn_cast<ConstantInt>(Divisor);
4493 return !CInt || CInt->isZero();
4494}
4495
4496void InnerLoopVectorizer::widenInstruction(Instruction &I) {
4497 switch (I.getOpcode()) {
4498 case Instruction::Br:
4499 case Instruction::PHI:
4500 llvm_unreachable("This instruction is handled by a different recipe.")::llvm::llvm_unreachable_internal("This instruction is handled by a different recipe."
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4500)
;
4501 case Instruction::GetElementPtr: {
4502 // Construct a vector GEP by widening the operands of the scalar GEP as
4503 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4504 // results in a vector of pointers when at least one operand of the GEP
4505 // is vector-typed. Thus, to keep the representation compact, we only use
4506 // vector-typed operands for loop-varying values.
4507 auto *GEP = cast<GetElementPtrInst>(&I);
4508
4509 if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
4510 // If we are vectorizing, but the GEP has only loop-invariant operands,
4511 // the GEP we build (by only using vector-typed operands for
4512 // loop-varying values) would be a scalar pointer. Thus, to ensure we
4513 // produce a vector of pointers, we need to either arbitrarily pick an
4514 // operand to broadcast, or broadcast a clone of the original GEP.
4515 // Here, we broadcast a clone of the original.
4516 //
4517 // TODO: If at some point we decide to scalarize instructions having
4518 // loop-invariant operands, this special case will no longer be
4519 // required. We would add the scalarization decision to
4520 // collectLoopScalars() and teach getVectorValue() to broadcast
4521 // the lane-zero scalar value.
4522 auto *Clone = Builder.Insert(GEP->clone());
4523 for (unsigned Part = 0; Part < UF; ++Part) {
4524 Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4525 VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
4526 addMetadata(EntryPart, GEP);
4527 }
4528 } else {
4529 // If the GEP has at least one loop-varying operand, we are sure to
4530 // produce a vector of pointers. But if we are only unrolling, we want
4531 // to produce a scalar GEP for each unroll part. Thus, the GEP we
4532 // produce with the code below will be scalar (if VF == 1) or vector
4533 // (otherwise). Note that for the unroll-only case, we still maintain
4534 // values in the vector mapping with initVector, as we do for other
4535 // instructions.
4536 for (unsigned Part = 0; Part < UF; ++Part) {
4537 // The pointer operand of the new GEP. If it's loop-invariant, we
4538 // won't broadcast it.
4539 auto *Ptr =
4540 OrigLoop->isLoopInvariant(GEP->getPointerOperand())
4541 ? GEP->getPointerOperand()
4542 : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
4543
4544 // Collect all the indices for the new GEP. If any index is
4545 // loop-invariant, we won't broadcast it.
4546 SmallVector<Value *, 4> Indices;
4547 for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
4548 if (OrigLoop->isLoopInvariant(U.get()))
4549 Indices.push_back(U.get());
4550 else
4551 Indices.push_back(getOrCreateVectorValue(U.get(), Part));
4552 }
4553
4554 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4555 // but it should be a vector, otherwise.
4556 auto *NewGEP = GEP->isInBounds()
4557 ? Builder.CreateInBoundsGEP(Ptr, Indices)
4558 : Builder.CreateGEP(Ptr, Indices);
4559 assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&(static_cast <bool> ((VF == 1 || NewGEP->getType()->
isVectorTy()) && "NewGEP is not a pointer vector") ? void
(0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4560, __extension__ __PRETTY_FUNCTION__))
4560 "NewGEP is not a pointer vector")(static_cast <bool> ((VF == 1 || NewGEP->getType()->
isVectorTy()) && "NewGEP is not a pointer vector") ? void
(0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4560, __extension__ __PRETTY_FUNCTION__))
;
4561 VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
4562 addMetadata(NewGEP, GEP);
4563 }
4564 }
4565
4566 break;
4567 }
4568 case Instruction::UDiv:
4569 case Instruction::SDiv:
4570 case Instruction::SRem:
4571 case Instruction::URem:
4572 case Instruction::Add:
4573 case Instruction::FAdd:
4574 case Instruction::Sub:
4575 case Instruction::FSub:
4576 case Instruction::Mul:
4577 case Instruction::FMul:
4578 case Instruction::FDiv:
4579 case Instruction::FRem:
4580 case Instruction::Shl:
4581 case Instruction::LShr:
4582 case Instruction::AShr:
4583 case Instruction::And:
4584 case Instruction::Or:
4585 case Instruction::Xor: {
4586 // Just widen binops.
4587 auto *BinOp = cast<BinaryOperator>(&I);
4588 setDebugLocFromInst(Builder, BinOp);
4589
4590 for (unsigned Part = 0; Part < UF; ++Part) {
4591 Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
4592 Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
4593 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
4594
4595 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4596 VecOp->copyIRFlags(BinOp);
4597
4598 // Use this vector value for all users of the original instruction.
4599 VectorLoopValueMap.setVectorValue(&I, Part, V);
4600 addMetadata(V, BinOp);
4601 }
4602
4603 break;
4604 }
4605 case Instruction::Select: {
4606 // Widen selects.
4607 // If the selector is loop invariant we can create a select
4608 // instruction with a scalar condition. Otherwise, use vector-select.
4609 auto *SE = PSE.getSE();
4610 bool InvariantCond =
4611 SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4612 setDebugLocFromInst(Builder, &I);
4613
4614 // The condition can be loop invariant but still defined inside the
4615 // loop. This means that we can't just use the original 'cond' value.
4616 // We have to take the 'vectorized' value and pick the first lane.
4617 // Instcombine will make this a no-op.
4618
4619 auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
4620
4621 for (unsigned Part = 0; Part < UF; ++Part) {
4622 Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
4623 Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
4624 Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
4625 Value *Sel =
4626 Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
4627 VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4628 addMetadata(Sel, &I);
4629 }
4630
4631 break;
4632 }
4633
4634 case Instruction::ICmp:
4635 case Instruction::FCmp: {
4636 // Widen compares. Generate vector compares.
4637 bool FCmp = (I.getOpcode() == Instruction::FCmp);
4638 auto *Cmp = dyn_cast<CmpInst>(&I);
4639 setDebugLocFromInst(Builder, Cmp);
4640 for (unsigned Part = 0; Part < UF; ++Part) {
4641 Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
4642 Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
4643 Value *C = nullptr;
4644 if (FCmp) {
4645 // Propagate fast math flags.
4646 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4647 Builder.setFastMathFlags(Cmp->getFastMathFlags());
4648 C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4649 } else {
4650 C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4651 }
4652 VectorLoopValueMap.setVectorValue(&I, Part, C);
4653 addMetadata(C, &I);
4654 }
4655
4656 break;
4657 }
4658
4659 case Instruction::ZExt:
4660 case Instruction::SExt:
4661 case Instruction::FPToUI:
4662 case Instruction::FPToSI:
4663 case Instruction::FPExt:
4664 case Instruction::PtrToInt:
4665 case Instruction::IntToPtr:
4666 case Instruction::SIToFP:
4667 case Instruction::UIToFP:
4668 case Instruction::Trunc:
4669 case Instruction::FPTrunc:
4670 case Instruction::BitCast: {
4671 auto *CI = dyn_cast<CastInst>(&I);
4672 setDebugLocFromInst(Builder, CI);
4673
4674 /// Vectorize casts.
4675 Type *DestTy =
4676 (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4677
4678 for (unsigned Part = 0; Part < UF; ++Part) {
4679 Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4680 Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4681 VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4682 addMetadata(Cast, &I);
4683 }
4684 break;
4685 }
4686
4687 case Instruction::Call: {
4688 // Ignore dbg intrinsics.
4689 if (isa<DbgInfoIntrinsic>(I))
4690 break;
4691 setDebugLocFromInst(Builder, &I);
4692
4693 Module *M = I.getParent()->getParent()->getParent();
4694 auto *CI = cast<CallInst>(&I);
4695
4696 StringRef FnName = CI->getCalledFunction()->getName();
4697 Function *F = CI->getCalledFunction();
4698 Type *RetTy = ToVectorTy(CI->getType(), VF);
4699 SmallVector<Type *, 4> Tys;
4700 for (Value *ArgOperand : CI->arg_operands())
4701 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4702
4703 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4704
4705 // The flag shows whether we use Intrinsic or a usual Call for vectorized
4706 // version of the instruction.
4707 // Is it beneficial to perform intrinsic call compared to lib call?
4708 bool NeedToScalarize;
4709 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4710 bool UseVectorIntrinsic =
4711 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4712 assert((UseVectorIntrinsic || !NeedToScalarize) &&(static_cast <bool> ((UseVectorIntrinsic || !NeedToScalarize
) && "Instruction should be scalarized elsewhere.") ?
void (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4713, __extension__ __PRETTY_FUNCTION__))
4713 "Instruction should be scalarized elsewhere.")(static_cast <bool> ((UseVectorIntrinsic || !NeedToScalarize
) && "Instruction should be scalarized elsewhere.") ?
void (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4713, __extension__ __PRETTY_FUNCTION__))
;
4714
4715 for (unsigned Part = 0; Part < UF; ++Part) {
4716 SmallVector<Value *, 4> Args;
4717 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4718 Value *Arg = CI->getArgOperand(i);
4719 // Some intrinsics have a scalar argument - don't replace it with a
4720 // vector.
4721 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
4722 Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4723 Args.push_back(Arg);
4724 }
4725
4726 Function *VectorF;
4727 if (UseVectorIntrinsic) {
4728 // Use vector version of the intrinsic.
4729 Type *TysForDecl[] = {CI->getType()};
4730 if (VF > 1)
4731 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4732 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4733 } else {
4734 // Use vector version of the library call.
4735 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4736 assert(!VFnName.empty() && "Vector function name is empty.")(static_cast <bool> (!VFnName.empty() && "Vector function name is empty."
) ? void (0) : __assert_fail ("!VFnName.empty() && \"Vector function name is empty.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4736, __extension__ __PRETTY_FUNCTION__))
;
4737 VectorF = M->getFunction(VFnName);
4738 if (!VectorF) {
4739 // Generate a declaration
4740 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4741 VectorF =
4742 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4743 VectorF->copyAttributesFrom(F);
4744 }
4745 }
4746 assert(VectorF && "Can't create vector function.")(static_cast <bool> (VectorF && "Can't create vector function."
) ? void (0) : __assert_fail ("VectorF && \"Can't create vector function.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4746, __extension__ __PRETTY_FUNCTION__))
;
4747
4748 SmallVector<OperandBundleDef, 1> OpBundles;
4749 CI->getOperandBundlesAsDefs(OpBundles);
4750 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4751
4752 if (isa<FPMathOperator>(V))
4753 V->copyFastMathFlags(CI);
4754
4755 VectorLoopValueMap.setVectorValue(&I, Part, V);
4756 addMetadata(V, &I);
4757 }
4758
4759 break;
4760 }
4761
4762 default:
4763 // This instruction is not vectorized by simple widening.
4764 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)
;
4765 llvm_unreachable("Unhandled instruction!")::llvm::llvm_unreachable_internal("Unhandled instruction!", "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4765)
;
4766 } // end of switch.
4767}
4768
4769void InnerLoopVectorizer::updateAnalysis() {
4770 // Forget the original basic block.
4771 PSE.getSE()->forgetLoop(OrigLoop);
4772
4773 // Update the dominator tree information.
4774 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&(static_cast <bool> (DT->properlyDominates(LoopBypassBlocks
.front(), LoopExitBlock) && "Entry does not dominate exit."
) ? void (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4775, __extension__ __PRETTY_FUNCTION__))
4775 "Entry does not dominate exit.")(static_cast <bool> (DT->properlyDominates(LoopBypassBlocks
.front(), LoopExitBlock) && "Entry does not dominate exit."
) ? void (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4775, __extension__ __PRETTY_FUNCTION__))
;
4776
4777 DT->addNewBlock(LoopMiddleBlock,
4778 LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4779 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4780 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4781 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4782 assert(DT->verify(DominatorTree::VerificationLevel::Fast))(static_cast <bool> (DT->verify(DominatorTree::VerificationLevel
::Fast)) ? void (0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast)"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4782, __extension__ __PRETTY_FUNCTION__))
;
4783}
4784
4785/// \brief Check whether it is safe to if-convert this phi node.
4786///
4787/// Phi nodes with constant expressions that can trap are not safe to if
4788/// convert.
4789static bool canIfConvertPHINodes(BasicBlock *BB) {
4790 for (PHINode &Phi : BB->phis()) {
4791 for (Value *V : Phi.incoming_values())
4792 if (auto *C = dyn_cast<Constant>(V))
4793 if (C->canTrap())
4794 return false;
4795 }
4796 return true;
4797}
4798
4799bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4800 if (!EnableIfConversion) {
4801 ORE->emit(createMissedAnalysis("IfConversionDisabled")
4802 << "if-conversion is disabled");
4803 return false;
4804 }
4805
4806 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable")(static_cast <bool> (TheLoop->getNumBlocks() > 1 &&
"Single block loops are vectorizable") ? void (0) : __assert_fail
("TheLoop->getNumBlocks() > 1 && \"Single block loops are vectorizable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4806, __extension__ __PRETTY_FUNCTION__))
;
4807
4808 // A list of pointers that we can safely read and write to.
4809 SmallPtrSet<Value *, 8> SafePointes;
4810
4811 // Collect safe addresses.
4812 for (BasicBlock *BB : TheLoop->blocks()) {
4813 if (blockNeedsPredication(BB))
4814 continue;
4815
4816 for (Instruction &I : *BB)
4817 if (auto *Ptr = getPointerOperand(&I))
4818 SafePointes.insert(Ptr);
4819 }
4820
4821 // Collect the blocks that need predication.
4822 BasicBlock *Header = TheLoop->getHeader();
4823 for (BasicBlock *BB : TheLoop->blocks()) {
4824 // We don't support switch statements inside loops.
4825 if (!isa<BranchInst>(BB->getTerminator())) {
4826 ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
4827 << "loop contains a switch statement");
4828 return false;
4829 }
4830
4831 // We must be able to predicate all blocks that need to be predicated.
4832 if (blockNeedsPredication(BB)) {
4833 if (!blockCanBePredicated(BB, SafePointes)) {
4834 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4835 << "control flow cannot be substituted for a select");
4836 return false;
4837 }
4838 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4839 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4840 << "control flow cannot be substituted for a select");
4841 return false;
4842 }
4843 }
4844
4845 // We can if-convert this loop.
4846 return true;
4847}
4848
4849bool LoopVectorizationLegality::canVectorize() {
4850 // Store the result and return it at the end instead of exiting early, in case
4851 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
4852 bool Result = true;
4853
4854 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE"loop-vectorize");
4855 // We must have a loop in canonical form. Loops with indirectbr in them cannot
4856 // be canonicalized.
4857 if (!TheLoop->getLoopPreheader()) {
4858 DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop doesn't have a legal pre-header.\n"
; } } while (false)
;
4859 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4860 << "loop control flow is not understood by vectorizer");
4861 if (DoExtraAnalysis)
4862 Result = false;
4863 else
4864 return false;
4865 }
4866
4867 // FIXME: The code is currently dead, since the loop gets sent to
4868 // LoopVectorizationLegality is already an innermost loop.
4869 //
4870 // We can only vectorize innermost loops.
4871 if (!TheLoop->empty()) {
4872 ORE->emit(createMissedAnalysis("NotInnermostLoop")
4873 << "loop is not the innermost loop");
4874 if (DoExtraAnalysis)
4875 Result = false;
4876 else
4877 return false;
4878 }
4879
4880 // We must have a single backedge.
4881 if (TheLoop->getNumBackEdges() != 1) {
4882 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4883 << "loop control flow is not understood by vectorizer");
4884 if (DoExtraAnalysis)
4885 Result = false;
4886 else
4887 return false;
4888 }
4889
4890 // We must have a single exiting block.
4891 if (!TheLoop->getExitingBlock()) {
4892 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4893 << "loop control flow is not understood by vectorizer");
4894 if (DoExtraAnalysis)
4895 Result = false;
4896 else
4897 return false;
4898 }
4899
4900 // We only handle bottom-tested loops, i.e. loop in which the condition is
4901 // checked at the end of each iteration. With that we can assume that all
4902 // instructions in the loop are executed the same number of times.
4903 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4904 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4905 << "loop control flow is not understood by vectorizer");
4906 if (DoExtraAnalysis)
4907 Result = false;
4908 else
4909 return false;
4910 }
4911
4912 // We need to have a loop header.
4913 DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a loop: " <<
TheLoop->getHeader()->getName() << '\n'; } } while
(false)
4914 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a loop: " <<
TheLoop->getHeader()->getName() << '\n'; } } while
(false)
;
4915
4916 // Check if we can if-convert non-single-bb loops.
4917 unsigned NumBlocks = TheLoop->getNumBlocks();
4918 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4919 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't if-convert the loop.\n"
; } } while (false)
;
4920 if (DoExtraAnalysis)
4921 Result = false;
4922 else
4923 return false;
4924 }
4925
4926 // Check if we can vectorize the instructions and CFG in this loop.
4927 if (!canVectorizeInstrs()) {
4928 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't vectorize the instructions or CFG\n"
; } } while (false)
;
4929 if (DoExtraAnalysis)
4930 Result = false;
4931 else
4932 return false;
4933 }
4934
4935 // Go over each instruction and look at memory deps.
4936 if (!canVectorizeMemory()) {
4937 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't vectorize due to memory conflicts\n"
; } } while (false)
;
4938 if (DoExtraAnalysis)
4939 Result = false;
4940 else
4941 return false;
4942 }
4943
4944 DEBUG(dbgs() << "LV: We can vectorize this loop"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4945 << (LAI->getRuntimePointerChecking()->Needdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4946 ? " (with a runtime bound check)"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4947 : "")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4948 << "!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
;
4949
4950 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4951
4952 // If an override option has been passed in for interleaved accesses, use it.
4953 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4954 UseInterleaved = EnableInterleavedMemAccesses;
4955
4956 // Analyze interleaved memory accesses.
4957 if (UseInterleaved)
4958 InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
4959
4960 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4961 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4962 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4963
4964 if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
4965 ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
4966 << "Too many SCEV assumptions need to be made and checked "
4967 << "at runtime");
4968 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Too many SCEV checks needed.\n"
; } } while (false)
;
4969 if (DoExtraAnalysis)
4970 Result = false;
4971 else
4972 return false;
4973 }
4974
4975 // Okay! We've done all the tests. If any have failed, return false. Otherwise
4976 // we can vectorize, and at this point we don't have any other mem analysis
4977 // which may limit our maximum vectorization factor, so just return true with
4978 // no restrictions.
4979 return Result;
4980}
4981
4982static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4983 if (Ty->isPointerTy())
4984 return DL.getIntPtrType(Ty);
4985
4986 // It is possible that char's or short's overflow when we ask for the loop's
4987 // trip count, work around this by changing the type size.
4988 if (Ty->getScalarSizeInBits() < 32)
4989 return Type::getInt32Ty(Ty->getContext());
4990
4991 return Ty;
4992}
4993
4994static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4995 Ty0 = convertPointerToIntegerType(DL, Ty0);
4996 Ty1 = convertPointerToIntegerType(DL, Ty1);
4997 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4998 return Ty0;
4999 return Ty1;
5000}
5001
5002/// \brief Check that the instruction has outside loop users and is not an
5003/// identified reduction variable.
5004static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
5005 SmallPtrSetImpl<Value *> &AllowedExit) {
5006 // Reduction and Induction instructions are allowed to have exit users. All
5007 // other instructions must not have external users.
5008 if (!AllowedExit.count(Inst))
5009 // Check that all of the users of the loop are inside the BB.
5010 for (User *U : Inst->users()) {
5011 Instruction *UI = cast<Instruction>(U);
5012 // This user may be a reduction exit value.
5013 if (!TheLoop->contains(UI)) {
5014 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an outside user for : "
<< *UI << '\n'; } } while (false)
;
5015 return true;
5016 }
5017 }
5018 return false;
5019}
5020
5021void LoopVectorizationLegality::addInductionPhi(
5022 PHINode *Phi, const InductionDescriptor &ID,
5023 SmallPtrSetImpl<Value *> &AllowedExit) {
5024 Inductions[Phi] = ID;
5025
5026 // In case this induction also comes with casts that we know we can ignore
5027 // in the vectorized loop body, record them here. All casts could be recorded
5028 // here for ignoring, but suffices to record only the first (as it is the
5029 // only one that may bw used outside the cast sequence).
5030 const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
5031 if (!Casts.empty())
5032 InductionCastsToIgnore.insert(*Casts.begin());
5033
5034 Type *PhiTy = Phi->getType();
5035 const DataLayout &DL = Phi->getModule()->getDataLayout();
5036
5037 // Get the widest type.
5038 if (!PhiTy->isFloatingPointTy()) {
5039 if (!WidestIndTy)
5040 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
5041 else
5042 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
5043 }
5044
5045 // Int inductions are special because we only allow one IV.
5046 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
5047 ID.getConstIntStepValue() &&
5048 ID.getConstIntStepValue()->isOne() &&
5049 isa<Constant>(ID.getStartValue()) &&
5050 cast<Constant>(ID.getStartValue())->isNullValue()) {
5051
5052 // Use the phi node with the widest type as induction. Use the last
5053 // one if there are multiple (no good reason for doing this other
5054 // than it is expedient). We've checked that it begins at zero and
5055 // steps by one, so this is a canonical induction variable.
5056 if (!PrimaryInduction || PhiTy == WidestIndTy)
5057 PrimaryInduction = Phi;
5058 }
5059
5060 // Both the PHI node itself, and the "post-increment" value feeding
5061 // back into the PHI node may have external users.
5062 // We can allow those uses, except if the SCEVs we have for them rely
5063 // on predicates that only hold within the loop, since allowing the exit
5064 // currently means re-using this SCEV outside the loop.
5065 if (PSE.getUnionPredicate().isAlwaysTrue()) {
5066 AllowedExit.insert(Phi);
5067 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
5068 }
5069
5070 DEBUG(dbgs() << "LV: Found an induction variable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an induction variable.\n"
; } } while (false)
;
5071}
5072
5073bool LoopVectorizationLegality::canVectorizeInstrs() {
5074 BasicBlock *Header = TheLoop->getHeader();
5075
5076 // Look for the attribute signaling the absence of NaNs.
5077 Function &F = *Header->getParent();
5078 HasFunNoNaNAttr =
5079 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
5080
5081 // For each block in the loop.
5082 for (BasicBlock *BB : TheLoop->blocks()) {
5083 // Scan the instructions in the block and look for hazards.
5084 for (Instruction &I : *BB) {
5085 if (auto *Phi = dyn_cast<PHINode>(&I)) {
5086 Type *PhiTy = Phi->getType();
5087 // Check that this PHI type is allowed.
5088 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
5089 !PhiTy->isPointerTy()) {
5090 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5091 << "loop control flow is not understood by vectorizer");
5092 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an non-int non-pointer PHI.\n"
; } } while (false)
;
5093 return false;
5094 }
5095
5096 // If this PHINode is not in the header block, then we know that we
5097 // can convert it to select during if-conversion. No need to check if
5098 // the PHIs in this block are induction or reduction variables.
5099 if (BB != Header) {
5100 // Check that this instruction has no outside users or is an
5101 // identified reduction value with an outside user.
5102 if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
5103 continue;
5104 ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi)
5105 << "value could not be identified as "
5106 "an induction or reduction variable");
5107 return false;
5108 }
5109
5110 // We only allow if-converted PHIs with exactly two incoming values.
5111 if (Phi->getNumIncomingValues() != 2) {
5112 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5113 << "control flow not understood by vectorizer");
5114 DEBUG(dbgs() << "LV: Found an invalid PHI.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an invalid PHI.\n"
; } } while (false)
;
5115 return false;
5116 }
5117
5118 RecurrenceDescriptor RedDes;
5119 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
5120 DT)) {
5121 if (RedDes.hasUnsafeAlgebra())
5122 Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
5123 AllowedExit.insert(RedDes.getLoopExitInstr());
5124 Reductions[Phi] = RedDes;
5125 continue;
5126 }
5127
5128 InductionDescriptor ID;
5129 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
5130 addInductionPhi(Phi, ID, AllowedExit);
5131 if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
5132 Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
5133 continue;
5134 }
5135
5136 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
5137 SinkAfter, DT)) {
5138 FirstOrderRecurrences.insert(Phi);
5139 continue;
5140 }
5141
5142 // As a last resort, coerce the PHI to a AddRec expression
5143 // and re-try classifying it a an induction PHI.
5144 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
5145 addInductionPhi(Phi, ID, AllowedExit);
5146 continue;
5147 }
5148
5149 ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
5150 << "value that could not be identified as "
5151 "reduction is used outside the loop");
5152 DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an unidentified PHI."
<< *Phi << "\n"; } } while (false)
;
5153 return false;
5154 } // end of PHI handling
5155
5156 // We handle calls that:
5157 // * Are debug info intrinsics.
5158 // * Have a mapping to an IR intrinsic.
5159 // * Have a vector version available.
5160 auto *CI = dyn_cast<CallInst>(&I);
5161 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
5162 !isa<DbgInfoIntrinsic>(CI) &&
5163 !(CI->getCalledFunction() && TLI &&
5164 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5165 ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
5166 << "call instruction cannot be vectorized");
5167 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n"
; } } while (false)
;
5168 return false;
5169 }
5170
5171 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
5172 // second argument is the same (i.e. loop invariant)
5173 if (CI && hasVectorInstrinsicScalarOpd(
5174 getVectorIntrinsicIDForCall(CI, TLI), 1)) {
5175 auto *SE = PSE.getSE();
5176 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
5177 ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
5178 << "intrinsic instruction cannot be vectorized");
5179 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found unvectorizable intrinsic "
<< *CI << "\n"; } } while (false)
;
5180 return false;
5181 }
5182 }
5183
5184 // Check that the instruction return type is vectorizable.
5185 // Also, we can't vectorize extractelement instructions.
5186 if ((!VectorType::isValidElementType(I.getType()) &&
5187 !I.getType()->isVoidTy()) ||
5188 isa<ExtractElementInst>(I)) {
5189 ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
5190 << "instruction return type cannot be vectorized");
5191 DEBUG(dbgs() << "LV: Found unvectorizable type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found unvectorizable type.\n"
; } } while (false)
;
5192 return false;
5193 }
5194
5195 // Check that the stored type is vectorizable.
5196 if (auto *ST = dyn_cast<StoreInst>(&I)) {
5197 Type *T = ST->getValueOperand()->getType();
5198 if (!VectorType::isValidElementType(T)) {
5199 ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
5200 << "store instruction cannot be vectorized");
5201 return false;
5202 }
5203
5204 // FP instructions can allow unsafe algebra, thus vectorizable by
5205 // non-IEEE-754 compliant SIMD units.
5206 // This applies to floating-point math operations and calls, not memory
5207 // operations, shuffles, or casts, as they don't change precision or
5208 // semantics.
5209 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
5210 !I.isFast()) {
5211 DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found FP op with unsafe algebra.\n"
; } } while (false)
;
5212 Hints->setPotentiallyUnsafe();
5213 }
5214
5215 // Reduction instructions are allowed to have exit users.
5216 // All other instructions must not have external users.
5217 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
5218 ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
5219 << "value cannot be used outside the loop");
5220 return false;
5221 }
5222 } // next instr.
5223 }
5224
5225 if (!PrimaryInduction) {
5226 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Did not find one integer induction var.\n"
; } } while (false)
;
5227 if (Inductions.empty()) {
5228 ORE->emit(createMissedAnalysis("NoInductionVariable")
5229 << "loop induction variable could not be identified");
5230 return false;
5231 }
5232 }
5233
5234 // Now we know the widest induction type, check if our found induction
5235 // is the same size. If it's not, unset it here and InnerLoopVectorizer
5236 // will create another.
5237 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5238 PrimaryInduction = nullptr;
5239
5240 return true;
5241}
5242
5243void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
5244 // We should not collect Scalars more than once per VF. Right now, this
5245 // function is called from collectUniformsAndScalars(), which already does
5246 // this check. Collecting Scalars for VF=1 does not make any sense.
5247 assert(VF >= 2 && !Scalars.count(VF) &&(static_cast <bool> (VF >= 2 && !Scalars.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Scalars.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5248, __extension__ __PRETTY_FUNCTION__))
5248 "This function should not be visited twice for the same VF")(static_cast <bool> (VF >= 2 && !Scalars.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Scalars.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5248, __extension__ __PRETTY_FUNCTION__))
;
5249
5250 SmallSetVector<Instruction *, 8> Worklist;
5251
5252 // These sets are used to seed the analysis with pointers used by memory
5253 // accesses that will remain scalar.
5254 SmallSetVector<Instruction *, 8> ScalarPtrs;
5255 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5256
5257 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5258 // The pointer operands of loads and stores will be scalar as long as the
5259 // memory access is not a gather or scatter operation. The value operand of a
5260 // store will remain scalar if the store is scalarized.
5261 auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5262 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5263 assert(WideningDecision != CM_Unknown &&(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5264, __extension__ __PRETTY_FUNCTION__))
5264 "Widening decision should be ready at this moment")(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5264, __extension__ __PRETTY_FUNCTION__))
;
5265 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5266 if (Ptr == Store->getValueOperand())
5267 return WideningDecision == CM_Scalarize;
5268 assert(Ptr == getPointerOperand(MemAccess) &&(static_cast <bool> (Ptr == getPointerOperand(MemAccess
) && "Ptr is neither a value or pointer operand") ? void
(0) : __assert_fail ("Ptr == getPointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5269, __extension__ __PRETTY_FUNCTION__))
5269 "Ptr is neither a value or pointer operand")(static_cast <bool> (Ptr == getPointerOperand(MemAccess
) && "Ptr is neither a value or pointer operand") ? void
(0) : __assert_fail ("Ptr == getPointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5269, __extension__ __PRETTY_FUNCTION__))
;
5270 return WideningDecision != CM_GatherScatter;
5271 };
5272
5273 // A helper that returns true if the given value is a bitcast or
5274 // getelementptr instruction contained in the loop.
5275 auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5276 return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5277 isa<GetElementPtrInst>(V)) &&
5278 !TheLoop->isLoopInvariant(V);
5279 };
5280
5281 // A helper that evaluates a memory access's use of a pointer. If the use
5282 // will be a scalar use, and the pointer is only used by memory accesses, we
5283 // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
5284 // PossibleNonScalarPtrs.
5285 auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5286 // We only care about bitcast and getelementptr instructions contained in
5287 // the loop.
5288 if (!isLoopVaryingBitCastOrGEP(Ptr))
5289 return;
5290
5291 // If the pointer has already been identified as scalar (e.g., if it was
5292 // also identified as uniform), there's nothing to do.
5293 auto *I = cast<Instruction>(Ptr);
5294 if (Worklist.count(I))
5295 return;
5296
5297 // If the use of the pointer will be a scalar use, and all users of the
5298 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5299 // place the pointer in PossibleNonScalarPtrs.
5300 if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5301 return isa<LoadInst>(U) || isa<StoreInst>(U);
5302 }))
5303 ScalarPtrs.insert(I);
5304 else
5305 PossibleNonScalarPtrs.insert(I);
5306 };
5307
5308 // We seed the scalars analysis with three classes of instructions: (1)
5309 // instructions marked uniform-after-vectorization, (2) bitcast and
5310 // getelementptr instructions used by memory accesses requiring a scalar use,
5311 // and (3) pointer induction variables and their update instructions (we
5312 // currently only scalarize these).
5313 //
5314 // (1) Add to the worklist all instructions that have been identified as
5315 // uniform-after-vectorization.
5316 Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5317
5318 // (2) Add to the worklist all bitcast and getelementptr instructions used by
5319 // memory accesses requiring a scalar use. The pointer operands of loads and
5320 // stores will be scalar as long as the memory accesses is not a gather or
5321 // scatter operation. The value operand of a store will remain scalar if the
5322 // store is scalarized.
5323 for (auto *BB : TheLoop->blocks())
5324 for (auto &I : *BB) {
5325 if (auto *Load = dyn_cast<LoadInst>(&I)) {
5326 evaluatePtrUse(Load, Load->getPointerOperand());
5327 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5328 evaluatePtrUse(Store, Store->getPointerOperand());
5329 evaluatePtrUse(Store, Store->getValueOperand());
5330 }
5331 }
5332 for (auto *I : ScalarPtrs)
5333 if (!PossibleNonScalarPtrs.count(I)) {
5334 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)
;
5335 Worklist.insert(I);
5336 }
5337
5338 // (3) Add to the worklist all pointer induction variables and their update
5339 // instructions.
5340 //
5341 // TODO: Once we are able to vectorize pointer induction variables we should
5342 // no longer insert them into the worklist here.
5343 auto *Latch = TheLoop->getLoopLatch();
5344 for (auto &Induction : *Legal->getInductionVars()) {
5345 auto *Ind = Induction.first;
5346 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5347 if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
5348 continue;
5349 Worklist.insert(Ind);
5350 Worklist.insert(IndUpdate);
5351 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)
;
5352 DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
5353 }
5354
5355 // Insert the forced scalars.
5356 // FIXME: Currently widenPHIInstruction() often creates a dead vector
5357 // induction variable when the PHI user is scalarized.
5358 if (ForcedScalars.count(VF))
5359 for (auto *I : ForcedScalars.find(VF)->second)
5360 Worklist.insert(I);
5361
5362 // Expand the worklist by looking through any bitcasts and getelementptr
5363 // instructions we've already identified as scalar. This is similar to the
5364 // expansion step in collectLoopUniforms(); however, here we're only
5365 // expanding to include additional bitcasts and getelementptr instructions.
5366 unsigned Idx = 0;
5367 while (Idx != Worklist.size()) {
5368 Instruction *Dst = Worklist[Idx++];
5369 if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5370 continue;
5371 auto *Src = cast<Instruction>(Dst->getOperand(0));
5372 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5373 auto *J = cast<Instruction>(U);
5374 return !TheLoop->contains(J) || Worklist.count(J) ||
5375 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5376 isScalarUse(J, Src));
5377 })) {
5378 Worklist.insert(Src);
5379 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)
;
5380 }
5381 }
5382
5383 // An induction variable will remain scalar if all users of the induction
5384 // variable and induction variable update remain scalar.
5385 for (auto &Induction : *Legal->getInductionVars()) {
5386 auto *Ind = Induction.first;
5387 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5388
5389 // We already considered pointer induction variables, so there's no reason
5390 // to look at their users again.
5391 //
5392 // TODO: Once we are able to vectorize pointer induction variables we
5393 // should no longer skip over them here.
5394 if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
5395 continue;
5396
5397 // Determine if all users of the induction variable are scalar after
5398 // vectorization.
5399 auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5400 auto *I = cast<Instruction>(U);
5401 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5402 });
5403 if (!ScalarInd)
5404 continue;
5405
5406 // Determine if all users of the induction variable update instruction are
5407 // scalar after vectorization.
5408 auto ScalarIndUpdate =
5409 llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5410 auto *I = cast<Instruction>(U);
5411 return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5412 });
5413 if (!ScalarIndUpdate)
5414 continue;
5415
5416 // The induction variable and its update instruction will remain scalar.
5417 Worklist.insert(Ind);
5418 Worklist.insert(IndUpdate);
5419 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)
;
5420 DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
5421 }
5422
5423 Scalars[VF].insert(Worklist.begin(), Worklist.end());
5424}
5425
5426bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) {
5427 if (!Legal->blockNeedsPredication(I->getParent()))
5428 return false;
5429 switch(I->getOpcode()) {
5430 default:
5431 break;
5432 case Instruction::Load:
5433 case Instruction::Store: {
5434 if (!Legal->isMaskRequired(I))
5435 return false;
5436 auto *Ptr = getPointerOperand(I);
5437 auto *Ty = getMemInstValueType(I);
5438 return isa<LoadInst>(I) ?
5439 !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty))
5440 : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
5441 }
5442 case Instruction::UDiv:
5443 case Instruction::SDiv:
5444 case Instruction::SRem:
5445 case Instruction::URem:
5446 return mayDivideByZero(*I);
5447 }
5448 return false;
5449}
5450
5451bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I,
5452 unsigned VF) {
5453 // Get and ensure we have a valid memory instruction.
5454 LoadInst *LI = dyn_cast<LoadInst>(I);
5455 StoreInst *SI = dyn_cast<StoreInst>(I);
5456 assert((LI || SI) && "Invalid memory instruction")(static_cast <bool> ((LI || SI) && "Invalid memory instruction"
) ? void (0) : __assert_fail ("(LI || SI) && \"Invalid memory instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5456, __extension__ __PRETTY_FUNCTION__))
;
5457
5458 auto *Ptr = getPointerOperand(I);
5459
5460 // In order to be widened, the pointer should be consecutive, first of all.
5461 if (!Legal->isConsecutivePtr(Ptr))
5462 return false;
5463
5464 // If the instruction is a store located in a predicated block, it will be
5465 // scalarized.
5466 if (isScalarWithPredication(I))
5467 return false;
5468
5469 // If the instruction's allocated size doesn't equal it's type size, it
5470 // requires padding and will be scalarized.
5471 auto &DL = I->getModule()->getDataLayout();
5472 auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5473 if (hasIrregularType(ScalarTy, DL, VF))
5474 return false;
5475
5476 return true;
5477}
5478
5479void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
5480 // We should not collect Uniforms more than once per VF. Right now,
5481 // this function is called from collectUniformsAndScalars(), which
5482 // already does this check. Collecting Uniforms for VF=1 does not make any
5483 // sense.
5484
5485 assert(VF >= 2 && !Uniforms.count(VF) &&(static_cast <bool> (VF >= 2 && !Uniforms.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Uniforms.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5486 "This function should not be visited twice for the same VF")(static_cast <bool> (VF >= 2 && !Uniforms.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Uniforms.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
;
5487
5488 // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5489 // not analyze again. Uniforms.count(VF) will return 1.
5490 Uniforms[VF].clear();
5491
5492 // We now know that the loop is vectorizable!
5493 // Collect instructions inside the loop that will remain uniform after
5494 // vectorization.
5495
5496 // Global values, params and instructions outside of current loop are out of
5497 // scope.
5498 auto isOutOfScope = [&](Value *V) -> bool {
5499 Instruction *I = dyn_cast<Instruction>(V);
5500 return (!I || !TheLoop->contains(I));
5501 };
5502
5503 SetVector<Instruction *> Worklist;
5504 BasicBlock *Latch = TheLoop->getLoopLatch();
5505
5506 // Start with the conditional branch. If the branch condition is an
5507 // instruction contained in the loop that is only used by the branch, it is
5508 // uniform.
5509 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5510 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
5511 Worklist.insert(Cmp);
5512 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)
;
5513 }
5514
5515 // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5516 // are pointers that are treated like consecutive pointers during
5517 // vectorization. The pointer operands of interleaved accesses are an
5518 // example.
5519 SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5520
5521 // Holds pointer operands of instructions that are possibly non-uniform.
5522 SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5523
5524 auto isUniformDecision = [&](Instruction *I, unsigned VF) {
5525 InstWidening WideningDecision = getWideningDecision(I, VF);
5526 assert(WideningDecision != CM_Unknown &&(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5527, __extension__ __PRETTY_FUNCTION__))
5527 "Widening decision should be ready at this moment")(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5527, __extension__ __PRETTY_FUNCTION__))
;
5528
5529 return (WideningDecision == CM_Widen ||
5530 WideningDecision == CM_Widen_Reverse ||
5531 WideningDecision == CM_Interleave);
5532 };
5533 // Iterate over the instructions in the loop, and collect all
5534 // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5535 // that a consecutive-like pointer operand will be scalarized, we collect it
5536 // in PossibleNonUniformPtrs instead. We use two sets here because a single
5537 // getelementptr instruction can be used by both vectorized and scalarized
5538 // memory instructions. For example, if a loop loads and stores from the same
5539 // location, but the store is conditional, the store will be scalarized, and
5540 // the getelementptr won't remain uniform.
5541 for (auto *BB : TheLoop->blocks())
5542 for (auto &I : *BB) {
5543 // If there's no pointer operand, there's nothing to do.
5544 auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I));
5545 if (!Ptr)
5546 continue;
5547
5548 // True if all users of Ptr are memory accesses that have Ptr as their
5549 // pointer operand.
5550 auto UsersAreMemAccesses =
5551 llvm::all_of(Ptr->users(), [&](User *U) -> bool {
5552 return getPointerOperand(U) == Ptr;
5553 });
5554
5555 // Ensure the memory instruction will not be scalarized or used by
5556 // gather/scatter, making its pointer operand non-uniform. If the pointer
5557 // operand is used by any instruction other than a memory access, we
5558 // conservatively assume the pointer operand may be non-uniform.
5559 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5560 PossibleNonUniformPtrs.insert(Ptr);
5561
5562 // If the memory instruction will be vectorized and its pointer operand
5563 // is consecutive-like, or interleaving - the pointer operand should
5564 // remain uniform.
5565 else
5566 ConsecutiveLikePtrs.insert(Ptr);
5567 }
5568
5569 // Add to the Worklist all consecutive and consecutive-like pointers that
5570 // aren't also identified as possibly non-uniform.
5571 for (auto *V : ConsecutiveLikePtrs)
5572 if (!PossibleNonUniformPtrs.count(V)) {
5573 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)
;
5574 Worklist.insert(V);
5575 }
5576
5577 // Expand Worklist in topological order: whenever a new instruction
5578 // is added , its users should be either already inside Worklist, or
5579 // out of scope. It ensures a uniform instruction will only be used
5580 // by uniform instructions or out of scope instructions.
5581 unsigned idx = 0;
5582 while (idx != Worklist.size()) {
5583 Instruction *I = Worklist[idx++];
5584
5585 for (auto OV : I->operand_values()) {
5586 if (isOutOfScope(OV))
5587 continue;
5588 auto *OI = cast<Instruction>(OV);
5589 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5590 auto *J = cast<Instruction>(U);
5591 return !TheLoop->contains(J) || Worklist.count(J) ||
5592 (OI == getPointerOperand(J) && isUniformDecision(J, VF));
5593 })) {
5594 Worklist.insert(OI);
5595 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)
;
5596 }
5597 }
5598 }
5599
5600 // Returns true if Ptr is the pointer operand of a memory access instruction
5601 // I, and I is known to not require scalarization.
5602 auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5603 return getPointerOperand(I) == Ptr && isUniformDecision(I, VF);
5604 };
5605
5606 // For an instruction to be added into Worklist above, all its users inside
5607 // the loop should also be in Worklist. However, this condition cannot be
5608 // true for phi nodes that form a cyclic dependence. We must process phi
5609 // nodes separately. An induction variable will remain uniform if all users
5610 // of the induction variable and induction variable update remain uniform.
5611 // The code below handles both pointer and non-pointer induction variables.
5612 for (auto &Induction : *Legal->getInductionVars()) {
5613 auto *Ind = Induction.first;
5614 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5615
5616 // Determine if all users of the induction variable are uniform after
5617 // vectorization.
5618 auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5619 auto *I = cast<Instruction>(U);
5620 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5621 isVectorizedMemAccessUse(I, Ind);
5622 });
5623 if (!UniformInd)
5624 continue;
5625
5626 // Determine if all users of the induction variable update instruction are
5627 // uniform after vectorization.
5628 auto UniformIndUpdate =
5629 llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5630 auto *I = cast<Instruction>(U);
5631 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5632 isVectorizedMemAccessUse(I, IndUpdate);
5633 });
5634 if (!UniformIndUpdate)
5635 continue;
5636
5637 // The induction variable and its update instruction will remain uniform.
5638 Worklist.insert(Ind);
5639 Worklist.insert(IndUpdate);
5640 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)
;
5641 DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
5642 }
5643
5644 Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5645}
5646
5647bool LoopVectorizationLegality::canVectorizeMemory() {
5648 LAI = &(*GetLAA)(*TheLoop);
5649 InterleaveInfo.setLAI(LAI);
5650 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
5651 if (LAR) {
5652 ORE->emit([&]() {
5653 return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
5654 "loop not vectorized: ", *LAR);
5655 });
5656 }
5657 if (!LAI->canVectorizeMemory())
5658 return false;
5659
5660 if (LAI->hasStoreToLoopInvariantAddress()) {
5661 ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
5662 << "write to a loop invariant address could not be vectorized");
5663 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We don't allow storing to uniform addresses\n"
; } } while (false)
;
5664 return false;
5665 }
5666
5667 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5668 PSE.addPredicate(LAI->getPSE().getUnionPredicate());
5669
5670 return true;
5671}
5672
5673bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
5674 Value *In0 = const_cast<Value *>(V);
5675 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5676 if (!PN)
5677 return false;
5678
5679 return Inductions.count(PN);
5680}
5681
5682bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
5683 auto *Inst = dyn_cast<Instruction>(V);
5684 return (Inst && InductionCastsToIgnore.count(Inst));
5685}
5686
5687bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5688 return isInductionPhi(V) || isCastedInductionVariable(V);
5689}
5690
5691bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
5692 return FirstOrderRecurrences.count(Phi);
5693}
5694
5695bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5696 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
5697}
5698
5699bool LoopVectorizationLegality::blockCanBePredicated(
5700 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
5701 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
5702
5703 for (Instruction &I : *BB) {
5704 // Check that we don't have a constant expression that can trap as operand.
5705 for (Value *Operand : I.operands()) {
5706 if (auto *C = dyn_cast<Constant>(Operand))
5707 if (C->canTrap())
5708 return false;
5709 }
5710 // We might be able to hoist the load.
5711 if (I.mayReadFromMemory()) {
5712 auto *LI = dyn_cast<LoadInst>(&I);
5713 if (!LI)
5714 return false;
5715 if (!SafePtrs.count(LI->getPointerOperand())) {
5716 // !llvm.mem.parallel_loop_access implies if-conversion safety.
5717 // Otherwise, record that the load needs (real or emulated) masking
5718 // and let the cost model decide.
5719 if (!IsAnnotatedParallel)
5720 MaskedOp.insert(LI);
5721 continue;
5722 }
5723 }
5724
5725 if (I.mayWriteToMemory()) {
5726 auto *SI = dyn_cast<StoreInst>(&I);
5727 if (!SI)
5728 return false;
5729 // Predicated store requires some form of masking:
5730 // 1) masked store HW instruction,
5731 // 2) emulation via load-blend-store (only if safe and legal to do so,
5732 // be aware on the race conditions), or
5733 // 3) element-by-element predicate check and scalar store.
5734 MaskedOp.insert(SI);
5735 continue;
5736 }
5737 if (I.mayThrow())
5738 return false;
5739 }
5740
5741 return true;
5742}
5743
5744void InterleavedAccessInfo::collectConstStrideAccesses(
5745 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
5746 const ValueToValueMap &Strides) {
5747 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5748
5749 // Since it's desired that the load/store instructions be maintained in
5750 // "program order" for the interleaved access analysis, we have to visit the
5751 // blocks in the loop in reverse postorder (i.e., in a topological order).
5752 // Such an ordering will ensure that any load/store that may be executed
5753 // before a second load/store will precede the second load/store in
5754 // AccessStrideInfo.
5755 LoopBlocksDFS DFS(TheLoop);
5756 DFS.perform(LI);
5757 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
5758 for (auto &I : *BB) {
5759 auto *LI = dyn_cast<LoadInst>(&I);
5760 auto *SI = dyn_cast<StoreInst>(&I);
5761 if (!LI && !SI)
5762 continue;
5763
5764 Value *Ptr = getPointerOperand(&I);
5765 // We don't check wrapping here because we don't know yet if Ptr will be
5766 // part of a full group or a group with gaps. Checking wrapping for all
5767 // pointers (even those that end up in groups with no gaps) will be overly
5768 // conservative. For full groups, wrapping should be ok since if we would
5769 // wrap around the address space we would do a memory access at nullptr
5770 // even without the transformation. The wrapping checks are therefore
5771 // deferred until after we've formed the interleaved groups.
5772 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
5773 /*Assume=*/true, /*ShouldCheckWrap=*/false);
5774
5775 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
5776 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
5777 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
5778
5779 // An alignment of 0 means target ABI alignment.
5780 unsigned Align = getMemInstAlignment(&I);
5781 if (!Align)
5782 Align = DL.getABITypeAlignment(PtrTy->getElementType());
5783
5784 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
5785 }
5786}
5787
5788// Analyze interleaved accesses and collect them into interleaved load and
5789// store groups.
5790//
5791// When generating code for an interleaved load group, we effectively hoist all
5792// loads in the group to the location of the first load in program order. When
5793// generating code for an interleaved store group, we sink all stores to the
5794// location of the last store. This code motion can change the order of load
5795// and store instructions and may break dependences.
5796//
5797// The code generation strategy mentioned above ensures that we won't violate
5798// any write-after-read (WAR) dependences.
5799//
5800// E.g., for the WAR dependence: a = A[i]; // (1)
5801// A[i] = b; // (2)
5802//
5803// The store group of (2) is always inserted at or below (2), and the load
5804// group of (1) is always inserted at or above (1). Thus, the instructions will
5805// never be reordered. All other dependences are checked to ensure the
5806// correctness of the instruction reordering.
5807//
5808// The algorithm visits all memory accesses in the loop in bottom-up program
5809// order. Program order is established by traversing the blocks in the loop in
5810// reverse postorder when collecting the accesses.
5811//
5812// We visit the memory accesses in bottom-up order because it can simplify the
5813// construction of store groups in the presence of write-after-write (WAW)
5814// dependences.
5815//
5816// E.g., for the WAW dependence: A[i] = a; // (1)
5817// A[i] = b; // (2)
5818// A[i + 1] = c; // (3)
5819//
5820// We will first create a store group with (3) and (2). (1) can't be added to
5821// this group because it and (2) are dependent. However, (1) can be grouped
5822// with other accesses that may precede it in program order. Note that a
5823// bottom-up order does not imply that WAW dependences should not be checked.
5824void InterleavedAccessInfo::analyzeInterleaving(
5825 const ValueToValueMap &Strides) {
5826 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Analyzing interleaved accesses...\n"
; } } while (false)
;
5827
5828 // Holds all accesses with a constant stride.
5829 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
5830 collectConstStrideAccesses(AccessStrideInfo, Strides);
5831
5832 if (AccessStrideInfo.empty())
5833 return;
5834
5835 // Collect the dependences in the loop.
5836 collectDependences();
5837
5838 // Holds all interleaved store groups temporarily.
5839 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
5840 // Holds all interleaved load groups temporarily.
5841 SmallSetVector<InterleaveGroup *, 4> LoadGroups;
5842
5843 // Search in bottom-up program order for pairs of accesses (A and B) that can
5844 // form interleaved load or store groups. In the algorithm below, access A
5845 // precedes access B in program order. We initialize a group for B in the
5846 // outer loop of the algorithm, and then in the inner loop, we attempt to
5847 // insert each A into B's group if:
5848 //
5849 // 1. A and B have the same stride,
5850 // 2. A and B have the same memory object size, and
5851 // 3. A belongs in B's group according to its distance from B.
5852 //
5853 // Special care is taken to ensure group formation will not break any
5854 // dependences.
5855 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
5856 BI != E; ++BI) {
5857 Instruction *B = BI->first;
5858 StrideDescriptor DesB = BI->second;
5859
5860 // Initialize a group for B if it has an allowable stride. Even if we don't
5861 // create a group for B, we continue with the bottom-up algorithm to ensure
5862 // we don't break any of B's dependences.
5863 InterleaveGroup *Group = nullptr;
5864 if (isStrided(DesB.Stride)) {
5865 Group = getInterleaveGroup(B);
5866 if (!Group) {
5867 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Creating an interleave group with:"
<< *B << '\n'; } } while (false)
;
5868 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
5869 }
5870 if (B->mayWriteToMemory())
5871 StoreGroups.insert(Group);
5872 else
5873 LoadGroups.insert(Group);
5874 }
5875
5876 for (auto AI = std::next(BI); AI != E; ++AI) {
5877 Instruction *A = AI->first;
5878 StrideDescriptor DesA = AI->second;
5879
5880 // Our code motion strategy implies that we can't have dependences
5881 // between accesses in an interleaved group and other accesses located
5882 // between the first and last member of the group. Note that this also
5883 // means that a group can't have more than one member at a given offset.
5884 // The accesses in a group can have dependences with other accesses, but
5885 // we must ensure we don't extend the boundaries of the group such that
5886 // we encompass those dependent accesses.
5887 //
5888 // For example, assume we have the sequence of accesses shown below in a
5889 // stride-2 loop:
5890 //
5891 // (1, 2) is a group | A[i] = a; // (1)
5892 // | A[i-1] = b; // (2) |
5893 // A[i-3] = c; // (3)
5894 // A[i] = d; // (4) | (2, 4) is not a group
5895 //
5896 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
5897 // but not with (4). If we did, the dependent access (3) would be within
5898 // the boundaries of the (2, 4) group.
5899 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
5900 // If a dependence exists and A is already in a group, we know that A
5901 // must be a store since A precedes B and WAR dependences are allowed.
5902 // Thus, A would be sunk below B. We release A's group to prevent this
5903 // illegal code motion. A will then be free to form another group with
5904 // instructions that precede it.
5905 if (isInterleaved(A)) {
5906 InterleaveGroup *StoreGroup = getInterleaveGroup(A);
5907 StoreGroups.remove(StoreGroup);
5908 releaseGroup(StoreGroup);
5909 }
5910
5911 // If a dependence exists and A is not already in a group (or it was
5912 // and we just released it), B might be hoisted above A (if B is a
5913 // load) or another store might be sunk below A (if B is a store). In
5914 // either case, we can't add additional instructions to B's group. B
5915 // will only form a group with instructions that it precedes.
5916 break;
5917 }
5918
5919 // At this point, we've checked for illegal code motion. If either A or B
5920 // isn't strided, there's nothing left to do.
5921 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
5922 continue;
5923
5924 // Ignore A if it's already in a group or isn't the same kind of memory
5925 // operation as B.
5926 // Note that mayReadFromMemory() isn't mutually exclusive to mayWriteToMemory
5927 // in the case of atomic loads. We shouldn't see those here, canVectorizeMemory()
5928 // should have returned false - except for the case we asked for optimization
5929 // remarks.
5930 if (isInterleaved(A) || (A->mayReadFromMemory() != B->mayReadFromMemory())
5931 || (A->mayWriteToMemory() != B->mayWriteToMemory()))
5932 continue;
5933
5934 // Check rules 1 and 2. Ignore A if its stride or size is different from
5935 // that of B.
5936 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
5937 continue;
5938
5939 // Ignore A if the memory object of A and B don't belong to the same
5940 // address space
5941 if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
5942 continue;
5943
5944 // Calculate the distance from A to B.
5945 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
5946 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
5947 if (!DistToB)
5948 continue;
5949 int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
5950
5951 // Check rule 3. Ignore A if its distance to B is not a multiple of the
5952 // size.
5953 if (DistanceToB % static_cast<int64_t>(DesB.Size))
5954 continue;
5955
5956 // Ignore A if either A or B is in a predicated block. Although we
5957 // currently prevent group formation for predicated accesses, we may be
5958 // able to relax this limitation in the future once we handle more
5959 // complicated blocks.
5960 if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
5961 continue;
5962
5963 // The index of A is the index of B plus A's distance to B in multiples
5964 // of the size.
5965 int IndexA =
5966 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
5967
5968 // Try to insert A into B's group.
5969 if (Group->insertMember(A, IndexA, DesA.Align)) {
5970 DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Inserted:" <<
*A << '\n' << " into the interleave group with"
<< *B << '\n'; } } while (false)
5971 << " into the interleave group with" << *B << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Inserted:" <<
*A << '\n' << " into the interleave group with"
<< *B << '\n'; } } while (false)
;
5972 InterleaveGroupMap[A] = Group;
5973
5974 // Set the first load in program order as the insert position.
5975 if (A->mayReadFromMemory())
5976 Group->setInsertPos(A);
5977 }
5978 } // Iteration over A accesses.
5979 } // Iteration over B accesses.
5980
5981 // Remove interleaved store groups with gaps.
5982 for (InterleaveGroup *Group : StoreGroups)
5983 if (Group->getNumMembers() != Group->getFactor()) {
5984 DEBUG(dbgs() << "LV: Invalidate candidate interleaved store group due "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved store group due "
"to gaps.\n"; } } while (false)
5985 "to gaps.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved store group due "
"to gaps.\n"; } } while (false)
;
5986 releaseGroup(Group);
5987 }
5988 // Remove interleaved groups with gaps (currently only loads) whose memory
5989 // accesses may wrap around. We have to revisit the getPtrStride analysis,
5990 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
5991 // not check wrapping (see documentation there).
5992 // FORNOW we use Assume=false;
5993 // TODO: Change to Assume=true but making sure we don't exceed the threshold
5994 // of runtime SCEV assumptions checks (thereby potentially failing to
5995 // vectorize altogether).
5996 // Additional optional optimizations:
5997 // TODO: If we are peeling the loop and we know that the first pointer doesn't
5998 // wrap then we can deduce that all pointers in the group don't wrap.
5999 // This means that we can forcefully peel the loop in order to only have to
6000 // check the first pointer for no-wrap. When we'll change to use Assume=true
6001 // we'll only need at most one runtime check per interleaved group.
6002 for (InterleaveGroup *Group : LoadGroups) {
6003 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
6004 // load would wrap around the address space we would do a memory access at
6005 // nullptr even without the transformation.
6006 if (Group->getNumMembers() == Group->getFactor())
6007 continue;
6008
6009 // Case 2: If first and last members of the group don't wrap this implies
6010 // that all the pointers in the group don't wrap.
6011 // So we check only group member 0 (which is always guaranteed to exist),
6012 // and group member Factor - 1; If the latter doesn't exist we rely on
6013 // peeling (if it is a non-reveresed accsess -- see Case 3).
6014 Value *FirstMemberPtr = getPointerOperand(Group->getMember(0));
6015 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
6016 /*ShouldCheckWrap=*/true)) {
6017 DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to "
"first group member potentially pointer-wrapping.\n"; } } while
(false)
6018 "first group member potentially pointer-wrapping.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to "
"first group member potentially pointer-wrapping.\n"; } } while
(false)
;
6019 releaseGroup(Group);
6020 continue;
6021 }
6022 Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
6023 if (LastMember) {
6024 Value *LastMemberPtr = getPointerOperand(LastMember);
6025 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
6026 /*ShouldCheckWrap=*/true)) {
6027 DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to "
"last group member potentially pointer-wrapping.\n"; } } while
(false)
6028 "last group member potentially pointer-wrapping.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to "
"last group member potentially pointer-wrapping.\n"; } } while
(false)
;
6029 releaseGroup(Group);
6030 }
6031 } else {
6032 // Case 3: A non-reversed interleaved load group with gaps: We need
6033 // to execute at least one scalar epilogue iteration. This will ensure
6034 // we don't speculatively access memory out-of-bounds. We only need
6035 // to look for a member at index factor - 1, since every group must have
6036 // a member at index zero.
6037 if (Group->isReverse()) {
6038 DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to "
"a reverse access with gaps.\n"; } } while (false)
6039 "a reverse access with gaps.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Invalidate candidate interleaved group due to "
"a reverse access with gaps.\n"; } } while (false)
;
6040 releaseGroup(Group);
6041 continue;
6042 }
6043 DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Interleaved group requires epilogue iteration.\n"
; } } while (false)
;
6044 RequiresScalarEpilogue = true;
6045 }
6046 }
6047}
6048
6049Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
6050 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
6051 // TODO: It may by useful to do since it's still likely to be dynamically
6052 // uniform if the target can skip.
6053 DEBUG(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)
;
6054
6055 ORE->emit(
6056 createMissedAnalysis("CantVersionLoopWithDivergentTarget")
6057 << "runtime pointer checks needed. Not enabled for divergent target");
6058
6059 return None;
6060 }
6061
6062 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6063 if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
6064 return computeFeasibleMaxVF(OptForSize, TC);
6065
6066 if (Legal->getRuntimePointerChecking()->Need) {
6067 ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
6068 << "runtime pointer checks needed. Enable vectorization of this "
6069 "loop with '#pragma clang loop vectorize(enable)' when "
6070 "compiling with -Os/-Oz");
6071 DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n"
; } } while (false)
6072 << "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)
;
6073 return None;
6074 }
6075
6076 // If we optimize the program for size, avoid creating the tail loop.
6077 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)
;
6078
6079 // If we don't know the precise trip count, don't try to vectorize.
6080 if (TC < 2) {
6081 ORE->emit(
6082 createMissedAnalysis("UnknownLoopCountComplexCFG")
6083 << "unable to calculate the loop count due to complex control flow");
6084 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"
; } } while (false)
;
6085 return None;
6086 }
6087
6088 unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
6089
6090 if (TC % MaxVF != 0) {
6091 // If the trip count that we found modulo the vectorization factor is not
6092 // zero then we require a tail.
6093 // FIXME: look for a smaller MaxVF that does divide TC rather than give up.
6094 // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a
6095 // smaller MaxVF that does not require a scalar epilog.
6096
6097 ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
6098 << "cannot optimize for size and vectorize at the "
6099 "same time. Enable vectorization of this loop "
6100 "with '#pragma clang loop vectorize(enable)' "
6101 "when compiling with -Os/-Oz");
6102 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"
; } } while (false)
;
6103 return None;
6104 }
6105
6106 return MaxVF;
6107}
6108
6109unsigned
6110LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
6111 unsigned ConstTripCount) {
6112 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
6113 unsigned SmallestType, WidestType;
6114 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
6115 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
6116
6117 // Get the maximum safe dependence distance in bits computed by LAA.
6118 // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
6119 // the memory accesses that is most restrictive (involved in the smallest
6120 // dependence distance).
6121 unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
6122
6123 WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
6124
6125 unsigned MaxVectorSize = WidestRegister / WidestType;
6126
6127 DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The Smallest and Widest types: "
<< SmallestType << " / " << WidestType <<
" bits.\n"; } } while (false)
6128 << WidestType << " bits.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The Smallest and Widest types: "
<< SmallestType << " / " << WidestType <<
" bits.\n"; } } while (false)
;
6129 DEBUG(dbgs() << "LV: The Widest register safe to use is: " << WidestRegisterdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The Widest register safe to use is: "
<< WidestRegister << " bits.\n"; } } while (false
)
6130 << " bits.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The Widest register safe to use is: "
<< WidestRegister << " bits.\n"; } } while (false
)
;
6131
6132 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"(static_cast <bool> (MaxVectorSize <= 64 && "Did not expect to pack so many elements"
" into one vector!") ? void (0) : __assert_fail ("MaxVectorSize <= 64 && \"Did not expect to pack so many elements\" \" into one vector!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6133, __extension__ __PRETTY_FUNCTION__))
6133 " into one vector!")(static_cast <bool> (MaxVectorSize <= 64 && "Did not expect to pack so many elements"
" into one vector!") ? void (0) : __assert_fail ("MaxVectorSize <= 64 && \"Did not expect to pack so many elements\" \" into one vector!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6133, __extension__ __PRETTY_FUNCTION__))
;
6134 if (MaxVectorSize == 0) {
6135 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)
;
6136 MaxVectorSize = 1;
6137 return MaxVectorSize;
6138 } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
6139 isPowerOf2_32(ConstTripCount)) {
6140 // We need to clamp the VF to be the ConstTripCount. There is no point in
6141 // choosing a higher viable VF as done in the loop below.
6142 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)
6143 << ConstTripCount << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
<< ConstTripCount << "\n"; } } while (false)
;
6144 MaxVectorSize = ConstTripCount;
6145 return MaxVectorSize;
6146 }
6147
6148 unsigned MaxVF = MaxVectorSize;
6149 if (MaximizeBandwidth && !OptForSize) {
6150 // Collect all viable vectorization factors larger than the default MaxVF
6151 // (i.e. MaxVectorSize).
6152 SmallVector<unsigned, 8> VFs;
6153 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
6154 for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
6155 VFs.push_back(VS);
6156
6157 // For each VF calculate its register usage.
6158 auto RUs = calculateRegisterUsage(VFs);
6159
6160 // Select the largest VF which doesn't require more registers than existing
6161 // ones.
6162 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
6163 for (int i = RUs.size() - 1; i >= 0; --i) {
6164 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
6165 MaxVF = VFs[i];
6166 break;
6167 }
6168 }
6169 }
6170 return MaxVF;
6171}
6172
6173VectorizationFactor
6174LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
6175 float Cost = expectedCost(1).first;
6176 const float ScalarCost = Cost;
6177 unsigned Width = 1;
6178 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)
;
6179
6180 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6181 // Ignore scalar width, because the user explicitly wants vectorization.
6182 if (ForceVectorization && MaxVF > 1) {
6183 Width = 2;
6184 Cost = expectedCost(Width).first / (float)Width;
6185 }
6186
6187 for (unsigned i = 2; i <= MaxVF; i *= 2) {
6188 // Notice that the vector loop needs to be executed less times, so
6189 // we need to divide the cost of the vector loops by the width of
6190 // the vector elements.
6191 VectorizationCostTy C = expectedCost(i);
6192 float VectorCost = C.first / (float)i;
6193 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)
6194 << " 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)
;
6195 if (!C.second && !ForceVectorization) {
6196 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)
6197 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)
6198 << " 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)
;
6199 continue;
6200 }
6201 if (VectorCost < Cost) {
6202 Cost = VectorCost;
6203 Width = i;
6204 }
6205 }
6206
6207 if (!EnableCondStoresVectorization && NumPredStores) {
6208 ORE->emit(createMissedAnalysis("ConditionalStore")
6209 << "store that is conditionally executed prevents vectorization");
6210 DEBUG(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)
;
6211 Width = 1;
6212 Cost = ScalarCost;
6213 }
6214
6215 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)
6216 << "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)
6217 << "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)
;
6218 DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Selecting VF: " <<
Width << ".\n"; } } while (false)
;
6219 VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
6220 return Factor;
6221}
6222
6223std::pair<unsigned, unsigned>
6224LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6225 unsigned MinWidth = -1U;
6226 unsigned MaxWidth = 8;
6227 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6228
6229 // For each block.
6230 for (BasicBlock *BB : TheLoop->blocks()) {
6231 // For each instruction in the loop.
6232 for (Instruction &I : *BB) {
6233 Type *T = I.getType();
6234
6235 // Skip ignored values.
6236 if (ValuesToIgnore.count(&I))
6237 continue;
6238
6239 // Only examine Loads, Stores and PHINodes.
6240 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6241 continue;
6242
6243 // Examine PHI nodes that are reduction variables. Update the type to
6244 // account for the recurrence type.
6245 if (auto *PN = dyn_cast<PHINode>(&I)) {
6246 if (!Legal->isReductionVariable(PN))
6247 continue;
6248 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
6249 T = RdxDesc.getRecurrenceType();
6250 }
6251
6252 // Examine the stored values.
6253 if (auto *ST = dyn_cast<StoreInst>(&I))
6254 T = ST->getValueOperand()->getType();
6255
6256 // Ignore loaded pointer types and stored pointer types that are not
6257 // vectorizable.
6258 //
6259 // FIXME: The check here attempts to predict whether a load or store will
6260 // be vectorized. We only know this for certain after a VF has
6261 // been selected. Here, we assume that if an access can be
6262 // vectorized, it will be. We should also look at extending this
6263 // optimization to non-pointer types.
6264 //
6265 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6266 !Legal->isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6267 continue;
6268
6269 MinWidth = std::min(MinWidth,
6270 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6271 MaxWidth = std::max(MaxWidth,
6272 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6273 }
6274 }
6275
6276 return {MinWidth, MaxWidth};
6277}
6278
6279unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
6280 unsigned VF,
6281 unsigned LoopCost) {
6282 // -- The interleave heuristics --
6283 // We interleave the loop in order to expose ILP and reduce the loop overhead.
6284 // There are many micro-architectural considerations that we can't predict
6285 // at this level. For example, frontend pressure (on decode or fetch) due to
6286 // code size, or the number and capabilities of the execution ports.
6287 //
6288 // We use the following heuristics to select the interleave count:
6289 // 1. If the code has reductions, then we interleave to break the cross
6290 // iteration dependency.
6291 // 2. If the loop is really small, then we interleave to reduce the loop
6292 // overhead.
6293 // 3. We don't interleave if we think that we will spill registers to memory
6294 // due to the increased register pressure.
6295
6296 // When we optimize for size, we don't interleave.
6297 if (OptForSize)
12
Taking false branch
6298 return 1;
6299
6300 // We used the distance for the interleave count.
6301 if (Legal->getMaxSafeDepDistBytes() != -1U)
13
Assuming the condition is false
14
Taking false branch
6302 return 1;
6303
6304 // Do not interleave loops with a relatively small trip count.
6305 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6306 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
15
Assuming 'TC' is <= 1
6307 return 1;
6308
6309 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
6310 DEBUG(dbgs() << "LV: The target has " << TargetNumRegistersdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The target has " <<
TargetNumRegisters << " registers\n"; } } while (false
)
6311 << " registers\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: The target has " <<
TargetNumRegisters << " registers\n"; } } while (false
)
;
6312
6313 if (VF == 1) {
16
Taking true branch
6314 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
17
Assuming the condition is false
18
Taking false branch
6315 TargetNumRegisters = ForceTargetNumScalarRegs;
6316 } else {
6317 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6318 TargetNumRegisters = ForceTargetNumVectorRegs;
6319 }
6320
6321 RegisterUsage R = calculateRegisterUsage({VF})[0];
6322 // We divide by these constants so assume that we have at least one
6323 // instruction that uses at least one register.
6324 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
6325 R.NumInstructions = std::max(R.NumInstructions, 1U);
6326
6327 // We calculate the interleave count using the following formula.
6328 // Subtract the number of loop invariants from the number of available
6329 // registers. These registers are used by all of the interleaved instances.
6330 // Next, divide the remaining registers by the number of registers that is
6331 // required by the loop, in order to estimate how many parallel instances
6332 // fit without causing spills. All of this is rounded down if necessary to be
6333 // a power of two. We want power of two interleave count to simplify any
6334 // addressing operations or alignment considerations.
6335 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
6336 R.MaxLocalUsers);
6337
6338 // Don't count the induction variable as interleaved.
6339 if (EnableIndVarRegisterHeur)
19
Assuming the condition is false
20
Taking false branch
6340 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
6341 std::max(1U, (R.MaxLocalUsers - 1)));
6342
6343 // Clamp the interleave ranges to reasonable counts.
6344 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
6345
6346 // Check if the user has overridden the max.
6347 if (VF == 1) {
21
Taking true branch
6348 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
22
Assuming the condition is false
23
Taking false branch
6349 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6350 } else {
6351 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6352 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6353 }
6354
6355 // If we did not calculate the cost for VF (because the user selected the VF)
6356 // then we calculate the cost of VF here.
6357 if (LoopCost == 0)
24
Taking true branch
6358 LoopCost = expectedCost(VF).first;
25
The value 0 is assigned to 'LoopCost'
6359
6360 // Clamp the calculated IC to be between the 1 and the max interleave count
6361 // that the target allows.
6362 if (IC > MaxInterleaveCount)
26
Taking false branch
6363 IC = MaxInterleaveCount;
6364 else if (IC < 1)
27
Assuming 'IC' is >= 1
28
Taking false branch
6365 IC = 1;
6366
6367 // Interleave if we vectorized this loop and there is a reduction that could
6368 // benefit from interleaving.
6369 if (VF > 1 && !Legal->getReductionVars()->empty()) {
6370 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)
;
6371 return IC;
6372 }
6373
6374 // Note that if we've already vectorized the loop we will have done the
6375 // runtime check and so interleaving won't require further checks.
6376 bool InterleavingRequiresRuntimePointerCheck =
6377 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
6378
6379 // We want to interleave small loops in order to reduce the loop overhead and
6380 // potentially expose ILP opportunities.
6381 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)
;
6382 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
29
Assuming 'InterleavingRequiresRuntimePointerCheck' is 0
30
Assuming the condition is true
31
Taking true branch
6383 // We assume that the cost overhead is 1 and we use the cost model
6384 // to estimate the cost of the loop and interleave until the cost of the
6385 // loop overhead is about 5% of the cost of the loop.
6386 unsigned SmallIC =
6387 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
32
Division by zero
6388
6389 // Interleave until store/load ports (estimated by max interleave count) are
6390 // saturated.
6391 unsigned NumStores = Legal->getNumStores();
6392 unsigned NumLoads = Legal->getNumLoads();
6393 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6394 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6395
6396 // If we have a scalar reduction (vector reductions are already dealt with
6397 // by this point), we can increase the critical path length if the loop
6398 // we're interleaving is inside another loop. Limit, by default to 2, so the
6399 // critical path only gets increased by one reduction operation.
6400 if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) {
6401 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6402 SmallIC = std::min(SmallIC, F);
6403 StoresIC = std::min(StoresIC, F);
6404 LoadsIC = std::min(LoadsIC, F);
6405 }
6406
6407 if (EnableLoadStoreRuntimeInterleave &&
6408 std::max(StoresIC, LoadsIC) > SmallIC) {
6409 DEBUG(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)
;
6410 return std::max(StoresIC, LoadsIC);
6411 }
6412
6413 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)
;
6414 return SmallIC;
6415 }
6416
6417 // Interleave if this is a large loop (small loops are already dealt with by
6418 // this point) that could benefit from interleaving.
6419 bool HasReductions = !Legal->getReductionVars()->empty();
6420 if (TTI.enableAggressiveInterleaving(HasReductions)) {
6421 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)
;
6422 return IC;
6423 }
6424
6425 DEBUG(dbgs() << "LV: Not Interleaving.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not Interleaving.\n"
; } } while (false)
;
6426 return 1;
6427}
6428
6429SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6430LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
6431 // This function calculates the register usage by measuring the highest number
6432 // of values that are alive at a single location. Obviously, this is a very
6433 // rough estimation. We scan the loop in a topological order in order and
6434 // assign a number to each instruction. We use RPO to ensure that defs are
6435 // met before their users. We assume that each instruction that has in-loop
6436 // users starts an interval. We record every time that an in-loop value is
6437 // used, so we have a list of the first and last occurrences of each
6438 // instruction. Next, we transpose this data structure into a multi map that
6439 // holds the list of intervals that *end* at a specific location. This multi
6440 // map allows us to perform a linear search. We scan the instructions linearly
6441 // and record each time that a new interval starts, by placing it in a set.
6442 // If we find this value in the multi-map then we remove it from the set.
6443 // The max register usage is the maximum size of the set.
6444 // We also search for instructions that are defined outside the loop, but are
6445 // used inside the loop. We need this number separately from the max-interval
6446 // usage number because when we unroll, loop-invariant values do not take
6447 // more register.
6448 LoopBlocksDFS DFS(TheLoop);
6449 DFS.perform(LI);
6450
6451 RegisterUsage RU;
6452 RU.NumInstructions = 0;
6453
6454 // Each 'key' in the map opens a new interval. The values
6455 // of the map are the index of the 'last seen' usage of the
6456 // instruction that is the key.
6457 using IntervalMap = DenseMap<Instruction *, unsigned>;
6458
6459 // Maps instruction to its index.
6460 DenseMap<unsigned, Instruction *> IdxToInstr;
6461 // Marks the end of each interval.
6462 IntervalMap EndPoint;
6463 // Saves the list of instruction indices that are used in the loop.
6464 SmallSet<Instruction *, 8> Ends;
6465 // Saves the list of values that are used in the loop but are
6466 // defined outside the loop, such as arguments and constants.
6467 SmallPtrSet<Value *, 8> LoopInvariants;
6468
6469 unsigned Index = 0;
6470 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6471 RU.NumInstructions += BB->size();
6472 for (Instruction &I : *BB) {
6473 IdxToInstr[Index++] = &I;
6474
6475 // Save the end location of each USE.
6476 for (Value *U : I.operands()) {
6477 auto *Instr = dyn_cast<Instruction>(U);
6478
6479 // Ignore non-instruction values such as arguments, constants, etc.
6480 if (!Instr)
6481 continue;
6482
6483 // If this instruction is outside the loop then record it and continue.
6484 if (!TheLoop->contains(Instr)) {
6485 LoopInvariants.insert(Instr);
6486 continue;
6487 }
6488
6489 // Overwrite previous end points.
6490 EndPoint[Instr] = Index;
6491 Ends.insert(Instr);
6492 }
6493 }
6494 }
6495
6496 // Saves the list of intervals that end with the index in 'key'.
6497 using InstrList = SmallVector<Instruction *, 2>;
6498 DenseMap<unsigned, InstrList> TransposeEnds;
6499
6500 // Transpose the EndPoints to a list of values that end at each index.
6501 for (auto &Interval : EndPoint)
6502 TransposeEnds[Interval.second].push_back(Interval.first);
6503
6504 SmallSet<Instruction *, 8> OpenIntervals;
6505
6506 // Get the size of the widest register.
6507 unsigned MaxSafeDepDist = -1U;
6508 if (Legal->getMaxSafeDepDistBytes() != -1U)
6509 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
6510 unsigned WidestRegister =
6511 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
6512 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6513
6514 SmallVector<RegisterUsage, 8> RUs(VFs.size());
6515 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
6516
6517 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)
;
6518
6519 // A lambda that gets the register usage for the given type and VF.
6520 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
6521 if (Ty->isTokenTy())
6522 return 0U;
6523 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
6524 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
6525 };
6526
6527 for (unsigned int i = 0; i < Index; ++i) {
6528 Instruction *I = IdxToInstr[i];
6529
6530 // Remove all of the instructions that end at this location.
6531 InstrList &List = TransposeEnds[i];
6532 for (Instruction *ToRemove : List)
6533 OpenIntervals.erase(ToRemove);
6534
6535 // Ignore instructions that are never used within the loop.
6536 if (!Ends.count(I))
6537 continue;
6538
6539 // Skip ignored values.
6540 if (ValuesToIgnore.count(I))
6541 continue;
6542
6543 // For each VF find the maximum usage of registers.
6544 for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6545 if (VFs[j] == 1) {
6546 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
6547 continue;
6548 }
6549 collectUniformsAndScalars(VFs[j]);
6550 // Count the number of live intervals.
6551 unsigned RegUsage = 0;
6552 for (auto Inst : OpenIntervals) {
6553 // Skip ignored values for VF > 1.
6554 if (VecValuesToIgnore.count(Inst) ||
6555 isScalarAfterVectorization(Inst, VFs[j]))
6556 continue;
6557 RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
6558 }
6559 MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
6560 }
6561
6562 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)
6563 << OpenIntervals.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV(REG): At #" <<
i << " Interval # " << OpenIntervals.size() <<
'\n'; } } while (false)
;
6564
6565 // Add the current instruction to the list of open intervals.
6566 OpenIntervals.insert(I);
6567 }
6568
6569 for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6570 unsigned Invariant = 0;
6571 if (VFs[i] == 1)
6572 Invariant = LoopInvariants.size();
6573 else {
6574 for (auto Inst : LoopInvariants)
6575 Invariant += GetRegUsage(Inst->getType(), VFs[i]);
6576 }
6577
6578 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)
;
6579 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)
;
6580 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV(REG): Found invariant usage: "
<< Invariant << '\n'; } } while (false)
;
6581 DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV(REG): LoopSize: " <<
RU.NumInstructions << '\n'; } } while (false)
;
6582
6583 RU.LoopInvariantRegs = Invariant;
6584 RU.MaxLocalUsers = MaxUsages[i];
6585 RUs[i] = RU;
6586 }
6587
6588 return RUs;
6589}
6590
6591bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6592 // TODO: Cost model for emulated masked load/store is completely
6593 // broken. This hack guides the cost model to use an artificially
6594 // high enough value to practically disable vectorization with such
6595 // operations, except where previously deployed legality hack allowed
6596 // using very low cost values. This is to avoid regressions coming simply
6597 // from moving "masked load/store" check from legality to cost model.
6598 // Masked Load/Gather emulation was previously never allowed.
6599 // Limited number of Masked Store/Scatter emulation was allowed.
6600 assert(isScalarWithPredication(I) &&(static_cast <bool> (isScalarWithPredication(I) &&
"Expecting a scalar emulated instruction") ? void (0) : __assert_fail
("isScalarWithPredication(I) && \"Expecting a scalar emulated instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6601, __extension__ __PRETTY_FUNCTION__))
6601 "Expecting a scalar emulated instruction")(static_cast <bool> (isScalarWithPredication(I) &&
"Expecting a scalar emulated instruction") ? void (0) : __assert_fail
("isScalarWithPredication(I) && \"Expecting a scalar emulated instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6601, __extension__ __PRETTY_FUNCTION__))
;
6602 return isa<LoadInst>(I) ||
6603 (isa<StoreInst>(I) &&
6604 NumPredStores > NumberOfStoresToPredicate);
6605}
6606
6607void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
6608 // If we aren't vectorizing the loop, or if we've already collected the
6609 // instructions to scalarize, there's nothing to do. Collection may already
6610 // have occurred if we have a user-selected VF and are now computing the
6611 // expected cost for interleaving.
6612 if (VF < 2 || InstsToScalarize.count(VF))
6613 return;
6614
6615 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6616 // not profitable to scalarize any instructions, the presence of VF in the
6617 // map will indicate that we've analyzed it already.
6618 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6619
6620 // Find all the instructions that are scalar with predication in the loop and
6621 // determine if it would be better to not if-convert the blocks they are in.
6622 // If so, we also record the instructions to scalarize.
6623 for (BasicBlock *BB : TheLoop->blocks()) {
6624 if (!Legal->blockNeedsPredication(BB))
6625 continue;
6626 for (Instruction &I : *BB)
6627 if (isScalarWithPredication(&I)) {
6628 ScalarCostsTy ScalarCosts;
6629 // Do not apply discount logic if hacked cost is needed
6630 // for emulated masked memrefs.
6631 if (!useEmulatedMaskMemRefHack(&I) &&
6632 computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6633 ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6634 // Remember that BB will remain after vectorization.
6635 PredicatedBBsAfterVectorization.insert(BB);
6636 }
6637 }
6638}
6639
6640int LoopVectorizationCostModel::computePredInstDiscount(
6641 Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
6642 unsigned VF) {
6643 assert(!isUniformAfterVectorization(PredInst, VF) &&(static_cast <bool> (!isUniformAfterVectorization(PredInst
, VF) && "Instruction marked uniform-after-vectorization will be predicated"
) ? void (0) : __assert_fail ("!isUniformAfterVectorization(PredInst, VF) && \"Instruction marked uniform-after-vectorization will be predicated\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6644, __extension__ __PRETTY_FUNCTION__))
6644 "Instruction marked uniform-after-vectorization will be predicated")(static_cast <bool> (!isUniformAfterVectorization(PredInst
, VF) && "Instruction marked uniform-after-vectorization will be predicated"
) ? void (0) : __assert_fail ("!isUniformAfterVectorization(PredInst, VF) && \"Instruction marked uniform-after-vectorization will be predicated\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6644, __extension__ __PRETTY_FUNCTION__))
;
6645
6646 // Initialize the discount to zero, meaning that the scalar version and the
6647 // vector version cost the same.
6648 int Discount = 0;
6649
6650 // Holds instructions to analyze. The instructions we visit are mapped in
6651 // ScalarCosts. Those instructions are the ones that would be scalarized if
6652 // we find that the scalar version costs less.
6653 SmallVector<Instruction *, 8> Worklist;
6654
6655 // Returns true if the given instruction can be scalarized.
6656 auto canBeScalarized = [&](Instruction *I) -> bool {
6657 // We only attempt to scalarize instructions forming a single-use chain
6658 // from the original predicated block that would otherwise be vectorized.
6659 // Although not strictly necessary, we give up on instructions we know will
6660 // already be scalar to avoid traversing chains that are unlikely to be
6661 // beneficial.
6662 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6663 isScalarAfterVectorization(I, VF))
6664 return false;
6665
6666 // If the instruction is scalar with predication, it will be analyzed
6667 // separately. We ignore it within the context of PredInst.
6668 if (isScalarWithPredication(I))
6669 return false;
6670
6671 // If any of the instruction's operands are uniform after vectorization,
6672 // the instruction cannot be scalarized. This prevents, for example, a
6673 // masked load from being scalarized.
6674 //
6675 // We assume we will only emit a value for lane zero of an instruction
6676 // marked uniform after vectorization, rather than VF identical values.
6677 // Thus, if we scalarize an instruction that uses a uniform, we would
6678 // create uses of values corresponding to the lanes we aren't emitting code
6679 // for. This behavior can be changed by allowing getScalarValue to clone
6680 // the lane zero values for uniforms rather than asserting.
6681 for (Use &U : I->operands())
6682 if (auto *J = dyn_cast<Instruction>(U.get()))
6683 if (isUniformAfterVectorization(J, VF))
6684 return false;
6685
6686 // Otherwise, we can scalarize the instruction.
6687 return true;
6688 };
6689
6690 // Returns true if an operand that cannot be scalarized must be extracted
6691 // from a vector. We will account for this scalarization overhead below. Note
6692 // that the non-void predicated instructions are placed in their own blocks,
6693 // and their return values are inserted into vectors. Thus, an extract would
6694 // still be required.
6695 auto needsExtract = [&](Instruction *I) -> bool {
6696 return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
6697 };
6698
6699 // Compute the expected cost discount from scalarizing the entire expression
6700 // feeding the predicated instruction. We currently only consider expressions
6701 // that are single-use instruction chains.
6702 Worklist.push_back(PredInst);
6703 while (!Worklist.empty()) {
6704 Instruction *I = Worklist.pop_back_val();
6705
6706 // If we've already analyzed the instruction, there's nothing to do.
6707 if (ScalarCosts.count(I))
6708 continue;
6709
6710 // Compute the cost of the vector instruction. Note that this cost already
6711 // includes the scalarization overhead of the predicated instruction.
6712 unsigned VectorCost = getInstructionCost(I, VF).first;
6713
6714 // Compute the cost of the scalarized instruction. This cost is the cost of
6715 // the instruction as if it wasn't if-converted and instead remained in the
6716 // predicated block. We will scale this cost by block probability after
6717 // computing the scalarization overhead.
6718 unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
6719
6720 // Compute the scalarization overhead of needed insertelement instructions
6721 // and phi nodes.
6722 if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6723 ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
6724 true, false);
6725 ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
6726 }
6727
6728 // Compute the scalarization overhead of needed extractelement
6729 // instructions. For each of the instruction's operands, if the operand can
6730 // be scalarized, add it to the worklist; otherwise, account for the
6731 // overhead.
6732 for (Use &U : I->operands())
6733 if (auto *J = dyn_cast<Instruction>(U.get())) {
6734 assert(VectorType::isValidElementType(J->getType()) &&(static_cast <bool> (VectorType::isValidElementType(J->
getType()) && "Instruction has non-scalar type") ? void
(0) : __assert_fail ("VectorType::isValidElementType(J->getType()) && \"Instruction has non-scalar type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6735, __extension__ __PRETTY_FUNCTION__))
6735 "Instruction has non-scalar type")(static_cast <bool> (VectorType::isValidElementType(J->
getType()) && "Instruction has non-scalar type") ? void
(0) : __assert_fail ("VectorType::isValidElementType(J->getType()) && \"Instruction has non-scalar type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6735, __extension__ __PRETTY_FUNCTION__))
;
6736 if (canBeScalarized(J))
6737 Worklist.push_back(J);
6738 else if (needsExtract(J))
6739 ScalarCost += TTI.getScalarizationOverhead(
6740 ToVectorTy(J->getType(),VF), false, true);
6741 }
6742
6743 // Scale the total scalar cost by block probability.
6744 ScalarCost /= getReciprocalPredBlockProb();
6745
6746 // Compute the discount. A non-negative discount means the vector version
6747 // of the instruction costs more, and scalarizing would be beneficial.
6748 Discount += VectorCost - ScalarCost;
6749 ScalarCosts[I] = ScalarCost;
6750 }
6751
6752 return Discount;
6753}
6754
6755LoopVectorizationCostModel::VectorizationCostTy
6756LoopVectorizationCostModel::expectedCost(unsigned VF) {
6757 VectorizationCostTy Cost;
6758
6759 // For each block.
6760 for (BasicBlock *BB : TheLoop->blocks()) {
6761 VectorizationCostTy BlockCost;
6762
6763 // For each instruction in the old loop.
6764 for (Instruction &I : *BB) {
6765 // Skip dbg intrinsics.
6766 if (isa<DbgInfoIntrinsic>(I))
6767 continue;
6768
6769 // Skip ignored values.
6770 if (ValuesToIgnore.count(&I) ||
6771 (VF > 1 && VecValuesToIgnore.count(&I)))
6772 continue;
6773
6774 VectorizationCostTy C = getInstructionCost(&I, VF);
6775
6776 // Check if we should override the cost.
6777 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6778 C.first = ForceTargetInstructionCost;
6779
6780 BlockCost.first += C.first;
6781 BlockCost.second |= C.second;
6782 DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "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)
6783 << VF << " For instruction: " << I << '\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)
;
6784 }
6785
6786 // If we are vectorizing a predicated block, it will have been
6787 // if-converted. This means that the block's instructions (aside from
6788 // stores and instructions that may divide by zero) will now be
6789 // unconditionally executed. For the scalar case, we may not always execute
6790 // the predicated block. Thus, scale the block's cost by the probability of
6791 // executing it.
6792 if (VF == 1 && Legal->blockNeedsPredication(BB))
6793 BlockCost.first /= getReciprocalPredBlockProb();
6794
6795 Cost.first += BlockCost.first;
6796 Cost.second |= BlockCost.second;
6797 }
6798
6799 return Cost;
6800}
6801
6802/// \brief Gets Address Access SCEV after verifying that the access pattern
6803/// is loop invariant except the induction variable dependence.
6804///
6805/// This SCEV can be sent to the Target in order to estimate the address
6806/// calculation cost.
6807static const SCEV *getAddressAccessSCEV(
6808 Value *Ptr,
6809 LoopVectorizationLegality *Legal,
6810 PredicatedScalarEvolution &PSE,
6811 const Loop *TheLoop) {
6812
6813 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6814 if (!Gep)
6815 return nullptr;
6816
6817 // We are looking for a gep with all loop invariant indices except for one
6818 // which should be an induction variable.
6819 auto SE = PSE.getSE();
6820 unsigned NumOperands = Gep->getNumOperands();
6821 for (unsigned i = 1; i < NumOperands; ++i) {
6822 Value *Opd = Gep->getOperand(i);
6823 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6824 !Legal->isInductionVariable(Opd))
6825 return nullptr;
6826 }
6827
6828 // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6829 return PSE.getSCEV(Ptr);
6830}
6831
6832static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6833 return Legal->hasStride(I->getOperand(0)) ||
6834 Legal->hasStride(I->getOperand(1));
6835}
6836
6837unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6838 unsigned VF) {
6839 Type *ValTy = getMemInstValueType(I);
6840 auto SE = PSE.getSE();
6841
6842 unsigned Alignment = getMemInstAlignment(I);
6843 unsigned AS = getMemInstAddressSpace(I);
6844 Value *Ptr = getPointerOperand(I);
6845 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6846
6847 // Figure out whether the access is strided and get the stride value
6848 // if it's known in compile time
6849 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6850
6851 // Get the cost of the scalar memory instruction and address computation.
6852 unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6853
6854 Cost += VF *
6855 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6856 AS, I);
6857
6858 // Get the overhead of the extractelement and insertelement instructions
6859 // we might create due to scalarization.
6860 Cost += getScalarizationOverhead(I, VF, TTI);
6861
6862 // If we have a predicated store, it may not be executed for each vector
6863 // lane. Scale the cost by the probability of executing the predicated
6864 // block.
6865 if (isScalarWithPredication(I)) {
6866 Cost /= getReciprocalPredBlockProb();
6867
6868 if (useEmulatedMaskMemRefHack(I))
6869 // Artificially setting to a high enough value to practically disable
6870 // vectorization with such operations.
6871 Cost = 3000000;
6872 }
6873
6874 return Cost;
6875}
6876
6877unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6878 unsigned VF) {
6879 Type *ValTy = getMemInstValueType(I);
6880 Type *VectorTy = ToVectorTy(ValTy, VF);
6881 unsigned Alignment = getMemInstAlignment(I);
6882 Value *Ptr = getPointerOperand(I);
6883 unsigned AS = getMemInstAddressSpace(I);
6884 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6885
6886 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride
== -1) && "Stride should be 1 or -1 for consecutive memory access"
) ? void (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Stride should be 1 or -1 for consecutive memory access\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6887, __extension__ __PRETTY_FUNCTION__))
6887 "Stride should be 1 or -1 for consecutive memory access")(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride
== -1) && "Stride should be 1 or -1 for consecutive memory access"
) ? void (0) : __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Stride should be 1 or -1 for consecutive memory access\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6887, __extension__ __PRETTY_FUNCTION__))
;
6888 unsigned Cost = 0;
6889 if (Legal->isMaskRequired(I))
6890 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6891 else
6892 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
6893
6894 bool Reverse = ConsecutiveStride < 0;
6895 if (Reverse)
6896 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6897 return Cost;
6898}
6899
6900unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6901 unsigned VF) {
6902 LoadInst *LI = cast<LoadInst>(I);
6903 Type *ValTy = LI->getType();
6904 Type *VectorTy = ToVectorTy(ValTy, VF);
6905 unsigned Alignment = LI->getAlignment();
6906 unsigned AS = LI->getPointerAddressSpace();
6907
6908 return TTI.getAddressComputationCost(ValTy) +
6909 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
6910 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6911}
6912
6913unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6914 unsigned VF) {
6915 Type *ValTy = getMemInstValueType(I);
6916 Type *VectorTy = ToVectorTy(ValTy, VF);
6917 unsigned Alignment = getMemInstAlignment(I);
6918 Value *Ptr = getPointerOperand(I);
6919
6920 return TTI.getAddressComputationCost(VectorTy) +
6921 TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
6922 Legal->isMaskRequired(I), Alignment);
6923}
6924
6925unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6926 unsigned VF) {
6927 Type *ValTy = getMemInstValueType(I);
6928 Type *VectorTy = ToVectorTy(ValTy, VF);
6929 unsigned AS = getMemInstAddressSpace(I);
6930
6931 auto Group = Legal->getInterleavedAccessGroup(I);
6932 assert(Group && "Fail to get an interleaved access group.")(static_cast <bool> (Group && "Fail to get an interleaved access group."
) ? void (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 6932, __extension__ __PRETTY_FUNCTION__))
;
6933
6934 unsigned InterleaveFactor = Group->getFactor();
6935 Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6936
6937 // Holds the indices of existing members in an interleaved load group.
6938 // An interleaved store group doesn't need this as it doesn't allow gaps.
6939 SmallVector<unsigned, 4> Indices;
6940 if (isa<LoadInst>(I)) {
6941 for (unsigned i = 0; i < InterleaveFactor; i++)
6942 if (Group->getMember(i))
6943 Indices.push_back(i);
6944 }
6945
6946 // Calculate the cost of the whole interleaved group.
6947 unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy,
6948 Group->getFactor(), Indices,
6949 Group->getAlignment(), AS);
6950
6951 if (Group->isReverse())
6952 Cost += Group->getNumMembers() *
6953 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6954 return Cost;
6955}
6956
6957unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6958 unsigned VF) {
6959 // Calculate scalar cost only. Vectorization cost should be ready at this
6960 // moment.
6961 if (VF == 1) {
6962 Type *ValTy = getMemInstValueType(I);
6963 unsigned Alignment = getMemInstAlignment(I);
6964 unsigned AS = getMemInstAddressSpace(I);
6965
6966 return TTI.getAddressComputationCost(ValTy) +
6967 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
6968 }
6969 return getWideningCost(I, VF);
6970}
6971
6972LoopVectorizationCostModel::VectorizationCostTy
6973LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
6974 // If we know that this instruction will remain uniform, check the cost of
6975 // the scalar version.
6976 if (isUniformAfterVectorization(I, VF))
6977 VF = 1;
6978
6979 if (VF > 1 && isProfitableToScalarize(I, VF))
6980 return VectorizationCostTy(InstsToScalarize[VF][I], false);
6981
6982 // Forced scalars do not have any scalarization overhead.
6983 if (VF > 1 && ForcedScalars.count(VF) &&
6984 ForcedScalars.find(VF)->second.count(I))
6985 return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false);
6986
6987 Type *VectorTy;
6988 unsigned C = getInstructionCost(I, VF, VectorTy);
6989
6990 bool TypeNotScalarized =
6991 VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF;
6992 return VectorizationCostTy(C, TypeNotScalarized);
6993}
6994
6995void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
6996 if (VF == 1)
6997 return;
6998 NumPredStores = 0;
6999 for (BasicBlock *BB : TheLoop->blocks()) {
7000 // For each instruction in the old loop.
7001 for (Instruction &I : *BB) {
7002 Value *Ptr = getPointerOperand(&I);
7003 if (!Ptr)
7004 continue;
7005
7006 if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7007 NumPredStores++;
7008 if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
7009 // Scalar load + broadcast
7010 unsigned Cost = getUniformMemOpCost(&I, VF);
7011 setWideningDecision(&I, VF, CM_Scalarize, Cost);
7012 continue;
7013 }
7014
7015 // We assume that widening is the best solution when possible.
7016 if (memoryInstructionCanBeWidened(&I, VF)) {
7017 unsigned Cost = getConsecutiveMemOpCost(&I, VF);
7018 int ConsecutiveStride = Legal->isConsecutivePtr(getPointerOperand(&I));
7019 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride
== -1) && "Expected consecutive stride.") ? void (0)
: __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Expected consecutive stride.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7020, __extension__ __PRETTY_FUNCTION__))
7020 "Expected consecutive stride.")(static_cast <bool> ((ConsecutiveStride == 1 || ConsecutiveStride
== -1) && "Expected consecutive stride.") ? void (0)
: __assert_fail ("(ConsecutiveStride == 1 || ConsecutiveStride == -1) && \"Expected consecutive stride.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7020, __extension__ __PRETTY_FUNCTION__))
;
7021 InstWidening Decision =
7022 ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7023 setWideningDecision(&I, VF, Decision, Cost);
7024 continue;
7025 }
7026
7027 // Choose between Interleaving, Gather/Scatter or Scalarization.
7028 unsigned InterleaveCost = std::numeric_limits<unsigned>::max();
7029 unsigned NumAccesses = 1;
7030 if (Legal->isAccessInterleaved(&I)) {
7031 auto Group = Legal->getInterleavedAccessGroup(&I);
7032 assert(Group && "Fail to get an interleaved access group.")(static_cast <bool> (Group && "Fail to get an interleaved access group."
) ? void (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7032, __extension__ __PRETTY_FUNCTION__))
;
7033
7034 // Make one decision for the whole group.
7035 if (getWideningDecision(&I, VF) != CM_Unknown)
7036 continue;
7037
7038 NumAccesses = Group->getNumMembers();
7039 InterleaveCost = getInterleaveGroupCost(&I, VF);
7040 }
7041
7042 unsigned GatherScatterCost =
7043 isLegalGatherOrScatter(&I)
7044 ? getGatherScatterCost(&I, VF) * NumAccesses
7045 : std::numeric_limits<unsigned>::max();
7046
7047 unsigned ScalarizationCost =
7048 getMemInstScalarizationCost(&I, VF) * NumAccesses;
7049
7050 // Choose better solution for the current VF,
7051 // write down this decision and use it during vectorization.
7052 unsigned Cost;
7053 InstWidening Decision;
7054 if (InterleaveCost <= GatherScatterCost &&
7055 InterleaveCost < ScalarizationCost) {
7056 Decision = CM_Interleave;
7057 Cost = InterleaveCost;
7058 } else if (GatherScatterCost < ScalarizationCost) {
7059 Decision = CM_GatherScatter;
7060 Cost = GatherScatterCost;
7061 } else {
7062 Decision = CM_Scalarize;
7063 Cost = ScalarizationCost;
7064 }
7065 // If the instructions belongs to an interleave group, the whole group
7066 // receives the same decision. The whole group receives the cost, but
7067 // the cost will actually be assigned to one instruction.
7068 if (auto Group = Legal->getInterleavedAccessGroup(&I))
7069 setWideningDecision(Group, VF, Decision, Cost);
7070 else
7071 setWideningDecision(&I, VF, Decision, Cost);
7072 }
7073 }
7074
7075 // Make sure that any load of address and any other address computation
7076 // remains scalar unless there is gather/scatter support. This avoids
7077 // inevitable extracts into address registers, and also has the benefit of
7078 // activating LSR more, since that pass can't optimize vectorized
7079 // addresses.
7080 if (TTI.prefersVectorizedAddressing())
7081 return;
7082
7083 // Start with all scalar pointer uses.
7084 SmallPtrSet<Instruction *, 8> AddrDefs;
7085 for (BasicBlock *BB : TheLoop->blocks())
7086 for (Instruction &I : *BB) {
7087 Instruction *PtrDef =
7088 dyn_cast_or_null<Instruction>(getPointerOperand(&I));
7089 if (PtrDef && TheLoop->contains(PtrDef) &&
7090 getWideningDecision(&I, VF) != CM_GatherScatter)
7091 AddrDefs.insert(PtrDef);
7092 }
7093
7094 // Add all instructions used to generate the addresses.
7095 SmallVector<Instruction *, 4> Worklist;
7096 for (auto *I : AddrDefs)
7097 Worklist.push_back(I);
7098 while (!Worklist.empty()) {
7099 Instruction *I = Worklist.pop_back_val();
7100 for (auto &Op : I->operands())
7101 if (auto *InstOp = dyn_cast<Instruction>(Op))
7102 if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7103 AddrDefs.insert(InstOp).second)
7104 Worklist.push_back(InstOp);
7105 }
7106
7107 for (auto *I : AddrDefs) {
7108 if (isa<LoadInst>(I)) {
7109 // Setting the desired widening decision should ideally be handled in
7110 // by cost functions, but since this involves the task of finding out
7111 // if the loaded register is involved in an address computation, it is
7112 // instead changed here when we know this is the case.
7113 InstWidening Decision = getWideningDecision(I, VF);
7114 if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7115 // Scalarize a widened load of address.
7116 setWideningDecision(I, VF, CM_Scalarize,
7117 (VF * getMemoryInstructionCost(I, 1)));
7118 else if (auto Group = Legal->getInterleavedAccessGroup(I)) {
7119 // Scalarize an interleave group of address loads.
7120 for (unsigned I = 0; I < Group->getFactor(); ++I) {
7121 if (Instruction *Member = Group->getMember(I))
7122 setWideningDecision(Member, VF, CM_Scalarize,
7123 (VF * getMemoryInstructionCost(Member, 1)));
7124 }
7125 }
7126 } else
7127 // Make sure I gets scalarized and a cost estimate without
7128 // scalarization overhead.
7129 ForcedScalars[VF].insert(I);
7130 }
7131}
7132
7133unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7134 unsigned VF,
7135 Type *&VectorTy) {
7136 Type *RetTy = I->getType();
7137 if (canTruncateToMinimalBitwidth(I, VF))
7138 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7139 VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
7140 auto SE = PSE.getSE();
7141
7142 // TODO: We need to estimate the cost of intrinsic calls.
7143 switch (I->getOpcode()) {
7144 case Instruction::GetElementPtr:
7145 // We mark this instruction as zero-cost because the cost of GEPs in
7146 // vectorized code depends on whether the corresponding memory instruction
7147 // is scalarized or not. Therefore, we handle GEPs with the memory
7148 // instruction cost.
7149 return 0;
7150 case Instruction::Br: {
7151 // In cases of scalarized and predicated instructions, there will be VF
7152 // predicated blocks in the vectorized loop. Each branch around these
7153 // blocks requires also an extract of its vector compare i1 element.
7154 bool ScalarPredicatedBB = false;
7155 BranchInst *BI = cast<BranchInst>(I);
7156 if (VF > 1 && BI->isConditional() &&
7157 (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7158 PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7159 ScalarPredicatedBB = true;
7160
7161 if (ScalarPredicatedBB) {
7162 // Return cost for branches around scalarized and predicated blocks.
7163 Type *Vec_i1Ty =
7164 VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7165 return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
7166 (TTI.getCFInstrCost(Instruction::Br) * VF));
7167 } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
7168 // The back-edge branch will remain, as will all scalar branches.
7169 return TTI.getCFInstrCost(Instruction::Br);
7170 else
7171 // This branch will be eliminated by if-conversion.
7172 return 0;
7173 // Note: We currently assume zero cost for an unconditional branch inside
7174 // a predicated block since it will become a fall-through, although we
7175 // may decide in the future to call TTI for all branches.
7176 }
7177 case Instruction::PHI: {
7178 auto *Phi = cast<PHINode>(I);
7179
7180 // First-order recurrences are replaced by vector shuffles inside the loop.
7181 if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
7182 return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
7183 VectorTy, VF - 1, VectorTy);
7184
7185 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7186 // converted into select instructions. We require N - 1 selects per phi
7187 // node, where N is the number of incoming values.
7188 if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
7189 return (Phi->getNumIncomingValues() - 1) *
7190 TTI.getCmpSelInstrCost(
7191 Instruction::Select, ToVectorTy(Phi->getType(), VF),
7192 ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF));
7193
7194 return TTI.getCFInstrCost(Instruction::PHI);
7195 }
7196 case Instruction::UDiv:
7197 case Instruction::SDiv:
7198 case Instruction::URem:
7199 case Instruction::SRem:
7200 // If we have a predicated instruction, it may not be executed for each
7201 // vector lane. Get the scalarization cost and scale this amount by the
7202 // probability of executing the predicated block. If the instruction is not
7203 // predicated, we fall through to the next case.
7204 if (VF > 1 && isScalarWithPredication(I)) {
7205 unsigned Cost = 0;
7206
7207 // These instructions have a non-void type, so account for the phi nodes
7208 // that we will create. This cost is likely to be zero. The phi node
7209 // cost, if any, should be scaled by the block probability because it
7210 // models a copy at the end of each predicated block.
7211 Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
7212
7213 // The cost of the non-predicated instruction.
7214 Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
7215
7216 // The cost of insertelement and extractelement instructions needed for
7217 // scalarization.
7218 Cost += getScalarizationOverhead(I, VF, TTI);
7219
7220 // Scale the cost by the probability of executing the predicated blocks.
7221 // This assumes the predicated block for each vector lane is equally
7222 // likely.
7223 return Cost / getReciprocalPredBlockProb();
7224 }
7225 LLVM_FALLTHROUGH[[clang::fallthrough]];
7226 case Instruction::Add:
7227 case Instruction::FAdd:
7228 case Instruction::Sub:
7229 case Instruction::FSub:
7230 case Instruction::Mul:
7231 case Instruction::FMul:
7232 case Instruction::FDiv:
7233 case Instruction::FRem:
7234 case Instruction::Shl:
7235 case Instruction::LShr:
7236 case Instruction::AShr:
7237 case Instruction::And:
7238 case Instruction::Or:
7239 case Instruction::Xor: {
7240 // Since we will replace the stride by 1 the multiplication should go away.
7241 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7242 return 0;
7243 // Certain instructions can be cheaper to vectorize if they have a constant
7244 // second vector operand. One example of this are shifts on x86.
7245 TargetTransformInfo::OperandValueKind Op1VK =
7246 TargetTransformInfo::OK_AnyValue;
7247 TargetTransformInfo::OperandValueKind Op2VK =
7248 TargetTransformInfo::OK_AnyValue;
7249 TargetTransformInfo::OperandValueProperties Op1VP =
7250 TargetTransformInfo::OP_None;
7251 TargetTransformInfo::OperandValueProperties Op2VP =
7252 TargetTransformInfo::OP_None;
7253 Value *Op2 = I->getOperand(1);
7254
7255 // Check for a splat or for a non uniform vector of constants.
7256 if (isa<ConstantInt>(Op2)) {
7257 ConstantInt *CInt = cast<ConstantInt>(Op2);
7258 if (CInt && CInt->getValue().isPowerOf2())
7259 Op2VP = TargetTransformInfo::OP_PowerOf2;
7260 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7261 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
7262 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
7263 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
7264 if (SplatValue) {
7265 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
7266 if (CInt && CInt->getValue().isPowerOf2())
7267 Op2VP = TargetTransformInfo::OP_PowerOf2;
7268 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7269 }
7270 } else if (Legal->isUniform(Op2)) {
7271 Op2VK = TargetTransformInfo::OK_UniformValue;
7272 }
7273 SmallVector<const Value *, 4> Operands(I->operand_values());
7274 unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7275 return N * TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK,
7276 Op2VK, Op1VP, Op2VP, Operands);
7277 }
7278 case Instruction::Select: {
7279 SelectInst *SI = cast<SelectInst>(I);
7280 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7281 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7282 Type *CondTy = SI->getCondition()->getType();
7283 if (!ScalarCond)
7284 CondTy = VectorType::get(CondTy, VF);
7285
7286 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
7287 }
7288 case Instruction::ICmp:
7289 case Instruction::FCmp: {
7290 Type *ValTy = I->getOperand(0)->getType();
7291 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7292 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7293 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7294 VectorTy = ToVectorTy(ValTy, VF);
7295 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
7296 }
7297 case Instruction::Store:
7298 case Instruction::Load: {
7299 unsigned Width = VF;
7300 if (Width > 1) {
7301 InstWidening Decision = getWideningDecision(I, Width);
7302 assert(Decision != CM_Unknown &&(static_cast <bool> (Decision != CM_Unknown && "CM decision should be taken at this point"
) ? void (0) : __assert_fail ("Decision != CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7303, __extension__ __PRETTY_FUNCTION__))
7303 "CM decision should be taken at this point")(static_cast <bool> (Decision != CM_Unknown && "CM decision should be taken at this point"
) ? void (0) : __assert_fail ("Decision != CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7303, __extension__ __PRETTY_FUNCTION__))
;
7304 if (Decision == CM_Scalarize)
7305 Width = 1;
7306 }
7307 VectorTy = ToVectorTy(getMemInstValueType(I), Width);
7308 return getMemoryInstructionCost(I, VF);
7309 }
7310 case Instruction::ZExt:
7311 case Instruction::SExt:
7312 case Instruction::FPToUI:
7313 case Instruction::FPToSI:
7314 case Instruction::FPExt:
7315 case Instruction::PtrToInt:
7316 case Instruction::IntToPtr:
7317 case Instruction::SIToFP:
7318 case Instruction::UIToFP:
7319 case Instruction::Trunc:
7320 case Instruction::FPTrunc:
7321 case Instruction::BitCast: {
7322 // We optimize the truncation of induction variables having constant
7323 // integer steps. The cost of these truncations is the same as the scalar
7324 // operation.
7325 if (isOptimizableIVTruncate(I, VF)) {
7326 auto *Trunc = cast<TruncInst>(I);
7327 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7328 Trunc->getSrcTy(), Trunc);
7329 }
7330
7331 Type *SrcScalarTy = I->getOperand(0)->getType();
7332 Type *SrcVecTy =
7333 VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7334 if (canTruncateToMinimalBitwidth(I, VF)) {
7335 // This cast is going to be shrunk. This may remove the cast or it might
7336 // turn it into slightly different cast. For example, if MinBW == 16,
7337 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7338 //
7339 // Calculate the modified src and dest types.
7340 Type *MinVecTy = VectorTy;
7341 if (I->getOpcode() == Instruction::Trunc) {
7342 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7343 VectorTy =
7344 largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7345 } else if (I->getOpcode() == Instruction::ZExt ||
7346 I->getOpcode() == Instruction::SExt) {
7347 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7348 VectorTy =
7349 smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7350 }
7351 }
7352
7353 unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7354 return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
7355 }
7356 case Instruction::Call: {
7357 bool NeedToScalarize;
7358 CallInst *CI = cast<CallInst>(I);
7359 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
7360 if (getVectorIntrinsicIDForCall(CI, TLI))
7361 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
7362 return CallCost;
7363 }
7364 default:
7365 // The cost of executing VF copies of the scalar instruction. This opcode
7366 // is unknown. Assume that it is the same as 'mul'.
7367 return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
7368 getScalarizationOverhead(I, VF, TTI);
7369 } // end of switch.
7370}
7371
7372char LoopVectorize::ID = 0;
7373
7374static const char lv_name[] = "Loop Vectorization";
7375
7376INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)static void *initializeLoopVectorizePassOnce(PassRegistry &
Registry) {
7377INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
7378INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)initializeBasicAAWrapperPassPass(Registry);
7379INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
7380INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)initializeGlobalsAAWrapperPassPass(Registry);
7381INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
7382INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)initializeBlockFrequencyInfoWrapperPassPass(Registry);
7383INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
7384INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)initializeScalarEvolutionWrapperPassPass(Registry);
7385INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry);
7386INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)initializeLoopAccessLegacyAnalysisPass(Registry);
7387INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)initializeDemandedBitsWrapperPassPass(Registry);
7388INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)initializeOptimizationRemarkEmitterWrapperPassPass(Registry);
7389INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)PassInfo *PI = new PassInfo( lv_name, "loop-vectorize", &
LoopVectorize::ID, PassInfo::NormalCtor_t(callDefaultCtor<
LoopVectorize>), false, false); Registry.registerPass(*PI,
true); return PI; } static llvm::once_flag InitializeLoopVectorizePassFlag
; void llvm::initializeLoopVectorizePass(PassRegistry &Registry
) { llvm::call_once(InitializeLoopVectorizePassFlag, initializeLoopVectorizePassOnce
, std::ref(Registry)); }
7390
7391namespace llvm {
7392
7393Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
7394 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
7395}
7396
7397} // end namespace llvm
7398
7399bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7400 // Check if the pointer operand of a load or store instruction is
7401 // consecutive.
7402 if (auto *Ptr = getPointerOperand(Inst))
7403 return Legal->isConsecutivePtr(Ptr);
7404 return false;
7405}
7406
7407void LoopVectorizationCostModel::collectValuesToIgnore() {
7408 // Ignore ephemeral values.
7409 CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7410
7411 // Ignore type-promoting instructions we identified during reduction
7412 // detection.
7413 for (auto &Reduction : *Legal->getReductionVars()) {
7414 RecurrenceDescriptor &RedDes = Reduction.second;
7415 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7416 VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7417 }
7418 // Ignore type-casting instructions we identified during induction
7419 // detection.
7420 for (auto &Induction : *Legal->getInductionVars()) {
7421 InductionDescriptor &IndDes = Induction.second;
7422 const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7423 VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7424 }
7425}
7426
7427VectorizationFactor
7428LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) {
7429 // Width 1 means no vectorize, cost 0 means uncomputed cost.
7430 const VectorizationFactor NoVectorization = {1U, 0U};
7431 Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
7432 if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize.
7433 return NoVectorization;
7434
7435 if (UserVF) {
7436 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Using user VF " <<
UserVF << ".\n"; } } while (false)
;
7437 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two")(static_cast <bool> (isPowerOf2_32(UserVF) && "VF needs to be a power of two"
) ? void (0) : __assert_fail ("isPowerOf2_32(UserVF) && \"VF needs to be a power of two\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7437, __extension__ __PRETTY_FUNCTION__))
;
7438 // Collect the instructions (and their associated costs) that will be more
7439 // profitable to scalarize.
7440 CM.selectUserVectorizationFactor(UserVF);
7441 buildVPlans(UserVF, UserVF);
7442 DEBUG(printPlans(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { printPlans(dbgs()); } } while (false)
;
7443 return {UserVF, 0};
7444 }
7445
7446 unsigned MaxVF = MaybeMaxVF.getValue();
7447 assert(MaxVF != 0 && "MaxVF is zero.")(static_cast <bool> (MaxVF != 0 && "MaxVF is zero."
) ? void (0) : __assert_fail ("MaxVF != 0 && \"MaxVF is zero.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7447, __extension__ __PRETTY_FUNCTION__))
;
7448
7449 for (unsigned VF = 1; VF <= MaxVF; VF *= 2) {
7450 // Collect Uniform and Scalar instructions after vectorization with VF.
7451 CM.collectUniformsAndScalars(VF);
7452
7453 // Collect the instructions (and their associated costs) that will be more
7454 // profitable to scalarize.
7455 if (VF > 1)
7456 CM.collectInstsToScalarize(VF);
7457 }
7458
7459 buildVPlans(1, MaxVF);
7460 DEBUG(printPlans(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { printPlans(dbgs()); } } while (false)
;
7461 if (MaxVF == 1)
7462 return NoVectorization;
7463
7464 // Select the optimal vectorization factor.
7465 return CM.selectVectorizationFactor(MaxVF);
7466}
7467
7468void LoopVectorizationPlanner::setBestPlan(unsigned VF, unsigned UF) {
7469 DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "Setting best plan to VF="
<< VF << ", UF=" << UF << '\n'; } } while
(false)
;
7470 BestVF = VF;
7471 BestUF = UF;
7472
7473 erase_if(VPlans, [VF](const VPlanPtr &Plan) {
7474 return !Plan->hasVF(VF);
7475 });
7476 assert(VPlans.size() == 1 && "Best VF has not a single VPlan.")(static_cast <bool> (VPlans.size() == 1 && "Best VF has not a single VPlan."
) ? void (0) : __assert_fail ("VPlans.size() == 1 && \"Best VF has not a single VPlan.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7476, __extension__ __PRETTY_FUNCTION__))
;
7477}
7478
7479void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
7480 DominatorTree *DT) {
7481 // Perform the actual loop transformation.
7482
7483 // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7484 VPCallbackILV CallbackILV(ILV);
7485
7486 VPTransformState State{BestVF, BestUF, LI,
7487 DT, ILV.Builder, ILV.VectorLoopValueMap,
7488 &ILV, CallbackILV};
7489 State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7490
7491 //===------------------------------------------------===//
7492 //
7493 // Notice: any optimization or new instruction that go
7494 // into the code below should also be implemented in
7495 // the cost-model.
7496 //
7497 //===------------------------------------------------===//
7498
7499 // 2. Copy and widen instructions from the old loop into the new loop.
7500 assert(VPlans.size() == 1 && "Not a single VPlan to execute.")(static_cast <bool> (VPlans.size() == 1 && "Not a single VPlan to execute."
) ? void (0) : __assert_fail ("VPlans.size() == 1 && \"Not a single VPlan to execute.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7500, __extension__ __PRETTY_FUNCTION__))
;
7501 VPlans.front()->execute(&State);
7502
7503 // 3. Fix the vectorized code: take care of header phi's, live-outs,
7504 // predication, updating analyses.
7505 ILV.fixVectorizedLoop();
7506}
7507
7508void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7509 SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7510 BasicBlock *Latch = OrigLoop->getLoopLatch();
7511
7512 // We create new control-flow for the vectorized loop, so the original
7513 // condition will be dead after vectorization if it's only used by the
7514 // branch.
7515 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
7516 if (Cmp && Cmp->hasOneUse())
7517 DeadInstructions.insert(Cmp);
7518
7519 // We create new "steps" for induction variable updates to which the original
7520 // induction variables map. An original update instruction will be dead if
7521 // all its users except the induction variable are dead.
7522 for (auto &Induction : *Legal->getInductionVars()) {
7523 PHINode *Ind = Induction.first;
7524 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7525 if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7526 return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7527 }))
7528 DeadInstructions.insert(IndUpdate);
7529
7530 // We record as "Dead" also the type-casting instructions we had identified
7531 // during induction analysis. We don't need any handling for them in the
7532 // vectorized loop because we have proven that, under a proper runtime
7533 // test guarding the vectorized loop, the value of the phi, and the casted
7534 // value of the phi, are the same. The last instruction in this casting chain
7535 // will get its scalar/vector/widened def from the scalar/vector/widened def
7536 // of the respective phi node. Any other casts in the induction def-use chain
7537 // have no other uses outside the phi update chain, and will be ignored.
7538 InductionDescriptor &IndDes = Induction.second;
7539 const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7540 DeadInstructions.insert(Casts.begin(), Casts.end());
7541 }
7542}
7543
7544Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
7545
7546Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7547
7548Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
7549 Instruction::BinaryOps BinOp) {
7550 // When unrolling and the VF is 1, we only need to add a simple scalar.
7551 Type *Ty = Val->getType();
7552 assert(!Ty->isVectorTy() && "Val must be a scalar")(static_cast <bool> (!Ty->isVectorTy() && "Val must be a scalar"
) ? void (0) : __assert_fail ("!Ty->isVectorTy() && \"Val must be a scalar\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7552, __extension__ __PRETTY_FUNCTION__))
;
7553
7554 if (Ty->isFloatingPointTy()) {
7555 Constant *C = ConstantFP::get(Ty, (double)StartIdx);
7556
7557 // Floating point operations had to be 'fast' to enable the unrolling.
7558 Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
7559 return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
7560 }
7561 Constant *C = ConstantInt::get(Ty, StartIdx);
7562 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
7563}
7564
7565static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7566 SmallVector<Metadata *, 4> MDs;
7567 // Reserve first location for self reference to the LoopID metadata node.
7568 MDs.push_back(nullptr);
7569 bool IsUnrollMetadata = false;
7570 MDNode *LoopID = L->getLoopID();
7571 if (LoopID) {
7572 // First find existing loop unrolling disable metadata.
7573 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7574 auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7575 if (MD) {
7576 const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7577 IsUnrollMetadata =
7578 S && S->getString().startswith("llvm.loop.unroll.disable");
7579 }
7580 MDs.push_back(LoopID->getOperand(i));
7581 }
7582 }
7583
7584 if (!IsUnrollMetadata) {
7585 // Add runtime unroll disable metadata.
7586 LLVMContext &Context = L->getHeader()->getContext();
7587 SmallVector<Metadata *, 1> DisableOperands;
7588 DisableOperands.push_back(
7589 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7590 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7591 MDs.push_back(DisableNode);
7592 MDNode *NewLoopID = MDNode::get(Context, MDs);
7593 // Set operand 0 to refer to the loop id itself.
7594 NewLoopID->replaceOperandWith(0, NewLoopID);
7595 L->setLoopID(NewLoopID);
7596 }
7597}
7598
7599bool LoopVectorizationPlanner::getDecisionAndClampRange(
7600 const std::function<bool(unsigned)> &Predicate, VFRange &Range) {
7601 assert(Range.End > Range.Start && "Trying to test an empty VF range.")(static_cast <bool> (Range.End > Range.Start &&
"Trying to test an empty VF range.") ? void (0) : __assert_fail
("Range.End > Range.Start && \"Trying to test an empty VF range.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7601, __extension__ __PRETTY_FUNCTION__))
;
7602 bool PredicateAtRangeStart = Predicate(Range.Start);
7603
7604 for (unsigned TmpVF = Range.Start * 2; TmpVF < Range.End; TmpVF *= 2)
7605 if (Predicate(TmpVF) != PredicateAtRangeStart) {
7606 Range.End = TmpVF;
7607 break;
7608 }
7609
7610 return PredicateAtRangeStart;
7611}
7612
7613/// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
7614/// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
7615/// of VF's starting at a given VF and extending it as much as possible. Each
7616/// vectorization decision can potentially shorten this sub-range during
7617/// buildVPlan().
7618void LoopVectorizationPlanner::buildVPlans(unsigned MinVF, unsigned MaxVF) {
7619
7620 // Collect conditions feeding internal conditional branches; they need to be
7621 // represented in VPlan for it to model masking.
7622 SmallPtrSet<Value *, 1> NeedDef;
7623
7624 auto *Latch = OrigLoop->getLoopLatch();
7625 for (BasicBlock *BB : OrigLoop->blocks()) {
7626 if (BB == Latch)
7627 continue;
7628 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
7629 if (Branch && Branch->isConditional())
7630 NeedDef.insert(Branch->getCondition());
7631 }
7632
7633 for (unsigned VF = MinVF; VF < MaxVF + 1;) {
7634 VFRange SubRange = {VF, MaxVF + 1};
7635 VPlans.push_back(buildVPlan(SubRange, NeedDef));
7636 VF = SubRange.End;
7637 }
7638}
7639
7640VPValue *LoopVectorizationPlanner::createEdgeMask(BasicBlock *Src,
7641 BasicBlock *Dst,
7642 VPlanPtr &Plan) {
7643 assert(is_contained(predecessors(Dst), Src) && "Invalid edge")(static_cast <bool> (is_contained(predecessors(Dst), Src
) && "Invalid edge") ? void (0) : __assert_fail ("is_contained(predecessors(Dst), Src) && \"Invalid edge\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7643, __extension__ __PRETTY_FUNCTION__))
;
7644
7645 // Look for cached value.
7646 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
7647 EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
7648 if (ECEntryIt != EdgeMaskCache.end())
7649 return ECEntryIt->second;
7650
7651 VPValue *SrcMask = createBlockInMask(Src, Plan);
7652
7653 // The terminator has to be a branch inst!
7654 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
7655 assert(BI && "Unexpected terminator found")(static_cast <bool> (BI && "Unexpected terminator found"
) ? void (0) : __assert_fail ("BI && \"Unexpected terminator found\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7655, __extension__ __PRETTY_FUNCTION__))
;
7656
7657 if (!BI->isConditional())
7658 return EdgeMaskCache[Edge] = SrcMask;
7659
7660 VPValue *EdgeMask = Plan->getVPValue(BI->getCondition());
7661 assert(EdgeMask && "No Edge Mask found for condition")(static_cast <bool> (EdgeMask && "No Edge Mask found for condition"
) ? void (0) : __assert_fail ("EdgeMask && \"No Edge Mask found for condition\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7661, __extension__ __PRETTY_FUNCTION__))
;
7662
7663 if (BI->getSuccessor(0) != Dst)
7664 EdgeMask = Builder.createNot(EdgeMask);
7665
7666 if (SrcMask) // Otherwise block in-mask is all-one, no need to AND.
7667 EdgeMask = Builder.createAnd(EdgeMask, SrcMask);
7668
7669 return EdgeMaskCache[Edge] = EdgeMask;
7670}
7671
7672VPValue *LoopVectorizationPlanner::createBlockInMask(BasicBlock *BB,
7673 VPlanPtr &Plan) {
7674 assert(OrigLoop->contains(BB) && "Block is not a part of a loop")(static_cast <bool> (OrigLoop->contains(BB) &&
"Block is not a part of a loop") ? void (0) : __assert_fail (
"OrigLoop->contains(BB) && \"Block is not a part of a loop\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7674, __extension__ __PRETTY_FUNCTION__))
;
7675
7676 // Look for cached value.
7677 BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
7678 if (BCEntryIt != BlockMaskCache.end())
7679 return BCEntryIt->second;
7680
7681 // All-one mask is modelled as no-mask following the convention for masked
7682 // load/store/gather/scatter. Initialize BlockMask to no-mask.
7683 VPValue *BlockMask = nullptr;
7684
7685 // Loop incoming mask is all-one.
7686 if (OrigLoop->getHeader() == BB)
7687 return BlockMaskCache[BB] = BlockMask;
7688
7689 // This is the block mask. We OR all incoming edges.
7690 for (auto *Predecessor : predecessors(BB)) {
7691 VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
7692 if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
7693 return BlockMaskCache[BB] = EdgeMask;
7694
7695 if (!BlockMask) { // BlockMask has its initialized nullptr value.
7696 BlockMask = EdgeMask;
7697 continue;
7698 }
7699
7700 BlockMask = Builder.createOr(BlockMask, EdgeMask);
7701 }
7702
7703 return BlockMaskCache[BB] = BlockMask;
7704}
7705
7706VPInterleaveRecipe *
7707LoopVectorizationPlanner::tryToInterleaveMemory(Instruction *I,
7708 VFRange &Range) {
7709 const InterleaveGroup *IG = Legal->getInterleavedAccessGroup(I);
7710 if (!IG)
7711 return nullptr;
7712
7713 // Now check if IG is relevant for VF's in the given range.
7714 auto isIGMember = [&](Instruction *I) -> std::function<bool(unsigned)> {
7715 return [=](unsigned VF) -> bool {
7716 return (VF >= 2 && // Query is illegal for VF == 1
7717 CM.getWideningDecision(I, VF) ==
7718 LoopVectorizationCostModel::CM_Interleave);
7719 };
7720 };
7721 if (!getDecisionAndClampRange(isIGMember(I), Range))
7722 return nullptr;
7723
7724 // I is a member of an InterleaveGroup for VF's in the (possibly trimmed)
7725 // range. If it's the primary member of the IG construct a VPInterleaveRecipe.
7726 // Otherwise, it's an adjunct member of the IG, do not construct any Recipe.
7727 assert(I == IG->getInsertPos() &&(static_cast <bool> (I == IG->getInsertPos() &&
"Generating a recipe for an adjunct member of an interleave group"
) ? void (0) : __assert_fail ("I == IG->getInsertPos() && \"Generating a recipe for an adjunct member of an interleave group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7728, __extension__ __PRETTY_FUNCTION__))
7728 "Generating a recipe for an adjunct member of an interleave group")(static_cast <bool> (I == IG->getInsertPos() &&
"Generating a recipe for an adjunct member of an interleave group"
) ? void (0) : __assert_fail ("I == IG->getInsertPos() && \"Generating a recipe for an adjunct member of an interleave group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7728, __extension__ __PRETTY_FUNCTION__))
;
7729
7730 return new VPInterleaveRecipe(IG);
7731}
7732
7733VPWidenMemoryInstructionRecipe *
7734LoopVectorizationPlanner::tryToWidenMemory(Instruction *I, VFRange &Range,
7735 VPlanPtr &Plan) {
7736 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
7737 return nullptr;
7738
7739 auto willWiden = [&](unsigned VF) -> bool {
7740 if (VF == 1)
7741 return false;
7742 if (CM.isScalarAfterVectorization(I, VF) ||
7743 CM.isProfitableToScalarize(I, VF))
7744 return false;
7745 LoopVectorizationCostModel::InstWidening Decision =
7746 CM.getWideningDecision(I, VF);
7747 assert(Decision != LoopVectorizationCostModel::CM_Unknown &&(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Unknown && "CM decision should be taken at this point."
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7748, __extension__ __PRETTY_FUNCTION__))
7748 "CM decision should be taken at this point.")(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Unknown && "CM decision should be taken at this point."
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7748, __extension__ __PRETTY_FUNCTION__))
;
7749 assert(Decision != LoopVectorizationCostModel::CM_Interleave &&(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Interleave && "Interleave memory opportunity should be caught earlier."
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Interleave && \"Interleave memory opportunity should be caught earlier.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7750, __extension__ __PRETTY_FUNCTION__))
7750 "Interleave memory opportunity should be caught earlier.")(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Interleave && "Interleave memory opportunity should be caught earlier."
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Interleave && \"Interleave memory opportunity should be caught earlier.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7750, __extension__ __PRETTY_FUNCTION__))
;
7751 return Decision != LoopVectorizationCostModel::CM_Scalarize;
7752 };
7753
7754 if (!getDecisionAndClampRange(willWiden, Range))
7755 return nullptr;
7756
7757 VPValue *Mask = nullptr;
7758 if (Legal->isMaskRequired(I))
7759 Mask = createBlockInMask(I->getParent(), Plan);
7760
7761 return new VPWidenMemoryInstructionRecipe(*I, Mask);
7762}
7763
7764VPWidenIntOrFpInductionRecipe *
7765LoopVectorizationPlanner::tryToOptimizeInduction(Instruction *I,
7766 VFRange &Range) {
7767 if (PHINode *Phi = dyn_cast<PHINode>(I)) {
7768 // Check if this is an integer or fp induction. If so, build the recipe that
7769 // produces its scalar and vector values.
7770 InductionDescriptor II = Legal->getInductionVars()->lookup(Phi);
7771 if (II.getKind() == InductionDescriptor::IK_IntInduction ||
7772 II.getKind() == InductionDescriptor::IK_FpInduction)
7773 return new VPWidenIntOrFpInductionRecipe(Phi);
7774
7775 return nullptr;
7776 }
7777
7778 // Optimize the special case where the source is a constant integer
7779 // induction variable. Notice that we can only optimize the 'trunc' case
7780 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
7781 // (c) other casts depend on pointer size.
7782
7783 // Determine whether \p K is a truncation based on an induction variable that
7784 // can be optimized.
7785 auto isOptimizableIVTruncate =
7786 [&](Instruction *K) -> std::function<bool(unsigned)> {
7787 return
7788 [=](unsigned VF) -> bool { return CM.isOptimizableIVTruncate(K, VF); };
7789 };
7790
7791 if (isa<TruncInst>(I) &&
7792 getDecisionAndClampRange(isOptimizableIVTruncate(I), Range))
7793 return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
7794 cast<TruncInst>(I));
7795 return nullptr;
7796}
7797
7798VPBlendRecipe *
7799LoopVectorizationPlanner::tryToBlend(Instruction *I, VPlanPtr &Plan) {
7800 PHINode *Phi = dyn_cast<PHINode>(I);
7801 if (!Phi || Phi->getParent() == OrigLoop->getHeader())
7802 return nullptr;
7803
7804 // We know that all PHIs in non-header blocks are converted into selects, so
7805 // we don't have to worry about the insertion order and we can just use the
7806 // builder. At this point we generate the predication tree. There may be
7807 // duplications since this is a simple recursive scan, but future
7808 // optimizations will clean it up.
7809
7810 SmallVector<VPValue *, 2> Masks;
7811 unsigned NumIncoming = Phi->getNumIncomingValues();
7812 for (unsigned In = 0; In < NumIncoming; In++) {
7813 VPValue *EdgeMask =
7814 createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
7815 assert((EdgeMask || NumIncoming == 1) &&(static_cast <bool> ((EdgeMask || NumIncoming == 1) &&
"Multiple predecessors with one having a full mask") ? void (
0) : __assert_fail ("(EdgeMask || NumIncoming == 1) && \"Multiple predecessors with one having a full mask\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7816, __extension__ __PRETTY_FUNCTION__))
7816 "Multiple predecessors with one having a full mask")(static_cast <bool> ((EdgeMask || NumIncoming == 1) &&
"Multiple predecessors with one having a full mask") ? void (
0) : __assert_fail ("(EdgeMask || NumIncoming == 1) && \"Multiple predecessors with one having a full mask\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7816, __extension__ __PRETTY_FUNCTION__))
;
7817 if (EdgeMask)
7818 Masks.push_back(EdgeMask);
7819 }
7820 return new VPBlendRecipe(Phi, Masks);
7821}
7822
7823bool LoopVectorizationPlanner::tryToWiden(Instruction *I, VPBasicBlock *VPBB,
7824 VFRange &Range) {
7825 if (CM.isScalarWithPredication(I))
7826 return false;
7827
7828 auto IsVectorizableOpcode = [](unsigned Opcode) {
7829 switch (Opcode) {
7830 case Instruction::Add:
7831 case Instruction::And:
7832 case Instruction::AShr:
7833 case Instruction::BitCast:
7834 case Instruction::Br:
7835 case Instruction::Call:
7836 case Instruction::FAdd:
7837 case Instruction::FCmp:
7838 case Instruction::FDiv:
7839 case Instruction::FMul:
7840 case Instruction::FPExt:
7841 case Instruction::FPToSI:
7842 case Instruction::FPToUI:
7843 case Instruction::FPTrunc:
7844 case Instruction::FRem:
7845 case Instruction::FSub:
7846 case Instruction::GetElementPtr:
7847 case Instruction::ICmp:
7848 case Instruction::IntToPtr:
7849 case Instruction::Load:
7850 case Instruction::LShr:
7851 case Instruction::Mul:
7852 case Instruction::Or:
7853 case Instruction::PHI:
7854 case Instruction::PtrToInt:
7855 case Instruction::SDiv:
7856 case Instruction::Select:
7857 case Instruction::SExt:
7858 case Instruction::Shl:
7859 case Instruction::SIToFP:
7860 case Instruction::SRem:
7861 case Instruction::Store:
7862 case Instruction::Sub:
7863 case Instruction::Trunc:
7864 case Instruction::UDiv:
7865 case Instruction::UIToFP:
7866 case Instruction::URem:
7867 case Instruction::Xor:
7868 case Instruction::ZExt:
7869 return true;
7870 }
7871 return false;
7872 };
7873
7874 if (!IsVectorizableOpcode(I->getOpcode()))
7875 return false;
7876
7877 if (CallInst *CI = dyn_cast<CallInst>(I)) {
7878 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7879 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
7880 ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
7881 return false;
7882 }
7883
7884 auto willWiden = [&](unsigned VF) -> bool {
7885 if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
7886 CM.isProfitableToScalarize(I, VF)))
7887 return false;
7888 if (CallInst *CI = dyn_cast<CallInst>(I)) {
7889 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7890 // The following case may be scalarized depending on the VF.
7891 // The flag shows whether we use Intrinsic or a usual Call for vectorized
7892 // version of the instruction.
7893 // Is it beneficial to perform intrinsic call compared to lib call?
7894 bool NeedToScalarize;
7895 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
7896 bool UseVectorIntrinsic =
7897 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
7898 return UseVectorIntrinsic || !NeedToScalarize;
7899 }
7900 if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
7901 assert(CM.getWideningDecision(I, VF) ==(static_cast <bool> (CM.getWideningDecision(I, VF) == LoopVectorizationCostModel
::CM_Scalarize && "Memory widening decisions should have been taken care by now"
) ? void (0) : __assert_fail ("CM.getWideningDecision(I, VF) == LoopVectorizationCostModel::CM_Scalarize && \"Memory widening decisions should have been taken care by now\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7903, __extension__ __PRETTY_FUNCTION__))
7902 LoopVectorizationCostModel::CM_Scalarize &&(static_cast <bool> (CM.getWideningDecision(I, VF) == LoopVectorizationCostModel
::CM_Scalarize && "Memory widening decisions should have been taken care by now"
) ? void (0) : __assert_fail ("CM.getWideningDecision(I, VF) == LoopVectorizationCostModel::CM_Scalarize && \"Memory widening decisions should have been taken care by now\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7903, __extension__ __PRETTY_FUNCTION__))
7903 "Memory widening decisions should have been taken care by now")(static_cast <bool> (CM.getWideningDecision(I, VF) == LoopVectorizationCostModel
::CM_Scalarize && "Memory widening decisions should have been taken care by now"
) ? void (0) : __assert_fail ("CM.getWideningDecision(I, VF) == LoopVectorizationCostModel::CM_Scalarize && \"Memory widening decisions should have been taken care by now\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7903, __extension__ __PRETTY_FUNCTION__))
;
7904 return false;
7905 }
7906 return true;
7907 };
7908
7909 if (!getDecisionAndClampRange(willWiden, Range))
7910 return false;
7911
7912 // Success: widen this instruction. We optimize the common case where
7913 // consecutive instructions can be represented by a single recipe.
7914 if (!VPBB->empty()) {
7915 VPWidenRecipe *LastWidenRecipe = dyn_cast<VPWidenRecipe>(&VPBB->back());
7916 if (LastWidenRecipe && LastWidenRecipe->appendInstruction(I))
7917 return true;
7918 }
7919
7920 VPBB->appendRecipe(new VPWidenRecipe(I));
7921 return true;
7922}
7923
7924VPBasicBlock *LoopVectorizationPlanner::handleReplication(
7925 Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
7926 DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
7927 VPlanPtr &Plan) {
7928 bool IsUniform = getDecisionAndClampRange(
7929 [&](unsigned VF) { return CM.isUniformAfterVectorization(I, VF); },
7930 Range);
7931
7932 bool IsPredicated = CM.isScalarWithPredication(I);
7933 auto *Recipe = new VPReplicateRecipe(I, IsUniform, IsPredicated);
7934
7935 // Find if I uses a predicated instruction. If so, it will use its scalar
7936 // value. Avoid hoisting the insert-element which packs the scalar value into
7937 // a vector value, as that happens iff all users use the vector value.
7938 for (auto &Op : I->operands())
7939 if (auto *PredInst = dyn_cast<Instruction>(Op))
7940 if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
7941 PredInst2Recipe[PredInst]->setAlsoPack(false);
7942
7943 // Finalize the recipe for Instr, first if it is not predicated.
7944 if (!IsPredicated) {
7945 DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Scalarizing:" <<
*I << "\n"; } } while (false)
;
7946 VPBB->appendRecipe(Recipe);
7947 return VPBB;
7948 }
7949 DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Scalarizing and predicating:"
<< *I << "\n"; } } while (false)
;
7950 assert(VPBB->getSuccessors().empty() &&(static_cast <bool> (VPBB->getSuccessors().empty() &&
"VPBB has successors when handling predicated replication.")
? void (0) : __assert_fail ("VPBB->getSuccessors().empty() && \"VPBB has successors when handling predicated replication.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7951, __extension__ __PRETTY_FUNCTION__))
7951 "VPBB has successors when handling predicated replication.")(static_cast <bool> (VPBB->getSuccessors().empty() &&
"VPBB has successors when handling predicated replication.")
? void (0) : __assert_fail ("VPBB->getSuccessors().empty() && \"VPBB has successors when handling predicated replication.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7951, __extension__ __PRETTY_FUNCTION__))
;
7952 // Record predicated instructions for above packing optimizations.
7953 PredInst2Recipe[I] = Recipe;
7954 VPBlockBase *Region =
7955 VPBB->setOneSuccessor(createReplicateRegion(I, Recipe, Plan));
7956 return cast<VPBasicBlock>(Region->setOneSuccessor(new VPBasicBlock()));
7957}
7958
7959VPRegionBlock *
7960LoopVectorizationPlanner::createReplicateRegion(Instruction *Instr,
7961 VPRecipeBase *PredRecipe,
7962 VPlanPtr &Plan) {
7963 // Instructions marked for predication are replicated and placed under an
7964 // if-then construct to prevent side-effects.
7965
7966 // Generate recipes to compute the block mask for this region.
7967 VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
7968
7969 // Build the triangular if-then region.
7970 std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
7971 assert(Instr->getParent() && "Predicated instruction not in any basic block")(static_cast <bool> (Instr->getParent() && "Predicated instruction not in any basic block"
) ? void (0) : __assert_fail ("Instr->getParent() && \"Predicated instruction not in any basic block\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 7971, __extension__ __PRETTY_FUNCTION__))
;
7972 auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
7973 auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
7974 auto *PHIRecipe =
7975 Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr);
7976 auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
7977 auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
7978 VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
7979
7980 // Note: first set Entry as region entry and then connect successors starting
7981 // from it in order, to propagate the "parent" of each VPBasicBlock.
7982 Entry->setTwoSuccessors(Pred, Exit);
7983 Pred->setOneSuccessor(Exit);
7984
7985 return Region;
7986}
7987
7988LoopVectorizationPlanner::VPlanPtr
7989LoopVectorizationPlanner::buildVPlan(VFRange &Range,
7990 const SmallPtrSetImpl<Value *> &NeedDef) {
7991 EdgeMaskCache.clear();
7992 BlockMaskCache.clear();
7993 DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
7994 DenseMap<Instruction *, Instruction *> SinkAfterInverse;
7995
7996 // Collect instructions from the original loop that will become trivially dead
7997 // in the vectorized loop. We don't need to vectorize these instructions. For
7998 // example, original induction update instructions can become dead because we
7999 // separately emit induction "steps" when generating code for the new loop.
8000 // Similarly, we create a new latch condition when setting up the structure
8001 // of the new loop, so the old one can become dead.
8002 SmallPtrSet<Instruction *, 4> DeadInstructions;
8003 collectTriviallyDeadInstructions(DeadInstructions);
8004
8005 // Hold a mapping from predicated instructions to their recipes, in order to
8006 // fix their AlsoPack behavior if a user is determined to replicate and use a
8007 // scalar instead of vector value.
8008 DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
8009
8010 // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
8011 VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
8012 auto Plan = llvm::make_unique<VPlan>(VPBB);
8013
8014 // Represent values that will have defs inside VPlan.
8015 for (Value *V : NeedDef)
8016 Plan->addVPValue(V);
8017
8018 // Scan the body of the loop in a topological order to visit each basic block
8019 // after having visited its predecessor basic blocks.
8020 LoopBlocksDFS DFS(OrigLoop);
8021 DFS.perform(LI);
8022
8023 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8024 // Relevant instructions from basic block BB will be grouped into VPRecipe
8025 // ingredients and fill a new VPBasicBlock.
8026 unsigned VPBBsForBB = 0;
8027 auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
8028 VPBB->setOneSuccessor(FirstVPBBForBB);
8029 VPBB = FirstVPBBForBB;
8030 Builder.setInsertPoint(VPBB);
8031
8032 std::vector<Instruction *> Ingredients;
8033
8034 // Organize the ingredients to vectorize from current basic block in the
8035 // right order.
8036 for (Instruction &I : *BB) {
8037 Instruction *Instr = &I;
8038
8039 // First filter out irrelevant instructions, to ensure no recipes are
8040 // built for them.
8041 if (isa<BranchInst>(Instr) || isa<DbgInfoIntrinsic>(Instr) ||
8042 DeadInstructions.count(Instr))
8043 continue;
8044
8045 // I is a member of an InterleaveGroup for Range.Start. If it's an adjunct
8046 // member of the IG, do not construct any Recipe for it.
8047 const InterleaveGroup *IG = Legal->getInterleavedAccessGroup(Instr);
8048 if (IG && Instr != IG->getInsertPos() &&
8049 Range.Start >= 2 && // Query is illegal for VF == 1
8050 CM.getWideningDecision(Instr, Range.Start) ==
8051 LoopVectorizationCostModel::CM_Interleave) {
8052 if (SinkAfterInverse.count(Instr))
8053 Ingredients.push_back(SinkAfterInverse.find(Instr)->second);
8054 continue;
8055 }
8056
8057 // Move instructions to handle first-order recurrences, step 1: avoid
8058 // handling this instruction until after we've handled the instruction it
8059 // should follow.
8060 auto SAIt = SinkAfter.find(Instr);
8061 if (SAIt != SinkAfter.end()) {
8062 DEBUG(dbgs() << "Sinking" << *SAIt->first << " after" << *SAIt->seconddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "Sinking" << *SAIt
->first << " after" << *SAIt->second <<
" to vectorize a 1st order recurrence.\n"; } } while (false)
8063 << " to vectorize a 1st order recurrence.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "Sinking" << *SAIt
->first << " after" << *SAIt->second <<
" to vectorize a 1st order recurrence.\n"; } } while (false)
;
8064 SinkAfterInverse[SAIt->second] = Instr;
8065 continue;
8066 }
8067
8068 Ingredients.push_back(Instr);
8069
8070 // Move instructions to handle first-order recurrences, step 2: push the
8071 // instruction to be sunk at its insertion point.
8072 auto SAInvIt = SinkAfterInverse.find(Instr);
8073 if (SAInvIt != SinkAfterInverse.end())
8074 Ingredients.push_back(SAInvIt->second);
8075 }
8076
8077 // Introduce each ingredient into VPlan.
8078 for (Instruction *Instr : Ingredients) {
8079 VPRecipeBase *Recipe = nullptr;
8080
8081 // Check if Instr should belong to an interleave memory recipe, or already
8082 // does. In the latter case Instr is irrelevant.
8083 if ((Recipe = tryToInterleaveMemory(Instr, Range))) {
8084 VPBB->appendRecipe(Recipe);
8085 continue;
8086 }
8087
8088 // Check if Instr is a memory operation that should be widened.
8089 if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) {
8090 VPBB->appendRecipe(Recipe);
8091 continue;
8092 }
8093
8094 // Check if Instr should form some PHI recipe.
8095 if ((Recipe = tryToOptimizeInduction(Instr, Range))) {
8096 VPBB->appendRecipe(Recipe);
8097 continue;
8098 }
8099 if ((Recipe = tryToBlend(Instr, Plan))) {
8100 VPBB->appendRecipe(Recipe);
8101 continue;
8102 }
8103 if (PHINode *Phi = dyn_cast<PHINode>(Instr)) {
8104 VPBB->appendRecipe(new VPWidenPHIRecipe(Phi));
8105 continue;
8106 }
8107
8108 // Check if Instr is to be widened by a general VPWidenRecipe, after
8109 // having first checked for specific widening recipes that deal with
8110 // Interleave Groups, Inductions and Phi nodes.
8111 if (tryToWiden(Instr, VPBB, Range))
8112 continue;
8113
8114 // Otherwise, if all widening options failed, Instruction is to be
8115 // replicated. This may create a successor for VPBB.
8116 VPBasicBlock *NextVPBB =
8117 handleReplication(Instr, Range, VPBB, PredInst2Recipe, Plan);
8118 if (NextVPBB != VPBB) {
8119 VPBB = NextVPBB;
8120 VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8121 : "");
8122 }
8123 }
8124 }
8125
8126 // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
8127 // may also be empty, such as the last one VPBB, reflecting original
8128 // basic-blocks with no recipes.
8129 VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
8130 assert(PreEntry->empty() && "Expecting empty pre-entry block.")(static_cast <bool> (PreEntry->empty() && "Expecting empty pre-entry block."
) ? void (0) : __assert_fail ("PreEntry->empty() && \"Expecting empty pre-entry block.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8130, __extension__ __PRETTY_FUNCTION__))
;
8131 VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
8132 PreEntry->disconnectSuccessor(Entry);
8133 delete PreEntry;
8134
8135 std::string PlanName;
8136 raw_string_ostream RSO(PlanName);
8137 unsigned VF = Range.Start;
8138 Plan->addVF(VF);
8139 RSO << "Initial VPlan for VF={" << VF;
8140 for (VF *= 2; VF < Range.End; VF *= 2) {
8141 Plan->addVF(VF);
8142 RSO << "," << VF;
8143 }
8144 RSO << "},UF>=1";
8145 RSO.flush();
8146 Plan->setName(PlanName);
8147
8148 return Plan;
8149}
8150
8151Value* LoopVectorizationPlanner::VPCallbackILV::
8152getOrCreateVectorValues(Value *V, unsigned Part) {
8153 return ILV.getOrCreateVectorValue(V, Part);
8154}
8155
8156void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent) const {
8157 O << " +\n"
8158 << Indent << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
8159 IG->getInsertPos()->printAsOperand(O, false);
8160 O << "\\l\"";
8161 for (unsigned i = 0; i < IG->getFactor(); ++i)
8162 if (Instruction *I = IG->getMember(i))
8163 O << " +\n"
8164 << Indent << "\" " << VPlanIngredient(I) << " " << i << "\\l\"";
8165}
8166
8167void VPWidenRecipe::execute(VPTransformState &State) {
8168 for (auto &Instr : make_range(Begin, End))
8169 State.ILV->widenInstruction(Instr);
8170}
8171
8172void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
8173 assert(!State.Instance && "Int or FP induction being replicated.")(static_cast <bool> (!State.Instance && "Int or FP induction being replicated."
) ? void (0) : __assert_fail ("!State.Instance && \"Int or FP induction being replicated.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8173, __extension__ __PRETTY_FUNCTION__))
;
8174 State.ILV->widenIntOrFpInduction(IV, Trunc);
8175}
8176
8177void VPWidenPHIRecipe::execute(VPTransformState &State) {
8178 State.ILV->widenPHIInstruction(Phi, State.UF, State.VF);
8179}
8180
8181void VPBlendRecipe::execute(VPTransformState &State) {
8182 State.ILV->setDebugLocFromInst(State.Builder, Phi);
8183 // We know that all PHIs in non-header blocks are converted into
8184 // selects, so we don't have to worry about the insertion order and we
8185 // can just use the builder.
8186 // At this point we generate the predication tree. There may be
8187 // duplications since this is a simple recursive scan, but future
8188 // optimizations will clean it up.
8189
8190 unsigned NumIncoming = Phi->getNumIncomingValues();
8191
8192 assert((User || NumIncoming == 1) &&(static_cast <bool> ((User || NumIncoming == 1) &&
"Multiple predecessors with predecessors having a full mask"
) ? void (0) : __assert_fail ("(User || NumIncoming == 1) && \"Multiple predecessors with predecessors having a full mask\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8193, __extension__ __PRETTY_FUNCTION__))
8193 "Multiple predecessors with predecessors having a full mask")(static_cast <bool> ((User || NumIncoming == 1) &&
"Multiple predecessors with predecessors having a full mask"
) ? void (0) : __assert_fail ("(User || NumIncoming == 1) && \"Multiple predecessors with predecessors having a full mask\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8193, __extension__ __PRETTY_FUNCTION__))
;
8194 // Generate a sequence of selects of the form:
8195 // SELECT(Mask3, In3,
8196 // SELECT(Mask2, In2,
8197 // ( ...)))
8198 InnerLoopVectorizer::VectorParts Entry(State.UF);
8199 for (unsigned In = 0; In < NumIncoming; ++In) {
8200 for (unsigned Part = 0; Part < State.UF; ++Part) {
8201 // We might have single edge PHIs (blocks) - use an identity
8202 // 'select' for the first PHI operand.
8203 Value *In0 =
8204 State.ILV->getOrCreateVectorValue(Phi->getIncomingValue(In), Part);
8205 if (In == 0)
8206 Entry[Part] = In0; // Initialize with the first incoming value.
8207 else {
8208 // Select between the current value and the previous incoming edge
8209 // based on the incoming mask.
8210 Value *Cond = State.get(User->getOperand(In), Part);
8211 Entry[Part] =
8212 State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
8213 }
8214 }
8215 }
8216 for (unsigned Part = 0; Part < State.UF; ++Part)
8217 State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
8218}
8219
8220void VPInterleaveRecipe::execute(VPTransformState &State) {
8221 assert(!State.Instance && "Interleave group being replicated.")(static_cast <bool> (!State.Instance && "Interleave group being replicated."
) ? void (0) : __assert_fail ("!State.Instance && \"Interleave group being replicated.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8221, __extension__ __PRETTY_FUNCTION__))
;
8222 State.ILV->vectorizeInterleaveGroup(IG->getInsertPos());
8223}
8224
8225void VPReplicateRecipe::execute(VPTransformState &State) {
8226 if (State.Instance) { // Generate a single instance.
8227 State.ILV->scalarizeInstruction(Ingredient, *State.Instance, IsPredicated);
8228 // Insert scalar instance packing it into a vector.
8229 if (AlsoPack && State.VF > 1) {
8230 // If we're constructing lane 0, initialize to start from undef.
8231 if (State.Instance->Lane == 0) {
8232 Value *Undef =
8233 UndefValue::get(VectorType::get(Ingredient->getType(), State.VF));
8234 State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef);
8235 }
8236 State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance);
8237 }
8238 return;
8239 }
8240
8241 // Generate scalar instances for all VF lanes of all UF parts, unless the
8242 // instruction is uniform inwhich case generate only the first lane for each
8243 // of the UF parts.
8244 unsigned EndLane = IsUniform ? 1 : State.VF;
8245 for (unsigned Part = 0; Part < State.UF; ++Part)
8246 for (unsigned Lane = 0; Lane < EndLane; ++Lane)
8247 State.ILV->scalarizeInstruction(Ingredient, {Part, Lane}, IsPredicated);
8248}
8249
8250void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
8251 assert(State.Instance && "Branch on Mask works only on single instance.")(static_cast <bool> (State.Instance && "Branch on Mask works only on single instance."
) ? void (0) : __assert_fail ("State.Instance && \"Branch on Mask works only on single instance.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8251, __extension__ __PRETTY_FUNCTION__))
;
8252
8253 unsigned Part = State.Instance->Part;
8254 unsigned Lane = State.Instance->Lane;
8255
8256 Value *ConditionBit = nullptr;
8257 if (!User) // Block in mask is all-one.
8258 ConditionBit = State.Builder.getTrue();
8259 else {
8260 VPValue *BlockInMask = User->getOperand(0);
8261 ConditionBit = State.get(BlockInMask, Part);
8262 if (ConditionBit->getType()->isVectorTy())
8263 ConditionBit = State.Builder.CreateExtractElement(
8264 ConditionBit, State.Builder.getInt32(Lane));
8265 }
8266
8267 // Replace the temporary unreachable terminator with a new conditional branch,
8268 // whose two destinations will be set later when they are created.
8269 auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
8270 assert(isa<UnreachableInst>(CurrentTerminator) &&(static_cast <bool> (isa<UnreachableInst>(CurrentTerminator
) && "Expected to replace unreachable terminator with conditional branch."
) ? void (0) : __assert_fail ("isa<UnreachableInst>(CurrentTerminator) && \"Expected to replace unreachable terminator with conditional branch.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8271, __extension__ __PRETTY_FUNCTION__))
8271 "Expected to replace unreachable terminator with conditional branch.")(static_cast <bool> (isa<UnreachableInst>(CurrentTerminator
) && "Expected to replace unreachable terminator with conditional branch."
) ? void (0) : __assert_fail ("isa<UnreachableInst>(CurrentTerminator) && \"Expected to replace unreachable terminator with conditional branch.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8271, __extension__ __PRETTY_FUNCTION__))
;
8272 auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
8273 CondBr->setSuccessor(0, nullptr);
8274 ReplaceInstWithInst(CurrentTerminator, CondBr);
8275}
8276
8277void VPPredInstPHIRecipe::execute(VPTransformState &State) {
8278 assert(State.Instance && "Predicated instruction PHI works per instance.")(static_cast <bool> (State.Instance && "Predicated instruction PHI works per instance."
) ? void (0) : __assert_fail ("State.Instance && \"Predicated instruction PHI works per instance.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8278, __extension__ __PRETTY_FUNCTION__))
;
8279 Instruction *ScalarPredInst = cast<Instruction>(
8280 State.ValueMap.getScalarValue(PredInst, *State.Instance));
8281 BasicBlock *PredicatedBB = ScalarPredInst->getParent();
8282 BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
8283 assert(PredicatingBB && "Predicated block has no single predecessor.")(static_cast <bool> (PredicatingBB && "Predicated block has no single predecessor."
) ? void (0) : __assert_fail ("PredicatingBB && \"Predicated block has no single predecessor.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8283, __extension__ __PRETTY_FUNCTION__))
;
8284
8285 // By current pack/unpack logic we need to generate only a single phi node: if
8286 // a vector value for the predicated instruction exists at this point it means
8287 // the instruction has vector users only, and a phi for the vector value is
8288 // needed. In this case the recipe of the predicated instruction is marked to
8289 // also do that packing, thereby "hoisting" the insert-element sequence.
8290 // Otherwise, a phi node for the scalar value is needed.
8291 unsigned Part = State.Instance->Part;
8292 if (State.ValueMap.hasVectorValue(PredInst, Part)) {
8293 Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
8294 InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
8295 PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
8296 VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
8297 VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
8298 State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
8299 } else {
8300 Type *PredInstType = PredInst->getType();
8301 PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
8302 Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB);
8303 Phi->addIncoming(ScalarPredInst, PredicatedBB);
8304 State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
8305 }
8306}
8307
8308void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
8309 if (!User)
8310 return State.ILV->vectorizeMemoryInstruction(&Instr);
8311
8312 // Last (and currently only) operand is a mask.
8313 InnerLoopVectorizer::VectorParts MaskValues(State.UF);
8314 VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
8315 for (unsigned Part = 0; Part < State.UF; ++Part)
8316 MaskValues[Part] = State.get(Mask, Part);
8317 State.ILV->vectorizeMemoryInstruction(&Instr, &MaskValues);
8318}
8319
8320bool LoopVectorizePass::processLoop(Loop *L) {
8321 assert(L->empty() && "Only process inner loops.")(static_cast <bool> (L->empty() && "Only process inner loops."
) ? void (0) : __assert_fail ("L->empty() && \"Only process inner loops.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8321, __extension__ __PRETTY_FUNCTION__))
;
8322
8323#ifndef NDEBUG
8324 const std::string DebugLocStr = getDebugLocString(L);
8325#endif /* NDEBUG */
8326
8327 DEBUG(dbgs() << "\nLV: Checking a loop in \""do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "\nLV: Checking a loop in \""
<< L->getHeader()->getParent()->getName() <<
"\" from " << DebugLocStr << "\n"; } } while (false
)
8328 << L->getHeader()->getParent()->getName() << "\" from "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "\nLV: Checking a loop in \""
<< L->getHeader()->getParent()->getName() <<
"\" from " << DebugLocStr << "\n"; } } while (false
)
8329 << DebugLocStr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "\nLV: Checking a loop in \""
<< L->getHeader()->getParent()->getName() <<
"\" from " << DebugLocStr << "\n"; } } while (false
)
;
8330
8331 LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
8332
8333 DEBUG(dbgs() << "LV: Loop hints:"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8334 << " force="do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8335 << (Hints.getForce() == LoopVectorizeHints::FK_Disableddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8336 ? "disabled"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8337 : (Hints.getForce() == LoopVectorizeHints::FK_Enableddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8338 ? "enabled"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8339 : "?"))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8340 << " width=" << Hints.getWidth()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
8341 << " unroll=" << Hints.getInterleave() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints:" <<
" force=" << (Hints.getForce() == LoopVectorizeHints::
FK_Disabled ? "disabled" : (Hints.getForce() == LoopVectorizeHints
::FK_Enabled ? "enabled" : "?")) << " width=" << Hints
.getWidth() << " unroll=" << Hints.getInterleave(
) << "\n"; } } while (false)
;
8342
8343 // Function containing loop
8344 Function *F = L->getHeader()->getParent();
8345
8346 // Looking at the diagnostic output is the only way to determine if a loop
8347 // was vectorized (other than looking at the IR or machine code), so it
8348 // is important to generate an optimization remark for each loop. Most of
8349 // these messages are generated as OptimizationRemarkAnalysis. Remarks
8350 // generated as OptimizationRemark and OptimizationRemarkMissed are
8351 // less verbose reporting vectorized loops and unvectorized loops that may
8352 // benefit from vectorization, respectively.
8353
8354 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1
Taking false branch
8355 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop hints prevent vectorization.\n"
; } } while (false)
;
8356 return false;
8357 }
8358
8359 PredicatedScalarEvolution PSE(*SE, *L);
8360
8361 // Check if it is legal to vectorize the loop.
8362 LoopVectorizationRequirements Requirements(*ORE);
8363 LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE,
8364 &Requirements, &Hints, DB, AC);
8365 if (!LVL.canVectorize()) {
2
Taking false branch
8366 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: Cannot prove legality.\n"
; } } while (false)
;
8367 emitMissedWarning(F, L, Hints, ORE);
8368 return false;
8369 }
8370
8371 // Check the function attributes to find out if this function should be
8372 // optimized for size.
8373 bool OptForSize =
8374 Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
3
Assuming the condition is false
8375
8376 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
8377 // count by optimizing for size, to minimize overheads.
8378 // Prefer constant trip counts over profile data, over upper bound estimate.
8379 unsigned ExpectedTC = 0;
8380 bool HasExpectedTC = false;
8381 if (const SCEVConstant *ConstExits =
4
Taking false branch
8382 dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) {
8383 const APInt &ExitsCount = ConstExits->getAPInt();
8384 // We are interested in small values for ExpectedTC. Skip over those that
8385 // can't fit an unsigned.
8386 if (ExitsCount.ult(std::numeric_limits<unsigned>::max())) {
8387 ExpectedTC = static_cast<unsigned>(ExitsCount.getZExtValue()) + 1;
8388 HasExpectedTC = true;
8389 }
8390 }
8391 // ExpectedTC may be large because it's bound by a variable. Check
8392 // profiling information to validate we should vectorize.
8393 if (!HasExpectedTC && LoopVectorizeWithBlockFrequency) {
5
Assuming the condition is false
6
Taking false branch
8394 auto EstimatedTC = getLoopEstimatedTripCount(L);
8395 if (EstimatedTC) {
8396 ExpectedTC = *EstimatedTC;
8397 HasExpectedTC = true;
8398 }
8399 }
8400 if (!HasExpectedTC) {
7
Taking true branch
8401 ExpectedTC = SE->getSmallConstantMaxTripCount(L);
8402 HasExpectedTC = (ExpectedTC > 0);
8
Assuming 'ExpectedTC' is <= 0
8403 }
8404
8405 if (HasExpectedTC && ExpectedTC < TinyTripCountVectorThreshold) {
8406 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a loop with a very small trip count. "
<< "This loop is worth vectorizing only if no scalar "
<< "iteration overheads are incurred."; } } while (false
)
8407 << "This loop is worth vectorizing only if no scalar "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a loop with a very small trip count. "
<< "This loop is worth vectorizing only if no scalar "
<< "iteration overheads are incurred."; } } while (false
)
8408 << "iteration overheads are incurred.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a loop with a very small trip count. "
<< "This loop is worth vectorizing only if no scalar "
<< "iteration overheads are incurred."; } } while (false
)
;
8409 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
8410 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << " But vectorizing was explicitly forced.\n"
; } } while (false)
;
8411 else {
8412 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "\n"; } } while (false)
;
8413 // Loops with a very small trip count are considered for vectorization
8414 // under OptForSize, thereby making sure the cost of their loop body is
8415 // dominant, free of runtime guards and scalar iteration overheads.
8416 OptForSize = true;
8417 }
8418 }
8419
8420 // Check the function attributes to see if implicit floats are allowed.
8421 // FIXME: This check doesn't seem possibly correct -- what if the loop is
8422 // an integer loop and the vector instructions selected are purely integer
8423 // vector instructions?
8424 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9
Assuming the condition is false
10
Taking false branch
8425 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
"attribute is used.\n"; } } while (false)
8426 "attribute is used.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
"attribute is used.\n"; } } while (false)
;
8427 ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
8428 "NoImplicitFloat", L)
8429 << "loop not vectorized due to NoImplicitFloat attribute");
8430 emitMissedWarning(F, L, Hints, ORE);
8431 return false;
8432 }
8433
8434 // Check if the target supports potentially unsafe FP vectorization.
8435 // FIXME: Add a check for the type of safety issue (denormal, signaling)
8436 // for the target we're vectorizing for, to make sure none of the
8437 // additional fp-math flags can help.
8438 if (Hints.isPotentiallyUnsafe() &&
8439 TTI->isFPVectorizationPotentiallyUnsafe()) {
8440 DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n"
; } } while (false)
;
8441 ORE->emit(
8442 createMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
8443 << "loop not vectorized due to unsafe FP support.");
8444 emitMissedWarning(F, L, Hints, ORE);
8445 return false;
8446 }
8447
8448 // Use the cost model.
8449 LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
8450 &Hints);
8451 CM.collectValuesToIgnore();
8452
8453 // Use the planner for vectorization.
8454 LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM);
8455
8456 // Get user vectorization factor.
8457 unsigned UserVF = Hints.getWidth();
8458
8459 // Plan how to best vectorize, return the best VF and its cost.
8460 VectorizationFactor VF = LVP.plan(OptForSize, UserVF);
8461
8462 // Select the interleave count.
8463 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
11
Calling 'LoopVectorizationCostModel::selectInterleaveCount'
8464
8465 // Get user interleave count.
8466 unsigned UserIC = Hints.getInterleave();
8467
8468 // Identify the diagnostic messages that should be produced.
8469 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
8470 bool VectorizeLoop = true, InterleaveLoop = true;
8471 if (Requirements.doesNotMeet(F, L, Hints)) {
8472 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
"requirements.\n"; } } while (false)
8473 "requirements.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
"requirements.\n"; } } while (false)
;
8474 emitMissedWarning(F, L, Hints, ORE);
8475 return false;
8476 }
8477
8478 if (VF.Width == 1) {
8479 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Vectorization is possible but not beneficial.\n"
; } } while (false)
;
8480 VecDiagMsg = std::make_pair(
8481 "VectorizationNotBeneficial",
8482 "the cost-model indicates that vectorization is not beneficial");
8483 VectorizeLoop = false;
8484 }
8485
8486 if (IC == 1 && UserIC <= 1) {
8487 // Tell the user interleaving is not beneficial.
8488 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Interleaving is not beneficial.\n"
; } } while (false)
;
8489 IntDiagMsg = std::make_pair(
8490 "InterleavingNotBeneficial",
8491 "the cost-model indicates that interleaving is not beneficial");
8492 InterleaveLoop = false;
8493 if (UserIC == 1) {
8494 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
8495 IntDiagMsg.second +=
8496 " and is explicitly disabled or interleave count is set to 1";
8497 }
8498 } else if (IC > 1 && UserIC == 1) {
8499 // Tell the user interleaving is beneficial, but it explicitly disabled.
8500 DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Interleaving is beneficial but is explicitly disabled."
; } } while (false)
8501 << "LV: Interleaving is beneficial but is explicitly disabled.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Interleaving is beneficial but is explicitly disabled."
; } } while (false)
;
8502 IntDiagMsg = std::make_pair(
8503 "InterleavingBeneficialButDisabled",
8504 "the cost-model indicates that interleaving is beneficial "
8505 "but is explicitly disabled or interleave count is set to 1");
8506 InterleaveLoop = false;
8507 }
8508
8509 // Override IC if user provided an interleave count.
8510 IC = UserIC > 0 ? UserIC : IC;
8511
8512 // Emit diagnostic messages, if any.
8513 const char *VAPassName = Hints.vectorizeAnalysisPassName();
8514 if (!VectorizeLoop && !InterleaveLoop) {
8515 // Do not vectorize or interleaving the loop.
8516 ORE->emit([&]() {
8517 return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
8518 L->getStartLoc(), L->getHeader())
8519 << VecDiagMsg.second;
8520 });
8521 ORE->emit([&]() {
8522 return OptimizationRemarkMissed(LV_NAME"loop-vectorize", IntDiagMsg.first,
8523 L->getStartLoc(), L->getHeader())
8524 << IntDiagMsg.second;
8525 });
8526 return false;
8527 } else if (!VectorizeLoop && InterleaveLoop) {
8528 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Interleave Count is "
<< IC << '\n'; } } while (false)
;
8529 ORE->emit([&]() {
8530 return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
8531 L->getStartLoc(), L->getHeader())
8532 << VecDiagMsg.second;
8533 });
8534 } else if (VectorizeLoop && !InterleaveLoop) {
8535 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop ("
<< VF.Width << ") in " << DebugLocStr <<
'\n'; } } while (false)
8536 << DebugLocStr << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop ("
<< VF.Width << ") in " << DebugLocStr <<
'\n'; } } while (false)
;
8537 ORE->emit([&]() {
8538 return OptimizationRemarkAnalysis(LV_NAME"loop-vectorize", IntDiagMsg.first,
8539 L->getStartLoc(), L->getHeader())
8540 << IntDiagMsg.second;
8541 });
8542 } else if (VectorizeLoop && InterleaveLoop) {
8543 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop ("
<< VF.Width << ") in " << DebugLocStr <<
'\n'; } } while (false)
8544 << DebugLocStr << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a vectorizable loop ("
<< VF.Width << ") in " << DebugLocStr <<
'\n'; } } while (false)
;
8545 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Interleave Count is "
<< IC << '\n'; } } while (false)
;
8546 }
8547
8548 LVP.setBestPlan(VF.Width, IC);
8549
8550 using namespace ore;
8551
8552 if (!VectorizeLoop) {
8553 assert(IC > 1 && "interleave count should not be 1 or 0")(static_cast <bool> (IC > 1 && "interleave count should not be 1 or 0"
) ? void (0) : __assert_fail ("IC > 1 && \"interleave count should not be 1 or 0\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 8553, __extension__ __PRETTY_FUNCTION__))
;
8554 // If we decided that it is not legal to vectorize the loop, then
8555 // interleave it.
8556 InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
8557 &CM);
8558 LVP.executePlan(Unroller, DT);
8559
8560 ORE->emit([&]() {
8561 return OptimizationRemark(LV_NAME"loop-vectorize", "Interleaved", L->getStartLoc(),
8562 L->getHeader())
8563 << "interleaved loop (interleaved count: "
8564 << NV("InterleaveCount", IC) << ")";
8565 });
8566 } else {
8567 // If we decided that it is *legal* to vectorize the loop, then do it.
8568 InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
8569 &LVL, &CM);
8570 LVP.executePlan(LB, DT);
8571 ++LoopsVectorized;
8572
8573 // Add metadata to disable runtime unrolling a scalar loop when there are
8574 // no runtime checks about strides and memory. A scalar loop that is
8575 // rarely used is not worth unrolling.
8576 if (!LB.areSafetyChecksAdded())
8577 AddRuntimeUnrollDisableMetaData(L);
8578
8579 // Report the vectorization decision.
8580 ORE->emit([&]() {
8581 return OptimizationRemark(LV_NAME"loop-vectorize", "Vectorized", L->getStartLoc(),
8582 L->getHeader())
8583 << "vectorized loop (vectorization width: "
8584 << NV("VectorizationFactor", VF.Width)
8585 << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
8586 });
8587 }
8588
8589 // Mark the loop as already vectorized to avoid vectorizing again.
8590 Hints.setAlreadyVectorized();
8591
8592 DEBUG(verifyFunction(*L->getHeader()->getParent()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { verifyFunction(*L->getHeader()->getParent
()); } } while (false)
;
8593 return true;
8594}
8595
8596bool LoopVectorizePass::runImpl(
8597 Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
8598 DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
8599 DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
8600 std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
8601 OptimizationRemarkEmitter &ORE_) {
8602 SE = &SE_;
8603 LI = &LI_;
8604 TTI = &TTI_;
8605 DT = &DT_;
8606 BFI = &BFI_;
8607 TLI = TLI_;
8608 AA = &AA_;
8609 AC = &AC_;
8610 GetLAA = &GetLAA_;
8611 DB = &DB_;
8612 ORE = &ORE_;
8613
8614 // Don't attempt if
8615 // 1. the target claims to have no vector registers, and
8616 // 2. interleaving won't help ILP.
8617 //
8618 // The second condition is necessary because, even if the target has no
8619 // vector registers, loop vectorization may still enable scalar
8620 // interleaving.
8621 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
8622 return false;
8623
8624 bool Changed = false;
8625
8626 // The vectorizer requires loops to be in simplified form.
8627 // Since simplification may add new inner loops, it has to run before the
8628 // legality and profitability checks. This means running the loop vectorizer
8629 // will simplify all loops, regardless of whether anything end up being
8630 // vectorized.
8631 for (auto &L : *LI)
8632 Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
8633
8634 // Build up a worklist of inner-loops to vectorize. This is necessary as
8635 // the act of vectorizing or partially unrolling a loop creates new loops
8636 // and can invalidate iterators across the loops.
8637 SmallVector<Loop *, 8> Worklist;
8638
8639 for (Loop *L : *LI)
8640 addAcyclicInnerLoop(*L, Worklist);
8641
8642 LoopsAnalyzed += Worklist.size();
8643
8644 // Now walk the identified inner loops.
8645 while (!Worklist.empty()) {
8646 Loop *L = Worklist.pop_back_val();
8647
8648 // For the inner loops we actually process, form LCSSA to simplify the
8649 // transform.
8650 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
8651
8652 Changed |= processLoop(L);
8653 }
8654
8655 // Process each loop nest in the function.
8656 return Changed;
8657}
8658
8659PreservedAnalyses LoopVectorizePass::run(Function &F,
8660 FunctionAnalysisManager &AM) {
8661 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
8662 auto &LI = AM.getResult<LoopAnalysis>(F);
8663 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
8664 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
8665 auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
8666 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
8667 auto &AA = AM.getResult<AAManager>(F);
8668 auto &AC = AM.getResult<AssumptionAnalysis>(F);
8669 auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
8670 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8671
8672 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
8673 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
8674 [&](Loop &L) -> const LoopAccessInfo & {
8675 LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, nullptr};
8676 return LAM.getResult<LoopAccessAnalysis>(L, AR);
8677 };
8678 bool Changed =
8679 runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
8680 if (!Changed)
8681 return PreservedAnalyses::all();
8682 PreservedAnalyses PA;
8683 PA.preserve<LoopAnalysis>();
8684 PA.preserve<DominatorTreeAnalysis>();
8685 PA.preserve<BasicAA>();
8686 PA.preserve<GlobalsAA>();
8687 return PA;
8688}