1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // The interleaved access vectorization is based on the paper:
38 // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
41 // Other ideas/concepts are from:
42 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
44 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
45 // Vectorizing Compilers.
47 //===----------------------------------------------------------------------===//
49 #include "llvm/Transforms/Vectorize.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/EquivalenceClasses.h"
52 #include "llvm/ADT/Hashing.h"
53 #include "llvm/ADT/MapVector.h"
54 #include "llvm/ADT/SetVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/SmallSet.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/StringExtras.h"
60 #include "llvm/Analysis/AliasAnalysis.h"
61 #include "llvm/Analysis/BasicAliasAnalysis.h"
62 #include "llvm/Analysis/AliasSetTracker.h"
63 #include "llvm/Analysis/AssumptionCache.h"
64 #include "llvm/Analysis/BlockFrequencyInfo.h"
65 #include "llvm/Analysis/CodeMetrics.h"
66 #include "llvm/Analysis/GlobalsModRef.h"
67 #include "llvm/Analysis/LoopAccessAnalysis.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Analysis/LoopIterator.h"
70 #include "llvm/Analysis/LoopPass.h"
71 #include "llvm/Analysis/ScalarEvolution.h"
72 #include "llvm/Analysis/ScalarEvolutionExpander.h"
73 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
74 #include "llvm/Analysis/TargetTransformInfo.h"
75 #include "llvm/Analysis/ValueTracking.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfo.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/DiagnosticInfo.h"
81 #include "llvm/IR/Dominators.h"
82 #include "llvm/IR/Function.h"
83 #include "llvm/IR/IRBuilder.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Module.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/IR/ValueHandle.h"
92 #include "llvm/IR/Verifier.h"
93 #include "llvm/Pass.h"
94 #include "llvm/Support/BranchProbability.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/raw_ostream.h"
98 #include "llvm/Transforms/Scalar.h"
99 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
100 #include "llvm/Transforms/Utils/Local.h"
101 #include "llvm/Analysis/VectorUtils.h"
102 #include "llvm/Transforms/Utils/LoopUtils.h"
107 using namespace llvm;
108 using namespace llvm::PatternMatch;
110 #define LV_NAME "loop-vectorize"
111 #define DEBUG_TYPE LV_NAME
113 STATISTIC(LoopsVectorized, "Number of loops vectorized");
114 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
117 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
118 cl::desc("Enable if-conversion during vectorization."));
120 /// We don't vectorize loops with a known constant trip count below this number.
121 static cl::opt<unsigned>
122 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
124 cl::desc("Don't vectorize loops with a constant "
125 "trip count that is smaller than this "
128 /// This enables versioning on the strides of symbolically striding memory
129 /// accesses in code like the following.
130 /// for (i = 0; i < N; ++i)
131 /// A[i * Stride1] += B[i * Stride2] ...
133 /// Will be roughly translated to
134 /// if (Stride1 == 1 && Stride2 == 1) {
135 /// for (i = 0; i < N; i+=4)
139 static cl::opt<bool> EnableMemAccessVersioning(
140 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
141 cl::desc("Enable symblic stride memory access versioning"));
143 static cl::opt<bool> EnableInterleavedMemAccesses(
144 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
145 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
147 /// Maximum factor for an interleaved memory access.
148 static cl::opt<unsigned> MaxInterleaveGroupFactor(
149 "max-interleave-group-factor", cl::Hidden,
150 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
153 /// We don't interleave loops with a known constant trip count below this
155 static const unsigned TinyTripCountInterleaveThreshold = 128;
157 static cl::opt<unsigned> ForceTargetNumScalarRegs(
158 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
159 cl::desc("A flag that overrides the target's number of scalar registers."));
161 static cl::opt<unsigned> ForceTargetNumVectorRegs(
162 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
163 cl::desc("A flag that overrides the target's number of vector registers."));
165 /// Maximum vectorization interleave count.
166 static const unsigned MaxInterleaveFactor = 16;
168 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
169 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
170 cl::desc("A flag that overrides the target's max interleave factor for "
173 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
174 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
175 cl::desc("A flag that overrides the target's max interleave factor for "
176 "vectorized loops."));
178 static cl::opt<unsigned> ForceTargetInstructionCost(
179 "force-target-instruction-cost", cl::init(0), cl::Hidden,
180 cl::desc("A flag that overrides the target's expected cost for "
181 "an instruction to a single constant value. Mostly "
182 "useful for getting consistent testing."));
184 static cl::opt<unsigned> SmallLoopCost(
185 "small-loop-cost", cl::init(20), cl::Hidden,
187 "The cost of a loop that is considered 'small' by the interleaver."));
189 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
190 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
191 cl::desc("Enable the use of the block frequency analysis to access PGO "
192 "heuristics minimizing code growth in cold regions and being more "
193 "aggressive in hot regions."));
195 // Runtime interleave loops for load/store throughput.
196 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
197 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
199 "Enable runtime interleaving until load/store ports are saturated"));
201 /// The number of stores in a loop that are allowed to need predication.
202 static cl::opt<unsigned> NumberOfStoresToPredicate(
203 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
204 cl::desc("Max number of stores to be predicated behind an if."));
206 static cl::opt<bool> EnableIndVarRegisterHeur(
207 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
208 cl::desc("Count the induction variable only once when interleaving"));
210 static cl::opt<bool> EnableCondStoresVectorization(
211 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
212 cl::desc("Enable if predication of stores during vectorization."));
214 static cl::opt<unsigned> MaxNestedScalarReductionIC(
215 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
216 cl::desc("The maximum interleave count to use when interleaving a scalar "
217 "reduction in a nested loop."));
219 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
220 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
221 cl::desc("The maximum allowed number of runtime memory checks with a "
222 "vectorize(enable) pragma."));
226 // Forward declarations.
227 class LoopVectorizeHints;
228 class LoopVectorizationLegality;
229 class LoopVectorizationCostModel;
230 class LoopVectorizationRequirements;
232 /// \brief This modifies LoopAccessReport to initialize message with
233 /// loop-vectorizer-specific part.
234 class VectorizationReport : public LoopAccessReport {
236 VectorizationReport(Instruction *I = nullptr)
237 : LoopAccessReport("loop not vectorized: ", I) {}
239 /// \brief This allows promotion of the loop-access analysis report into the
240 /// loop-vectorizer report. It modifies the message to add the
241 /// loop-vectorizer-specific part of the message.
242 explicit VectorizationReport(const LoopAccessReport &R)
243 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
247 /// A helper function for converting Scalar types to vector types.
248 /// If the incoming type is void, we return void. If the VF is 1, we return
250 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
251 if (Scalar->isVoidTy() || VF == 1)
253 return VectorType::get(Scalar, VF);
256 /// InnerLoopVectorizer vectorizes loops which contain only one basic
257 /// block to a specified vectorization factor (VF).
258 /// This class performs the widening of scalars into vectors, or multiple
259 /// scalars. This class also implements the following features:
260 /// * It inserts an epilogue loop for handling loops that don't have iteration
261 /// counts that are known to be a multiple of the vectorization factor.
262 /// * It handles the code generation for reduction variables.
263 /// * Scalarization (implementation using scalars) of un-vectorizable
265 /// InnerLoopVectorizer does not perform any vectorization-legality
266 /// checks, and relies on the caller to check for the different legality
267 /// aspects. The InnerLoopVectorizer relies on the
268 /// LoopVectorizationLegality class to provide information about the induction
269 /// and reduction variables that were found to a given vectorization factor.
270 class InnerLoopVectorizer {
272 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
273 DominatorTree *DT, const TargetLibraryInfo *TLI,
274 const TargetTransformInfo *TTI, unsigned VecWidth,
275 unsigned UnrollFactor)
276 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
277 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
278 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
279 TripCount(nullptr), VectorTripCount(nullptr), Legal(nullptr),
280 AddedSafetyChecks(false) {}
282 // Perform the actual loop widening (vectorization).
283 void vectorize(LoopVectorizationLegality *L) {
285 // Create a new empty loop. Unlink the old loop and connect the new one.
287 // Widen each instruction in the old loop to a new one in the new loop.
288 // Use the Legality module to find the induction and reduction variables.
292 // Return true if any runtime check is added.
293 bool IsSafetyChecksAdded() {
294 return AddedSafetyChecks;
297 virtual ~InnerLoopVectorizer() {}
300 /// A small list of PHINodes.
301 typedef SmallVector<PHINode*, 4> PhiVector;
302 /// When we unroll loops we have multiple vector values for each scalar.
303 /// This data structure holds the unrolled and vectorized values that
304 /// originated from one scalar instruction.
305 typedef SmallVector<Value*, 2> VectorParts;
307 // When we if-convert we need to create edge masks. We have to cache values
308 // so that we don't end up with exponential recursion/IR.
309 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
310 VectorParts> EdgeMaskCache;
312 /// \brief Add checks for strides that were assumed to be 1.
314 /// Returns the last check instruction and the first check instruction in the
315 /// pair as (first, last).
316 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
318 /// Create an empty loop, based on the loop ranges of the old loop.
319 void createEmptyLoop();
320 /// Create a new induction variable inside L.
321 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
322 Value *Step, Instruction *DL);
323 /// Copy and widen the instructions from the old loop.
324 virtual void vectorizeLoop();
326 /// \brief The Loop exit block may have single value PHI nodes where the
327 /// incoming value is 'Undef'. While vectorizing we only handled real values
328 /// that were defined inside the loop. Here we fix the 'undef case'.
332 /// A helper function that computes the predicate of the block BB, assuming
333 /// that the header block of the loop is set to True. It returns the *entry*
334 /// mask for the block BB.
335 VectorParts createBlockInMask(BasicBlock *BB);
336 /// A helper function that computes the predicate of the edge between SRC
338 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
340 /// A helper function to vectorize a single BB within the innermost loop.
341 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
343 /// Vectorize a single PHINode in a block. This method handles the induction
344 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
345 /// arbitrary length vectors.
346 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
347 unsigned UF, unsigned VF, PhiVector *PV);
349 /// Insert the new loop to the loop hierarchy and pass manager
350 /// and update the analysis passes.
351 void updateAnalysis();
353 /// This instruction is un-vectorizable. Implement it as a sequence
354 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
355 /// scalarized instruction behind an if block predicated on the control
356 /// dependence of the instruction.
357 virtual void scalarizeInstruction(Instruction *Instr,
358 bool IfPredicateStore=false);
360 /// Vectorize Load and Store instructions,
361 virtual void vectorizeMemoryInstruction(Instruction *Instr);
363 /// Create a broadcast instruction. This method generates a broadcast
364 /// instruction (shuffle) for loop invariant values and for the induction
365 /// value. If this is the induction variable then we extend it to N, N+1, ...
366 /// this is needed because each iteration in the loop corresponds to a SIMD
368 virtual Value *getBroadcastInstrs(Value *V);
370 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
371 /// to each vector element of Val. The sequence starts at StartIndex.
372 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
374 /// When we go over instructions in the basic block we rely on previous
375 /// values within the current basic block or on loop invariant values.
376 /// When we widen (vectorize) values we place them in the map. If the values
377 /// are not within the map, they have to be loop invariant, so we simply
378 /// broadcast them into a vector.
379 VectorParts &getVectorValue(Value *V);
381 /// Try to vectorize the interleaved access group that \p Instr belongs to.
382 void vectorizeInterleaveGroup(Instruction *Instr);
384 /// Generate a shuffle sequence that will reverse the vector Vec.
385 virtual Value *reverseVector(Value *Vec);
387 /// Returns (and creates if needed) the original loop trip count.
388 Value *getOrCreateTripCount(Loop *NewLoop);
390 /// Returns (and creates if needed) the trip count of the widened loop.
391 Value *getOrCreateVectorTripCount(Loop *NewLoop);
393 /// Emit a bypass check to see if the trip count would overflow, or we
394 /// wouldn't have enough iterations to execute one vector loop.
395 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
396 /// Emit a bypass check to see if the vector trip count is nonzero.
397 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
398 /// Emit bypass checks to check if strides we've assumed to be one really are.
399 void emitStrideChecks(Loop *L, BasicBlock *Bypass);
400 /// Emit bypass checks to check any memory assumptions we may have made.
401 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
403 /// This is a helper class that holds the vectorizer state. It maps scalar
404 /// instructions to vector instructions. When the code is 'unrolled' then
405 /// then a single scalar value is mapped to multiple vector parts. The parts
406 /// are stored in the VectorPart type.
408 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
410 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
412 /// \return True if 'Key' is saved in the Value Map.
413 bool has(Value *Key) const { return MapStorage.count(Key); }
415 /// Initializes a new entry in the map. Sets all of the vector parts to the
416 /// save value in 'Val'.
417 /// \return A reference to a vector with splat values.
418 VectorParts &splat(Value *Key, Value *Val) {
419 VectorParts &Entry = MapStorage[Key];
420 Entry.assign(UF, Val);
424 ///\return A reference to the value that is stored at 'Key'.
425 VectorParts &get(Value *Key) {
426 VectorParts &Entry = MapStorage[Key];
429 assert(Entry.size() == UF);
434 /// The unroll factor. Each entry in the map stores this number of vector
438 /// Map storage. We use std::map and not DenseMap because insertions to a
439 /// dense map invalidates its iterators.
440 std::map<Value *, VectorParts> MapStorage;
443 /// The original loop.
445 /// Scev analysis to use.
453 /// Target Library Info.
454 const TargetLibraryInfo *TLI;
455 /// Target Transform Info.
456 const TargetTransformInfo *TTI;
458 /// The vectorization SIMD factor to use. Each vector will have this many
463 /// The vectorization unroll factor to use. Each scalar is vectorized to this
464 /// many different vector instructions.
467 /// The builder that we use
470 // --- Vectorization state ---
472 /// The vector-loop preheader.
473 BasicBlock *LoopVectorPreHeader;
474 /// The scalar-loop preheader.
475 BasicBlock *LoopScalarPreHeader;
476 /// Middle Block between the vector and the scalar.
477 BasicBlock *LoopMiddleBlock;
478 ///The ExitBlock of the scalar loop.
479 BasicBlock *LoopExitBlock;
480 ///The vector loop body.
481 SmallVector<BasicBlock *, 4> LoopVectorBody;
482 ///The scalar loop body.
483 BasicBlock *LoopScalarBody;
484 /// A list of all bypass blocks. The first block is the entry of the loop.
485 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
487 /// The new Induction variable which was added to the new block.
489 /// The induction variable of the old basic block.
490 PHINode *OldInduction;
491 /// Maps scalars to widened vectors.
493 /// Store instructions that should be predicated, as a pair
494 /// <StoreInst, Predicate>
495 SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
496 EdgeMaskCache MaskCache;
497 /// Trip count of the original loop.
499 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
500 Value *VectorTripCount;
502 LoopVectorizationLegality *Legal;
504 // Record whether runtime check is added.
505 bool AddedSafetyChecks;
508 class InnerLoopUnroller : public InnerLoopVectorizer {
510 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
511 DominatorTree *DT, const TargetLibraryInfo *TLI,
512 const TargetTransformInfo *TTI, unsigned UnrollFactor)
513 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
516 void scalarizeInstruction(Instruction *Instr,
517 bool IfPredicateStore = false) override;
518 void vectorizeMemoryInstruction(Instruction *Instr) override;
519 Value *getBroadcastInstrs(Value *V) override;
520 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
521 Value *reverseVector(Value *Vec) override;
524 /// \brief Look for a meaningful debug location on the instruction or it's
526 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
531 if (I->getDebugLoc() != Empty)
534 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
535 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
536 if (OpInst->getDebugLoc() != Empty)
543 /// \brief Set the debug location in the builder using the debug location in the
545 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
546 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
547 B.SetCurrentDebugLocation(Inst->getDebugLoc());
549 B.SetCurrentDebugLocation(DebugLoc());
553 /// \return string containing a file name and a line # for the given loop.
554 static std::string getDebugLocString(const Loop *L) {
557 raw_string_ostream OS(Result);
558 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
559 LoopDbgLoc.print(OS);
561 // Just print the module name.
562 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
569 /// \brief Propagate known metadata from one instruction to another.
570 static void propagateMetadata(Instruction *To, const Instruction *From) {
571 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
572 From->getAllMetadataOtherThanDebugLoc(Metadata);
574 for (auto M : Metadata) {
575 unsigned Kind = M.first;
577 // These are safe to transfer (this is safe for TBAA, even when we
578 // if-convert, because should that metadata have had a control dependency
579 // on the condition, and thus actually aliased with some other
580 // non-speculated memory access when the condition was false, this would be
581 // caught by the runtime overlap checks).
582 if (Kind != LLVMContext::MD_tbaa &&
583 Kind != LLVMContext::MD_alias_scope &&
584 Kind != LLVMContext::MD_noalias &&
585 Kind != LLVMContext::MD_fpmath &&
586 Kind != LLVMContext::MD_nontemporal)
589 To->setMetadata(Kind, M.second);
593 /// \brief Propagate known metadata from one instruction to a vector of others.
594 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
596 if (Instruction *I = dyn_cast<Instruction>(V))
597 propagateMetadata(I, From);
600 /// \brief The group of interleaved loads/stores sharing the same stride and
601 /// close to each other.
603 /// Each member in this group has an index starting from 0, and the largest
604 /// index should be less than interleaved factor, which is equal to the absolute
605 /// value of the access's stride.
607 /// E.g. An interleaved load group of factor 4:
608 /// for (unsigned i = 0; i < 1024; i+=4) {
609 /// a = A[i]; // Member of index 0
610 /// b = A[i+1]; // Member of index 1
611 /// d = A[i+3]; // Member of index 3
615 /// An interleaved store group of factor 4:
616 /// for (unsigned i = 0; i < 1024; i+=4) {
618 /// A[i] = a; // Member of index 0
619 /// A[i+1] = b; // Member of index 1
620 /// A[i+2] = c; // Member of index 2
621 /// A[i+3] = d; // Member of index 3
624 /// Note: the interleaved load group could have gaps (missing members), but
625 /// the interleaved store group doesn't allow gaps.
626 class InterleaveGroup {
628 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
629 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
630 assert(Align && "The alignment should be non-zero");
632 Factor = std::abs(Stride);
633 assert(Factor > 1 && "Invalid interleave factor");
635 Reverse = Stride < 0;
639 bool isReverse() const { return Reverse; }
640 unsigned getFactor() const { return Factor; }
641 unsigned getAlignment() const { return Align; }
642 unsigned getNumMembers() const { return Members.size(); }
644 /// \brief Try to insert a new member \p Instr with index \p Index and
645 /// alignment \p NewAlign. The index is related to the leader and it could be
646 /// negative if it is the new leader.
648 /// \returns false if the instruction doesn't belong to the group.
649 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
650 assert(NewAlign && "The new member's alignment should be non-zero");
652 int Key = Index + SmallestKey;
654 // Skip if there is already a member with the same index.
655 if (Members.count(Key))
658 if (Key > LargestKey) {
659 // The largest index is always less than the interleave factor.
660 if (Index >= static_cast<int>(Factor))
664 } else if (Key < SmallestKey) {
665 // The largest index is always less than the interleave factor.
666 if (LargestKey - Key >= static_cast<int>(Factor))
672 // It's always safe to select the minimum alignment.
673 Align = std::min(Align, NewAlign);
674 Members[Key] = Instr;
678 /// \brief Get the member with the given index \p Index
680 /// \returns nullptr if contains no such member.
681 Instruction *getMember(unsigned Index) const {
682 int Key = SmallestKey + Index;
683 if (!Members.count(Key))
686 return Members.find(Key)->second;
689 /// \brief Get the index for the given member. Unlike the key in the member
690 /// map, the index starts from 0.
691 unsigned getIndex(Instruction *Instr) const {
692 for (auto I : Members)
693 if (I.second == Instr)
694 return I.first - SmallestKey;
696 llvm_unreachable("InterleaveGroup contains no such member");
699 Instruction *getInsertPos() const { return InsertPos; }
700 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
703 unsigned Factor; // Interleave Factor.
706 DenseMap<int, Instruction *> Members;
710 // To avoid breaking dependences, vectorized instructions of an interleave
711 // group should be inserted at either the first load or the last store in
714 // E.g. %even = load i32 // Insert Position
715 // %add = add i32 %even // Use of %even
719 // %odd = add i32 // Def of %odd
720 // store i32 %odd // Insert Position
721 Instruction *InsertPos;
724 /// \brief Drive the analysis of interleaved memory accesses in the loop.
726 /// Use this class to analyze interleaved accesses only when we can vectorize
727 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
728 /// on interleaved accesses is unsafe.
730 /// The analysis collects interleave groups and records the relationships
731 /// between the member and the group in a map.
732 class InterleavedAccessInfo {
734 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
735 : SE(SE), TheLoop(L), DT(DT) {}
737 ~InterleavedAccessInfo() {
738 SmallSet<InterleaveGroup *, 4> DelSet;
739 // Avoid releasing a pointer twice.
740 for (auto &I : InterleaveGroupMap)
741 DelSet.insert(I.second);
742 for (auto *Ptr : DelSet)
746 /// \brief Analyze the interleaved accesses and collect them in interleave
747 /// groups. Substitute symbolic strides using \p Strides.
748 void analyzeInterleaving(const ValueToValueMap &Strides);
750 /// \brief Check if \p Instr belongs to any interleave group.
751 bool isInterleaved(Instruction *Instr) const {
752 return InterleaveGroupMap.count(Instr);
755 /// \brief Get the interleave group that \p Instr belongs to.
757 /// \returns nullptr if doesn't have such group.
758 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
759 if (InterleaveGroupMap.count(Instr))
760 return InterleaveGroupMap.find(Instr)->second;
769 /// Holds the relationships between the members and the interleave group.
770 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
772 /// \brief The descriptor for a strided memory access.
773 struct StrideDescriptor {
774 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
776 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
778 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
780 int Stride; // The access's stride. It is negative for a reverse access.
781 const SCEV *Scev; // The scalar expression of this access
782 unsigned Size; // The size of the memory object.
783 unsigned Align; // The alignment of this access.
786 /// \brief Create a new interleave group with the given instruction \p Instr,
787 /// stride \p Stride and alignment \p Align.
789 /// \returns the newly created interleave group.
790 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
792 assert(!InterleaveGroupMap.count(Instr) &&
793 "Already in an interleaved access group");
794 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
795 return InterleaveGroupMap[Instr];
798 /// \brief Release the group and remove all the relationships.
799 void releaseGroup(InterleaveGroup *Group) {
800 for (unsigned i = 0; i < Group->getFactor(); i++)
801 if (Instruction *Member = Group->getMember(i))
802 InterleaveGroupMap.erase(Member);
807 /// \brief Collect all the accesses with a constant stride in program order.
808 void collectConstStridedAccesses(
809 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
810 const ValueToValueMap &Strides);
813 /// Utility class for getting and setting loop vectorizer hints in the form
814 /// of loop metadata.
815 /// This class keeps a number of loop annotations locally (as member variables)
816 /// and can, upon request, write them back as metadata on the loop. It will
817 /// initially scan the loop for existing metadata, and will update the local
818 /// values based on information in the loop.
819 /// We cannot write all values to metadata, as the mere presence of some info,
820 /// for example 'force', means a decision has been made. So, we need to be
821 /// careful NOT to add them if the user hasn't specifically asked so.
822 class LoopVectorizeHints {
829 /// Hint - associates name and validation with the hint value.
832 unsigned Value; // This may have to change for non-numeric values.
835 Hint(const char * Name, unsigned Value, HintKind Kind)
836 : Name(Name), Value(Value), Kind(Kind) { }
838 bool validate(unsigned Val) {
841 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
843 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
851 /// Vectorization width.
853 /// Vectorization interleave factor.
855 /// Vectorization forced
858 /// Return the loop metadata prefix.
859 static StringRef Prefix() { return "llvm.loop."; }
863 FK_Undefined = -1, ///< Not selected.
864 FK_Disabled = 0, ///< Forcing disabled.
865 FK_Enabled = 1, ///< Forcing enabled.
868 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
869 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
871 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
872 Force("vectorize.enable", FK_Undefined, HK_FORCE),
874 // Populate values with existing loop metadata.
875 getHintsFromMetadata();
877 // force-vector-interleave overrides DisableInterleaving.
878 if (VectorizerParams::isInterleaveForced())
879 Interleave.Value = VectorizerParams::VectorizationInterleave;
881 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
882 << "LV: Interleaving disabled by the pass manager\n");
885 /// Mark the loop L as already vectorized by setting the width to 1.
886 void setAlreadyVectorized() {
887 Width.Value = Interleave.Value = 1;
888 Hint Hints[] = {Width, Interleave};
889 writeHintsToMetadata(Hints);
892 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
893 if (getForce() == LoopVectorizeHints::FK_Disabled) {
894 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
895 emitOptimizationRemarkAnalysis(F->getContext(),
896 vectorizeAnalysisPassName(), *F,
897 L->getStartLoc(), emitRemark());
901 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
902 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
903 emitOptimizationRemarkAnalysis(F->getContext(),
904 vectorizeAnalysisPassName(), *F,
905 L->getStartLoc(), emitRemark());
909 if (getWidth() == 1 && getInterleave() == 1) {
910 // FIXME: Add a separate metadata to indicate when the loop has already
911 // been vectorized instead of setting width and count to 1.
912 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
913 // FIXME: Add interleave.disable metadata. This will allow
914 // vectorize.disable to be used without disabling the pass and errors
915 // to differentiate between disabled vectorization and a width of 1.
916 emitOptimizationRemarkAnalysis(
917 F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
918 "loop not vectorized: vectorization and interleaving are explicitly "
919 "disabled, or vectorize width and interleave count are both set to "
927 /// Dumps all the hint information.
928 std::string emitRemark() const {
929 VectorizationReport R;
930 if (Force.Value == LoopVectorizeHints::FK_Disabled)
931 R << "vectorization is explicitly disabled";
933 R << "use -Rpass-analysis=loop-vectorize for more info";
934 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
936 if (Width.Value != 0)
937 R << ", Vector Width=" << Width.Value;
938 if (Interleave.Value != 0)
939 R << ", Interleave Count=" << Interleave.Value;
947 unsigned getWidth() const { return Width.Value; }
948 unsigned getInterleave() const { return Interleave.Value; }
949 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
950 const char *vectorizeAnalysisPassName() const {
951 // If hints are provided that don't disable vectorization use the
952 // AlwaysPrint pass name to force the frontend to print the diagnostic.
955 if (getForce() == LoopVectorizeHints::FK_Disabled)
957 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
959 return DiagnosticInfo::AlwaysPrint;
962 bool allowReordering() const {
963 // When enabling loop hints are provided we allow the vectorizer to change
964 // the order of operations that is given by the scalar loop. This is not
965 // enabled by default because can be unsafe or inefficient. For example,
966 // reordering floating-point operations will change the way round-off
967 // error accumulates in the loop.
968 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
972 /// Find hints specified in the loop metadata and update local values.
973 void getHintsFromMetadata() {
974 MDNode *LoopID = TheLoop->getLoopID();
978 // First operand should refer to the loop id itself.
979 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
980 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
982 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
983 const MDString *S = nullptr;
984 SmallVector<Metadata *, 4> Args;
986 // The expected hint is either a MDString or a MDNode with the first
987 // operand a MDString.
988 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
989 if (!MD || MD->getNumOperands() == 0)
991 S = dyn_cast<MDString>(MD->getOperand(0));
992 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
993 Args.push_back(MD->getOperand(i));
995 S = dyn_cast<MDString>(LoopID->getOperand(i));
996 assert(Args.size() == 0 && "too many arguments for MDString");
1002 // Check if the hint starts with the loop metadata prefix.
1003 StringRef Name = S->getString();
1004 if (Args.size() == 1)
1005 setHint(Name, Args[0]);
1009 /// Checks string hint with one operand and set value if valid.
1010 void setHint(StringRef Name, Metadata *Arg) {
1011 if (!Name.startswith(Prefix()))
1013 Name = Name.substr(Prefix().size(), StringRef::npos);
1015 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1017 unsigned Val = C->getZExtValue();
1019 Hint *Hints[] = {&Width, &Interleave, &Force};
1020 for (auto H : Hints) {
1021 if (Name == H->Name) {
1022 if (H->validate(Val))
1025 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1031 /// Create a new hint from name / value pair.
1032 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1033 LLVMContext &Context = TheLoop->getHeader()->getContext();
1034 Metadata *MDs[] = {MDString::get(Context, Name),
1035 ConstantAsMetadata::get(
1036 ConstantInt::get(Type::getInt32Ty(Context), V))};
1037 return MDNode::get(Context, MDs);
1040 /// Matches metadata with hint name.
1041 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1042 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1046 for (auto H : HintTypes)
1047 if (Name->getString().endswith(H.Name))
1052 /// Sets current hints into loop metadata, keeping other values intact.
1053 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1054 if (HintTypes.size() == 0)
1057 // Reserve the first element to LoopID (see below).
1058 SmallVector<Metadata *, 4> MDs(1);
1059 // If the loop already has metadata, then ignore the existing operands.
1060 MDNode *LoopID = TheLoop->getLoopID();
1062 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1063 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1064 // If node in update list, ignore old value.
1065 if (!matchesHintMetadataName(Node, HintTypes))
1066 MDs.push_back(Node);
1070 // Now, add the missing hints.
1071 for (auto H : HintTypes)
1072 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1074 // Replace current metadata node with new one.
1075 LLVMContext &Context = TheLoop->getHeader()->getContext();
1076 MDNode *NewLoopID = MDNode::get(Context, MDs);
1077 // Set operand 0 to refer to the loop id itself.
1078 NewLoopID->replaceOperandWith(0, NewLoopID);
1080 TheLoop->setLoopID(NewLoopID);
1083 /// The loop these hints belong to.
1084 const Loop *TheLoop;
1087 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1088 const LoopVectorizeHints &Hints,
1089 const LoopAccessReport &Message) {
1090 const char *Name = Hints.vectorizeAnalysisPassName();
1091 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1094 static void emitMissedWarning(Function *F, Loop *L,
1095 const LoopVectorizeHints &LH) {
1096 emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1099 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1100 if (LH.getWidth() != 1)
1101 emitLoopVectorizeWarning(
1102 F->getContext(), *F, L->getStartLoc(),
1103 "failed explicitly specified loop vectorization");
1104 else if (LH.getInterleave() != 1)
1105 emitLoopInterleaveWarning(
1106 F->getContext(), *F, L->getStartLoc(),
1107 "failed explicitly specified loop interleaving");
1111 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1112 /// to what vectorization factor.
1113 /// This class does not look at the profitability of vectorization, only the
1114 /// legality. This class has two main kinds of checks:
1115 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1116 /// will change the order of memory accesses in a way that will change the
1117 /// correctness of the program.
1118 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1119 /// checks for a number of different conditions, such as the availability of a
1120 /// single induction variable, that all types are supported and vectorize-able,
1121 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1122 /// This class is also used by InnerLoopVectorizer for identifying
1123 /// induction variable and the different reduction variables.
1124 class LoopVectorizationLegality {
1126 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1127 TargetLibraryInfo *TLI, AliasAnalysis *AA,
1128 Function *F, const TargetTransformInfo *TTI,
1129 LoopAccessAnalysis *LAA,
1130 LoopVectorizationRequirements *R,
1131 const LoopVectorizeHints *H)
1132 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
1133 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
1134 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
1135 Requirements(R), Hints(H) {}
1137 /// ReductionList contains the reduction descriptors for all
1138 /// of the reductions that were found in the loop.
1139 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1141 /// InductionList saves induction variables and maps them to the
1142 /// induction descriptor.
1143 typedef MapVector<PHINode*, InductionDescriptor> InductionList;
1145 /// Returns true if it is legal to vectorize this loop.
1146 /// This does not mean that it is profitable to vectorize this
1147 /// loop, only that it is legal to do so.
1148 bool canVectorize();
1150 /// Returns the Induction variable.
1151 PHINode *getInduction() { return Induction; }
1153 /// Returns the reduction variables found in the loop.
1154 ReductionList *getReductionVars() { return &Reductions; }
1156 /// Returns the induction variables found in the loop.
1157 InductionList *getInductionVars() { return &Inductions; }
1159 /// Returns the widest induction type.
1160 Type *getWidestInductionType() { return WidestIndTy; }
1162 /// Returns True if V is an induction variable in this loop.
1163 bool isInductionVariable(const Value *V);
1165 /// Return true if the block BB needs to be predicated in order for the loop
1166 /// to be vectorized.
1167 bool blockNeedsPredication(BasicBlock *BB);
1169 /// Check if this pointer is consecutive when vectorizing. This happens
1170 /// when the last index of the GEP is the induction variable, or that the
1171 /// pointer itself is an induction variable.
1172 /// This check allows us to vectorize A[idx] into a wide load/store.
1174 /// 0 - Stride is unknown or non-consecutive.
1175 /// 1 - Address is consecutive.
1176 /// -1 - Address is consecutive, and decreasing.
1177 int isConsecutivePtr(Value *Ptr);
1179 /// Returns true if the value V is uniform within the loop.
1180 bool isUniform(Value *V);
1182 /// Returns true if this instruction will remain scalar after vectorization.
1183 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
1185 /// Returns the information that we collected about runtime memory check.
1186 const RuntimePointerChecking *getRuntimePointerChecking() const {
1187 return LAI->getRuntimePointerChecking();
1190 const LoopAccessInfo *getLAI() const {
1194 /// \brief Check if \p Instr belongs to any interleaved access group.
1195 bool isAccessInterleaved(Instruction *Instr) {
1196 return InterleaveInfo.isInterleaved(Instr);
1199 /// \brief Get the interleaved access group that \p Instr belongs to.
1200 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1201 return InterleaveInfo.getInterleaveGroup(Instr);
1204 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1206 bool hasStride(Value *V) { return StrideSet.count(V); }
1207 bool mustCheckStrides() { return !StrideSet.empty(); }
1208 SmallPtrSet<Value *, 8>::iterator strides_begin() {
1209 return StrideSet.begin();
1211 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
1213 /// Returns true if the target machine supports masked store operation
1214 /// for the given \p DataType and kind of access to \p Ptr.
1215 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1216 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
1218 /// Returns true if the target machine supports masked load operation
1219 /// for the given \p DataType and kind of access to \p Ptr.
1220 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1221 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
1223 /// Returns true if vector representation of the instruction \p I
1225 bool isMaskRequired(const Instruction* I) {
1226 return (MaskedOp.count(I) != 0);
1228 unsigned getNumStores() const {
1229 return LAI->getNumStores();
1231 unsigned getNumLoads() const {
1232 return LAI->getNumLoads();
1234 unsigned getNumPredStores() const {
1235 return NumPredStores;
1238 /// Check if a single basic block loop is vectorizable.
1239 /// At this point we know that this is a loop with a constant trip count
1240 /// and we only need to check individual instructions.
1241 bool canVectorizeInstrs();
1243 /// When we vectorize loops we may change the order in which
1244 /// we read and write from memory. This method checks if it is
1245 /// legal to vectorize the code, considering only memory constrains.
1246 /// Returns true if the loop is vectorizable
1247 bool canVectorizeMemory();
1249 /// Return true if we can vectorize this loop using the IF-conversion
1251 bool canVectorizeWithIfConvert();
1253 /// Collect the variables that need to stay uniform after vectorization.
1254 void collectLoopUniforms();
1256 /// Return true if all of the instructions in the block can be speculatively
1257 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1258 /// and we know that we can read from them without segfault.
1259 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1261 /// \brief Collect memory access with loop invariant strides.
1263 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1265 void collectStridedAccess(Value *LoadOrStoreInst);
1267 /// Report an analysis message to assist the user in diagnosing loops that are
1268 /// not vectorized. These are handled as LoopAccessReport rather than
1269 /// VectorizationReport because the << operator of VectorizationReport returns
1270 /// LoopAccessReport.
1271 void emitAnalysis(const LoopAccessReport &Message) const {
1272 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1275 unsigned NumPredStores;
1277 /// The loop that we evaluate.
1280 ScalarEvolution *SE;
1281 /// Target Library Info.
1282 TargetLibraryInfo *TLI;
1284 Function *TheFunction;
1285 /// Target Transform Info
1286 const TargetTransformInfo *TTI;
1289 // LoopAccess analysis.
1290 LoopAccessAnalysis *LAA;
1291 // And the loop-accesses info corresponding to this loop. This pointer is
1292 // null until canVectorizeMemory sets it up.
1293 const LoopAccessInfo *LAI;
1295 /// The interleave access information contains groups of interleaved accesses
1296 /// with the same stride and close to each other.
1297 InterleavedAccessInfo InterleaveInfo;
1299 // --- vectorization state --- //
1301 /// Holds the integer induction variable. This is the counter of the
1304 /// Holds the reduction variables.
1305 ReductionList Reductions;
1306 /// Holds all of the induction variables that we found in the loop.
1307 /// Notice that inductions don't need to start at zero and that induction
1308 /// variables can be pointers.
1309 InductionList Inductions;
1310 /// Holds the widest induction type encountered.
1313 /// Allowed outside users. This holds the reduction
1314 /// vars which can be accessed from outside the loop.
1315 SmallPtrSet<Value*, 4> AllowedExit;
1316 /// This set holds the variables which are known to be uniform after
1318 SmallPtrSet<Instruction*, 4> Uniforms;
1320 /// Can we assume the absence of NaNs.
1321 bool HasFunNoNaNAttr;
1323 /// Vectorization requirements that will go through late-evaluation.
1324 LoopVectorizationRequirements *Requirements;
1326 /// Used to emit an analysis of any legality issues.
1327 const LoopVectorizeHints *Hints;
1329 ValueToValueMap Strides;
1330 SmallPtrSet<Value *, 8> StrideSet;
1332 /// While vectorizing these instructions we have to generate a
1333 /// call to the appropriate masked intrinsic
1334 SmallPtrSet<const Instruction*, 8> MaskedOp;
1337 /// LoopVectorizationCostModel - estimates the expected speedups due to
1339 /// In many cases vectorization is not profitable. This can happen because of
1340 /// a number of reasons. In this class we mainly attempt to predict the
1341 /// expected speedup/slowdowns due to the supported instruction set. We use the
1342 /// TargetTransformInfo to query the different backends for the cost of
1343 /// different operations.
1344 class LoopVectorizationCostModel {
1346 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1347 LoopVectorizationLegality *Legal,
1348 const TargetTransformInfo &TTI,
1349 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1350 const Function *F, const LoopVectorizeHints *Hints,
1351 SmallPtrSetImpl<const Value *> &ValuesToIgnore)
1352 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1353 TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
1355 /// Information about vectorization costs
1356 struct VectorizationFactor {
1357 unsigned Width; // Vector width with best cost
1358 unsigned Cost; // Cost of the loop with that width
1360 /// \return The most profitable vectorization factor and the cost of that VF.
1361 /// This method checks every power of two up to VF. If UserVF is not ZERO
1362 /// then this vectorization factor will be selected if vectorization is
1364 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1366 /// \return The size (in bits) of the widest type in the code that
1367 /// needs to be vectorized. We ignore values that remain scalar such as
1368 /// 64 bit loop indices.
1369 unsigned getWidestType();
1371 /// \return The desired interleave count.
1372 /// If interleave count has been specified by metadata it will be returned.
1373 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1374 /// are the selected vectorization factor and the cost of the selected VF.
1375 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1378 /// \return The most profitable unroll factor.
1379 /// This method finds the best unroll-factor based on register pressure and
1380 /// other parameters. VF and LoopCost are the selected vectorization factor
1381 /// and the cost of the selected VF.
1382 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1385 /// \brief A struct that represents some properties of the register usage
1387 struct RegisterUsage {
1388 /// Holds the number of loop invariant values that are used in the loop.
1389 unsigned LoopInvariantRegs;
1390 /// Holds the maximum number of concurrent live intervals in the loop.
1391 unsigned MaxLocalUsers;
1392 /// Holds the number of instructions in the loop.
1393 unsigned NumInstructions;
1396 /// \return information about the register usage of the loop.
1397 RegisterUsage calculateRegisterUsage();
1400 /// Returns the expected execution cost. The unit of the cost does
1401 /// not matter because we use the 'cost' units to compare different
1402 /// vector widths. The cost that is returned is *not* normalized by
1403 /// the factor width.
1404 unsigned expectedCost(unsigned VF);
1406 /// Returns the execution time cost of an instruction for a given vector
1407 /// width. Vector width of one means scalar.
1408 unsigned getInstructionCost(Instruction *I, unsigned VF);
1410 /// Returns whether the instruction is a load or store and will be a emitted
1411 /// as a vector operation.
1412 bool isConsecutiveLoadOrStore(Instruction *I);
1414 /// Report an analysis message to assist the user in diagnosing loops that are
1415 /// not vectorized. These are handled as LoopAccessReport rather than
1416 /// VectorizationReport because the << operator of VectorizationReport returns
1417 /// LoopAccessReport.
1418 void emitAnalysis(const LoopAccessReport &Message) const {
1419 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1422 /// The loop that we evaluate.
1425 ScalarEvolution *SE;
1426 /// Loop Info analysis.
1428 /// Vectorization legality.
1429 LoopVectorizationLegality *Legal;
1430 /// Vector target information.
1431 const TargetTransformInfo &TTI;
1432 /// Target Library Info.
1433 const TargetLibraryInfo *TLI;
1434 const Function *TheFunction;
1435 // Loop Vectorize Hint.
1436 const LoopVectorizeHints *Hints;
1437 // Values to ignore in the cost model.
1438 const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
1441 /// \brief This holds vectorization requirements that must be verified late in
1442 /// the process. The requirements are set by legalize and costmodel. Once
1443 /// vectorization has been determined to be possible and profitable the
1444 /// requirements can be verified by looking for metadata or compiler options.
1445 /// For example, some loops require FP commutativity which is only allowed if
1446 /// vectorization is explicitly specified or if the fast-math compiler option
1447 /// has been provided.
1448 /// Late evaluation of these requirements allows helpful diagnostics to be
1449 /// composed that tells the user what need to be done to vectorize the loop. For
1450 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1451 /// evaluation should be used only when diagnostics can generated that can be
1452 /// followed by a non-expert user.
1453 class LoopVectorizationRequirements {
1455 LoopVectorizationRequirements()
1456 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1458 void addUnsafeAlgebraInst(Instruction *I) {
1459 // First unsafe algebra instruction.
1460 if (!UnsafeAlgebraInst)
1461 UnsafeAlgebraInst = I;
1464 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1466 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1467 const char *Name = Hints.vectorizeAnalysisPassName();
1468 bool Failed = false;
1469 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1470 emitOptimizationRemarkAnalysisFPCommute(
1471 F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1472 VectorizationReport() << "cannot prove it is safe to reorder "
1473 "floating-point operations");
1477 // Test if runtime memcheck thresholds are exceeded.
1478 bool PragmaThresholdReached =
1479 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1480 bool ThresholdReached =
1481 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1482 if ((ThresholdReached && !Hints.allowReordering()) ||
1483 PragmaThresholdReached) {
1484 emitOptimizationRemarkAnalysisAliasing(
1485 F->getContext(), Name, *F, L->getStartLoc(),
1486 VectorizationReport()
1487 << "cannot prove it is safe to reorder memory operations");
1488 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1496 unsigned NumRuntimePointerChecks;
1497 Instruction *UnsafeAlgebraInst;
1500 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1502 return V.push_back(&L);
1504 for (Loop *InnerL : L)
1505 addInnerLoop(*InnerL, V);
1508 /// The LoopVectorize Pass.
1509 struct LoopVectorize : public FunctionPass {
1510 /// Pass identification, replacement for typeid
1513 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1515 DisableUnrolling(NoUnrolling),
1516 AlwaysVectorize(AlwaysVectorize) {
1517 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1520 ScalarEvolution *SE;
1522 TargetTransformInfo *TTI;
1524 BlockFrequencyInfo *BFI;
1525 TargetLibraryInfo *TLI;
1527 AssumptionCache *AC;
1528 LoopAccessAnalysis *LAA;
1529 bool DisableUnrolling;
1530 bool AlwaysVectorize;
1532 BlockFrequency ColdEntryFreq;
1534 bool runOnFunction(Function &F) override {
1535 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1536 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1537 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1538 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1539 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1540 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1541 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1542 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1543 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1544 LAA = &getAnalysis<LoopAccessAnalysis>();
1546 // Compute some weights outside of the loop over the loops. Compute this
1547 // using a BranchProbability to re-use its scaling math.
1548 const BranchProbability ColdProb(1, 5); // 20%
1549 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1552 // 1. the target claims to have no vector registers, and
1553 // 2. interleaving won't help ILP.
1555 // The second condition is necessary because, even if the target has no
1556 // vector registers, loop vectorization may still enable scalar
1558 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1561 // Build up a worklist of inner-loops to vectorize. This is necessary as
1562 // the act of vectorizing or partially unrolling a loop creates new loops
1563 // and can invalidate iterators across the loops.
1564 SmallVector<Loop *, 8> Worklist;
1567 addInnerLoop(*L, Worklist);
1569 LoopsAnalyzed += Worklist.size();
1571 // Now walk the identified inner loops.
1572 bool Changed = false;
1573 while (!Worklist.empty())
1574 Changed |= processLoop(Worklist.pop_back_val());
1576 // Process each loop nest in the function.
1580 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1581 SmallVector<Metadata *, 4> MDs;
1582 // Reserve first location for self reference to the LoopID metadata node.
1583 MDs.push_back(nullptr);
1584 bool IsUnrollMetadata = false;
1585 MDNode *LoopID = L->getLoopID();
1587 // First find existing loop unrolling disable metadata.
1588 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1589 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1591 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1593 S && S->getString().startswith("llvm.loop.unroll.disable");
1595 MDs.push_back(LoopID->getOperand(i));
1599 if (!IsUnrollMetadata) {
1600 // Add runtime unroll disable metadata.
1601 LLVMContext &Context = L->getHeader()->getContext();
1602 SmallVector<Metadata *, 1> DisableOperands;
1603 DisableOperands.push_back(
1604 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1605 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1606 MDs.push_back(DisableNode);
1607 MDNode *NewLoopID = MDNode::get(Context, MDs);
1608 // Set operand 0 to refer to the loop id itself.
1609 NewLoopID->replaceOperandWith(0, NewLoopID);
1610 L->setLoopID(NewLoopID);
1614 bool processLoop(Loop *L) {
1615 assert(L->empty() && "Only process inner loops.");
1618 const std::string DebugLocStr = getDebugLocString(L);
1621 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1622 << L->getHeader()->getParent()->getName() << "\" from "
1623 << DebugLocStr << "\n");
1625 LoopVectorizeHints Hints(L, DisableUnrolling);
1627 DEBUG(dbgs() << "LV: Loop hints:"
1629 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1631 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1633 : "?")) << " width=" << Hints.getWidth()
1634 << " unroll=" << Hints.getInterleave() << "\n");
1636 // Function containing loop
1637 Function *F = L->getHeader()->getParent();
1639 // Looking at the diagnostic output is the only way to determine if a loop
1640 // was vectorized (other than looking at the IR or machine code), so it
1641 // is important to generate an optimization remark for each loop. Most of
1642 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1643 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1644 // less verbose reporting vectorized loops and unvectorized loops that may
1645 // benefit from vectorization, respectively.
1647 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1648 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1652 // Check the loop for a trip count threshold:
1653 // do not vectorize loops with a tiny trip count.
1654 const unsigned TC = SE->getSmallConstantTripCount(L);
1655 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1656 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1657 << "This loop is not worth vectorizing.");
1658 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1659 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1661 DEBUG(dbgs() << "\n");
1662 emitAnalysisDiag(F, L, Hints, VectorizationReport()
1663 << "vectorization is not beneficial "
1664 "and is not explicitly forced");
1669 // Check if it is legal to vectorize the loop.
1670 LoopVectorizationRequirements Requirements;
1671 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1672 &Requirements, &Hints);
1673 if (!LVL.canVectorize()) {
1674 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1675 emitMissedWarning(F, L, Hints);
1679 // Collect values we want to ignore in the cost model. This includes
1680 // type-promoting instructions we identified during reduction detection.
1681 SmallPtrSet<const Value *, 32> ValuesToIgnore;
1682 CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
1683 for (auto &Reduction : *LVL.getReductionVars()) {
1684 RecurrenceDescriptor &RedDes = Reduction.second;
1685 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
1686 ValuesToIgnore.insert(Casts.begin(), Casts.end());
1689 // Use the cost model.
1690 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints,
1693 // Check the function attributes to find out if this function should be
1694 // optimized for size.
1695 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1698 // Compute the weighted frequency of this loop being executed and see if it
1699 // is less than 20% of the function entry baseline frequency. Note that we
1700 // always have a canonical loop here because we think we *can* vectorize.
1701 // FIXME: This is hidden behind a flag due to pervasive problems with
1702 // exactly what block frequency models.
1703 if (LoopVectorizeWithBlockFrequency) {
1704 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1705 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1706 LoopEntryFreq < ColdEntryFreq)
1710 // Check the function attributes to see if implicit floats are allowed.
1711 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1712 // an integer loop and the vector instructions selected are purely integer
1713 // vector instructions?
1714 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1715 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1716 "attribute is used.\n");
1719 VectorizationReport()
1720 << "loop not vectorized due to NoImplicitFloat attribute");
1721 emitMissedWarning(F, L, Hints);
1725 // Select the optimal vectorization factor.
1726 const LoopVectorizationCostModel::VectorizationFactor VF =
1727 CM.selectVectorizationFactor(OptForSize);
1729 // Select the interleave count.
1730 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1732 // Get user interleave count.
1733 unsigned UserIC = Hints.getInterleave();
1735 // Identify the diagnostic messages that should be produced.
1736 std::string VecDiagMsg, IntDiagMsg;
1737 bool VectorizeLoop = true, InterleaveLoop = true;
1739 if (Requirements.doesNotMeet(F, L, Hints)) {
1740 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1742 emitMissedWarning(F, L, Hints);
1746 if (VF.Width == 1) {
1747 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1749 "the cost-model indicates that vectorization is not beneficial";
1750 VectorizeLoop = false;
1753 if (IC == 1 && UserIC <= 1) {
1754 // Tell the user interleaving is not beneficial.
1755 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1757 "the cost-model indicates that interleaving is not beneficial";
1758 InterleaveLoop = false;
1761 " and is explicitly disabled or interleave count is set to 1";
1762 } else if (IC > 1 && UserIC == 1) {
1763 // Tell the user interleaving is beneficial, but it explicitly disabled.
1765 << "LV: Interleaving is beneficial but is explicitly disabled.");
1766 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1767 "but is explicitly disabled or interleave count is set to 1";
1768 InterleaveLoop = false;
1771 // Override IC if user provided an interleave count.
1772 IC = UserIC > 0 ? UserIC : IC;
1774 // Emit diagnostic messages, if any.
1775 const char *VAPassName = Hints.vectorizeAnalysisPassName();
1776 if (!VectorizeLoop && !InterleaveLoop) {
1777 // Do not vectorize or interleaving the loop.
1778 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1779 L->getStartLoc(), VecDiagMsg);
1780 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1781 L->getStartLoc(), IntDiagMsg);
1783 } else if (!VectorizeLoop && InterleaveLoop) {
1784 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1785 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1786 L->getStartLoc(), VecDiagMsg);
1787 } else if (VectorizeLoop && !InterleaveLoop) {
1788 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1789 << DebugLocStr << '\n');
1790 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1791 L->getStartLoc(), IntDiagMsg);
1792 } else if (VectorizeLoop && InterleaveLoop) {
1793 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1794 << DebugLocStr << '\n');
1795 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1798 if (!VectorizeLoop) {
1799 assert(IC > 1 && "interleave count should not be 1 or 0");
1800 // If we decided that it is not legal to vectorize the loop then
1802 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC);
1803 Unroller.vectorize(&LVL);
1805 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1806 Twine("interleaved loop (interleaved count: ") +
1809 // If we decided that it is *legal* to vectorize the loop then do it.
1810 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC);
1814 // Add metadata to disable runtime unrolling scalar loop when there's no
1815 // runtime check about strides and memory. Because at this situation,
1816 // scalar loop is rarely used not worthy to be unrolled.
1817 if (!LB.IsSafetyChecksAdded())
1818 AddRuntimeUnrollDisableMetaData(L);
1820 // Report the vectorization decision.
1821 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1822 Twine("vectorized loop (vectorization width: ") +
1823 Twine(VF.Width) + ", interleaved count: " +
1827 // Mark the loop as already vectorized to avoid vectorizing again.
1828 Hints.setAlreadyVectorized();
1830 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1834 void getAnalysisUsage(AnalysisUsage &AU) const override {
1835 AU.addRequired<AssumptionCacheTracker>();
1836 AU.addRequiredID(LoopSimplifyID);
1837 AU.addRequiredID(LCSSAID);
1838 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1839 AU.addRequired<DominatorTreeWrapperPass>();
1840 AU.addRequired<LoopInfoWrapperPass>();
1841 AU.addRequired<ScalarEvolutionWrapperPass>();
1842 AU.addRequired<TargetTransformInfoWrapperPass>();
1843 AU.addRequired<AAResultsWrapperPass>();
1844 AU.addRequired<LoopAccessAnalysis>();
1845 AU.addPreserved<LoopInfoWrapperPass>();
1846 AU.addPreserved<DominatorTreeWrapperPass>();
1847 AU.addPreserved<BasicAAWrapperPass>();
1848 AU.addPreserved<AAResultsWrapperPass>();
1849 AU.addPreserved<GlobalsAAWrapperPass>();
1854 } // end anonymous namespace
1856 //===----------------------------------------------------------------------===//
1857 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1858 // LoopVectorizationCostModel.
1859 //===----------------------------------------------------------------------===//
1861 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1862 // We need to place the broadcast of invariant variables outside the loop.
1863 Instruction *Instr = dyn_cast<Instruction>(V);
1865 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1866 Instr->getParent()) != LoopVectorBody.end());
1867 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1869 // Place the code for broadcasting invariant variables in the new preheader.
1870 IRBuilder<>::InsertPointGuard Guard(Builder);
1872 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1874 // Broadcast the scalar into all locations in the vector.
1875 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1880 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1882 assert(Val->getType()->isVectorTy() && "Must be a vector");
1883 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1884 "Elem must be an integer");
1885 assert(Step->getType() == Val->getType()->getScalarType() &&
1886 "Step has wrong type");
1887 // Create the types.
1888 Type *ITy = Val->getType()->getScalarType();
1889 VectorType *Ty = cast<VectorType>(Val->getType());
1890 int VLen = Ty->getNumElements();
1891 SmallVector<Constant*, 8> Indices;
1893 // Create a vector of consecutive numbers from zero to VF.
1894 for (int i = 0; i < VLen; ++i)
1895 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1897 // Add the consecutive indices to the vector value.
1898 Constant *Cv = ConstantVector::get(Indices);
1899 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1900 Step = Builder.CreateVectorSplat(VLen, Step);
1901 assert(Step->getType() == Val->getType() && "Invalid step vec");
1902 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1903 // which can be found from the original scalar operations.
1904 Step = Builder.CreateMul(Cv, Step);
1905 return Builder.CreateAdd(Val, Step, "induction");
1908 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1909 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1910 // Make sure that the pointer does not point to structs.
1911 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1914 // If this value is a pointer induction variable we know it is consecutive.
1915 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1916 if (Phi && Inductions.count(Phi)) {
1917 InductionDescriptor II = Inductions[Phi];
1918 return II.getConsecutiveDirection();
1921 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1925 unsigned NumOperands = Gep->getNumOperands();
1926 Value *GpPtr = Gep->getPointerOperand();
1927 // If this GEP value is a consecutive pointer induction variable and all of
1928 // the indices are constant then we know it is consecutive. We can
1929 Phi = dyn_cast<PHINode>(GpPtr);
1930 if (Phi && Inductions.count(Phi)) {
1932 // Make sure that the pointer does not point to structs.
1933 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1934 if (GepPtrType->getElementType()->isAggregateType())
1937 // Make sure that all of the index operands are loop invariant.
1938 for (unsigned i = 1; i < NumOperands; ++i)
1939 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1942 InductionDescriptor II = Inductions[Phi];
1943 return II.getConsecutiveDirection();
1946 unsigned InductionOperand = getGEPInductionOperand(Gep);
1948 // Check that all of the gep indices are uniform except for our induction
1950 for (unsigned i = 0; i != NumOperands; ++i)
1951 if (i != InductionOperand &&
1952 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1955 // We can emit wide load/stores only if the last non-zero index is the
1956 // induction variable.
1957 const SCEV *Last = nullptr;
1958 if (!Strides.count(Gep))
1959 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1961 // Because of the multiplication by a stride we can have a s/zext cast.
1962 // We are going to replace this stride by 1 so the cast is safe to ignore.
1964 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1965 // %0 = trunc i64 %indvars.iv to i32
1966 // %mul = mul i32 %0, %Stride1
1967 // %idxprom = zext i32 %mul to i64 << Safe cast.
1968 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1970 Last = replaceSymbolicStrideSCEV(SE, Strides,
1971 Gep->getOperand(InductionOperand), Gep);
1972 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1974 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1978 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1979 const SCEV *Step = AR->getStepRecurrence(*SE);
1981 // The memory is consecutive because the last index is consecutive
1982 // and all other indices are loop invariant.
1985 if (Step->isAllOnesValue())
1992 bool LoopVectorizationLegality::isUniform(Value *V) {
1993 return LAI->isUniform(V);
1996 InnerLoopVectorizer::VectorParts&
1997 InnerLoopVectorizer::getVectorValue(Value *V) {
1998 assert(V != Induction && "The new induction variable should not be used.");
1999 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2001 // If we have a stride that is replaced by one, do it here.
2002 if (Legal->hasStride(V))
2003 V = ConstantInt::get(V->getType(), 1);
2005 // If we have this scalar in the map, return it.
2006 if (WidenMap.has(V))
2007 return WidenMap.get(V);
2009 // If this scalar is unknown, assume that it is a constant or that it is
2010 // loop invariant. Broadcast V and save the value for future uses.
2011 Value *B = getBroadcastInstrs(V);
2012 return WidenMap.splat(V, B);
2015 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2016 assert(Vec->getType()->isVectorTy() && "Invalid type");
2017 SmallVector<Constant*, 8> ShuffleMask;
2018 for (unsigned i = 0; i < VF; ++i)
2019 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2021 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2022 ConstantVector::get(ShuffleMask),
2026 // Get a mask to interleave \p NumVec vectors into a wide vector.
2027 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2028 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2029 // <0, 4, 1, 5, 2, 6, 3, 7>
2030 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2032 SmallVector<Constant *, 16> Mask;
2033 for (unsigned i = 0; i < VF; i++)
2034 for (unsigned j = 0; j < NumVec; j++)
2035 Mask.push_back(Builder.getInt32(j * VF + i));
2037 return ConstantVector::get(Mask);
2040 // Get the strided mask starting from index \p Start.
2041 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2042 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2043 unsigned Stride, unsigned VF) {
2044 SmallVector<Constant *, 16> Mask;
2045 for (unsigned i = 0; i < VF; i++)
2046 Mask.push_back(Builder.getInt32(Start + i * Stride));
2048 return ConstantVector::get(Mask);
2051 // Get a mask of two parts: The first part consists of sequential integers
2052 // starting from 0, The second part consists of UNDEFs.
2053 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2054 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2055 unsigned NumUndef) {
2056 SmallVector<Constant *, 16> Mask;
2057 for (unsigned i = 0; i < NumInt; i++)
2058 Mask.push_back(Builder.getInt32(i));
2060 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2061 for (unsigned i = 0; i < NumUndef; i++)
2062 Mask.push_back(Undef);
2064 return ConstantVector::get(Mask);
2067 // Concatenate two vectors with the same element type. The 2nd vector should
2068 // not have more elements than the 1st vector. If the 2nd vector has less
2069 // elements, extend it with UNDEFs.
2070 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2072 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2073 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2074 assert(VecTy1 && VecTy2 &&
2075 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2076 "Expect two vectors with the same element type");
2078 unsigned NumElts1 = VecTy1->getNumElements();
2079 unsigned NumElts2 = VecTy2->getNumElements();
2080 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2082 if (NumElts1 > NumElts2) {
2083 // Extend with UNDEFs.
2085 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2086 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2089 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2090 return Builder.CreateShuffleVector(V1, V2, Mask);
2093 // Concatenate vectors in the given list. All vectors have the same type.
2094 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2095 ArrayRef<Value *> InputList) {
2096 unsigned NumVec = InputList.size();
2097 assert(NumVec > 1 && "Should be at least two vectors");
2099 SmallVector<Value *, 8> ResList;
2100 ResList.append(InputList.begin(), InputList.end());
2102 SmallVector<Value *, 8> TmpList;
2103 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2104 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2105 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2106 "Only the last vector may have a different type");
2108 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2111 // Push the last vector if the total number of vectors is odd.
2112 if (NumVec % 2 != 0)
2113 TmpList.push_back(ResList[NumVec - 1]);
2116 NumVec = ResList.size();
2117 } while (NumVec > 1);
2122 // Try to vectorize the interleave group that \p Instr belongs to.
2124 // E.g. Translate following interleaved load group (factor = 3):
2125 // for (i = 0; i < N; i+=3) {
2126 // R = Pic[i]; // Member of index 0
2127 // G = Pic[i+1]; // Member of index 1
2128 // B = Pic[i+2]; // Member of index 2
2129 // ... // do something to R, G, B
2132 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2133 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2134 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2135 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2137 // Or translate following interleaved store group (factor = 3):
2138 // for (i = 0; i < N; i+=3) {
2139 // ... do something to R, G, B
2140 // Pic[i] = R; // Member of index 0
2141 // Pic[i+1] = G; // Member of index 1
2142 // Pic[i+2] = B; // Member of index 2
2145 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2146 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2147 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2148 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2149 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2150 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2151 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2152 assert(Group && "Fail to get an interleaved access group.");
2154 // Skip if current instruction is not the insert position.
2155 if (Instr != Group->getInsertPos())
2158 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2159 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2160 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2162 // Prepare for the vector type of the interleaved load/store.
2163 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2164 unsigned InterleaveFactor = Group->getFactor();
2165 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2166 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2168 // Prepare for the new pointers.
2169 setDebugLocFromInst(Builder, Ptr);
2170 VectorParts &PtrParts = getVectorValue(Ptr);
2171 SmallVector<Value *, 2> NewPtrs;
2172 unsigned Index = Group->getIndex(Instr);
2173 for (unsigned Part = 0; Part < UF; Part++) {
2174 // Extract the pointer for current instruction from the pointer vector. A
2175 // reverse access uses the pointer in the last lane.
2176 Value *NewPtr = Builder.CreateExtractElement(
2178 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2180 // Notice current instruction could be any index. Need to adjust the address
2181 // to the member of index 0.
2183 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2184 // b = A[i]; // Member of index 0
2185 // Current pointer is pointed to A[i+1], adjust it to A[i].
2187 // E.g. A[i+1] = a; // Member of index 1
2188 // A[i] = b; // Member of index 0
2189 // A[i+2] = c; // Member of index 2 (Current instruction)
2190 // Current pointer is pointed to A[i+2], adjust it to A[i].
2191 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2193 // Cast to the vector pointer type.
2194 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2197 setDebugLocFromInst(Builder, Instr);
2198 Value *UndefVec = UndefValue::get(VecTy);
2200 // Vectorize the interleaved load group.
2202 for (unsigned Part = 0; Part < UF; Part++) {
2203 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2204 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2206 for (unsigned i = 0; i < InterleaveFactor; i++) {
2207 Instruction *Member = Group->getMember(i);
2209 // Skip the gaps in the group.
2213 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2214 Value *StridedVec = Builder.CreateShuffleVector(
2215 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2217 // If this member has different type, cast the result type.
2218 if (Member->getType() != ScalarTy) {
2219 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2220 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2223 VectorParts &Entry = WidenMap.get(Member);
2225 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2228 propagateMetadata(NewLoadInstr, Instr);
2233 // The sub vector type for current instruction.
2234 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2236 // Vectorize the interleaved store group.
2237 for (unsigned Part = 0; Part < UF; Part++) {
2238 // Collect the stored vector from each member.
2239 SmallVector<Value *, 4> StoredVecs;
2240 for (unsigned i = 0; i < InterleaveFactor; i++) {
2241 // Interleaved store group doesn't allow a gap, so each index has a member
2242 Instruction *Member = Group->getMember(i);
2243 assert(Member && "Fail to get a member from an interleaved store group");
2246 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2247 if (Group->isReverse())
2248 StoredVec = reverseVector(StoredVec);
2250 // If this member has different type, cast it to an unified type.
2251 if (StoredVec->getType() != SubVT)
2252 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2254 StoredVecs.push_back(StoredVec);
2257 // Concatenate all vectors into a wide vector.
2258 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2260 // Interleave the elements in the wide vector.
2261 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2262 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2265 Instruction *NewStoreInstr =
2266 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2267 propagateMetadata(NewStoreInstr, Instr);
2271 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2272 // Attempt to issue a wide load.
2273 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2274 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2276 assert((LI || SI) && "Invalid Load/Store instruction");
2278 // Try to vectorize the interleave group if this access is interleaved.
2279 if (Legal->isAccessInterleaved(Instr))
2280 return vectorizeInterleaveGroup(Instr);
2282 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2283 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2284 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2285 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2286 // An alignment of 0 means target abi alignment. We need to use the scalar's
2287 // target abi alignment in such a case.
2288 const DataLayout &DL = Instr->getModule()->getDataLayout();
2290 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2291 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2292 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2293 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2295 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2296 !Legal->isMaskRequired(SI))
2297 return scalarizeInstruction(Instr, true);
2299 if (ScalarAllocatedSize != VectorElementSize)
2300 return scalarizeInstruction(Instr);
2302 // If the pointer is loop invariant or if it is non-consecutive,
2303 // scalarize the load.
2304 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2305 bool Reverse = ConsecutiveStride < 0;
2306 bool UniformLoad = LI && Legal->isUniform(Ptr);
2307 if (!ConsecutiveStride || UniformLoad)
2308 return scalarizeInstruction(Instr);
2310 Constant *Zero = Builder.getInt32(0);
2311 VectorParts &Entry = WidenMap.get(Instr);
2313 // Handle consecutive loads/stores.
2314 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2315 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2316 setDebugLocFromInst(Builder, Gep);
2317 Value *PtrOperand = Gep->getPointerOperand();
2318 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2319 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2321 // Create the new GEP with the new induction variable.
2322 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2323 Gep2->setOperand(0, FirstBasePtr);
2324 Gep2->setName("gep.indvar.base");
2325 Ptr = Builder.Insert(Gep2);
2327 setDebugLocFromInst(Builder, Gep);
2328 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2329 OrigLoop) && "Base ptr must be invariant");
2331 // The last index does not have to be the induction. It can be
2332 // consecutive and be a function of the index. For example A[I+1];
2333 unsigned NumOperands = Gep->getNumOperands();
2334 unsigned InductionOperand = getGEPInductionOperand(Gep);
2335 // Create the new GEP with the new induction variable.
2336 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2338 for (unsigned i = 0; i < NumOperands; ++i) {
2339 Value *GepOperand = Gep->getOperand(i);
2340 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2342 // Update last index or loop invariant instruction anchored in loop.
2343 if (i == InductionOperand ||
2344 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2345 assert((i == InductionOperand ||
2346 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2347 "Must be last index or loop invariant");
2349 VectorParts &GEPParts = getVectorValue(GepOperand);
2350 Value *Index = GEPParts[0];
2351 Index = Builder.CreateExtractElement(Index, Zero);
2352 Gep2->setOperand(i, Index);
2353 Gep2->setName("gep.indvar.idx");
2356 Ptr = Builder.Insert(Gep2);
2358 // Use the induction element ptr.
2359 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2360 setDebugLocFromInst(Builder, Ptr);
2361 VectorParts &PtrVal = getVectorValue(Ptr);
2362 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2365 VectorParts Mask = createBlockInMask(Instr->getParent());
2368 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2369 "We do not allow storing to uniform addresses");
2370 setDebugLocFromInst(Builder, SI);
2371 // We don't want to update the value in the map as it might be used in
2372 // another expression. So don't use a reference type for "StoredVal".
2373 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2375 for (unsigned Part = 0; Part < UF; ++Part) {
2376 // Calculate the pointer for the specific unroll-part.
2378 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2381 // If we store to reverse consecutive memory locations, then we need
2382 // to reverse the order of elements in the stored value.
2383 StoredVal[Part] = reverseVector(StoredVal[Part]);
2384 // If the address is consecutive but reversed, then the
2385 // wide store needs to start at the last vector element.
2386 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2387 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2388 Mask[Part] = reverseVector(Mask[Part]);
2391 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2392 DataTy->getPointerTo(AddressSpace));
2395 if (Legal->isMaskRequired(SI))
2396 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2399 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2400 propagateMetadata(NewSI, SI);
2406 assert(LI && "Must have a load instruction");
2407 setDebugLocFromInst(Builder, LI);
2408 for (unsigned Part = 0; Part < UF; ++Part) {
2409 // Calculate the pointer for the specific unroll-part.
2411 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2414 // If the address is consecutive but reversed, then the
2415 // wide load needs to start at the last vector element.
2416 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2417 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2418 Mask[Part] = reverseVector(Mask[Part]);
2422 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2423 DataTy->getPointerTo(AddressSpace));
2424 if (Legal->isMaskRequired(LI))
2425 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2426 UndefValue::get(DataTy),
2427 "wide.masked.load");
2429 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2430 propagateMetadata(NewLI, LI);
2431 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2435 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2436 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2437 // Holds vector parameters or scalars, in case of uniform vals.
2438 SmallVector<VectorParts, 4> Params;
2440 setDebugLocFromInst(Builder, Instr);
2442 // Find all of the vectorized parameters.
2443 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2444 Value *SrcOp = Instr->getOperand(op);
2446 // If we are accessing the old induction variable, use the new one.
2447 if (SrcOp == OldInduction) {
2448 Params.push_back(getVectorValue(SrcOp));
2452 // Try using previously calculated values.
2453 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2455 // If the src is an instruction that appeared earlier in the basic block,
2456 // then it should already be vectorized.
2457 if (SrcInst && OrigLoop->contains(SrcInst)) {
2458 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2459 // The parameter is a vector value from earlier.
2460 Params.push_back(WidenMap.get(SrcInst));
2462 // The parameter is a scalar from outside the loop. Maybe even a constant.
2463 VectorParts Scalars;
2464 Scalars.append(UF, SrcOp);
2465 Params.push_back(Scalars);
2469 assert(Params.size() == Instr->getNumOperands() &&
2470 "Invalid number of operands");
2472 // Does this instruction return a value ?
2473 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2475 Value *UndefVec = IsVoidRetTy ? nullptr :
2476 UndefValue::get(VectorType::get(Instr->getType(), VF));
2477 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2478 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2481 if (IfPredicateStore) {
2482 assert(Instr->getParent()->getSinglePredecessor() &&
2483 "Only support single predecessor blocks");
2484 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2485 Instr->getParent());
2488 // For each vector unroll 'part':
2489 for (unsigned Part = 0; Part < UF; ++Part) {
2490 // For each scalar that we create:
2491 for (unsigned Width = 0; Width < VF; ++Width) {
2494 Value *Cmp = nullptr;
2495 if (IfPredicateStore) {
2496 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2497 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2500 Instruction *Cloned = Instr->clone();
2502 Cloned->setName(Instr->getName() + ".cloned");
2503 // Replace the operands of the cloned instructions with extracted scalars.
2504 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2505 Value *Op = Params[op][Part];
2506 // Param is a vector. Need to extract the right lane.
2507 if (Op->getType()->isVectorTy())
2508 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2509 Cloned->setOperand(op, Op);
2512 // Place the cloned scalar in the new loop.
2513 Builder.Insert(Cloned);
2515 // If the original scalar returns a value we need to place it in a vector
2516 // so that future users will be able to use it.
2518 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2519 Builder.getInt32(Width));
2521 if (IfPredicateStore)
2522 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
2528 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2532 if (Instruction *I = dyn_cast<Instruction>(V))
2533 return I->getParent() == Loc->getParent() ? I : nullptr;
2537 std::pair<Instruction *, Instruction *>
2538 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2539 Instruction *tnullptr = nullptr;
2540 if (!Legal->mustCheckStrides())
2541 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2543 IRBuilder<> ChkBuilder(Loc);
2546 Value *Check = nullptr;
2547 Instruction *FirstInst = nullptr;
2548 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2549 SE = Legal->strides_end();
2551 Value *Ptr = stripIntegerCast(*SI);
2552 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2554 // Store the first instruction we create.
2555 FirstInst = getFirstInst(FirstInst, C, Loc);
2557 Check = ChkBuilder.CreateOr(Check, C);
2562 // We have to do this trickery because the IRBuilder might fold the check to a
2563 // constant expression in which case there is no Instruction anchored in a
2565 LLVMContext &Ctx = Loc->getContext();
2566 Instruction *TheCheck =
2567 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2568 ChkBuilder.Insert(TheCheck, "stride.not.one");
2569 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2571 return std::make_pair(FirstInst, TheCheck);
2574 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L,
2579 BasicBlock *Header = L->getHeader();
2580 BasicBlock *Latch = L->getLoopLatch();
2581 // As we're just creating this loop, it's possible no latch exists
2582 // yet. If so, use the header as this will be a single block loop.
2586 IRBuilder<> Builder(Header->getFirstInsertionPt());
2587 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2588 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2590 Builder.SetInsertPoint(Latch->getTerminator());
2592 // Create i+1 and fill the PHINode.
2593 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2594 Induction->addIncoming(Start, L->getLoopPreheader());
2595 Induction->addIncoming(Next, Latch);
2596 // Create the compare.
2597 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2598 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2600 // Now we have two terminators. Remove the old one from the block.
2601 Latch->getTerminator()->eraseFromParent();
2606 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2610 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2611 // Find the loop boundaries.
2612 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(OrigLoop);
2613 assert(BackedgeTakenCount != SE->getCouldNotCompute() && "Invalid loop count");
2615 Type *IdxTy = Legal->getWidestInductionType();
2617 // The exit count might have the type of i64 while the phi is i32. This can
2618 // happen if we have an induction variable that is sign extended before the
2619 // compare. The only way that we get a backedge taken count is that the
2620 // induction variable was signed and as such will not overflow. In such a case
2621 // truncation is legal.
2622 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2623 IdxTy->getPrimitiveSizeInBits())
2624 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2625 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2627 // Get the total trip count from the count by adding 1.
2628 const SCEV *ExitCount =
2629 SE->getAddExpr(BackedgeTakenCount,
2630 SE->getConstant(BackedgeTakenCount->getType(), 1));
2632 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2634 // Expand the trip count and place the new instructions in the preheader.
2635 // Notice that the pre-header does not change, only the loop body.
2636 SCEVExpander Exp(*SE, DL, "induction");
2638 // Count holds the overall loop count (N).
2639 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2640 L->getLoopPreheader()->getTerminator());
2642 if (TripCount->getType()->isPointerTy())
2644 CastInst::CreatePointerCast(TripCount, IdxTy,
2645 "exitcount.ptrcnt.to.int",
2646 L->getLoopPreheader()->getTerminator());
2651 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2652 if (VectorTripCount)
2653 return VectorTripCount;
2655 Value *TC = getOrCreateTripCount(L);
2656 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2658 // Now we need to generate the expression for N - (N % VF), which is
2659 // the part that the vectorized body will execute.
2660 // The loop step is equal to the vectorization factor (num of SIMD elements)
2661 // times the unroll factor (num of SIMD instructions).
2662 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2663 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2664 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2666 return VectorTripCount;
2669 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2670 BasicBlock *Bypass) {
2671 Value *Count = getOrCreateTripCount(L);
2672 BasicBlock *BB = L->getLoopPreheader();
2673 IRBuilder<> Builder(BB->getTerminator());
2675 // Generate code to check that the loop's trip count that we computed by
2676 // adding one to the backedge-taken count will not overflow.
2677 Value *CheckMinIters =
2678 Builder.CreateICmpULT(Count,
2679 ConstantInt::get(Count->getType(), VF * UF),
2682 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2683 "min.iters.checked");
2684 if (L->getParentLoop())
2685 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2686 ReplaceInstWithInst(BB->getTerminator(),
2687 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2688 LoopBypassBlocks.push_back(BB);
2691 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2692 BasicBlock *Bypass) {
2693 Value *TC = getOrCreateVectorTripCount(L);
2694 BasicBlock *BB = L->getLoopPreheader();
2695 IRBuilder<> Builder(BB->getTerminator());
2697 // Now, compare the new count to zero. If it is zero skip the vector loop and
2698 // jump to the scalar loop.
2699 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2702 // Generate code to check that the loop's trip count that we computed by
2703 // adding one to the backedge-taken count will not overflow.
2704 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2706 if (L->getParentLoop())
2707 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2708 ReplaceInstWithInst(BB->getTerminator(),
2709 BranchInst::Create(Bypass, NewBB, Cmp));
2710 LoopBypassBlocks.push_back(BB);
2713 void InnerLoopVectorizer::emitStrideChecks(Loop *L,
2714 BasicBlock *Bypass) {
2715 BasicBlock *BB = L->getLoopPreheader();
2717 // Generate the code to check that the strides we assumed to be one are really
2718 // one. We want the new basic block to start at the first instruction in a
2719 // sequence of instructions that form a check.
2720 Instruction *StrideCheck;
2721 Instruction *FirstCheckInst;
2722 std::tie(FirstCheckInst, StrideCheck) = addStrideCheck(BB->getTerminator());
2726 // Create a new block containing the stride check.
2727 BB->setName("vector.stridecheck");
2728 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2729 if (L->getParentLoop())
2730 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2731 ReplaceInstWithInst(BB->getTerminator(),
2732 BranchInst::Create(Bypass, NewBB, StrideCheck));
2733 LoopBypassBlocks.push_back(BB);
2734 AddedSafetyChecks = true;
2737 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
2738 BasicBlock *Bypass) {
2739 BasicBlock *BB = L->getLoopPreheader();
2741 // Generate the code that checks in runtime if arrays overlap. We put the
2742 // checks into a separate block to make the more common case of few elements
2744 Instruction *FirstCheckInst;
2745 Instruction *MemRuntimeCheck;
2746 std::tie(FirstCheckInst, MemRuntimeCheck) =
2747 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2748 if (!MemRuntimeCheck)
2751 // Create a new block containing the memory check.
2752 BB->setName("vector.memcheck");
2753 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2754 if (L->getParentLoop())
2755 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2756 ReplaceInstWithInst(BB->getTerminator(),
2757 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2758 LoopBypassBlocks.push_back(BB);
2759 AddedSafetyChecks = true;
2763 void InnerLoopVectorizer::createEmptyLoop() {
2765 In this function we generate a new loop. The new loop will contain
2766 the vectorized instructions while the old loop will continue to run the
2769 [ ] <-- loop iteration number check.
2772 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2775 || [ ] <-- vector pre header.
2779 | [ ]_| <-- vector loop.
2782 | -[ ] <--- middle-block.
2785 -|- >[ ] <--- new preheader.
2789 | [ ]_| <-- old scalar loop to handle remainder.
2792 >[ ] <-- exit block.
2796 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2797 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2798 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2799 assert(VectorPH && "Invalid loop structure");
2800 assert(ExitBlock && "Must have an exit block");
2802 // Some loops have a single integer induction variable, while other loops
2803 // don't. One example is c++ iterators that often have multiple pointer
2804 // induction variables. In the code below we also support a case where we
2805 // don't have a single induction variable.
2807 // We try to obtain an induction variable from the original loop as hard
2808 // as possible. However if we don't find one that:
2810 // - counts from zero, stepping by one
2811 // - is the size of the widest induction variable type
2812 // then we create a new one.
2813 OldInduction = Legal->getInduction();
2814 Type *IdxTy = Legal->getWidestInductionType();
2816 // Split the single block loop into the two loop structure described above.
2817 BasicBlock *VecBody =
2818 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2819 BasicBlock *MiddleBlock =
2820 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2821 BasicBlock *ScalarPH =
2822 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2824 // Create and register the new vector loop.
2825 Loop* Lp = new Loop();
2826 Loop *ParentLoop = OrigLoop->getParentLoop();
2828 // Insert the new loop into the loop nest and register the new basic blocks
2829 // before calling any utilities such as SCEV that require valid LoopInfo.
2831 ParentLoop->addChildLoop(Lp);
2832 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2833 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2835 LI->addTopLevelLoop(Lp);
2837 Lp->addBasicBlockToLoop(VecBody, *LI);
2839 // Find the loop boundaries.
2840 Value *Count = getOrCreateTripCount(Lp);
2842 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2844 // We need to test whether the backedge-taken count is uint##_max. Adding one
2845 // to it will cause overflow and an incorrect loop trip count in the vector
2846 // body. In case of overflow we want to directly jump to the scalar remainder
2848 emitMinimumIterationCountCheck(Lp, ScalarPH);
2849 // Now, compare the new count to zero. If it is zero skip the vector loop and
2850 // jump to the scalar loop.
2851 emitVectorLoopEnteredCheck(Lp, ScalarPH);
2852 // Generate the code to check that the strides we assumed to be one are really
2853 // one. We want the new basic block to start at the first instruction in a
2854 // sequence of instructions that form a check.
2855 emitStrideChecks(Lp, ScalarPH);
2856 // Generate the code that checks in runtime if arrays overlap. We put the
2857 // checks into a separate block to make the more common case of few elements
2859 emitMemRuntimeChecks(Lp, ScalarPH);
2861 // Generate the induction variable.
2862 // The loop step is equal to the vectorization factor (num of SIMD elements)
2863 // times the unroll factor (num of SIMD instructions).
2864 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2865 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2867 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2868 getDebugLocFromInstOrOperands(OldInduction));
2870 // We are going to resume the execution of the scalar loop.
2871 // Go over all of the induction variables that we found and fix the
2872 // PHIs that are left in the scalar version of the loop.
2873 // The starting values of PHI nodes depend on the counter of the last
2874 // iteration in the vectorized loop.
2875 // If we come from a bypass edge then we need to start from the original
2878 // This variable saves the new starting index for the scalar loop. It is used
2879 // to test if there are any tail iterations left once the vector loop has
2881 LoopVectorizationLegality::InductionList::iterator I, E;
2882 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2883 for (I = List->begin(), E = List->end(); I != E; ++I) {
2884 PHINode *OrigPhi = I->first;
2885 InductionDescriptor II = I->second;
2887 // Create phi nodes to merge from the backedge-taken check block.
2888 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
2890 ScalarPH->getTerminator());
2892 if (OrigPhi == OldInduction) {
2893 // We know what the end value is.
2894 EndValue = CountRoundDown;
2896 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
2897 Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
2898 II.getStepValue()->getType(),
2900 EndValue = II.transform(B, CRD);
2901 EndValue->setName("ind.end");
2904 // The new PHI merges the original incoming value, in case of a bypass,
2905 // or the value at the end of the vectorized loop.
2906 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2908 // Fix the scalar body counter (PHI node).
2909 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2911 // The old induction's phi node in the scalar body needs the truncated
2913 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2914 BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
2915 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2918 // Add a check in the middle block to see if we have completed
2919 // all of the iterations in the first vector loop.
2920 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2921 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2922 CountRoundDown, "cmp.n",
2923 MiddleBlock->getTerminator());
2924 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2925 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2927 // Get ready to start creating new instructions into the vectorized body.
2928 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2931 LoopVectorPreHeader = Lp->getLoopPreheader();
2932 LoopScalarPreHeader = ScalarPH;
2933 LoopMiddleBlock = MiddleBlock;
2934 LoopExitBlock = ExitBlock;
2935 LoopVectorBody.push_back(VecBody);
2936 LoopScalarBody = OldBasicBlock;
2938 LoopVectorizeHints Hints(Lp, true);
2939 Hints.setAlreadyVectorized();
2943 struct CSEDenseMapInfo {
2944 static bool canHandle(Instruction *I) {
2945 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2946 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2948 static inline Instruction *getEmptyKey() {
2949 return DenseMapInfo<Instruction *>::getEmptyKey();
2951 static inline Instruction *getTombstoneKey() {
2952 return DenseMapInfo<Instruction *>::getTombstoneKey();
2954 static unsigned getHashValue(Instruction *I) {
2955 assert(canHandle(I) && "Unknown instruction!");
2956 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2957 I->value_op_end()));
2959 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2960 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2961 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2963 return LHS->isIdenticalTo(RHS);
2968 /// \brief Check whether this block is a predicated block.
2969 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2970 /// = ...; " blocks. We start with one vectorized basic block. For every
2971 /// conditional block we split this vectorized block. Therefore, every second
2972 /// block will be a predicated one.
2973 static bool isPredicatedBlock(unsigned BlockNum) {
2974 return BlockNum % 2;
2977 ///\brief Perform cse of induction variable instructions.
2978 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2979 // Perform simple cse.
2980 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2981 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2982 BasicBlock *BB = BBs[i];
2983 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2984 Instruction *In = I++;
2986 if (!CSEDenseMapInfo::canHandle(In))
2989 // Check if we can replace this instruction with any of the
2990 // visited instructions.
2991 if (Instruction *V = CSEMap.lookup(In)) {
2992 In->replaceAllUsesWith(V);
2993 In->eraseFromParent();
2996 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2997 // ...;" blocks for predicated stores. Every second block is a predicated
2999 if (isPredicatedBlock(i))
3007 /// \brief Adds a 'fast' flag to floating point operations.
3008 static Value *addFastMathFlag(Value *V) {
3009 if (isa<FPMathOperator>(V)){
3010 FastMathFlags Flags;
3011 Flags.setUnsafeAlgebra();
3012 cast<Instruction>(V)->setFastMathFlags(Flags);
3017 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3018 /// the result needs to be inserted and/or extracted from vectors.
3019 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3020 const TargetTransformInfo &TTI) {
3024 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3027 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3029 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3031 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3037 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3038 // Return the cost of the instruction, including scalarization overhead if it's
3039 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3040 // i.e. either vector version isn't available, or is too expensive.
3041 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3042 const TargetTransformInfo &TTI,
3043 const TargetLibraryInfo *TLI,
3044 bool &NeedToScalarize) {
3045 Function *F = CI->getCalledFunction();
3046 StringRef FnName = CI->getCalledFunction()->getName();
3047 Type *ScalarRetTy = CI->getType();
3048 SmallVector<Type *, 4> Tys, ScalarTys;
3049 for (auto &ArgOp : CI->arg_operands())
3050 ScalarTys.push_back(ArgOp->getType());
3052 // Estimate cost of scalarized vector call. The source operands are assumed
3053 // to be vectors, so we need to extract individual elements from there,
3054 // execute VF scalar calls, and then gather the result into the vector return
3056 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3058 return ScalarCallCost;
3060 // Compute corresponding vector type for return value and arguments.
3061 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3062 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3063 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3065 // Compute costs of unpacking argument values for the scalar calls and
3066 // packing the return values to a vector.
3067 unsigned ScalarizationCost =
3068 getScalarizationOverhead(RetTy, true, false, TTI);
3069 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3070 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3072 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3074 // If we can't emit a vector call for this function, then the currently found
3075 // cost is the cost we need to return.
3076 NeedToScalarize = true;
3077 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3080 // If the corresponding vector cost is cheaper, return its cost.
3081 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3082 if (VectorCallCost < Cost) {
3083 NeedToScalarize = false;
3084 return VectorCallCost;
3089 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3090 // factor VF. Return the cost of the instruction, including scalarization
3091 // overhead if it's needed.
3092 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3093 const TargetTransformInfo &TTI,
3094 const TargetLibraryInfo *TLI) {
3095 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3096 assert(ID && "Expected intrinsic call!");
3098 Type *RetTy = ToVectorTy(CI->getType(), VF);
3099 SmallVector<Type *, 4> Tys;
3100 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3101 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3103 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3106 void InnerLoopVectorizer::vectorizeLoop() {
3107 //===------------------------------------------------===//
3109 // Notice: any optimization or new instruction that go
3110 // into the code below should be also be implemented in
3113 //===------------------------------------------------===//
3114 Constant *Zero = Builder.getInt32(0);
3116 // In order to support reduction variables we need to be able to vectorize
3117 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3118 // stages. First, we create a new vector PHI node with no incoming edges.
3119 // We use this value when we vectorize all of the instructions that use the
3120 // PHI. Next, after all of the instructions in the block are complete we
3121 // add the new incoming edges to the PHI. At this point all of the
3122 // instructions in the basic block are vectorized, so we can use them to
3123 // construct the PHI.
3124 PhiVector RdxPHIsToFix;
3126 // Scan the loop in a topological order to ensure that defs are vectorized
3128 LoopBlocksDFS DFS(OrigLoop);
3131 // Vectorize all of the blocks in the original loop.
3132 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3133 be = DFS.endRPO(); bb != be; ++bb)
3134 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3136 // At this point every instruction in the original loop is widened to
3137 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3138 // that we vectorized. The PHI nodes are currently empty because we did
3139 // not want to introduce cycles. Notice that the remaining PHI nodes
3140 // that we need to fix are reduction variables.
3142 // Create the 'reduced' values for each of the induction vars.
3143 // The reduced values are the vector values that we scalarize and combine
3144 // after the loop is finished.
3145 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3147 PHINode *RdxPhi = *it;
3148 assert(RdxPhi && "Unable to recover vectorized PHI");
3150 // Find the reduction variable descriptor.
3151 assert(Legal->getReductionVars()->count(RdxPhi) &&
3152 "Unable to find the reduction variable");
3153 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3155 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3156 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3157 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3158 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3159 RdxDesc.getMinMaxRecurrenceKind();
3160 setDebugLocFromInst(Builder, ReductionStartValue);
3162 // We need to generate a reduction vector from the incoming scalar.
3163 // To do so, we need to generate the 'identity' vector and override
3164 // one of the elements with the incoming scalar reduction. We need
3165 // to do it in the vector-loop preheader.
3166 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3168 // This is the vector-clone of the value that leaves the loop.
3169 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3170 Type *VecTy = VectorExit[0]->getType();
3172 // Find the reduction identity variable. Zero for addition, or, xor,
3173 // one for multiplication, -1 for And.
3176 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3177 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3178 // MinMax reduction have the start value as their identify.
3180 VectorStart = Identity = ReductionStartValue;
3182 VectorStart = Identity =
3183 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3186 // Handle other reduction kinds:
3187 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3188 RK, VecTy->getScalarType());
3191 // This vector is the Identity vector where the first element is the
3192 // incoming scalar reduction.
3193 VectorStart = ReductionStartValue;
3195 Identity = ConstantVector::getSplat(VF, Iden);
3197 // This vector is the Identity vector where the first element is the
3198 // incoming scalar reduction.
3200 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3204 // Fix the vector-loop phi.
3206 // Reductions do not have to start at zero. They can start with
3207 // any loop invariant values.
3208 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3209 BasicBlock *Latch = OrigLoop->getLoopLatch();
3210 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3211 VectorParts &Val = getVectorValue(LoopVal);
3212 for (unsigned part = 0; part < UF; ++part) {
3213 // Make sure to add the reduction stat value only to the
3214 // first unroll part.
3215 Value *StartVal = (part == 0) ? VectorStart : Identity;
3216 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3217 LoopVectorPreHeader);
3218 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3219 LoopVectorBody.back());
3222 // Before each round, move the insertion point right between
3223 // the PHIs and the values we are going to write.
3224 // This allows us to write both PHINodes and the extractelement
3226 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3228 VectorParts RdxParts = getVectorValue(LoopExitInst);
3229 setDebugLocFromInst(Builder, LoopExitInst);
3231 // If the vector reduction can be performed in a smaller type, we truncate
3232 // then extend the loop exit value to enable InstCombine to evaluate the
3233 // entire expression in the smaller type.
3234 if (VF > 1 && RdxPhi->getType() != RdxDesc.getRecurrenceType()) {
3235 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3236 Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
3237 for (unsigned part = 0; part < UF; ++part) {
3238 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3239 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3240 : Builder.CreateZExt(Trunc, VecTy);
3241 for (Value::user_iterator UI = RdxParts[part]->user_begin();
3242 UI != RdxParts[part]->user_end();)
3244 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3245 RdxParts[part] = Extnd;
3250 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3251 for (unsigned part = 0; part < UF; ++part)
3252 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3255 // Reduce all of the unrolled parts into a single vector.
3256 Value *ReducedPartRdx = RdxParts[0];
3257 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3258 setDebugLocFromInst(Builder, ReducedPartRdx);
3259 for (unsigned part = 1; part < UF; ++part) {
3260 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3261 // Floating point operations had to be 'fast' to enable the reduction.
3262 ReducedPartRdx = addFastMathFlag(
3263 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3264 ReducedPartRdx, "bin.rdx"));
3266 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3267 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3271 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3272 // and vector ops, reducing the set of values being computed by half each
3274 assert(isPowerOf2_32(VF) &&
3275 "Reduction emission only supported for pow2 vectors!");
3276 Value *TmpVec = ReducedPartRdx;
3277 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3278 for (unsigned i = VF; i != 1; i >>= 1) {
3279 // Move the upper half of the vector to the lower half.
3280 for (unsigned j = 0; j != i/2; ++j)
3281 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3283 // Fill the rest of the mask with undef.
3284 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3285 UndefValue::get(Builder.getInt32Ty()));
3288 Builder.CreateShuffleVector(TmpVec,
3289 UndefValue::get(TmpVec->getType()),
3290 ConstantVector::get(ShuffleMask),
3293 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3294 // Floating point operations had to be 'fast' to enable the reduction.
3295 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3296 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3298 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3302 // The result is in the first element of the vector.
3303 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3304 Builder.getInt32(0));
3306 // If the reduction can be performed in a smaller type, we need to extend
3307 // the reduction to the wider type before we branch to the original loop.
3308 if (RdxPhi->getType() != RdxDesc.getRecurrenceType())
3311 ? Builder.CreateSExt(ReducedPartRdx, RdxPhi->getType())
3312 : Builder.CreateZExt(ReducedPartRdx, RdxPhi->getType());
3315 // Create a phi node that merges control-flow from the backedge-taken check
3316 // block and the middle block.
3317 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3318 LoopScalarPreHeader->getTerminator());
3319 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3320 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3321 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3323 // Now, we need to fix the users of the reduction variable
3324 // inside and outside of the scalar remainder loop.
3325 // We know that the loop is in LCSSA form. We need to update the
3326 // PHI nodes in the exit blocks.
3327 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3328 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3329 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3330 if (!LCSSAPhi) break;
3332 // All PHINodes need to have a single entry edge, or two if
3333 // we already fixed them.
3334 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3336 // We found our reduction value exit-PHI. Update it with the
3337 // incoming bypass edge.
3338 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3339 // Add an edge coming from the bypass.
3340 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3343 }// end of the LCSSA phi scan.
3345 // Fix the scalar loop reduction variable with the incoming reduction sum
3346 // from the vector body and from the backedge value.
3347 int IncomingEdgeBlockIdx =
3348 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3349 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3350 // Pick the other block.
3351 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3352 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3353 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3354 }// end of for each redux variable.
3358 // Make sure DomTree is updated.
3361 // Predicate any stores.
3362 for (auto KV : PredicatedStores) {
3363 BasicBlock::iterator I(KV.first);
3364 auto *BB = SplitBlock(I->getParent(), std::next(I), DT, LI);
3365 auto *T = SplitBlockAndInsertIfThen(KV.second, I, /*Unreachable=*/false,
3366 /*BranchWeights=*/nullptr, DT);
3368 I->getParent()->setName("pred.store.if");
3369 BB->setName("pred.store.continue");
3371 DEBUG(DT->verifyDomTree());
3372 // Remove redundant induction instructions.
3373 cse(LoopVectorBody);
3376 void InnerLoopVectorizer::fixLCSSAPHIs() {
3377 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3378 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3379 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3380 if (!LCSSAPhi) break;
3381 if (LCSSAPhi->getNumIncomingValues() == 1)
3382 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3387 InnerLoopVectorizer::VectorParts
3388 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3389 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3392 // Look for cached value.
3393 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3394 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3395 if (ECEntryIt != MaskCache.end())
3396 return ECEntryIt->second;
3398 VectorParts SrcMask = createBlockInMask(Src);
3400 // The terminator has to be a branch inst!
3401 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3402 assert(BI && "Unexpected terminator found");
3404 if (BI->isConditional()) {
3405 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3407 if (BI->getSuccessor(0) != Dst)
3408 for (unsigned part = 0; part < UF; ++part)
3409 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3411 for (unsigned part = 0; part < UF; ++part)
3412 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3414 MaskCache[Edge] = EdgeMask;
3418 MaskCache[Edge] = SrcMask;
3422 InnerLoopVectorizer::VectorParts
3423 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3424 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3426 // Loop incoming mask is all-one.
3427 if (OrigLoop->getHeader() == BB) {
3428 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3429 return getVectorValue(C);
3432 // This is the block mask. We OR all incoming edges, and with zero.
3433 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3434 VectorParts BlockMask = getVectorValue(Zero);
3437 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3438 VectorParts EM = createEdgeMask(*it, BB);
3439 for (unsigned part = 0; part < UF; ++part)
3440 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3446 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3447 InnerLoopVectorizer::VectorParts &Entry,
3448 unsigned UF, unsigned VF, PhiVector *PV) {
3449 PHINode* P = cast<PHINode>(PN);
3450 // Handle reduction variables:
3451 if (Legal->getReductionVars()->count(P)) {
3452 for (unsigned part = 0; part < UF; ++part) {
3453 // This is phase one of vectorizing PHIs.
3454 Type *VecTy = (VF == 1) ? PN->getType() :
3455 VectorType::get(PN->getType(), VF);
3456 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3457 LoopVectorBody.back()-> getFirstInsertionPt());
3463 setDebugLocFromInst(Builder, P);
3464 // Check for PHI nodes that are lowered to vector selects.
3465 if (P->getParent() != OrigLoop->getHeader()) {
3466 // We know that all PHIs in non-header blocks are converted into
3467 // selects, so we don't have to worry about the insertion order and we
3468 // can just use the builder.
3469 // At this point we generate the predication tree. There may be
3470 // duplications since this is a simple recursive scan, but future
3471 // optimizations will clean it up.
3473 unsigned NumIncoming = P->getNumIncomingValues();
3475 // Generate a sequence of selects of the form:
3476 // SELECT(Mask3, In3,
3477 // SELECT(Mask2, In2,
3479 for (unsigned In = 0; In < NumIncoming; In++) {
3480 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3482 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3484 for (unsigned part = 0; part < UF; ++part) {
3485 // We might have single edge PHIs (blocks) - use an identity
3486 // 'select' for the first PHI operand.
3488 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3491 // Select between the current value and the previous incoming edge
3492 // based on the incoming mask.
3493 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3494 Entry[part], "predphi");
3500 // This PHINode must be an induction variable.
3501 // Make sure that we know about it.
3502 assert(Legal->getInductionVars()->count(P) &&
3503 "Not an induction variable");
3505 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3507 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3508 // which can be found from the original scalar operations.
3509 switch (II.getKind()) {
3510 case InductionDescriptor::IK_NoInduction:
3511 llvm_unreachable("Unknown induction");
3512 case InductionDescriptor::IK_IntInduction: {
3513 assert(P->getType() == II.getStartValue()->getType() && "Types must match");
3514 // Handle other induction variables that are now based on the
3516 Value *V = Induction;
3517 if (P != OldInduction) {
3518 V = Builder.CreateSExtOrTrunc(Induction, P->getType());
3519 V = II.transform(Builder, V);
3520 V->setName("offset.idx");
3522 Value *Broadcasted = getBroadcastInstrs(V);
3523 // After broadcasting the induction variable we need to make the vector
3524 // consecutive by adding 0, 1, 2, etc.
3525 for (unsigned part = 0; part < UF; ++part)
3526 Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
3529 case InductionDescriptor::IK_PtrInduction:
3530 // Handle the pointer induction variable case.
3531 assert(P->getType()->isPointerTy() && "Unexpected type.");
3532 // This is the normalized GEP that starts counting at zero.
3533 Value *PtrInd = Induction;
3534 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
3535 // This is the vector of results. Notice that we don't generate
3536 // vector geps because scalar geps result in better code.
3537 for (unsigned part = 0; part < UF; ++part) {
3539 int EltIndex = part;
3540 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3541 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3542 Value *SclrGep = II.transform(Builder, GlobalIdx);
3543 SclrGep->setName("next.gep");
3544 Entry[part] = SclrGep;
3548 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3549 for (unsigned int i = 0; i < VF; ++i) {
3550 int EltIndex = i + part * VF;
3551 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3552 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3553 Value *SclrGep = II.transform(Builder, GlobalIdx);
3554 SclrGep->setName("next.gep");
3555 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3556 Builder.getInt32(i),
3559 Entry[part] = VecVal;
3565 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3566 // For each instruction in the old loop.
3567 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3568 VectorParts &Entry = WidenMap.get(it);
3569 switch (it->getOpcode()) {
3570 case Instruction::Br:
3571 // Nothing to do for PHIs and BR, since we already took care of the
3572 // loop control flow instructions.
3574 case Instruction::PHI: {
3575 // Vectorize PHINodes.
3576 widenPHIInstruction(it, Entry, UF, VF, PV);
3580 case Instruction::Add:
3581 case Instruction::FAdd:
3582 case Instruction::Sub:
3583 case Instruction::FSub:
3584 case Instruction::Mul:
3585 case Instruction::FMul:
3586 case Instruction::UDiv:
3587 case Instruction::SDiv:
3588 case Instruction::FDiv:
3589 case Instruction::URem:
3590 case Instruction::SRem:
3591 case Instruction::FRem:
3592 case Instruction::Shl:
3593 case Instruction::LShr:
3594 case Instruction::AShr:
3595 case Instruction::And:
3596 case Instruction::Or:
3597 case Instruction::Xor: {
3598 // Just widen binops.
3599 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3600 setDebugLocFromInst(Builder, BinOp);
3601 VectorParts &A = getVectorValue(it->getOperand(0));
3602 VectorParts &B = getVectorValue(it->getOperand(1));
3604 // Use this vector value for all users of the original instruction.
3605 for (unsigned Part = 0; Part < UF; ++Part) {
3606 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3608 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3609 VecOp->copyIRFlags(BinOp);
3614 propagateMetadata(Entry, it);
3617 case Instruction::Select: {
3619 // If the selector is loop invariant we can create a select
3620 // instruction with a scalar condition. Otherwise, use vector-select.
3621 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3623 setDebugLocFromInst(Builder, it);
3625 // The condition can be loop invariant but still defined inside the
3626 // loop. This means that we can't just use the original 'cond' value.
3627 // We have to take the 'vectorized' value and pick the first lane.
3628 // Instcombine will make this a no-op.
3629 VectorParts &Cond = getVectorValue(it->getOperand(0));
3630 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3631 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3633 Value *ScalarCond = (VF == 1) ? Cond[0] :
3634 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3636 for (unsigned Part = 0; Part < UF; ++Part) {
3637 Entry[Part] = Builder.CreateSelect(
3638 InvariantCond ? ScalarCond : Cond[Part],
3643 propagateMetadata(Entry, it);
3647 case Instruction::ICmp:
3648 case Instruction::FCmp: {
3649 // Widen compares. Generate vector compares.
3650 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3651 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3652 setDebugLocFromInst(Builder, it);
3653 VectorParts &A = getVectorValue(it->getOperand(0));
3654 VectorParts &B = getVectorValue(it->getOperand(1));
3655 for (unsigned Part = 0; Part < UF; ++Part) {
3658 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3660 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3664 propagateMetadata(Entry, it);
3668 case Instruction::Store:
3669 case Instruction::Load:
3670 vectorizeMemoryInstruction(it);
3672 case Instruction::ZExt:
3673 case Instruction::SExt:
3674 case Instruction::FPToUI:
3675 case Instruction::FPToSI:
3676 case Instruction::FPExt:
3677 case Instruction::PtrToInt:
3678 case Instruction::IntToPtr:
3679 case Instruction::SIToFP:
3680 case Instruction::UIToFP:
3681 case Instruction::Trunc:
3682 case Instruction::FPTrunc:
3683 case Instruction::BitCast: {
3684 CastInst *CI = dyn_cast<CastInst>(it);
3685 setDebugLocFromInst(Builder, it);
3686 /// Optimize the special case where the source is the induction
3687 /// variable. Notice that we can only optimize the 'trunc' case
3688 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3689 /// c. other casts depend on pointer size.
3690 if (CI->getOperand(0) == OldInduction &&
3691 it->getOpcode() == Instruction::Trunc) {
3692 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3694 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3695 InductionDescriptor II = Legal->getInductionVars()->lookup(OldInduction);
3697 ConstantInt::getSigned(CI->getType(), II.getStepValue()->getSExtValue());
3698 for (unsigned Part = 0; Part < UF; ++Part)
3699 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3700 propagateMetadata(Entry, it);
3703 /// Vectorize casts.
3704 Type *DestTy = (VF == 1) ? CI->getType() :
3705 VectorType::get(CI->getType(), VF);
3707 VectorParts &A = getVectorValue(it->getOperand(0));
3708 for (unsigned Part = 0; Part < UF; ++Part)
3709 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3710 propagateMetadata(Entry, it);
3714 case Instruction::Call: {
3715 // Ignore dbg intrinsics.
3716 if (isa<DbgInfoIntrinsic>(it))
3718 setDebugLocFromInst(Builder, it);
3720 Module *M = BB->getParent()->getParent();
3721 CallInst *CI = cast<CallInst>(it);
3723 StringRef FnName = CI->getCalledFunction()->getName();
3724 Function *F = CI->getCalledFunction();
3725 Type *RetTy = ToVectorTy(CI->getType(), VF);
3726 SmallVector<Type *, 4> Tys;
3727 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3728 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3730 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3732 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3733 ID == Intrinsic::lifetime_start)) {
3734 scalarizeInstruction(it);
3737 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3738 // version of the instruction.
3739 // Is it beneficial to perform intrinsic call compared to lib call?
3740 bool NeedToScalarize;
3741 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3742 bool UseVectorIntrinsic =
3743 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3744 if (!UseVectorIntrinsic && NeedToScalarize) {
3745 scalarizeInstruction(it);
3749 for (unsigned Part = 0; Part < UF; ++Part) {
3750 SmallVector<Value *, 4> Args;
3751 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3752 Value *Arg = CI->getArgOperand(i);
3753 // Some intrinsics have a scalar argument - don't replace it with a
3755 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3756 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3757 Arg = VectorArg[Part];
3759 Args.push_back(Arg);
3763 if (UseVectorIntrinsic) {
3764 // Use vector version of the intrinsic.
3765 Type *TysForDecl[] = {CI->getType()};
3767 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3768 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3770 // Use vector version of the library call.
3771 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3772 assert(!VFnName.empty() && "Vector function name is empty.");
3773 VectorF = M->getFunction(VFnName);
3775 // Generate a declaration
3776 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3778 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3779 VectorF->copyAttributesFrom(F);
3782 assert(VectorF && "Can't create vector function.");
3783 Entry[Part] = Builder.CreateCall(VectorF, Args);
3786 propagateMetadata(Entry, it);
3791 // All other instructions are unsupported. Scalarize them.
3792 scalarizeInstruction(it);
3795 }// end of for_each instr.
3798 void InnerLoopVectorizer::updateAnalysis() {
3799 // Forget the original basic block.
3800 SE->forgetLoop(OrigLoop);
3802 // Update the dominator tree information.
3803 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3804 "Entry does not dominate exit.");
3806 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3807 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3808 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3810 // We don't predicate stores by this point, so the vector body should be a
3812 assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
3813 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3815 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
3816 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3817 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3818 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3820 DEBUG(DT->verifyDomTree());
3823 /// \brief Check whether it is safe to if-convert this phi node.
3825 /// Phi nodes with constant expressions that can trap are not safe to if
3827 static bool canIfConvertPHINodes(BasicBlock *BB) {
3828 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3829 PHINode *Phi = dyn_cast<PHINode>(I);
3832 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3833 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3840 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3841 if (!EnableIfConversion) {
3842 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3846 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3848 // A list of pointers that we can safely read and write to.
3849 SmallPtrSet<Value *, 8> SafePointes;
3851 // Collect safe addresses.
3852 for (Loop::block_iterator BI = TheLoop->block_begin(),
3853 BE = TheLoop->block_end(); BI != BE; ++BI) {
3854 BasicBlock *BB = *BI;
3856 if (blockNeedsPredication(BB))
3859 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3860 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3861 SafePointes.insert(LI->getPointerOperand());
3862 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3863 SafePointes.insert(SI->getPointerOperand());
3867 // Collect the blocks that need predication.
3868 BasicBlock *Header = TheLoop->getHeader();
3869 for (Loop::block_iterator BI = TheLoop->block_begin(),
3870 BE = TheLoop->block_end(); BI != BE; ++BI) {
3871 BasicBlock *BB = *BI;
3873 // We don't support switch statements inside loops.
3874 if (!isa<BranchInst>(BB->getTerminator())) {
3875 emitAnalysis(VectorizationReport(BB->getTerminator())
3876 << "loop contains a switch statement");
3880 // We must be able to predicate all blocks that need to be predicated.
3881 if (blockNeedsPredication(BB)) {
3882 if (!blockCanBePredicated(BB, SafePointes)) {
3883 emitAnalysis(VectorizationReport(BB->getTerminator())
3884 << "control flow cannot be substituted for a select");
3887 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3888 emitAnalysis(VectorizationReport(BB->getTerminator())
3889 << "control flow cannot be substituted for a select");
3894 // We can if-convert this loop.
3898 bool LoopVectorizationLegality::canVectorize() {
3899 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3900 // be canonicalized.
3901 if (!TheLoop->getLoopPreheader()) {
3903 VectorizationReport() <<
3904 "loop control flow is not understood by vectorizer");
3908 // We can only vectorize innermost loops.
3909 if (!TheLoop->empty()) {
3910 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3914 // We must have a single backedge.
3915 if (TheLoop->getNumBackEdges() != 1) {
3917 VectorizationReport() <<
3918 "loop control flow is not understood by vectorizer");
3922 // We must have a single exiting block.
3923 if (!TheLoop->getExitingBlock()) {
3925 VectorizationReport() <<
3926 "loop control flow is not understood by vectorizer");
3930 // We only handle bottom-tested loops, i.e. loop in which the condition is
3931 // checked at the end of each iteration. With that we can assume that all
3932 // instructions in the loop are executed the same number of times.
3933 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3935 VectorizationReport() <<
3936 "loop control flow is not understood by vectorizer");
3940 // We need to have a loop header.
3941 DEBUG(dbgs() << "LV: Found a loop: " <<
3942 TheLoop->getHeader()->getName() << '\n');
3944 // Check if we can if-convert non-single-bb loops.
3945 unsigned NumBlocks = TheLoop->getNumBlocks();
3946 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3947 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3951 // ScalarEvolution needs to be able to find the exit count.
3952 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3953 if (ExitCount == SE->getCouldNotCompute()) {
3954 emitAnalysis(VectorizationReport() <<
3955 "could not determine number of loop iterations");
3956 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3960 // Check if we can vectorize the instructions and CFG in this loop.
3961 if (!canVectorizeInstrs()) {
3962 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3966 // Go over each instruction and look at memory deps.
3967 if (!canVectorizeMemory()) {
3968 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3972 // Collect all of the variables that remain uniform after vectorization.
3973 collectLoopUniforms();
3975 DEBUG(dbgs() << "LV: We can vectorize this loop"
3976 << (LAI->getRuntimePointerChecking()->Need
3977 ? " (with a runtime bound check)"
3981 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
3983 // If an override option has been passed in for interleaved accesses, use it.
3984 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
3985 UseInterleaved = EnableInterleavedMemAccesses;
3987 // Analyze interleaved memory accesses.
3989 InterleaveInfo.analyzeInterleaving(Strides);
3991 // Okay! We can vectorize. At this point we don't have any other mem analysis
3992 // which may limit our maximum vectorization factor, so just return true with
3997 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3998 if (Ty->isPointerTy())
3999 return DL.getIntPtrType(Ty);
4001 // It is possible that char's or short's overflow when we ask for the loop's
4002 // trip count, work around this by changing the type size.
4003 if (Ty->getScalarSizeInBits() < 32)
4004 return Type::getInt32Ty(Ty->getContext());
4009 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4010 Ty0 = convertPointerToIntegerType(DL, Ty0);
4011 Ty1 = convertPointerToIntegerType(DL, Ty1);
4012 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4017 /// \brief Check that the instruction has outside loop users and is not an
4018 /// identified reduction variable.
4019 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4020 SmallPtrSetImpl<Value *> &Reductions) {
4021 // Reduction instructions are allowed to have exit users. All other
4022 // instructions must not have external users.
4023 if (!Reductions.count(Inst))
4024 //Check that all of the users of the loop are inside the BB.
4025 for (User *U : Inst->users()) {
4026 Instruction *UI = cast<Instruction>(U);
4027 // This user may be a reduction exit value.
4028 if (!TheLoop->contains(UI)) {
4029 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4036 bool LoopVectorizationLegality::canVectorizeInstrs() {
4037 BasicBlock *Header = TheLoop->getHeader();
4039 // Look for the attribute signaling the absence of NaNs.
4040 Function &F = *Header->getParent();
4041 const DataLayout &DL = F.getParent()->getDataLayout();
4042 if (F.hasFnAttribute("no-nans-fp-math"))
4044 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4046 // For each block in the loop.
4047 for (Loop::block_iterator bb = TheLoop->block_begin(),
4048 be = TheLoop->block_end(); bb != be; ++bb) {
4050 // Scan the instructions in the block and look for hazards.
4051 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4054 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4055 Type *PhiTy = Phi->getType();
4056 // Check that this PHI type is allowed.
4057 if (!PhiTy->isIntegerTy() &&
4058 !PhiTy->isFloatingPointTy() &&
4059 !PhiTy->isPointerTy()) {
4060 emitAnalysis(VectorizationReport(it)
4061 << "loop control flow is not understood by vectorizer");
4062 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4066 // If this PHINode is not in the header block, then we know that we
4067 // can convert it to select during if-conversion. No need to check if
4068 // the PHIs in this block are induction or reduction variables.
4069 if (*bb != Header) {
4070 // Check that this instruction has no outside users or is an
4071 // identified reduction value with an outside user.
4072 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
4074 emitAnalysis(VectorizationReport(it) <<
4075 "value could not be identified as "
4076 "an induction or reduction variable");
4080 // We only allow if-converted PHIs with exactly two incoming values.
4081 if (Phi->getNumIncomingValues() != 2) {
4082 emitAnalysis(VectorizationReport(it)
4083 << "control flow not understood by vectorizer");
4084 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4088 InductionDescriptor ID;
4089 if (InductionDescriptor::isInductionPHI(Phi, SE, ID)) {
4090 Inductions[Phi] = ID;
4091 // Get the widest type.
4093 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4095 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4097 // Int inductions are special because we only allow one IV.
4098 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4099 ID.getStepValue()->isOne() &&
4100 isa<Constant>(ID.getStartValue()) &&
4101 cast<Constant>(ID.getStartValue())->isNullValue()) {
4102 // Use the phi node with the widest type as induction. Use the last
4103 // one if there are multiple (no good reason for doing this other
4104 // than it is expedient). We've checked that it begins at zero and
4105 // steps by one, so this is a canonical induction variable.
4106 if (!Induction || PhiTy == WidestIndTy)
4110 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4112 // Until we explicitly handle the case of an induction variable with
4113 // an outside loop user we have to give up vectorizing this loop.
4114 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4115 emitAnalysis(VectorizationReport(it) <<
4116 "use of induction value outside of the "
4117 "loop is not handled by vectorizer");
4124 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4126 if (Reductions[Phi].hasUnsafeAlgebra())
4127 Requirements->addUnsafeAlgebraInst(
4128 Reductions[Phi].getUnsafeAlgebraInst());
4129 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4133 emitAnalysis(VectorizationReport(it) <<
4134 "value that could not be identified as "
4135 "reduction is used outside the loop");
4136 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4138 }// end of PHI handling
4140 // We handle calls that:
4141 // * Are debug info intrinsics.
4142 // * Have a mapping to an IR intrinsic.
4143 // * Have a vector version available.
4144 CallInst *CI = dyn_cast<CallInst>(it);
4145 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4146 !(CI->getCalledFunction() && TLI &&
4147 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4148 emitAnalysis(VectorizationReport(it) <<
4149 "call instruction cannot be vectorized");
4150 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4154 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4155 // second argument is the same (i.e. loop invariant)
4157 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4158 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4159 emitAnalysis(VectorizationReport(it)
4160 << "intrinsic instruction cannot be vectorized");
4161 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4166 // Check that the instruction return type is vectorizable.
4167 // Also, we can't vectorize extractelement instructions.
4168 if ((!VectorType::isValidElementType(it->getType()) &&
4169 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4170 emitAnalysis(VectorizationReport(it)
4171 << "instruction return type cannot be vectorized");
4172 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4176 // Check that the stored type is vectorizable.
4177 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4178 Type *T = ST->getValueOperand()->getType();
4179 if (!VectorType::isValidElementType(T)) {
4180 emitAnalysis(VectorizationReport(ST) <<
4181 "store instruction cannot be vectorized");
4184 if (EnableMemAccessVersioning)
4185 collectStridedAccess(ST);
4188 if (EnableMemAccessVersioning)
4189 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4190 collectStridedAccess(LI);
4192 // Reduction instructions are allowed to have exit users.
4193 // All other instructions must not have external users.
4194 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4195 emitAnalysis(VectorizationReport(it) <<
4196 "value cannot be used outside the loop");
4205 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4206 if (Inductions.empty()) {
4207 emitAnalysis(VectorizationReport()
4208 << "loop induction variable could not be identified");
4213 // Now we know the widest induction type, check if our found induction
4214 // is the same size. If it's not, unset it here and InnerLoopVectorizer
4215 // will create another.
4216 if (Induction && WidestIndTy != Induction->getType())
4217 Induction = nullptr;
4222 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4223 Value *Ptr = nullptr;
4224 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4225 Ptr = LI->getPointerOperand();
4226 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4227 Ptr = SI->getPointerOperand();
4231 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4235 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4236 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4237 Strides[Ptr] = Stride;
4238 StrideSet.insert(Stride);
4241 void LoopVectorizationLegality::collectLoopUniforms() {
4242 // We now know that the loop is vectorizable!
4243 // Collect variables that will remain uniform after vectorization.
4244 std::vector<Value*> Worklist;
4245 BasicBlock *Latch = TheLoop->getLoopLatch();
4247 // Start with the conditional branch and walk up the block.
4248 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4250 // Also add all consecutive pointer values; these values will be uniform
4251 // after vectorization (and subsequent cleanup) and, until revectorization is
4252 // supported, all dependencies must also be uniform.
4253 for (Loop::block_iterator B = TheLoop->block_begin(),
4254 BE = TheLoop->block_end(); B != BE; ++B)
4255 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4257 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4258 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4260 while (!Worklist.empty()) {
4261 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4262 Worklist.pop_back();
4264 // Look at instructions inside this loop.
4265 // Stop when reaching PHI nodes.
4266 // TODO: we need to follow values all over the loop, not only in this block.
4267 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4270 // This is a known uniform.
4273 // Insert all operands.
4274 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4278 bool LoopVectorizationLegality::canVectorizeMemory() {
4279 LAI = &LAA->getInfo(TheLoop, Strides);
4280 auto &OptionalReport = LAI->getReport();
4282 emitAnalysis(VectorizationReport(*OptionalReport));
4283 if (!LAI->canVectorizeMemory())
4286 if (LAI->hasStoreToLoopInvariantAddress()) {
4288 VectorizationReport()
4289 << "write to a loop invariant address could not be vectorized");
4290 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4294 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4299 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4300 Value *In0 = const_cast<Value*>(V);
4301 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4305 return Inductions.count(PN);
4308 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4309 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4312 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4313 SmallPtrSetImpl<Value *> &SafePtrs) {
4315 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4316 // Check that we don't have a constant expression that can trap as operand.
4317 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4319 if (Constant *C = dyn_cast<Constant>(*OI))
4323 // We might be able to hoist the load.
4324 if (it->mayReadFromMemory()) {
4325 LoadInst *LI = dyn_cast<LoadInst>(it);
4328 if (!SafePtrs.count(LI->getPointerOperand())) {
4329 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4330 MaskedOp.insert(LI);
4337 // We don't predicate stores at the moment.
4338 if (it->mayWriteToMemory()) {
4339 StoreInst *SI = dyn_cast<StoreInst>(it);
4340 // We only support predication of stores in basic blocks with one
4345 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4346 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4348 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4349 !isSinglePredecessor) {
4350 // Build a masked store if it is legal for the target, otherwise scalarize
4352 bool isLegalMaskedOp =
4353 isLegalMaskedStore(SI->getValueOperand()->getType(),
4354 SI->getPointerOperand());
4355 if (isLegalMaskedOp) {
4357 MaskedOp.insert(SI);
4366 // The instructions below can trap.
4367 switch (it->getOpcode()) {
4369 case Instruction::UDiv:
4370 case Instruction::SDiv:
4371 case Instruction::URem:
4372 case Instruction::SRem:
4380 void InterleavedAccessInfo::collectConstStridedAccesses(
4381 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4382 const ValueToValueMap &Strides) {
4383 // Holds load/store instructions in program order.
4384 SmallVector<Instruction *, 16> AccessList;
4386 for (auto *BB : TheLoop->getBlocks()) {
4387 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4389 for (auto &I : *BB) {
4390 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4392 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4396 AccessList.push_back(&I);
4400 if (AccessList.empty())
4403 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4404 for (auto I : AccessList) {
4405 LoadInst *LI = dyn_cast<LoadInst>(I);
4406 StoreInst *SI = dyn_cast<StoreInst>(I);
4408 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4409 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4411 // The factor of the corresponding interleave group.
4412 unsigned Factor = std::abs(Stride);
4414 // Ignore the access if the factor is too small or too large.
4415 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4418 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4419 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4420 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4422 // An alignment of 0 means target ABI alignment.
4423 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4425 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4427 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4431 // Analyze interleaved accesses and collect them into interleave groups.
4433 // Notice that the vectorization on interleaved groups will change instruction
4434 // orders and may break dependences. But the memory dependence check guarantees
4435 // that there is no overlap between two pointers of different strides, element
4436 // sizes or underlying bases.
4438 // For pointers sharing the same stride, element size and underlying base, no
4439 // need to worry about Read-After-Write dependences and Write-After-Read
4442 // E.g. The RAW dependence: A[i] = a;
4444 // This won't exist as it is a store-load forwarding conflict, which has
4445 // already been checked and forbidden in the dependence check.
4447 // E.g. The WAR dependence: a = A[i]; // (1)
4449 // The store group of (2) is always inserted at or below (2), and the load group
4450 // of (1) is always inserted at or above (1). The dependence is safe.
4451 void InterleavedAccessInfo::analyzeInterleaving(
4452 const ValueToValueMap &Strides) {
4453 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4455 // Holds all the stride accesses.
4456 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4457 collectConstStridedAccesses(StrideAccesses, Strides);
4459 if (StrideAccesses.empty())
4462 // Holds all interleaved store groups temporarily.
4463 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4465 // Search the load-load/write-write pair B-A in bottom-up order and try to
4466 // insert B into the interleave group of A according to 3 rules:
4467 // 1. A and B have the same stride.
4468 // 2. A and B have the same memory object size.
4469 // 3. B belongs to the group according to the distance.
4471 // The bottom-up order can avoid breaking the Write-After-Write dependences
4472 // between two pointers of the same base.
4473 // E.g. A[i] = a; (1)
4476 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4477 // above (1), which guarantees that (1) is always above (2).
4478 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4480 Instruction *A = I->first;
4481 StrideDescriptor DesA = I->second;
4483 InterleaveGroup *Group = getInterleaveGroup(A);
4485 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4486 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4489 if (A->mayWriteToMemory())
4490 StoreGroups.insert(Group);
4492 for (auto II = std::next(I); II != E; ++II) {
4493 Instruction *B = II->first;
4494 StrideDescriptor DesB = II->second;
4496 // Ignore if B is already in a group or B is a different memory operation.
4497 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4500 // Check the rule 1 and 2.
4501 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4504 // Calculate the distance and prepare for the rule 3.
4505 const SCEVConstant *DistToA =
4506 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4510 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4512 // Skip if the distance is not multiple of size as they are not in the
4514 if (DistanceToA % static_cast<int>(DesA.Size))
4517 // The index of B is the index of A plus the related index to A.
4519 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4521 // Try to insert B into the group.
4522 if (Group->insertMember(B, IndexB, DesB.Align)) {
4523 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4524 << " into the interleave group with" << *A << '\n');
4525 InterleaveGroupMap[B] = Group;
4527 // Set the first load in program order as the insert position.
4528 if (B->mayReadFromMemory())
4529 Group->setInsertPos(B);
4531 } // Iteration on instruction B
4532 } // Iteration on instruction A
4534 // Remove interleaved store groups with gaps.
4535 for (InterleaveGroup *Group : StoreGroups)
4536 if (Group->getNumMembers() != Group->getFactor())
4537 releaseGroup(Group);
4540 LoopVectorizationCostModel::VectorizationFactor
4541 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4542 // Width 1 means no vectorize
4543 VectorizationFactor Factor = { 1U, 0U };
4544 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4545 emitAnalysis(VectorizationReport() <<
4546 "runtime pointer checks needed. Enable vectorization of this "
4547 "loop with '#pragma clang loop vectorize(enable)' when "
4548 "compiling with -Os/-Oz");
4550 "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4554 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4555 emitAnalysis(VectorizationReport() <<
4556 "store that is conditionally executed prevents vectorization");
4557 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4561 // Find the trip count.
4562 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4563 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4565 unsigned WidestType = getWidestType();
4566 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4567 unsigned MaxSafeDepDist = -1U;
4568 if (Legal->getMaxSafeDepDistBytes() != -1U)
4569 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4570 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4571 WidestRegister : MaxSafeDepDist);
4572 unsigned MaxVectorSize = WidestRegister / WidestType;
4573 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4574 DEBUG(dbgs() << "LV: The Widest register is: "
4575 << WidestRegister << " bits.\n");
4577 if (MaxVectorSize == 0) {
4578 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4582 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4583 " into one vector!");
4585 unsigned VF = MaxVectorSize;
4587 // If we optimize the program for size, avoid creating the tail loop.
4589 // If we are unable to calculate the trip count then don't try to vectorize.
4592 (VectorizationReport() <<
4593 "unable to calculate the loop count due to complex control flow");
4594 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4598 // Find the maximum SIMD width that can fit within the trip count.
4599 VF = TC % MaxVectorSize;
4604 // If the trip count that we found modulo the vectorization factor is not
4605 // zero then we require a tail.
4606 emitAnalysis(VectorizationReport() <<
4607 "cannot optimize for size and vectorize at the "
4608 "same time. Enable vectorization of this loop "
4609 "with '#pragma clang loop vectorize(enable)' "
4610 "when compiling with -Os/-Oz");
4611 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4616 int UserVF = Hints->getWidth();
4618 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4619 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4621 Factor.Width = UserVF;
4625 float Cost = expectedCost(1);
4627 const float ScalarCost = Cost;
4630 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4632 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4633 // Ignore scalar width, because the user explicitly wants vectorization.
4634 if (ForceVectorization && VF > 1) {
4636 Cost = expectedCost(Width) / (float)Width;
4639 for (unsigned i=2; i <= VF; i*=2) {
4640 // Notice that the vector loop needs to be executed less times, so
4641 // we need to divide the cost of the vector loops by the width of
4642 // the vector elements.
4643 float VectorCost = expectedCost(i) / (float)i;
4644 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4645 (int)VectorCost << ".\n");
4646 if (VectorCost < Cost) {
4652 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4653 << "LV: Vectorization seems to be not beneficial, "
4654 << "but was forced by a user.\n");
4655 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4656 Factor.Width = Width;
4657 Factor.Cost = Width * Cost;
4661 unsigned LoopVectorizationCostModel::getWidestType() {
4662 unsigned MaxWidth = 8;
4663 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4666 for (Loop::block_iterator bb = TheLoop->block_begin(),
4667 be = TheLoop->block_end(); bb != be; ++bb) {
4668 BasicBlock *BB = *bb;
4670 // For each instruction in the loop.
4671 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4672 Type *T = it->getType();
4674 // Skip ignored values.
4675 if (ValuesToIgnore.count(it))
4678 // Only examine Loads, Stores and PHINodes.
4679 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4682 // Examine PHI nodes that are reduction variables. Update the type to
4683 // account for the recurrence type.
4684 if (PHINode *PN = dyn_cast<PHINode>(it)) {
4685 if (!Legal->getReductionVars()->count(PN))
4687 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4688 T = RdxDesc.getRecurrenceType();
4691 // Examine the stored values.
4692 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4693 T = ST->getValueOperand()->getType();
4695 // Ignore loaded pointer types and stored pointer types that are not
4696 // consecutive. However, we do want to take consecutive stores/loads of
4697 // pointer vectors into account.
4698 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4701 MaxWidth = std::max(MaxWidth,
4702 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4709 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4711 unsigned LoopCost) {
4713 // -- The interleave heuristics --
4714 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4715 // There are many micro-architectural considerations that we can't predict
4716 // at this level. For example, frontend pressure (on decode or fetch) due to
4717 // code size, or the number and capabilities of the execution ports.
4719 // We use the following heuristics to select the interleave count:
4720 // 1. If the code has reductions, then we interleave to break the cross
4721 // iteration dependency.
4722 // 2. If the loop is really small, then we interleave to reduce the loop
4724 // 3. We don't interleave if we think that we will spill registers to memory
4725 // due to the increased register pressure.
4727 // When we optimize for size, we don't interleave.
4731 // We used the distance for the interleave count.
4732 if (Legal->getMaxSafeDepDistBytes() != -1U)
4735 // Do not interleave loops with a relatively small trip count.
4736 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4737 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4740 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4741 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4745 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4746 TargetNumRegisters = ForceTargetNumScalarRegs;
4748 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4749 TargetNumRegisters = ForceTargetNumVectorRegs;
4752 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4753 // We divide by these constants so assume that we have at least one
4754 // instruction that uses at least one register.
4755 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4756 R.NumInstructions = std::max(R.NumInstructions, 1U);
4758 // We calculate the interleave count using the following formula.
4759 // Subtract the number of loop invariants from the number of available
4760 // registers. These registers are used by all of the interleaved instances.
4761 // Next, divide the remaining registers by the number of registers that is
4762 // required by the loop, in order to estimate how many parallel instances
4763 // fit without causing spills. All of this is rounded down if necessary to be
4764 // a power of two. We want power of two interleave count to simplify any
4765 // addressing operations or alignment considerations.
4766 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4769 // Don't count the induction variable as interleaved.
4770 if (EnableIndVarRegisterHeur)
4771 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4772 std::max(1U, (R.MaxLocalUsers - 1)));
4774 // Clamp the interleave ranges to reasonable counts.
4775 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4777 // Check if the user has overridden the max.
4779 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4780 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4782 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4783 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4786 // If we did not calculate the cost for VF (because the user selected the VF)
4787 // then we calculate the cost of VF here.
4789 LoopCost = expectedCost(VF);
4791 // Clamp the calculated IC to be between the 1 and the max interleave count
4792 // that the target allows.
4793 if (IC > MaxInterleaveCount)
4794 IC = MaxInterleaveCount;
4798 // Interleave if we vectorized this loop and there is a reduction that could
4799 // benefit from interleaving.
4800 if (VF > 1 && Legal->getReductionVars()->size()) {
4801 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4805 // Note that if we've already vectorized the loop we will have done the
4806 // runtime check and so interleaving won't require further checks.
4807 bool InterleavingRequiresRuntimePointerCheck =
4808 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4810 // We want to interleave small loops in order to reduce the loop overhead and
4811 // potentially expose ILP opportunities.
4812 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4813 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4814 // We assume that the cost overhead is 1 and we use the cost model
4815 // to estimate the cost of the loop and interleave until the cost of the
4816 // loop overhead is about 5% of the cost of the loop.
4818 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4820 // Interleave until store/load ports (estimated by max interleave count) are
4822 unsigned NumStores = Legal->getNumStores();
4823 unsigned NumLoads = Legal->getNumLoads();
4824 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4825 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4827 // If we have a scalar reduction (vector reductions are already dealt with
4828 // by this point), we can increase the critical path length if the loop
4829 // we're interleaving is inside another loop. Limit, by default to 2, so the
4830 // critical path only gets increased by one reduction operation.
4831 if (Legal->getReductionVars()->size() &&
4832 TheLoop->getLoopDepth() > 1) {
4833 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4834 SmallIC = std::min(SmallIC, F);
4835 StoresIC = std::min(StoresIC, F);
4836 LoadsIC = std::min(LoadsIC, F);
4839 if (EnableLoadStoreRuntimeInterleave &&
4840 std::max(StoresIC, LoadsIC) > SmallIC) {
4841 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4842 return std::max(StoresIC, LoadsIC);
4845 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4849 // Interleave if this is a large loop (small loops are already dealt with by
4851 // point) that could benefit from interleaving.
4852 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4853 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4854 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4858 DEBUG(dbgs() << "LV: Not Interleaving.\n");
4862 LoopVectorizationCostModel::RegisterUsage
4863 LoopVectorizationCostModel::calculateRegisterUsage() {
4864 // This function calculates the register usage by measuring the highest number
4865 // of values that are alive at a single location. Obviously, this is a very
4866 // rough estimation. We scan the loop in a topological order in order and
4867 // assign a number to each instruction. We use RPO to ensure that defs are
4868 // met before their users. We assume that each instruction that has in-loop
4869 // users starts an interval. We record every time that an in-loop value is
4870 // used, so we have a list of the first and last occurrences of each
4871 // instruction. Next, we transpose this data structure into a multi map that
4872 // holds the list of intervals that *end* at a specific location. This multi
4873 // map allows us to perform a linear search. We scan the instructions linearly
4874 // and record each time that a new interval starts, by placing it in a set.
4875 // If we find this value in the multi-map then we remove it from the set.
4876 // The max register usage is the maximum size of the set.
4877 // We also search for instructions that are defined outside the loop, but are
4878 // used inside the loop. We need this number separately from the max-interval
4879 // usage number because when we unroll, loop-invariant values do not take
4881 LoopBlocksDFS DFS(TheLoop);
4885 R.NumInstructions = 0;
4887 // Each 'key' in the map opens a new interval. The values
4888 // of the map are the index of the 'last seen' usage of the
4889 // instruction that is the key.
4890 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4891 // Maps instruction to its index.
4892 DenseMap<unsigned, Instruction*> IdxToInstr;
4893 // Marks the end of each interval.
4894 IntervalMap EndPoint;
4895 // Saves the list of instruction indices that are used in the loop.
4896 SmallSet<Instruction*, 8> Ends;
4897 // Saves the list of values that are used in the loop but are
4898 // defined outside the loop, such as arguments and constants.
4899 SmallPtrSet<Value*, 8> LoopInvariants;
4902 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4903 be = DFS.endRPO(); bb != be; ++bb) {
4904 R.NumInstructions += (*bb)->size();
4905 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4907 Instruction *I = it;
4908 IdxToInstr[Index++] = I;
4910 // Save the end location of each USE.
4911 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4912 Value *U = I->getOperand(i);
4913 Instruction *Instr = dyn_cast<Instruction>(U);
4915 // Ignore non-instruction values such as arguments, constants, etc.
4916 if (!Instr) continue;
4918 // If this instruction is outside the loop then record it and continue.
4919 if (!TheLoop->contains(Instr)) {
4920 LoopInvariants.insert(Instr);
4924 // Overwrite previous end points.
4925 EndPoint[Instr] = Index;
4931 // Saves the list of intervals that end with the index in 'key'.
4932 typedef SmallVector<Instruction*, 2> InstrList;
4933 DenseMap<unsigned, InstrList> TransposeEnds;
4935 // Transpose the EndPoints to a list of values that end at each index.
4936 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4938 TransposeEnds[it->second].push_back(it->first);
4940 SmallSet<Instruction*, 8> OpenIntervals;
4941 unsigned MaxUsage = 0;
4944 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4945 for (unsigned int i = 0; i < Index; ++i) {
4946 Instruction *I = IdxToInstr[i];
4947 // Ignore instructions that are never used within the loop.
4948 if (!Ends.count(I)) continue;
4950 // Skip ignored values.
4951 if (ValuesToIgnore.count(I))
4954 // Remove all of the instructions that end at this location.
4955 InstrList &List = TransposeEnds[i];
4956 for (unsigned int j=0, e = List.size(); j < e; ++j)
4957 OpenIntervals.erase(List[j]);
4959 // Count the number of live interals.
4960 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4962 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4963 OpenIntervals.size() << '\n');
4965 // Add the current instruction to the list of open intervals.
4966 OpenIntervals.insert(I);
4969 unsigned Invariant = LoopInvariants.size();
4970 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4971 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4972 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4974 R.LoopInvariantRegs = Invariant;
4975 R.MaxLocalUsers = MaxUsage;
4979 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4983 for (Loop::block_iterator bb = TheLoop->block_begin(),
4984 be = TheLoop->block_end(); bb != be; ++bb) {
4985 unsigned BlockCost = 0;
4986 BasicBlock *BB = *bb;
4988 // For each instruction in the old loop.
4989 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4990 // Skip dbg intrinsics.
4991 if (isa<DbgInfoIntrinsic>(it))
4994 // Skip ignored values.
4995 if (ValuesToIgnore.count(it))
4998 unsigned C = getInstructionCost(it, VF);
5000 // Check if we should override the cost.
5001 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5002 C = ForceTargetInstructionCost;
5005 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5006 VF << " For instruction: " << *it << '\n');
5009 // We assume that if-converted blocks have a 50% chance of being executed.
5010 // When the code is scalar then some of the blocks are avoided due to CF.
5011 // When the code is vectorized we execute all code paths.
5012 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5021 /// \brief Check whether the address computation for a non-consecutive memory
5022 /// access looks like an unlikely candidate for being merged into the indexing
5025 /// We look for a GEP which has one index that is an induction variable and all
5026 /// other indices are loop invariant. If the stride of this access is also
5027 /// within a small bound we decide that this address computation can likely be
5028 /// merged into the addressing mode.
5029 /// In all other cases, we identify the address computation as complex.
5030 static bool isLikelyComplexAddressComputation(Value *Ptr,
5031 LoopVectorizationLegality *Legal,
5032 ScalarEvolution *SE,
5033 const Loop *TheLoop) {
5034 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5038 // We are looking for a gep with all loop invariant indices except for one
5039 // which should be an induction variable.
5040 unsigned NumOperands = Gep->getNumOperands();
5041 for (unsigned i = 1; i < NumOperands; ++i) {
5042 Value *Opd = Gep->getOperand(i);
5043 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5044 !Legal->isInductionVariable(Opd))
5048 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5049 // can likely be merged into the address computation.
5050 unsigned MaxMergeDistance = 64;
5052 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5056 // Check the step is constant.
5057 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5058 // Calculate the pointer stride and check if it is consecutive.
5059 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5063 const APInt &APStepVal = C->getValue()->getValue();
5065 // Huge step value - give up.
5066 if (APStepVal.getBitWidth() > 64)
5069 int64_t StepVal = APStepVal.getSExtValue();
5071 return StepVal > MaxMergeDistance;
5074 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5075 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5081 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5082 // If we know that this instruction will remain uniform, check the cost of
5083 // the scalar version.
5084 if (Legal->isUniformAfterVectorization(I))
5087 Type *RetTy = I->getType();
5088 Type *VectorTy = ToVectorTy(RetTy, VF);
5090 // TODO: We need to estimate the cost of intrinsic calls.
5091 switch (I->getOpcode()) {
5092 case Instruction::GetElementPtr:
5093 // We mark this instruction as zero-cost because the cost of GEPs in
5094 // vectorized code depends on whether the corresponding memory instruction
5095 // is scalarized or not. Therefore, we handle GEPs with the memory
5096 // instruction cost.
5098 case Instruction::Br: {
5099 return TTI.getCFInstrCost(I->getOpcode());
5101 case Instruction::PHI:
5102 //TODO: IF-converted IFs become selects.
5104 case Instruction::Add:
5105 case Instruction::FAdd:
5106 case Instruction::Sub:
5107 case Instruction::FSub:
5108 case Instruction::Mul:
5109 case Instruction::FMul:
5110 case Instruction::UDiv:
5111 case Instruction::SDiv:
5112 case Instruction::FDiv:
5113 case Instruction::URem:
5114 case Instruction::SRem:
5115 case Instruction::FRem:
5116 case Instruction::Shl:
5117 case Instruction::LShr:
5118 case Instruction::AShr:
5119 case Instruction::And:
5120 case Instruction::Or:
5121 case Instruction::Xor: {
5122 // Since we will replace the stride by 1 the multiplication should go away.
5123 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5125 // Certain instructions can be cheaper to vectorize if they have a constant
5126 // second vector operand. One example of this are shifts on x86.
5127 TargetTransformInfo::OperandValueKind Op1VK =
5128 TargetTransformInfo::OK_AnyValue;
5129 TargetTransformInfo::OperandValueKind Op2VK =
5130 TargetTransformInfo::OK_AnyValue;
5131 TargetTransformInfo::OperandValueProperties Op1VP =
5132 TargetTransformInfo::OP_None;
5133 TargetTransformInfo::OperandValueProperties Op2VP =
5134 TargetTransformInfo::OP_None;
5135 Value *Op2 = I->getOperand(1);
5137 // Check for a splat of a constant or for a non uniform vector of constants.
5138 if (isa<ConstantInt>(Op2)) {
5139 ConstantInt *CInt = cast<ConstantInt>(Op2);
5140 if (CInt && CInt->getValue().isPowerOf2())
5141 Op2VP = TargetTransformInfo::OP_PowerOf2;
5142 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5143 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5144 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5145 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5147 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5148 if (CInt && CInt->getValue().isPowerOf2())
5149 Op2VP = TargetTransformInfo::OP_PowerOf2;
5150 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5154 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5157 case Instruction::Select: {
5158 SelectInst *SI = cast<SelectInst>(I);
5159 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5160 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5161 Type *CondTy = SI->getCondition()->getType();
5163 CondTy = VectorType::get(CondTy, VF);
5165 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5167 case Instruction::ICmp:
5168 case Instruction::FCmp: {
5169 Type *ValTy = I->getOperand(0)->getType();
5170 VectorTy = ToVectorTy(ValTy, VF);
5171 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5173 case Instruction::Store:
5174 case Instruction::Load: {
5175 StoreInst *SI = dyn_cast<StoreInst>(I);
5176 LoadInst *LI = dyn_cast<LoadInst>(I);
5177 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5179 VectorTy = ToVectorTy(ValTy, VF);
5181 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5182 unsigned AS = SI ? SI->getPointerAddressSpace() :
5183 LI->getPointerAddressSpace();
5184 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5185 // We add the cost of address computation here instead of with the gep
5186 // instruction because only here we know whether the operation is
5189 return TTI.getAddressComputationCost(VectorTy) +
5190 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5192 // For an interleaved access, calculate the total cost of the whole
5193 // interleave group.
5194 if (Legal->isAccessInterleaved(I)) {
5195 auto Group = Legal->getInterleavedAccessGroup(I);
5196 assert(Group && "Fail to get an interleaved access group.");
5198 // Only calculate the cost once at the insert position.
5199 if (Group->getInsertPos() != I)
5202 unsigned InterleaveFactor = Group->getFactor();
5204 VectorType::get(VectorTy->getVectorElementType(),
5205 VectorTy->getVectorNumElements() * InterleaveFactor);
5207 // Holds the indices of existing members in an interleaved load group.
5208 // An interleaved store group doesn't need this as it dones't allow gaps.
5209 SmallVector<unsigned, 4> Indices;
5211 for (unsigned i = 0; i < InterleaveFactor; i++)
5212 if (Group->getMember(i))
5213 Indices.push_back(i);
5216 // Calculate the cost of the whole interleaved group.
5217 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5218 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5219 Group->getAlignment(), AS);
5221 if (Group->isReverse())
5223 Group->getNumMembers() *
5224 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5226 // FIXME: The interleaved load group with a huge gap could be even more
5227 // expensive than scalar operations. Then we could ignore such group and
5228 // use scalar operations instead.
5232 // Scalarized loads/stores.
5233 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5234 bool Reverse = ConsecutiveStride < 0;
5235 const DataLayout &DL = I->getModule()->getDataLayout();
5236 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5237 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5238 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5239 bool IsComplexComputation =
5240 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5242 // The cost of extracting from the value vector and pointer vector.
5243 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5244 for (unsigned i = 0; i < VF; ++i) {
5245 // The cost of extracting the pointer operand.
5246 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5247 // In case of STORE, the cost of ExtractElement from the vector.
5248 // In case of LOAD, the cost of InsertElement into the returned
5250 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5251 Instruction::InsertElement,
5255 // The cost of the scalar loads/stores.
5256 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5257 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5262 // Wide load/stores.
5263 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5264 if (Legal->isMaskRequired(I))
5265 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5268 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5271 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5275 case Instruction::ZExt:
5276 case Instruction::SExt:
5277 case Instruction::FPToUI:
5278 case Instruction::FPToSI:
5279 case Instruction::FPExt:
5280 case Instruction::PtrToInt:
5281 case Instruction::IntToPtr:
5282 case Instruction::SIToFP:
5283 case Instruction::UIToFP:
5284 case Instruction::Trunc:
5285 case Instruction::FPTrunc:
5286 case Instruction::BitCast: {
5287 // We optimize the truncation of induction variable.
5288 // The cost of these is the same as the scalar operation.
5289 if (I->getOpcode() == Instruction::Trunc &&
5290 Legal->isInductionVariable(I->getOperand(0)))
5291 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5292 I->getOperand(0)->getType());
5294 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5295 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5297 case Instruction::Call: {
5298 bool NeedToScalarize;
5299 CallInst *CI = cast<CallInst>(I);
5300 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5301 if (getIntrinsicIDForCall(CI, TLI))
5302 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5306 // We are scalarizing the instruction. Return the cost of the scalar
5307 // instruction, plus the cost of insert and extract into vector
5308 // elements, times the vector width.
5311 if (!RetTy->isVoidTy() && VF != 1) {
5312 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5314 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5317 // The cost of inserting the results plus extracting each one of the
5319 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5322 // The cost of executing VF copies of the scalar instruction. This opcode
5323 // is unknown. Assume that it is the same as 'mul'.
5324 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5330 char LoopVectorize::ID = 0;
5331 static const char lv_name[] = "Loop Vectorization";
5332 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5333 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5334 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
5335 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5336 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
5337 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5338 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5339 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5340 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5341 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5342 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5343 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5344 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5345 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5348 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5349 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5353 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5354 // Check for a store.
5355 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5356 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5358 // Check for a load.
5359 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5360 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5366 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5367 bool IfPredicateStore) {
5368 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5369 // Holds vector parameters or scalars, in case of uniform vals.
5370 SmallVector<VectorParts, 4> Params;
5372 setDebugLocFromInst(Builder, Instr);
5374 // Find all of the vectorized parameters.
5375 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5376 Value *SrcOp = Instr->getOperand(op);
5378 // If we are accessing the old induction variable, use the new one.
5379 if (SrcOp == OldInduction) {
5380 Params.push_back(getVectorValue(SrcOp));
5384 // Try using previously calculated values.
5385 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5387 // If the src is an instruction that appeared earlier in the basic block
5388 // then it should already be vectorized.
5389 if (SrcInst && OrigLoop->contains(SrcInst)) {
5390 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5391 // The parameter is a vector value from earlier.
5392 Params.push_back(WidenMap.get(SrcInst));
5394 // The parameter is a scalar from outside the loop. Maybe even a constant.
5395 VectorParts Scalars;
5396 Scalars.append(UF, SrcOp);
5397 Params.push_back(Scalars);
5401 assert(Params.size() == Instr->getNumOperands() &&
5402 "Invalid number of operands");
5404 // Does this instruction return a value ?
5405 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5407 Value *UndefVec = IsVoidRetTy ? nullptr :
5408 UndefValue::get(Instr->getType());
5409 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5410 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5413 if (IfPredicateStore) {
5414 assert(Instr->getParent()->getSinglePredecessor() &&
5415 "Only support single predecessor blocks");
5416 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5417 Instr->getParent());
5420 // For each vector unroll 'part':
5421 for (unsigned Part = 0; Part < UF; ++Part) {
5422 // For each scalar that we create:
5424 // Start an "if (pred) a[i] = ..." block.
5425 Value *Cmp = nullptr;
5426 if (IfPredicateStore) {
5427 if (Cond[Part]->getType()->isVectorTy())
5429 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5430 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5431 ConstantInt::get(Cond[Part]->getType(), 1));
5434 Instruction *Cloned = Instr->clone();
5436 Cloned->setName(Instr->getName() + ".cloned");
5437 // Replace the operands of the cloned instructions with extracted scalars.
5438 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5439 Value *Op = Params[op][Part];
5440 Cloned->setOperand(op, Op);
5443 // Place the cloned scalar in the new loop.
5444 Builder.Insert(Cloned);
5446 // If the original scalar returns a value we need to place it in a vector
5447 // so that future users will be able to use it.
5449 VecResults[Part] = Cloned;
5452 if (IfPredicateStore)
5453 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
5458 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5459 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5460 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5462 return scalarizeInstruction(Instr, IfPredicateStore);
5465 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5469 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5473 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5474 // When unrolling and the VF is 1, we only need to add a simple scalar.
5475 Type *ITy = Val->getType();
5476 assert(!ITy->isVectorTy() && "Val must be a scalar");
5477 Constant *C = ConstantInt::get(ITy, StartIdx);
5478 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");