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/AliasSetTracker.h"
62 #include "llvm/Analysis/AssumptionCache.h"
63 #include "llvm/Analysis/BlockFrequencyInfo.h"
64 #include "llvm/Analysis/CodeMetrics.h"
65 #include "llvm/Analysis/LoopAccessAnalysis.h"
66 #include "llvm/Analysis/LoopInfo.h"
67 #include "llvm/Analysis/LoopIterator.h"
68 #include "llvm/Analysis/LoopPass.h"
69 #include "llvm/Analysis/ScalarEvolution.h"
70 #include "llvm/Analysis/ScalarEvolutionExpander.h"
71 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
72 #include "llvm/Analysis/TargetTransformInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfo.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/DiagnosticInfo.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/IRBuilder.h"
82 #include "llvm/IR/Instructions.h"
83 #include "llvm/IR/IntrinsicInst.h"
84 #include "llvm/IR/LLVMContext.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/Value.h"
89 #include "llvm/IR/ValueHandle.h"
90 #include "llvm/IR/Verifier.h"
91 #include "llvm/Pass.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/CommandLine.h"
94 #include "llvm/Support/Debug.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Transforms/Scalar.h"
97 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
98 #include "llvm/Transforms/Utils/Local.h"
99 #include "llvm/Analysis/VectorUtils.h"
100 #include "llvm/Transforms/Utils/LoopUtils.h"
105 using namespace llvm;
106 using namespace llvm::PatternMatch;
108 #define LV_NAME "loop-vectorize"
109 #define DEBUG_TYPE LV_NAME
111 STATISTIC(LoopsVectorized, "Number of loops vectorized");
112 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
115 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
116 cl::desc("Enable if-conversion during vectorization."));
118 /// We don't vectorize loops with a known constant trip count below this number.
119 static cl::opt<unsigned>
120 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
122 cl::desc("Don't vectorize loops with a constant "
123 "trip count that is smaller than this "
126 /// This enables versioning on the strides of symbolically striding memory
127 /// accesses in code like the following.
128 /// for (i = 0; i < N; ++i)
129 /// A[i * Stride1] += B[i * Stride2] ...
131 /// Will be roughly translated to
132 /// if (Stride1 == 1 && Stride2 == 1) {
133 /// for (i = 0; i < N; i+=4)
137 static cl::opt<bool> EnableMemAccessVersioning(
138 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
139 cl::desc("Enable symblic stride memory access versioning"));
141 static cl::opt<bool> EnableInterleavedMemAccesses(
142 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
143 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
145 /// Maximum factor for an interleaved memory access.
146 static cl::opt<unsigned> MaxInterleaveGroupFactor(
147 "max-interleave-group-factor", cl::Hidden,
148 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
151 /// We don't interleave loops with a known constant trip count below this
153 static const unsigned TinyTripCountInterleaveThreshold = 128;
155 static cl::opt<unsigned> ForceTargetNumScalarRegs(
156 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's number of scalar registers."));
159 static cl::opt<unsigned> ForceTargetNumVectorRegs(
160 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
161 cl::desc("A flag that overrides the target's number of vector registers."));
163 /// Maximum vectorization interleave count.
164 static const unsigned MaxInterleaveFactor = 16;
166 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
167 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
168 cl::desc("A flag that overrides the target's max interleave factor for "
171 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
172 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
173 cl::desc("A flag that overrides the target's max interleave factor for "
174 "vectorized loops."));
176 static cl::opt<unsigned> ForceTargetInstructionCost(
177 "force-target-instruction-cost", cl::init(0), cl::Hidden,
178 cl::desc("A flag that overrides the target's expected cost for "
179 "an instruction to a single constant value. Mostly "
180 "useful for getting consistent testing."));
182 static cl::opt<unsigned> SmallLoopCost(
183 "small-loop-cost", cl::init(20), cl::Hidden,
185 "The cost of a loop that is considered 'small' by the interleaver."));
187 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
188 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
189 cl::desc("Enable the use of the block frequency analysis to access PGO "
190 "heuristics minimizing code growth in cold regions and being more "
191 "aggressive in hot regions."));
193 // Runtime interleave loops for load/store throughput.
194 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
195 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
197 "Enable runtime interleaving until load/store ports are saturated"));
199 /// The number of stores in a loop that are allowed to need predication.
200 static cl::opt<unsigned> NumberOfStoresToPredicate(
201 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
202 cl::desc("Max number of stores to be predicated behind an if."));
204 static cl::opt<bool> EnableIndVarRegisterHeur(
205 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
206 cl::desc("Count the induction variable only once when interleaving"));
208 static cl::opt<bool> EnableCondStoresVectorization(
209 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
210 cl::desc("Enable if predication of stores during vectorization."));
212 static cl::opt<unsigned> MaxNestedScalarReductionIC(
213 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
214 cl::desc("The maximum interleave count to use when interleaving a scalar "
215 "reduction in a nested loop."));
217 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
218 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
219 cl::desc("The maximum allowed number of runtime memory checks with a "
220 "vectorize(enable) pragma."));
224 // Forward declarations.
225 class LoopVectorizeHints;
226 class LoopVectorizationLegality;
227 class LoopVectorizationCostModel;
228 class LoopVectorizationRequirements;
230 /// \brief This modifies LoopAccessReport to initialize message with
231 /// loop-vectorizer-specific part.
232 class VectorizationReport : public LoopAccessReport {
234 VectorizationReport(Instruction *I = nullptr)
235 : LoopAccessReport("loop not vectorized: ", I) {}
237 /// \brief This allows promotion of the loop-access analysis report into the
238 /// loop-vectorizer report. It modifies the message to add the
239 /// loop-vectorizer-specific part of the message.
240 explicit VectorizationReport(const LoopAccessReport &R)
241 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
245 /// A helper function for converting Scalar types to vector types.
246 /// If the incoming type is void, we return void. If the VF is 1, we return
248 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
249 if (Scalar->isVoidTy() || VF == 1)
251 return VectorType::get(Scalar, VF);
254 /// InnerLoopVectorizer vectorizes loops which contain only one basic
255 /// block to a specified vectorization factor (VF).
256 /// This class performs the widening of scalars into vectors, or multiple
257 /// scalars. This class also implements the following features:
258 /// * It inserts an epilogue loop for handling loops that don't have iteration
259 /// counts that are known to be a multiple of the vectorization factor.
260 /// * It handles the code generation for reduction variables.
261 /// * Scalarization (implementation using scalars) of un-vectorizable
263 /// InnerLoopVectorizer does not perform any vectorization-legality
264 /// checks, and relies on the caller to check for the different legality
265 /// aspects. The InnerLoopVectorizer relies on the
266 /// LoopVectorizationLegality class to provide information about the induction
267 /// and reduction variables that were found to a given vectorization factor.
268 class InnerLoopVectorizer {
270 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
271 DominatorTree *DT, const TargetLibraryInfo *TLI,
272 const TargetTransformInfo *TTI, unsigned VecWidth,
273 unsigned UnrollFactor)
274 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
275 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
276 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
277 TripCount(nullptr), VectorTripCount(nullptr), Legal(nullptr),
278 AddedSafetyChecks(false) {}
280 // Perform the actual loop widening (vectorization).
281 void vectorize(LoopVectorizationLegality *L) {
283 // Create a new empty loop. Unlink the old loop and connect the new one.
285 // Widen each instruction in the old loop to a new one in the new loop.
286 // Use the Legality module to find the induction and reduction variables.
290 // Return true if any runtime check is added.
291 bool IsSafetyChecksAdded() {
292 return AddedSafetyChecks;
295 virtual ~InnerLoopVectorizer() {}
298 /// A small list of PHINodes.
299 typedef SmallVector<PHINode*, 4> PhiVector;
300 /// When we unroll loops we have multiple vector values for each scalar.
301 /// This data structure holds the unrolled and vectorized values that
302 /// originated from one scalar instruction.
303 typedef SmallVector<Value*, 2> VectorParts;
305 // When we if-convert we need to create edge masks. We have to cache values
306 // so that we don't end up with exponential recursion/IR.
307 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
308 VectorParts> EdgeMaskCache;
310 /// \brief Add checks for strides that were assumed to be 1.
312 /// Returns the last check instruction and the first check instruction in the
313 /// pair as (first, last).
314 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
316 /// Create an empty loop, based on the loop ranges of the old loop.
317 void createEmptyLoop();
318 /// Create a new induction variable inside L.
319 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
320 Value *Step, Instruction *DL);
321 /// Copy and widen the instructions from the old loop.
322 virtual void vectorizeLoop();
324 /// \brief The Loop exit block may have single value PHI nodes where the
325 /// incoming value is 'Undef'. While vectorizing we only handled real values
326 /// that were defined inside the loop. Here we fix the 'undef case'.
330 /// A helper function that computes the predicate of the block BB, assuming
331 /// that the header block of the loop is set to True. It returns the *entry*
332 /// mask for the block BB.
333 VectorParts createBlockInMask(BasicBlock *BB);
334 /// A helper function that computes the predicate of the edge between SRC
336 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
338 /// A helper function to vectorize a single BB within the innermost loop.
339 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
341 /// Vectorize a single PHINode in a block. This method handles the induction
342 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
343 /// arbitrary length vectors.
344 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
345 unsigned UF, unsigned VF, PhiVector *PV);
347 /// Insert the new loop to the loop hierarchy and pass manager
348 /// and update the analysis passes.
349 void updateAnalysis();
351 /// This instruction is un-vectorizable. Implement it as a sequence
352 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
353 /// scalarized instruction behind an if block predicated on the control
354 /// dependence of the instruction.
355 virtual void scalarizeInstruction(Instruction *Instr,
356 bool IfPredicateStore=false);
358 /// Vectorize Load and Store instructions,
359 virtual void vectorizeMemoryInstruction(Instruction *Instr);
361 /// Create a broadcast instruction. This method generates a broadcast
362 /// instruction (shuffle) for loop invariant values and for the induction
363 /// value. If this is the induction variable then we extend it to N, N+1, ...
364 /// this is needed because each iteration in the loop corresponds to a SIMD
366 virtual Value *getBroadcastInstrs(Value *V);
368 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
369 /// to each vector element of Val. The sequence starts at StartIndex.
370 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
372 /// When we go over instructions in the basic block we rely on previous
373 /// values within the current basic block or on loop invariant values.
374 /// When we widen (vectorize) values we place them in the map. If the values
375 /// are not within the map, they have to be loop invariant, so we simply
376 /// broadcast them into a vector.
377 VectorParts &getVectorValue(Value *V);
379 /// Try to vectorize the interleaved access group that \p Instr belongs to.
380 void vectorizeInterleaveGroup(Instruction *Instr);
382 /// Generate a shuffle sequence that will reverse the vector Vec.
383 virtual Value *reverseVector(Value *Vec);
385 /// Returns (and creates if needed) the original loop trip count.
386 Value *getOrCreateTripCount(Loop *NewLoop);
388 /// Returns (and creates if needed) the trip count of the widened loop.
389 Value *getOrCreateVectorTripCount(Loop *NewLoop);
391 /// Emit a bypass check to see if the trip count would overflow, or we
392 /// wouldn't have enough iterations to execute one vector loop.
393 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
394 /// Emit a bypass check to see if the vector trip count is nonzero.
395 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
396 /// Emit bypass checks to check if strides we've assumed to be one really are.
397 void emitStrideChecks(Loop *L, BasicBlock *Bypass);
398 /// Emit bypass checks to check any memory assumptions we may have made.
399 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
401 /// This is a helper class that holds the vectorizer state. It maps scalar
402 /// instructions to vector instructions. When the code is 'unrolled' then
403 /// then a single scalar value is mapped to multiple vector parts. The parts
404 /// are stored in the VectorPart type.
406 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
408 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
410 /// \return True if 'Key' is saved in the Value Map.
411 bool has(Value *Key) const { return MapStorage.count(Key); }
413 /// Initializes a new entry in the map. Sets all of the vector parts to the
414 /// save value in 'Val'.
415 /// \return A reference to a vector with splat values.
416 VectorParts &splat(Value *Key, Value *Val) {
417 VectorParts &Entry = MapStorage[Key];
418 Entry.assign(UF, Val);
422 ///\return A reference to the value that is stored at 'Key'.
423 VectorParts &get(Value *Key) {
424 VectorParts &Entry = MapStorage[Key];
427 assert(Entry.size() == UF);
432 /// The unroll factor. Each entry in the map stores this number of vector
436 /// Map storage. We use std::map and not DenseMap because insertions to a
437 /// dense map invalidates its iterators.
438 std::map<Value *, VectorParts> MapStorage;
441 /// The original loop.
443 /// Scev analysis to use.
451 /// Target Library Info.
452 const TargetLibraryInfo *TLI;
453 /// Target Transform Info.
454 const TargetTransformInfo *TTI;
456 /// The vectorization SIMD factor to use. Each vector will have this many
461 /// The vectorization unroll factor to use. Each scalar is vectorized to this
462 /// many different vector instructions.
465 /// The builder that we use
468 // --- Vectorization state ---
470 /// The vector-loop preheader.
471 BasicBlock *LoopVectorPreHeader;
472 /// The scalar-loop preheader.
473 BasicBlock *LoopScalarPreHeader;
474 /// Middle Block between the vector and the scalar.
475 BasicBlock *LoopMiddleBlock;
476 ///The ExitBlock of the scalar loop.
477 BasicBlock *LoopExitBlock;
478 ///The vector loop body.
479 SmallVector<BasicBlock *, 4> LoopVectorBody;
480 ///The scalar loop body.
481 BasicBlock *LoopScalarBody;
482 /// A list of all bypass blocks. The first block is the entry of the loop.
483 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
485 /// The new Induction variable which was added to the new block.
487 /// The induction variable of the old basic block.
488 PHINode *OldInduction;
489 /// Maps scalars to widened vectors.
491 /// Store instructions that should be predicated, as a pair
492 /// <StoreInst, Predicate>
493 SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
494 EdgeMaskCache MaskCache;
495 /// Trip count of the original loop.
497 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
498 Value *VectorTripCount;
500 LoopVectorizationLegality *Legal;
502 // Record whether runtime check is added.
503 bool AddedSafetyChecks;
506 class InnerLoopUnroller : public InnerLoopVectorizer {
508 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
509 DominatorTree *DT, const TargetLibraryInfo *TLI,
510 const TargetTransformInfo *TTI, unsigned UnrollFactor)
511 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
514 void scalarizeInstruction(Instruction *Instr,
515 bool IfPredicateStore = false) override;
516 void vectorizeMemoryInstruction(Instruction *Instr) override;
517 Value *getBroadcastInstrs(Value *V) override;
518 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
519 Value *reverseVector(Value *Vec) override;
522 /// \brief Look for a meaningful debug location on the instruction or it's
524 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
529 if (I->getDebugLoc() != Empty)
532 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
533 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
534 if (OpInst->getDebugLoc() != Empty)
541 /// \brief Set the debug location in the builder using the debug location in the
543 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
544 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
545 B.SetCurrentDebugLocation(Inst->getDebugLoc());
547 B.SetCurrentDebugLocation(DebugLoc());
551 /// \return string containing a file name and a line # for the given loop.
552 static std::string getDebugLocString(const Loop *L) {
555 raw_string_ostream OS(Result);
556 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
557 LoopDbgLoc.print(OS);
559 // Just print the module name.
560 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
567 /// \brief Propagate known metadata from one instruction to another.
568 static void propagateMetadata(Instruction *To, const Instruction *From) {
569 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
570 From->getAllMetadataOtherThanDebugLoc(Metadata);
572 for (auto M : Metadata) {
573 unsigned Kind = M.first;
575 // These are safe to transfer (this is safe for TBAA, even when we
576 // if-convert, because should that metadata have had a control dependency
577 // on the condition, and thus actually aliased with some other
578 // non-speculated memory access when the condition was false, this would be
579 // caught by the runtime overlap checks).
580 if (Kind != LLVMContext::MD_tbaa &&
581 Kind != LLVMContext::MD_alias_scope &&
582 Kind != LLVMContext::MD_noalias &&
583 Kind != LLVMContext::MD_fpmath &&
584 Kind != LLVMContext::MD_nontemporal)
587 To->setMetadata(Kind, M.second);
591 /// \brief Propagate known metadata from one instruction to a vector of others.
592 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
594 if (Instruction *I = dyn_cast<Instruction>(V))
595 propagateMetadata(I, From);
598 /// \brief The group of interleaved loads/stores sharing the same stride and
599 /// close to each other.
601 /// Each member in this group has an index starting from 0, and the largest
602 /// index should be less than interleaved factor, which is equal to the absolute
603 /// value of the access's stride.
605 /// E.g. An interleaved load group of factor 4:
606 /// for (unsigned i = 0; i < 1024; i+=4) {
607 /// a = A[i]; // Member of index 0
608 /// b = A[i+1]; // Member of index 1
609 /// d = A[i+3]; // Member of index 3
613 /// An interleaved store group of factor 4:
614 /// for (unsigned i = 0; i < 1024; i+=4) {
616 /// A[i] = a; // Member of index 0
617 /// A[i+1] = b; // Member of index 1
618 /// A[i+2] = c; // Member of index 2
619 /// A[i+3] = d; // Member of index 3
622 /// Note: the interleaved load group could have gaps (missing members), but
623 /// the interleaved store group doesn't allow gaps.
624 class InterleaveGroup {
626 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
627 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
628 assert(Align && "The alignment should be non-zero");
630 Factor = std::abs(Stride);
631 assert(Factor > 1 && "Invalid interleave factor");
633 Reverse = Stride < 0;
637 bool isReverse() const { return Reverse; }
638 unsigned getFactor() const { return Factor; }
639 unsigned getAlignment() const { return Align; }
640 unsigned getNumMembers() const { return Members.size(); }
642 /// \brief Try to insert a new member \p Instr with index \p Index and
643 /// alignment \p NewAlign. The index is related to the leader and it could be
644 /// negative if it is the new leader.
646 /// \returns false if the instruction doesn't belong to the group.
647 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
648 assert(NewAlign && "The new member's alignment should be non-zero");
650 int Key = Index + SmallestKey;
652 // Skip if there is already a member with the same index.
653 if (Members.count(Key))
656 if (Key > LargestKey) {
657 // The largest index is always less than the interleave factor.
658 if (Index >= static_cast<int>(Factor))
662 } else if (Key < SmallestKey) {
663 // The largest index is always less than the interleave factor.
664 if (LargestKey - Key >= static_cast<int>(Factor))
670 // It's always safe to select the minimum alignment.
671 Align = std::min(Align, NewAlign);
672 Members[Key] = Instr;
676 /// \brief Get the member with the given index \p Index
678 /// \returns nullptr if contains no such member.
679 Instruction *getMember(unsigned Index) const {
680 int Key = SmallestKey + Index;
681 if (!Members.count(Key))
684 return Members.find(Key)->second;
687 /// \brief Get the index for the given member. Unlike the key in the member
688 /// map, the index starts from 0.
689 unsigned getIndex(Instruction *Instr) const {
690 for (auto I : Members)
691 if (I.second == Instr)
692 return I.first - SmallestKey;
694 llvm_unreachable("InterleaveGroup contains no such member");
697 Instruction *getInsertPos() const { return InsertPos; }
698 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
701 unsigned Factor; // Interleave Factor.
704 DenseMap<int, Instruction *> Members;
708 // To avoid breaking dependences, vectorized instructions of an interleave
709 // group should be inserted at either the first load or the last store in
712 // E.g. %even = load i32 // Insert Position
713 // %add = add i32 %even // Use of %even
717 // %odd = add i32 // Def of %odd
718 // store i32 %odd // Insert Position
719 Instruction *InsertPos;
722 /// \brief Drive the analysis of interleaved memory accesses in the loop.
724 /// Use this class to analyze interleaved accesses only when we can vectorize
725 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
726 /// on interleaved accesses is unsafe.
728 /// The analysis collects interleave groups and records the relationships
729 /// between the member and the group in a map.
730 class InterleavedAccessInfo {
732 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
733 : SE(SE), TheLoop(L), DT(DT) {}
735 ~InterleavedAccessInfo() {
736 SmallSet<InterleaveGroup *, 4> DelSet;
737 // Avoid releasing a pointer twice.
738 for (auto &I : InterleaveGroupMap)
739 DelSet.insert(I.second);
740 for (auto *Ptr : DelSet)
744 /// \brief Analyze the interleaved accesses and collect them in interleave
745 /// groups. Substitute symbolic strides using \p Strides.
746 void analyzeInterleaving(const ValueToValueMap &Strides);
748 /// \brief Check if \p Instr belongs to any interleave group.
749 bool isInterleaved(Instruction *Instr) const {
750 return InterleaveGroupMap.count(Instr);
753 /// \brief Get the interleave group that \p Instr belongs to.
755 /// \returns nullptr if doesn't have such group.
756 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
757 if (InterleaveGroupMap.count(Instr))
758 return InterleaveGroupMap.find(Instr)->second;
767 /// Holds the relationships between the members and the interleave group.
768 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
770 /// \brief The descriptor for a strided memory access.
771 struct StrideDescriptor {
772 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
774 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
776 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
778 int Stride; // The access's stride. It is negative for a reverse access.
779 const SCEV *Scev; // The scalar expression of this access
780 unsigned Size; // The size of the memory object.
781 unsigned Align; // The alignment of this access.
784 /// \brief Create a new interleave group with the given instruction \p Instr,
785 /// stride \p Stride and alignment \p Align.
787 /// \returns the newly created interleave group.
788 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
790 assert(!InterleaveGroupMap.count(Instr) &&
791 "Already in an interleaved access group");
792 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
793 return InterleaveGroupMap[Instr];
796 /// \brief Release the group and remove all the relationships.
797 void releaseGroup(InterleaveGroup *Group) {
798 for (unsigned i = 0; i < Group->getFactor(); i++)
799 if (Instruction *Member = Group->getMember(i))
800 InterleaveGroupMap.erase(Member);
805 /// \brief Collect all the accesses with a constant stride in program order.
806 void collectConstStridedAccesses(
807 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
808 const ValueToValueMap &Strides);
811 /// Utility class for getting and setting loop vectorizer hints in the form
812 /// of loop metadata.
813 /// This class keeps a number of loop annotations locally (as member variables)
814 /// and can, upon request, write them back as metadata on the loop. It will
815 /// initially scan the loop for existing metadata, and will update the local
816 /// values based on information in the loop.
817 /// We cannot write all values to metadata, as the mere presence of some info,
818 /// for example 'force', means a decision has been made. So, we need to be
819 /// careful NOT to add them if the user hasn't specifically asked so.
820 class LoopVectorizeHints {
827 /// Hint - associates name and validation with the hint value.
830 unsigned Value; // This may have to change for non-numeric values.
833 Hint(const char * Name, unsigned Value, HintKind Kind)
834 : Name(Name), Value(Value), Kind(Kind) { }
836 bool validate(unsigned Val) {
839 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
841 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
849 /// Vectorization width.
851 /// Vectorization interleave factor.
853 /// Vectorization forced
856 /// Return the loop metadata prefix.
857 static StringRef Prefix() { return "llvm.loop."; }
861 FK_Undefined = -1, ///< Not selected.
862 FK_Disabled = 0, ///< Forcing disabled.
863 FK_Enabled = 1, ///< Forcing enabled.
866 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
867 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
869 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
870 Force("vectorize.enable", FK_Undefined, HK_FORCE),
872 // Populate values with existing loop metadata.
873 getHintsFromMetadata();
875 // force-vector-interleave overrides DisableInterleaving.
876 if (VectorizerParams::isInterleaveForced())
877 Interleave.Value = VectorizerParams::VectorizationInterleave;
879 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
880 << "LV: Interleaving disabled by the pass manager\n");
883 /// Mark the loop L as already vectorized by setting the width to 1.
884 void setAlreadyVectorized() {
885 Width.Value = Interleave.Value = 1;
886 Hint Hints[] = {Width, Interleave};
887 writeHintsToMetadata(Hints);
890 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
891 if (getForce() == LoopVectorizeHints::FK_Disabled) {
892 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
893 emitOptimizationRemarkAnalysis(F->getContext(),
894 vectorizeAnalysisPassName(), *F,
895 L->getStartLoc(), emitRemark());
899 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
900 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
901 emitOptimizationRemarkAnalysis(F->getContext(),
902 vectorizeAnalysisPassName(), *F,
903 L->getStartLoc(), emitRemark());
907 if (getWidth() == 1 && getInterleave() == 1) {
908 // FIXME: Add a separate metadata to indicate when the loop has already
909 // been vectorized instead of setting width and count to 1.
910 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
911 // FIXME: Add interleave.disable metadata. This will allow
912 // vectorize.disable to be used without disabling the pass and errors
913 // to differentiate between disabled vectorization and a width of 1.
914 emitOptimizationRemarkAnalysis(
915 F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
916 "loop not vectorized: vectorization and interleaving are explicitly "
917 "disabled, or vectorize width and interleave count are both set to "
925 /// Dumps all the hint information.
926 std::string emitRemark() const {
927 VectorizationReport R;
928 if (Force.Value == LoopVectorizeHints::FK_Disabled)
929 R << "vectorization is explicitly disabled";
931 R << "use -Rpass-analysis=loop-vectorize for more info";
932 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
934 if (Width.Value != 0)
935 R << ", Vector Width=" << Width.Value;
936 if (Interleave.Value != 0)
937 R << ", Interleave Count=" << Interleave.Value;
945 unsigned getWidth() const { return Width.Value; }
946 unsigned getInterleave() const { return Interleave.Value; }
947 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
948 const char *vectorizeAnalysisPassName() const {
949 // If hints are provided that don't disable vectorization use the
950 // AlwaysPrint pass name to force the frontend to print the diagnostic.
953 if (getForce() == LoopVectorizeHints::FK_Disabled)
955 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
957 return DiagnosticInfo::AlwaysPrint;
960 bool allowReordering() const {
961 // When enabling loop hints are provided we allow the vectorizer to change
962 // the order of operations that is given by the scalar loop. This is not
963 // enabled by default because can be unsafe or inefficient. For example,
964 // reordering floating-point operations will change the way round-off
965 // error accumulates in the loop.
966 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
970 /// Find hints specified in the loop metadata and update local values.
971 void getHintsFromMetadata() {
972 MDNode *LoopID = TheLoop->getLoopID();
976 // First operand should refer to the loop id itself.
977 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
978 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
980 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
981 const MDString *S = nullptr;
982 SmallVector<Metadata *, 4> Args;
984 // The expected hint is either a MDString or a MDNode with the first
985 // operand a MDString.
986 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
987 if (!MD || MD->getNumOperands() == 0)
989 S = dyn_cast<MDString>(MD->getOperand(0));
990 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
991 Args.push_back(MD->getOperand(i));
993 S = dyn_cast<MDString>(LoopID->getOperand(i));
994 assert(Args.size() == 0 && "too many arguments for MDString");
1000 // Check if the hint starts with the loop metadata prefix.
1001 StringRef Name = S->getString();
1002 if (Args.size() == 1)
1003 setHint(Name, Args[0]);
1007 /// Checks string hint with one operand and set value if valid.
1008 void setHint(StringRef Name, Metadata *Arg) {
1009 if (!Name.startswith(Prefix()))
1011 Name = Name.substr(Prefix().size(), StringRef::npos);
1013 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1015 unsigned Val = C->getZExtValue();
1017 Hint *Hints[] = {&Width, &Interleave, &Force};
1018 for (auto H : Hints) {
1019 if (Name == H->Name) {
1020 if (H->validate(Val))
1023 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1029 /// Create a new hint from name / value pair.
1030 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1031 LLVMContext &Context = TheLoop->getHeader()->getContext();
1032 Metadata *MDs[] = {MDString::get(Context, Name),
1033 ConstantAsMetadata::get(
1034 ConstantInt::get(Type::getInt32Ty(Context), V))};
1035 return MDNode::get(Context, MDs);
1038 /// Matches metadata with hint name.
1039 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1040 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1044 for (auto H : HintTypes)
1045 if (Name->getString().endswith(H.Name))
1050 /// Sets current hints into loop metadata, keeping other values intact.
1051 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1052 if (HintTypes.size() == 0)
1055 // Reserve the first element to LoopID (see below).
1056 SmallVector<Metadata *, 4> MDs(1);
1057 // If the loop already has metadata, then ignore the existing operands.
1058 MDNode *LoopID = TheLoop->getLoopID();
1060 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1061 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1062 // If node in update list, ignore old value.
1063 if (!matchesHintMetadataName(Node, HintTypes))
1064 MDs.push_back(Node);
1068 // Now, add the missing hints.
1069 for (auto H : HintTypes)
1070 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1072 // Replace current metadata node with new one.
1073 LLVMContext &Context = TheLoop->getHeader()->getContext();
1074 MDNode *NewLoopID = MDNode::get(Context, MDs);
1075 // Set operand 0 to refer to the loop id itself.
1076 NewLoopID->replaceOperandWith(0, NewLoopID);
1078 TheLoop->setLoopID(NewLoopID);
1081 /// The loop these hints belong to.
1082 const Loop *TheLoop;
1085 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1086 const LoopVectorizeHints &Hints,
1087 const LoopAccessReport &Message) {
1088 const char *Name = Hints.vectorizeAnalysisPassName();
1089 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1092 static void emitMissedWarning(Function *F, Loop *L,
1093 const LoopVectorizeHints &LH) {
1094 emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1097 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1098 if (LH.getWidth() != 1)
1099 emitLoopVectorizeWarning(
1100 F->getContext(), *F, L->getStartLoc(),
1101 "failed explicitly specified loop vectorization");
1102 else if (LH.getInterleave() != 1)
1103 emitLoopInterleaveWarning(
1104 F->getContext(), *F, L->getStartLoc(),
1105 "failed explicitly specified loop interleaving");
1109 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1110 /// to what vectorization factor.
1111 /// This class does not look at the profitability of vectorization, only the
1112 /// legality. This class has two main kinds of checks:
1113 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1114 /// will change the order of memory accesses in a way that will change the
1115 /// correctness of the program.
1116 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1117 /// checks for a number of different conditions, such as the availability of a
1118 /// single induction variable, that all types are supported and vectorize-able,
1119 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1120 /// This class is also used by InnerLoopVectorizer for identifying
1121 /// induction variable and the different reduction variables.
1122 class LoopVectorizationLegality {
1124 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1125 TargetLibraryInfo *TLI, AliasAnalysis *AA,
1126 Function *F, const TargetTransformInfo *TTI,
1127 LoopAccessAnalysis *LAA,
1128 LoopVectorizationRequirements *R,
1129 const LoopVectorizeHints *H)
1130 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
1131 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
1132 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
1133 Requirements(R), Hints(H) {}
1135 /// ReductionList contains the reduction descriptors for all
1136 /// of the reductions that were found in the loop.
1137 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1139 /// InductionList saves induction variables and maps them to the
1140 /// induction descriptor.
1141 typedef MapVector<PHINode*, InductionDescriptor> InductionList;
1143 /// Returns true if it is legal to vectorize this loop.
1144 /// This does not mean that it is profitable to vectorize this
1145 /// loop, only that it is legal to do so.
1146 bool canVectorize();
1148 /// Returns the Induction variable.
1149 PHINode *getInduction() { return Induction; }
1151 /// Returns the reduction variables found in the loop.
1152 ReductionList *getReductionVars() { return &Reductions; }
1154 /// Returns the induction variables found in the loop.
1155 InductionList *getInductionVars() { return &Inductions; }
1157 /// Returns the widest induction type.
1158 Type *getWidestInductionType() { return WidestIndTy; }
1160 /// Returns True if V is an induction variable in this loop.
1161 bool isInductionVariable(const Value *V);
1163 /// Return true if the block BB needs to be predicated in order for the loop
1164 /// to be vectorized.
1165 bool blockNeedsPredication(BasicBlock *BB);
1167 /// Check if this pointer is consecutive when vectorizing. This happens
1168 /// when the last index of the GEP is the induction variable, or that the
1169 /// pointer itself is an induction variable.
1170 /// This check allows us to vectorize A[idx] into a wide load/store.
1172 /// 0 - Stride is unknown or non-consecutive.
1173 /// 1 - Address is consecutive.
1174 /// -1 - Address is consecutive, and decreasing.
1175 int isConsecutivePtr(Value *Ptr);
1177 /// Returns true if the value V is uniform within the loop.
1178 bool isUniform(Value *V);
1180 /// Returns true if this instruction will remain scalar after vectorization.
1181 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
1183 /// Returns the information that we collected about runtime memory check.
1184 const RuntimePointerChecking *getRuntimePointerChecking() const {
1185 return LAI->getRuntimePointerChecking();
1188 const LoopAccessInfo *getLAI() const {
1192 /// \brief Check if \p Instr belongs to any interleaved access group.
1193 bool isAccessInterleaved(Instruction *Instr) {
1194 return InterleaveInfo.isInterleaved(Instr);
1197 /// \brief Get the interleaved access group that \p Instr belongs to.
1198 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1199 return InterleaveInfo.getInterleaveGroup(Instr);
1202 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1204 bool hasStride(Value *V) { return StrideSet.count(V); }
1205 bool mustCheckStrides() { return !StrideSet.empty(); }
1206 SmallPtrSet<Value *, 8>::iterator strides_begin() {
1207 return StrideSet.begin();
1209 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
1211 /// Returns true if the target machine supports masked store operation
1212 /// for the given \p DataType and kind of access to \p Ptr.
1213 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1214 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
1216 /// Returns true if the target machine supports masked load operation
1217 /// for the given \p DataType and kind of access to \p Ptr.
1218 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1219 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
1221 /// Returns true if vector representation of the instruction \p I
1223 bool isMaskRequired(const Instruction* I) {
1224 return (MaskedOp.count(I) != 0);
1226 unsigned getNumStores() const {
1227 return LAI->getNumStores();
1229 unsigned getNumLoads() const {
1230 return LAI->getNumLoads();
1232 unsigned getNumPredStores() const {
1233 return NumPredStores;
1236 /// Check if a single basic block loop is vectorizable.
1237 /// At this point we know that this is a loop with a constant trip count
1238 /// and we only need to check individual instructions.
1239 bool canVectorizeInstrs();
1241 /// When we vectorize loops we may change the order in which
1242 /// we read and write from memory. This method checks if it is
1243 /// legal to vectorize the code, considering only memory constrains.
1244 /// Returns true if the loop is vectorizable
1245 bool canVectorizeMemory();
1247 /// Return true if we can vectorize this loop using the IF-conversion
1249 bool canVectorizeWithIfConvert();
1251 /// Collect the variables that need to stay uniform after vectorization.
1252 void collectLoopUniforms();
1254 /// Return true if all of the instructions in the block can be speculatively
1255 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1256 /// and we know that we can read from them without segfault.
1257 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1259 /// \brief Collect memory access with loop invariant strides.
1261 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1263 void collectStridedAccess(Value *LoadOrStoreInst);
1265 /// Report an analysis message to assist the user in diagnosing loops that are
1266 /// not vectorized. These are handled as LoopAccessReport rather than
1267 /// VectorizationReport because the << operator of VectorizationReport returns
1268 /// LoopAccessReport.
1269 void emitAnalysis(const LoopAccessReport &Message) const {
1270 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1273 unsigned NumPredStores;
1275 /// The loop that we evaluate.
1278 ScalarEvolution *SE;
1279 /// Target Library Info.
1280 TargetLibraryInfo *TLI;
1282 Function *TheFunction;
1283 /// Target Transform Info
1284 const TargetTransformInfo *TTI;
1287 // LoopAccess analysis.
1288 LoopAccessAnalysis *LAA;
1289 // And the loop-accesses info corresponding to this loop. This pointer is
1290 // null until canVectorizeMemory sets it up.
1291 const LoopAccessInfo *LAI;
1293 /// The interleave access information contains groups of interleaved accesses
1294 /// with the same stride and close to each other.
1295 InterleavedAccessInfo InterleaveInfo;
1297 // --- vectorization state --- //
1299 /// Holds the integer induction variable. This is the counter of the
1302 /// Holds the reduction variables.
1303 ReductionList Reductions;
1304 /// Holds all of the induction variables that we found in the loop.
1305 /// Notice that inductions don't need to start at zero and that induction
1306 /// variables can be pointers.
1307 InductionList Inductions;
1308 /// Holds the widest induction type encountered.
1311 /// Allowed outside users. This holds the reduction
1312 /// vars which can be accessed from outside the loop.
1313 SmallPtrSet<Value*, 4> AllowedExit;
1314 /// This set holds the variables which are known to be uniform after
1316 SmallPtrSet<Instruction*, 4> Uniforms;
1318 /// Can we assume the absence of NaNs.
1319 bool HasFunNoNaNAttr;
1321 /// Vectorization requirements that will go through late-evaluation.
1322 LoopVectorizationRequirements *Requirements;
1324 /// Used to emit an analysis of any legality issues.
1325 const LoopVectorizeHints *Hints;
1327 ValueToValueMap Strides;
1328 SmallPtrSet<Value *, 8> StrideSet;
1330 /// While vectorizing these instructions we have to generate a
1331 /// call to the appropriate masked intrinsic
1332 SmallPtrSet<const Instruction*, 8> MaskedOp;
1335 /// LoopVectorizationCostModel - estimates the expected speedups due to
1337 /// In many cases vectorization is not profitable. This can happen because of
1338 /// a number of reasons. In this class we mainly attempt to predict the
1339 /// expected speedup/slowdowns due to the supported instruction set. We use the
1340 /// TargetTransformInfo to query the different backends for the cost of
1341 /// different operations.
1342 class LoopVectorizationCostModel {
1344 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1345 LoopVectorizationLegality *Legal,
1346 const TargetTransformInfo &TTI,
1347 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1348 const Function *F, const LoopVectorizeHints *Hints,
1349 SmallPtrSetImpl<const Value *> &ValuesToIgnore)
1350 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1351 TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
1353 /// Information about vectorization costs
1354 struct VectorizationFactor {
1355 unsigned Width; // Vector width with best cost
1356 unsigned Cost; // Cost of the loop with that width
1358 /// \return The most profitable vectorization factor and the cost of that VF.
1359 /// This method checks every power of two up to VF. If UserVF is not ZERO
1360 /// then this vectorization factor will be selected if vectorization is
1362 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1364 /// \return The size (in bits) of the widest type in the code that
1365 /// needs to be vectorized. We ignore values that remain scalar such as
1366 /// 64 bit loop indices.
1367 unsigned getWidestType();
1369 /// \return The desired interleave count.
1370 /// If interleave count has been specified by metadata it will be returned.
1371 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1372 /// are the selected vectorization factor and the cost of the selected VF.
1373 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1376 /// \return The most profitable unroll factor.
1377 /// This method finds the best unroll-factor based on register pressure and
1378 /// other parameters. VF and LoopCost are the selected vectorization factor
1379 /// and the cost of the selected VF.
1380 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1383 /// \brief A struct that represents some properties of the register usage
1385 struct RegisterUsage {
1386 /// Holds the number of loop invariant values that are used in the loop.
1387 unsigned LoopInvariantRegs;
1388 /// Holds the maximum number of concurrent live intervals in the loop.
1389 unsigned MaxLocalUsers;
1390 /// Holds the number of instructions in the loop.
1391 unsigned NumInstructions;
1394 /// \return information about the register usage of the loop.
1395 RegisterUsage calculateRegisterUsage();
1398 /// Returns the expected execution cost. The unit of the cost does
1399 /// not matter because we use the 'cost' units to compare different
1400 /// vector widths. The cost that is returned is *not* normalized by
1401 /// the factor width.
1402 unsigned expectedCost(unsigned VF);
1404 /// Returns the execution time cost of an instruction for a given vector
1405 /// width. Vector width of one means scalar.
1406 unsigned getInstructionCost(Instruction *I, unsigned VF);
1408 /// Returns whether the instruction is a load or store and will be a emitted
1409 /// as a vector operation.
1410 bool isConsecutiveLoadOrStore(Instruction *I);
1412 /// Report an analysis message to assist the user in diagnosing loops that are
1413 /// not vectorized. These are handled as LoopAccessReport rather than
1414 /// VectorizationReport because the << operator of VectorizationReport returns
1415 /// LoopAccessReport.
1416 void emitAnalysis(const LoopAccessReport &Message) const {
1417 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1420 /// The loop that we evaluate.
1423 ScalarEvolution *SE;
1424 /// Loop Info analysis.
1426 /// Vectorization legality.
1427 LoopVectorizationLegality *Legal;
1428 /// Vector target information.
1429 const TargetTransformInfo &TTI;
1430 /// Target Library Info.
1431 const TargetLibraryInfo *TLI;
1432 const Function *TheFunction;
1433 // Loop Vectorize Hint.
1434 const LoopVectorizeHints *Hints;
1435 // Values to ignore in the cost model.
1436 const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
1439 /// \brief This holds vectorization requirements that must be verified late in
1440 /// the process. The requirements are set by legalize and costmodel. Once
1441 /// vectorization has been determined to be possible and profitable the
1442 /// requirements can be verified by looking for metadata or compiler options.
1443 /// For example, some loops require FP commutativity which is only allowed if
1444 /// vectorization is explicitly specified or if the fast-math compiler option
1445 /// has been provided.
1446 /// Late evaluation of these requirements allows helpful diagnostics to be
1447 /// composed that tells the user what need to be done to vectorize the loop. For
1448 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1449 /// evaluation should be used only when diagnostics can generated that can be
1450 /// followed by a non-expert user.
1451 class LoopVectorizationRequirements {
1453 LoopVectorizationRequirements()
1454 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1456 void addUnsafeAlgebraInst(Instruction *I) {
1457 // First unsafe algebra instruction.
1458 if (!UnsafeAlgebraInst)
1459 UnsafeAlgebraInst = I;
1462 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1464 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1465 const char *Name = Hints.vectorizeAnalysisPassName();
1466 bool Failed = false;
1467 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1468 emitOptimizationRemarkAnalysisFPCommute(
1469 F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1470 VectorizationReport() << "cannot prove it is safe to reorder "
1471 "floating-point operations");
1475 // Test if runtime memcheck thresholds are exceeded.
1476 bool PragmaThresholdReached =
1477 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1478 bool ThresholdReached =
1479 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1480 if ((ThresholdReached && !Hints.allowReordering()) ||
1481 PragmaThresholdReached) {
1482 emitOptimizationRemarkAnalysisAliasing(
1483 F->getContext(), Name, *F, L->getStartLoc(),
1484 VectorizationReport()
1485 << "cannot prove it is safe to reorder memory operations");
1486 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1494 unsigned NumRuntimePointerChecks;
1495 Instruction *UnsafeAlgebraInst;
1498 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1500 return V.push_back(&L);
1502 for (Loop *InnerL : L)
1503 addInnerLoop(*InnerL, V);
1506 /// The LoopVectorize Pass.
1507 struct LoopVectorize : public FunctionPass {
1508 /// Pass identification, replacement for typeid
1511 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1513 DisableUnrolling(NoUnrolling),
1514 AlwaysVectorize(AlwaysVectorize) {
1515 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1518 ScalarEvolution *SE;
1520 TargetTransformInfo *TTI;
1522 BlockFrequencyInfo *BFI;
1523 TargetLibraryInfo *TLI;
1525 AssumptionCache *AC;
1526 LoopAccessAnalysis *LAA;
1527 bool DisableUnrolling;
1528 bool AlwaysVectorize;
1530 BlockFrequency ColdEntryFreq;
1532 bool runOnFunction(Function &F) override {
1533 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1534 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1535 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1536 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1537 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1538 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1539 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1540 AA = &getAnalysis<AliasAnalysis>();
1541 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1542 LAA = &getAnalysis<LoopAccessAnalysis>();
1544 // Compute some weights outside of the loop over the loops. Compute this
1545 // using a BranchProbability to re-use its scaling math.
1546 const BranchProbability ColdProb(1, 5); // 20%
1547 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1550 // 1. the target claims to have no vector registers, and
1551 // 2. interleaving won't help ILP.
1553 // The second condition is necessary because, even if the target has no
1554 // vector registers, loop vectorization may still enable scalar
1556 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1559 // Build up a worklist of inner-loops to vectorize. This is necessary as
1560 // the act of vectorizing or partially unrolling a loop creates new loops
1561 // and can invalidate iterators across the loops.
1562 SmallVector<Loop *, 8> Worklist;
1565 addInnerLoop(*L, Worklist);
1567 LoopsAnalyzed += Worklist.size();
1569 // Now walk the identified inner loops.
1570 bool Changed = false;
1571 while (!Worklist.empty())
1572 Changed |= processLoop(Worklist.pop_back_val());
1574 // Process each loop nest in the function.
1578 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1579 SmallVector<Metadata *, 4> MDs;
1580 // Reserve first location for self reference to the LoopID metadata node.
1581 MDs.push_back(nullptr);
1582 bool IsUnrollMetadata = false;
1583 MDNode *LoopID = L->getLoopID();
1585 // First find existing loop unrolling disable metadata.
1586 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1587 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1589 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1591 S && S->getString().startswith("llvm.loop.unroll.disable");
1593 MDs.push_back(LoopID->getOperand(i));
1597 if (!IsUnrollMetadata) {
1598 // Add runtime unroll disable metadata.
1599 LLVMContext &Context = L->getHeader()->getContext();
1600 SmallVector<Metadata *, 1> DisableOperands;
1601 DisableOperands.push_back(
1602 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1603 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1604 MDs.push_back(DisableNode);
1605 MDNode *NewLoopID = MDNode::get(Context, MDs);
1606 // Set operand 0 to refer to the loop id itself.
1607 NewLoopID->replaceOperandWith(0, NewLoopID);
1608 L->setLoopID(NewLoopID);
1612 bool processLoop(Loop *L) {
1613 assert(L->empty() && "Only process inner loops.");
1616 const std::string DebugLocStr = getDebugLocString(L);
1619 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1620 << L->getHeader()->getParent()->getName() << "\" from "
1621 << DebugLocStr << "\n");
1623 LoopVectorizeHints Hints(L, DisableUnrolling);
1625 DEBUG(dbgs() << "LV: Loop hints:"
1627 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1629 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1631 : "?")) << " width=" << Hints.getWidth()
1632 << " unroll=" << Hints.getInterleave() << "\n");
1634 // Function containing loop
1635 Function *F = L->getHeader()->getParent();
1637 // Looking at the diagnostic output is the only way to determine if a loop
1638 // was vectorized (other than looking at the IR or machine code), so it
1639 // is important to generate an optimization remark for each loop. Most of
1640 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1641 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1642 // less verbose reporting vectorized loops and unvectorized loops that may
1643 // benefit from vectorization, respectively.
1645 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1646 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1650 // Check the loop for a trip count threshold:
1651 // do not vectorize loops with a tiny trip count.
1652 const unsigned TC = SE->getSmallConstantTripCount(L);
1653 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1654 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1655 << "This loop is not worth vectorizing.");
1656 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1657 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1659 DEBUG(dbgs() << "\n");
1660 emitAnalysisDiag(F, L, Hints, VectorizationReport()
1661 << "vectorization is not beneficial "
1662 "and is not explicitly forced");
1667 // Check if it is legal to vectorize the loop.
1668 LoopVectorizationRequirements Requirements;
1669 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1670 &Requirements, &Hints);
1671 if (!LVL.canVectorize()) {
1672 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1673 emitMissedWarning(F, L, Hints);
1677 // Collect values we want to ignore in the cost model. This includes
1678 // type-promoting instructions we identified during reduction detection.
1679 SmallPtrSet<const Value *, 32> ValuesToIgnore;
1680 CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
1681 for (auto &Reduction : *LVL.getReductionVars()) {
1682 RecurrenceDescriptor &RedDes = Reduction.second;
1683 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
1684 ValuesToIgnore.insert(Casts.begin(), Casts.end());
1687 // Use the cost model.
1688 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints,
1691 // Check the function attributes to find out if this function should be
1692 // optimized for size.
1693 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1696 // Compute the weighted frequency of this loop being executed and see if it
1697 // is less than 20% of the function entry baseline frequency. Note that we
1698 // always have a canonical loop here because we think we *can* vectorize.
1699 // FIXME: This is hidden behind a flag due to pervasive problems with
1700 // exactly what block frequency models.
1701 if (LoopVectorizeWithBlockFrequency) {
1702 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1703 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1704 LoopEntryFreq < ColdEntryFreq)
1708 // Check the function attributes to see if implicit floats are allowed.
1709 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1710 // an integer loop and the vector instructions selected are purely integer
1711 // vector instructions?
1712 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1713 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1714 "attribute is used.\n");
1717 VectorizationReport()
1718 << "loop not vectorized due to NoImplicitFloat attribute");
1719 emitMissedWarning(F, L, Hints);
1723 // Select the optimal vectorization factor.
1724 const LoopVectorizationCostModel::VectorizationFactor VF =
1725 CM.selectVectorizationFactor(OptForSize);
1727 // Select the interleave count.
1728 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1730 // Get user interleave count.
1731 unsigned UserIC = Hints.getInterleave();
1733 // Identify the diagnostic messages that should be produced.
1734 std::string VecDiagMsg, IntDiagMsg;
1735 bool VectorizeLoop = true, InterleaveLoop = true;
1737 if (Requirements.doesNotMeet(F, L, Hints)) {
1738 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1740 emitMissedWarning(F, L, Hints);
1744 if (VF.Width == 1) {
1745 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1747 "the cost-model indicates that vectorization is not beneficial";
1748 VectorizeLoop = false;
1751 if (IC == 1 && UserIC <= 1) {
1752 // Tell the user interleaving is not beneficial.
1753 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1755 "the cost-model indicates that interleaving is not beneficial";
1756 InterleaveLoop = false;
1759 " and is explicitly disabled or interleave count is set to 1";
1760 } else if (IC > 1 && UserIC == 1) {
1761 // Tell the user interleaving is beneficial, but it explicitly disabled.
1763 << "LV: Interleaving is beneficial but is explicitly disabled.");
1764 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1765 "but is explicitly disabled or interleave count is set to 1";
1766 InterleaveLoop = false;
1769 // Override IC if user provided an interleave count.
1770 IC = UserIC > 0 ? UserIC : IC;
1772 // Emit diagnostic messages, if any.
1773 const char *VAPassName = Hints.vectorizeAnalysisPassName();
1774 if (!VectorizeLoop && !InterleaveLoop) {
1775 // Do not vectorize or interleaving the loop.
1776 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1777 L->getStartLoc(), VecDiagMsg);
1778 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1779 L->getStartLoc(), IntDiagMsg);
1781 } else if (!VectorizeLoop && InterleaveLoop) {
1782 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1783 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1784 L->getStartLoc(), VecDiagMsg);
1785 } else if (VectorizeLoop && !InterleaveLoop) {
1786 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1787 << DebugLocStr << '\n');
1788 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1789 L->getStartLoc(), IntDiagMsg);
1790 } else if (VectorizeLoop && InterleaveLoop) {
1791 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1792 << DebugLocStr << '\n');
1793 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1796 if (!VectorizeLoop) {
1797 assert(IC > 1 && "interleave count should not be 1 or 0");
1798 // If we decided that it is not legal to vectorize the loop then
1800 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC);
1801 Unroller.vectorize(&LVL);
1803 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1804 Twine("interleaved loop (interleaved count: ") +
1807 // If we decided that it is *legal* to vectorize the loop then do it.
1808 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC);
1812 // Add metadata to disable runtime unrolling scalar loop when there's no
1813 // runtime check about strides and memory. Because at this situation,
1814 // scalar loop is rarely used not worthy to be unrolled.
1815 if (!LB.IsSafetyChecksAdded())
1816 AddRuntimeUnrollDisableMetaData(L);
1818 // Report the vectorization decision.
1819 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1820 Twine("vectorized loop (vectorization width: ") +
1821 Twine(VF.Width) + ", interleaved count: " +
1825 // Mark the loop as already vectorized to avoid vectorizing again.
1826 Hints.setAlreadyVectorized();
1828 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1832 void getAnalysisUsage(AnalysisUsage &AU) const override {
1833 AU.addRequired<AssumptionCacheTracker>();
1834 AU.addRequiredID(LoopSimplifyID);
1835 AU.addRequiredID(LCSSAID);
1836 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1837 AU.addRequired<DominatorTreeWrapperPass>();
1838 AU.addRequired<LoopInfoWrapperPass>();
1839 AU.addRequired<ScalarEvolutionWrapperPass>();
1840 AU.addRequired<TargetTransformInfoWrapperPass>();
1841 AU.addRequired<AliasAnalysis>();
1842 AU.addRequired<LoopAccessAnalysis>();
1843 AU.addPreserved<LoopInfoWrapperPass>();
1844 AU.addPreserved<DominatorTreeWrapperPass>();
1845 AU.addPreserved<AliasAnalysis>();
1850 } // end anonymous namespace
1852 //===----------------------------------------------------------------------===//
1853 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1854 // LoopVectorizationCostModel.
1855 //===----------------------------------------------------------------------===//
1857 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1858 // We need to place the broadcast of invariant variables outside the loop.
1859 Instruction *Instr = dyn_cast<Instruction>(V);
1861 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1862 Instr->getParent()) != LoopVectorBody.end());
1863 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1865 // Place the code for broadcasting invariant variables in the new preheader.
1866 IRBuilder<>::InsertPointGuard Guard(Builder);
1868 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1870 // Broadcast the scalar into all locations in the vector.
1871 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1876 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1878 assert(Val->getType()->isVectorTy() && "Must be a vector");
1879 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1880 "Elem must be an integer");
1881 assert(Step->getType() == Val->getType()->getScalarType() &&
1882 "Step has wrong type");
1883 // Create the types.
1884 Type *ITy = Val->getType()->getScalarType();
1885 VectorType *Ty = cast<VectorType>(Val->getType());
1886 int VLen = Ty->getNumElements();
1887 SmallVector<Constant*, 8> Indices;
1889 // Create a vector of consecutive numbers from zero to VF.
1890 for (int i = 0; i < VLen; ++i)
1891 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1893 // Add the consecutive indices to the vector value.
1894 Constant *Cv = ConstantVector::get(Indices);
1895 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1896 Step = Builder.CreateVectorSplat(VLen, Step);
1897 assert(Step->getType() == Val->getType() && "Invalid step vec");
1898 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1899 // which can be found from the original scalar operations.
1900 Step = Builder.CreateMul(Cv, Step);
1901 return Builder.CreateAdd(Val, Step, "induction");
1904 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1905 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1906 // Make sure that the pointer does not point to structs.
1907 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1910 // If this value is a pointer induction variable we know it is consecutive.
1911 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1912 if (Phi && Inductions.count(Phi)) {
1913 InductionDescriptor II = Inductions[Phi];
1914 return II.getConsecutiveDirection();
1917 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1921 unsigned NumOperands = Gep->getNumOperands();
1922 Value *GpPtr = Gep->getPointerOperand();
1923 // If this GEP value is a consecutive pointer induction variable and all of
1924 // the indices are constant then we know it is consecutive. We can
1925 Phi = dyn_cast<PHINode>(GpPtr);
1926 if (Phi && Inductions.count(Phi)) {
1928 // Make sure that the pointer does not point to structs.
1929 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1930 if (GepPtrType->getElementType()->isAggregateType())
1933 // Make sure that all of the index operands are loop invariant.
1934 for (unsigned i = 1; i < NumOperands; ++i)
1935 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1938 InductionDescriptor II = Inductions[Phi];
1939 return II.getConsecutiveDirection();
1942 unsigned InductionOperand = getGEPInductionOperand(Gep);
1944 // Check that all of the gep indices are uniform except for our induction
1946 for (unsigned i = 0; i != NumOperands; ++i)
1947 if (i != InductionOperand &&
1948 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1951 // We can emit wide load/stores only if the last non-zero index is the
1952 // induction variable.
1953 const SCEV *Last = nullptr;
1954 if (!Strides.count(Gep))
1955 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1957 // Because of the multiplication by a stride we can have a s/zext cast.
1958 // We are going to replace this stride by 1 so the cast is safe to ignore.
1960 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1961 // %0 = trunc i64 %indvars.iv to i32
1962 // %mul = mul i32 %0, %Stride1
1963 // %idxprom = zext i32 %mul to i64 << Safe cast.
1964 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1966 Last = replaceSymbolicStrideSCEV(SE, Strides,
1967 Gep->getOperand(InductionOperand), Gep);
1968 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1970 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1974 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1975 const SCEV *Step = AR->getStepRecurrence(*SE);
1977 // The memory is consecutive because the last index is consecutive
1978 // and all other indices are loop invariant.
1981 if (Step->isAllOnesValue())
1988 bool LoopVectorizationLegality::isUniform(Value *V) {
1989 return LAI->isUniform(V);
1992 InnerLoopVectorizer::VectorParts&
1993 InnerLoopVectorizer::getVectorValue(Value *V) {
1994 assert(V != Induction && "The new induction variable should not be used.");
1995 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1997 // If we have a stride that is replaced by one, do it here.
1998 if (Legal->hasStride(V))
1999 V = ConstantInt::get(V->getType(), 1);
2001 // If we have this scalar in the map, return it.
2002 if (WidenMap.has(V))
2003 return WidenMap.get(V);
2005 // If this scalar is unknown, assume that it is a constant or that it is
2006 // loop invariant. Broadcast V and save the value for future uses.
2007 Value *B = getBroadcastInstrs(V);
2008 return WidenMap.splat(V, B);
2011 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2012 assert(Vec->getType()->isVectorTy() && "Invalid type");
2013 SmallVector<Constant*, 8> ShuffleMask;
2014 for (unsigned i = 0; i < VF; ++i)
2015 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2017 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2018 ConstantVector::get(ShuffleMask),
2022 // Get a mask to interleave \p NumVec vectors into a wide vector.
2023 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2024 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2025 // <0, 4, 1, 5, 2, 6, 3, 7>
2026 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2028 SmallVector<Constant *, 16> Mask;
2029 for (unsigned i = 0; i < VF; i++)
2030 for (unsigned j = 0; j < NumVec; j++)
2031 Mask.push_back(Builder.getInt32(j * VF + i));
2033 return ConstantVector::get(Mask);
2036 // Get the strided mask starting from index \p Start.
2037 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2038 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2039 unsigned Stride, unsigned VF) {
2040 SmallVector<Constant *, 16> Mask;
2041 for (unsigned i = 0; i < VF; i++)
2042 Mask.push_back(Builder.getInt32(Start + i * Stride));
2044 return ConstantVector::get(Mask);
2047 // Get a mask of two parts: The first part consists of sequential integers
2048 // starting from 0, The second part consists of UNDEFs.
2049 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2050 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2051 unsigned NumUndef) {
2052 SmallVector<Constant *, 16> Mask;
2053 for (unsigned i = 0; i < NumInt; i++)
2054 Mask.push_back(Builder.getInt32(i));
2056 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2057 for (unsigned i = 0; i < NumUndef; i++)
2058 Mask.push_back(Undef);
2060 return ConstantVector::get(Mask);
2063 // Concatenate two vectors with the same element type. The 2nd vector should
2064 // not have more elements than the 1st vector. If the 2nd vector has less
2065 // elements, extend it with UNDEFs.
2066 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2068 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2069 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2070 assert(VecTy1 && VecTy2 &&
2071 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2072 "Expect two vectors with the same element type");
2074 unsigned NumElts1 = VecTy1->getNumElements();
2075 unsigned NumElts2 = VecTy2->getNumElements();
2076 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2078 if (NumElts1 > NumElts2) {
2079 // Extend with UNDEFs.
2081 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2082 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2085 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2086 return Builder.CreateShuffleVector(V1, V2, Mask);
2089 // Concatenate vectors in the given list. All vectors have the same type.
2090 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2091 ArrayRef<Value *> InputList) {
2092 unsigned NumVec = InputList.size();
2093 assert(NumVec > 1 && "Should be at least two vectors");
2095 SmallVector<Value *, 8> ResList;
2096 ResList.append(InputList.begin(), InputList.end());
2098 SmallVector<Value *, 8> TmpList;
2099 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2100 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2101 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2102 "Only the last vector may have a different type");
2104 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2107 // Push the last vector if the total number of vectors is odd.
2108 if (NumVec % 2 != 0)
2109 TmpList.push_back(ResList[NumVec - 1]);
2112 NumVec = ResList.size();
2113 } while (NumVec > 1);
2118 // Try to vectorize the interleave group that \p Instr belongs to.
2120 // E.g. Translate following interleaved load group (factor = 3):
2121 // for (i = 0; i < N; i+=3) {
2122 // R = Pic[i]; // Member of index 0
2123 // G = Pic[i+1]; // Member of index 1
2124 // B = Pic[i+2]; // Member of index 2
2125 // ... // do something to R, G, B
2128 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2129 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2130 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2131 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2133 // Or translate following interleaved store group (factor = 3):
2134 // for (i = 0; i < N; i+=3) {
2135 // ... do something to R, G, B
2136 // Pic[i] = R; // Member of index 0
2137 // Pic[i+1] = G; // Member of index 1
2138 // Pic[i+2] = B; // Member of index 2
2141 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2142 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2143 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2144 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2145 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2146 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2147 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2148 assert(Group && "Fail to get an interleaved access group.");
2150 // Skip if current instruction is not the insert position.
2151 if (Instr != Group->getInsertPos())
2154 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2155 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2156 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2158 // Prepare for the vector type of the interleaved load/store.
2159 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2160 unsigned InterleaveFactor = Group->getFactor();
2161 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2162 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2164 // Prepare for the new pointers.
2165 setDebugLocFromInst(Builder, Ptr);
2166 VectorParts &PtrParts = getVectorValue(Ptr);
2167 SmallVector<Value *, 2> NewPtrs;
2168 unsigned Index = Group->getIndex(Instr);
2169 for (unsigned Part = 0; Part < UF; Part++) {
2170 // Extract the pointer for current instruction from the pointer vector. A
2171 // reverse access uses the pointer in the last lane.
2172 Value *NewPtr = Builder.CreateExtractElement(
2174 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2176 // Notice current instruction could be any index. Need to adjust the address
2177 // to the member of index 0.
2179 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2180 // b = A[i]; // Member of index 0
2181 // Current pointer is pointed to A[i+1], adjust it to A[i].
2183 // E.g. A[i+1] = a; // Member of index 1
2184 // A[i] = b; // Member of index 0
2185 // A[i+2] = c; // Member of index 2 (Current instruction)
2186 // Current pointer is pointed to A[i+2], adjust it to A[i].
2187 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2189 // Cast to the vector pointer type.
2190 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2193 setDebugLocFromInst(Builder, Instr);
2194 Value *UndefVec = UndefValue::get(VecTy);
2196 // Vectorize the interleaved load group.
2198 for (unsigned Part = 0; Part < UF; Part++) {
2199 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2200 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2202 for (unsigned i = 0; i < InterleaveFactor; i++) {
2203 Instruction *Member = Group->getMember(i);
2205 // Skip the gaps in the group.
2209 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2210 Value *StridedVec = Builder.CreateShuffleVector(
2211 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2213 // If this member has different type, cast the result type.
2214 if (Member->getType() != ScalarTy) {
2215 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2216 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2219 VectorParts &Entry = WidenMap.get(Member);
2221 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2224 propagateMetadata(NewLoadInstr, Instr);
2229 // The sub vector type for current instruction.
2230 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2232 // Vectorize the interleaved store group.
2233 for (unsigned Part = 0; Part < UF; Part++) {
2234 // Collect the stored vector from each member.
2235 SmallVector<Value *, 4> StoredVecs;
2236 for (unsigned i = 0; i < InterleaveFactor; i++) {
2237 // Interleaved store group doesn't allow a gap, so each index has a member
2238 Instruction *Member = Group->getMember(i);
2239 assert(Member && "Fail to get a member from an interleaved store group");
2242 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2243 if (Group->isReverse())
2244 StoredVec = reverseVector(StoredVec);
2246 // If this member has different type, cast it to an unified type.
2247 if (StoredVec->getType() != SubVT)
2248 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2250 StoredVecs.push_back(StoredVec);
2253 // Concatenate all vectors into a wide vector.
2254 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2256 // Interleave the elements in the wide vector.
2257 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2258 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2261 Instruction *NewStoreInstr =
2262 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2263 propagateMetadata(NewStoreInstr, Instr);
2267 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2268 // Attempt to issue a wide load.
2269 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2270 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2272 assert((LI || SI) && "Invalid Load/Store instruction");
2274 // Try to vectorize the interleave group if this access is interleaved.
2275 if (Legal->isAccessInterleaved(Instr))
2276 return vectorizeInterleaveGroup(Instr);
2278 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2279 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2280 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2281 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2282 // An alignment of 0 means target abi alignment. We need to use the scalar's
2283 // target abi alignment in such a case.
2284 const DataLayout &DL = Instr->getModule()->getDataLayout();
2286 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2287 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2288 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2289 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2291 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2292 !Legal->isMaskRequired(SI))
2293 return scalarizeInstruction(Instr, true);
2295 if (ScalarAllocatedSize != VectorElementSize)
2296 return scalarizeInstruction(Instr);
2298 // If the pointer is loop invariant or if it is non-consecutive,
2299 // scalarize the load.
2300 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2301 bool Reverse = ConsecutiveStride < 0;
2302 bool UniformLoad = LI && Legal->isUniform(Ptr);
2303 if (!ConsecutiveStride || UniformLoad)
2304 return scalarizeInstruction(Instr);
2306 Constant *Zero = Builder.getInt32(0);
2307 VectorParts &Entry = WidenMap.get(Instr);
2309 // Handle consecutive loads/stores.
2310 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2311 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2312 setDebugLocFromInst(Builder, Gep);
2313 Value *PtrOperand = Gep->getPointerOperand();
2314 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2315 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2317 // Create the new GEP with the new induction variable.
2318 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2319 Gep2->setOperand(0, FirstBasePtr);
2320 Gep2->setName("gep.indvar.base");
2321 Ptr = Builder.Insert(Gep2);
2323 setDebugLocFromInst(Builder, Gep);
2324 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2325 OrigLoop) && "Base ptr must be invariant");
2327 // The last index does not have to be the induction. It can be
2328 // consecutive and be a function of the index. For example A[I+1];
2329 unsigned NumOperands = Gep->getNumOperands();
2330 unsigned InductionOperand = getGEPInductionOperand(Gep);
2331 // Create the new GEP with the new induction variable.
2332 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2334 for (unsigned i = 0; i < NumOperands; ++i) {
2335 Value *GepOperand = Gep->getOperand(i);
2336 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2338 // Update last index or loop invariant instruction anchored in loop.
2339 if (i == InductionOperand ||
2340 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2341 assert((i == InductionOperand ||
2342 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2343 "Must be last index or loop invariant");
2345 VectorParts &GEPParts = getVectorValue(GepOperand);
2346 Value *Index = GEPParts[0];
2347 Index = Builder.CreateExtractElement(Index, Zero);
2348 Gep2->setOperand(i, Index);
2349 Gep2->setName("gep.indvar.idx");
2352 Ptr = Builder.Insert(Gep2);
2354 // Use the induction element ptr.
2355 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2356 setDebugLocFromInst(Builder, Ptr);
2357 VectorParts &PtrVal = getVectorValue(Ptr);
2358 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2361 VectorParts Mask = createBlockInMask(Instr->getParent());
2364 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2365 "We do not allow storing to uniform addresses");
2366 setDebugLocFromInst(Builder, SI);
2367 // We don't want to update the value in the map as it might be used in
2368 // another expression. So don't use a reference type for "StoredVal".
2369 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2371 for (unsigned Part = 0; Part < UF; ++Part) {
2372 // Calculate the pointer for the specific unroll-part.
2374 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2377 // If we store to reverse consecutive memory locations, then we need
2378 // to reverse the order of elements in the stored value.
2379 StoredVal[Part] = reverseVector(StoredVal[Part]);
2380 // If the address is consecutive but reversed, then the
2381 // wide store needs to start at the last vector element.
2382 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2383 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2384 Mask[Part] = reverseVector(Mask[Part]);
2387 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2388 DataTy->getPointerTo(AddressSpace));
2391 if (Legal->isMaskRequired(SI))
2392 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2395 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2396 propagateMetadata(NewSI, SI);
2402 assert(LI && "Must have a load instruction");
2403 setDebugLocFromInst(Builder, LI);
2404 for (unsigned Part = 0; Part < UF; ++Part) {
2405 // Calculate the pointer for the specific unroll-part.
2407 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2410 // If the address is consecutive but reversed, then the
2411 // wide load needs to start at the last vector element.
2412 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2413 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2414 Mask[Part] = reverseVector(Mask[Part]);
2418 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2419 DataTy->getPointerTo(AddressSpace));
2420 if (Legal->isMaskRequired(LI))
2421 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2422 UndefValue::get(DataTy),
2423 "wide.masked.load");
2425 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2426 propagateMetadata(NewLI, LI);
2427 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2431 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2432 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2433 // Holds vector parameters or scalars, in case of uniform vals.
2434 SmallVector<VectorParts, 4> Params;
2436 setDebugLocFromInst(Builder, Instr);
2438 // Find all of the vectorized parameters.
2439 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2440 Value *SrcOp = Instr->getOperand(op);
2442 // If we are accessing the old induction variable, use the new one.
2443 if (SrcOp == OldInduction) {
2444 Params.push_back(getVectorValue(SrcOp));
2448 // Try using previously calculated values.
2449 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2451 // If the src is an instruction that appeared earlier in the basic block,
2452 // then it should already be vectorized.
2453 if (SrcInst && OrigLoop->contains(SrcInst)) {
2454 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2455 // The parameter is a vector value from earlier.
2456 Params.push_back(WidenMap.get(SrcInst));
2458 // The parameter is a scalar from outside the loop. Maybe even a constant.
2459 VectorParts Scalars;
2460 Scalars.append(UF, SrcOp);
2461 Params.push_back(Scalars);
2465 assert(Params.size() == Instr->getNumOperands() &&
2466 "Invalid number of operands");
2468 // Does this instruction return a value ?
2469 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2471 Value *UndefVec = IsVoidRetTy ? nullptr :
2472 UndefValue::get(VectorType::get(Instr->getType(), VF));
2473 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2474 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2477 if (IfPredicateStore) {
2478 assert(Instr->getParent()->getSinglePredecessor() &&
2479 "Only support single predecessor blocks");
2480 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2481 Instr->getParent());
2484 // For each vector unroll 'part':
2485 for (unsigned Part = 0; Part < UF; ++Part) {
2486 // For each scalar that we create:
2487 for (unsigned Width = 0; Width < VF; ++Width) {
2490 Value *Cmp = nullptr;
2491 if (IfPredicateStore) {
2492 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2493 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2496 Instruction *Cloned = Instr->clone();
2498 Cloned->setName(Instr->getName() + ".cloned");
2499 // Replace the operands of the cloned instructions with extracted scalars.
2500 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2501 Value *Op = Params[op][Part];
2502 // Param is a vector. Need to extract the right lane.
2503 if (Op->getType()->isVectorTy())
2504 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2505 Cloned->setOperand(op, Op);
2508 // Place the cloned scalar in the new loop.
2509 Builder.Insert(Cloned);
2511 // If the original scalar returns a value we need to place it in a vector
2512 // so that future users will be able to use it.
2514 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2515 Builder.getInt32(Width));
2517 if (IfPredicateStore)
2518 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
2524 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2528 if (Instruction *I = dyn_cast<Instruction>(V))
2529 return I->getParent() == Loc->getParent() ? I : nullptr;
2533 std::pair<Instruction *, Instruction *>
2534 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2535 Instruction *tnullptr = nullptr;
2536 if (!Legal->mustCheckStrides())
2537 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2539 IRBuilder<> ChkBuilder(Loc);
2542 Value *Check = nullptr;
2543 Instruction *FirstInst = nullptr;
2544 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2545 SE = Legal->strides_end();
2547 Value *Ptr = stripIntegerCast(*SI);
2548 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2550 // Store the first instruction we create.
2551 FirstInst = getFirstInst(FirstInst, C, Loc);
2553 Check = ChkBuilder.CreateOr(Check, C);
2558 // We have to do this trickery because the IRBuilder might fold the check to a
2559 // constant expression in which case there is no Instruction anchored in a
2561 LLVMContext &Ctx = Loc->getContext();
2562 Instruction *TheCheck =
2563 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2564 ChkBuilder.Insert(TheCheck, "stride.not.one");
2565 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2567 return std::make_pair(FirstInst, TheCheck);
2570 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L,
2575 BasicBlock *Header = L->getHeader();
2576 BasicBlock *Latch = L->getLoopLatch();
2577 // As we're just creating this loop, it's possible no latch exists
2578 // yet. If so, use the header as this will be a single block loop.
2582 IRBuilder<> Builder(Header->getFirstInsertionPt());
2583 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2584 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2586 Builder.SetInsertPoint(Latch->getTerminator());
2588 // Create i+1 and fill the PHINode.
2589 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2590 Induction->addIncoming(Start, L->getLoopPreheader());
2591 Induction->addIncoming(Next, Latch);
2592 // Create the compare.
2593 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2594 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2596 // Now we have two terminators. Remove the old one from the block.
2597 Latch->getTerminator()->eraseFromParent();
2602 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2606 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2607 // Find the loop boundaries.
2608 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2609 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2611 Type *IdxTy = Legal->getWidestInductionType();
2613 // The exit count might have the type of i64 while the phi is i32. This can
2614 // happen if we have an induction variable that is sign extended before the
2615 // compare. The only way that we get a backedge taken count is that the
2616 // induction variable was signed and as such will not overflow. In such a case
2617 // truncation is legal.
2618 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2619 IdxTy->getPrimitiveSizeInBits())
2620 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2622 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2623 // Get the total trip count from the count by adding 1.
2624 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2625 SE->getConstant(BackedgeTakeCount->getType(), 1));
2627 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2629 // Expand the trip count and place the new instructions in the preheader.
2630 // Notice that the pre-header does not change, only the loop body.
2631 SCEVExpander Exp(*SE, DL, "induction");
2633 // Count holds the overall loop count (N).
2634 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2635 L->getLoopPreheader()->getTerminator());
2637 if (TripCount->getType()->isPointerTy())
2639 CastInst::CreatePointerCast(TripCount, IdxTy,
2640 "exitcount.ptrcnt.to.int",
2641 L->getLoopPreheader()->getTerminator());
2646 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2647 if (VectorTripCount)
2648 return VectorTripCount;
2650 Value *TC = getOrCreateTripCount(L);
2651 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2653 // Now we need to generate the expression for N - (N % VF), which is
2654 // the part that the vectorized body will execute.
2655 // The loop step is equal to the vectorization factor (num of SIMD elements)
2656 // times the unroll factor (num of SIMD instructions).
2657 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2658 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2659 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2661 return VectorTripCount;
2664 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2665 BasicBlock *Bypass) {
2666 Value *Count = getOrCreateTripCount(L);
2667 BasicBlock *BB = L->getLoopPreheader();
2668 IRBuilder<> Builder(BB->getTerminator());
2670 // Generate code to check that the loop's trip count that we computed by
2671 // adding one to the backedge-taken count will not overflow.
2672 Value *CheckMinIters =
2673 Builder.CreateICmpULT(Count,
2674 ConstantInt::get(Count->getType(), VF * UF),
2677 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2678 "min.iters.checked");
2679 if (L->getParentLoop())
2680 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2681 ReplaceInstWithInst(BB->getTerminator(),
2682 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2683 LoopBypassBlocks.push_back(BB);
2686 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2687 BasicBlock *Bypass) {
2688 Value *TC = getOrCreateVectorTripCount(L);
2689 BasicBlock *BB = L->getLoopPreheader();
2690 IRBuilder<> Builder(BB->getTerminator());
2692 // Now, compare the new count to zero. If it is zero skip the vector loop and
2693 // jump to the scalar loop.
2694 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2697 // Generate code to check that the loop's trip count that we computed by
2698 // adding one to the backedge-taken count will not overflow.
2699 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2701 if (L->getParentLoop())
2702 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2703 ReplaceInstWithInst(BB->getTerminator(),
2704 BranchInst::Create(Bypass, NewBB, Cmp));
2705 LoopBypassBlocks.push_back(BB);
2708 void InnerLoopVectorizer::emitStrideChecks(Loop *L,
2709 BasicBlock *Bypass) {
2710 BasicBlock *BB = L->getLoopPreheader();
2712 // Generate the code to check that the strides we assumed to be one are really
2713 // one. We want the new basic block to start at the first instruction in a
2714 // sequence of instructions that form a check.
2715 Instruction *StrideCheck;
2716 Instruction *FirstCheckInst;
2717 std::tie(FirstCheckInst, StrideCheck) = addStrideCheck(BB->getTerminator());
2721 // Create a new block containing the stride check.
2722 BB->setName("vector.stridecheck");
2723 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2724 if (L->getParentLoop())
2725 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2726 ReplaceInstWithInst(BB->getTerminator(),
2727 BranchInst::Create(Bypass, NewBB, StrideCheck));
2728 LoopBypassBlocks.push_back(BB);
2729 AddedSafetyChecks = true;
2732 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
2733 BasicBlock *Bypass) {
2734 BasicBlock *BB = L->getLoopPreheader();
2736 // Generate the code that checks in runtime if arrays overlap. We put the
2737 // checks into a separate block to make the more common case of few elements
2739 Instruction *FirstCheckInst;
2740 Instruction *MemRuntimeCheck;
2741 std::tie(FirstCheckInst, MemRuntimeCheck) =
2742 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2743 if (!MemRuntimeCheck)
2746 // Create a new block containing the memory check.
2747 BB->setName("vector.memcheck");
2748 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2749 if (L->getParentLoop())
2750 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2751 ReplaceInstWithInst(BB->getTerminator(),
2752 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2753 LoopBypassBlocks.push_back(BB);
2754 AddedSafetyChecks = true;
2758 void InnerLoopVectorizer::createEmptyLoop() {
2760 In this function we generate a new loop. The new loop will contain
2761 the vectorized instructions while the old loop will continue to run the
2764 [ ] <-- loop iteration number check.
2767 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2770 || [ ] <-- vector pre header.
2774 | [ ]_| <-- vector loop.
2777 | -[ ] <--- middle-block.
2780 -|- >[ ] <--- new preheader.
2784 | [ ]_| <-- old scalar loop to handle remainder.
2787 >[ ] <-- exit block.
2791 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2792 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2793 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2794 assert(VectorPH && "Invalid loop structure");
2795 assert(ExitBlock && "Must have an exit block");
2797 // Some loops have a single integer induction variable, while other loops
2798 // don't. One example is c++ iterators that often have multiple pointer
2799 // induction variables. In the code below we also support a case where we
2800 // don't have a single induction variable.
2802 // We try to obtain an induction variable from the original loop as hard
2803 // as possible. However if we don't find one that:
2805 // - counts from zero, stepping by one
2806 // - is the size of the widest induction variable type
2807 // then we create a new one.
2808 OldInduction = Legal->getInduction();
2809 Type *IdxTy = Legal->getWidestInductionType();
2811 // Split the single block loop into the two loop structure described above.
2812 BasicBlock *VecBody =
2813 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2814 BasicBlock *MiddleBlock =
2815 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2816 BasicBlock *ScalarPH =
2817 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2819 // Create and register the new vector loop.
2820 Loop* Lp = new Loop();
2821 Loop *ParentLoop = OrigLoop->getParentLoop();
2823 // Insert the new loop into the loop nest and register the new basic blocks
2824 // before calling any utilities such as SCEV that require valid LoopInfo.
2826 ParentLoop->addChildLoop(Lp);
2827 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2828 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2830 LI->addTopLevelLoop(Lp);
2832 Lp->addBasicBlockToLoop(VecBody, *LI);
2834 // Find the loop boundaries.
2835 Value *Count = getOrCreateTripCount(Lp);
2837 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2839 // We need to test whether the backedge-taken count is uint##_max. Adding one
2840 // to it will cause overflow and an incorrect loop trip count in the vector
2841 // body. In case of overflow we want to directly jump to the scalar remainder
2843 emitMinimumIterationCountCheck(Lp, ScalarPH);
2844 // Now, compare the new count to zero. If it is zero skip the vector loop and
2845 // jump to the scalar loop.
2846 emitVectorLoopEnteredCheck(Lp, ScalarPH);
2847 // Generate the code to check that the strides we assumed to be one are really
2848 // one. We want the new basic block to start at the first instruction in a
2849 // sequence of instructions that form a check.
2850 emitStrideChecks(Lp, ScalarPH);
2851 // Generate the code that checks in runtime if arrays overlap. We put the
2852 // checks into a separate block to make the more common case of few elements
2854 emitMemRuntimeChecks(Lp, ScalarPH);
2856 // Generate the induction variable.
2857 // The loop step is equal to the vectorization factor (num of SIMD elements)
2858 // times the unroll factor (num of SIMD instructions).
2859 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2860 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2862 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2863 getDebugLocFromInstOrOperands(OldInduction));
2865 // We are going to resume the execution of the scalar loop.
2866 // Go over all of the induction variables that we found and fix the
2867 // PHIs that are left in the scalar version of the loop.
2868 // The starting values of PHI nodes depend on the counter of the last
2869 // iteration in the vectorized loop.
2870 // If we come from a bypass edge then we need to start from the original
2873 // This variable saves the new starting index for the scalar loop. It is used
2874 // to test if there are any tail iterations left once the vector loop has
2876 LoopVectorizationLegality::InductionList::iterator I, E;
2877 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2878 for (I = List->begin(), E = List->end(); I != E; ++I) {
2879 PHINode *OrigPhi = I->first;
2880 InductionDescriptor II = I->second;
2882 // Create phi nodes to merge from the backedge-taken check block.
2883 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
2885 ScalarPH->getTerminator());
2887 if (OrigPhi == OldInduction) {
2888 // We know what the end value is.
2889 EndValue = CountRoundDown;
2891 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
2892 Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
2893 II.getStepValue()->getType(),
2895 EndValue = II.transform(B, CRD);
2896 EndValue->setName("ind.end");
2899 // The new PHI merges the original incoming value, in case of a bypass,
2900 // or the value at the end of the vectorized loop.
2901 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2903 // Fix the scalar body counter (PHI node).
2904 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2906 // The old induction's phi node in the scalar body needs the truncated
2908 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2909 BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
2910 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2913 // Add a check in the middle block to see if we have completed
2914 // all of the iterations in the first vector loop.
2915 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2916 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2917 CountRoundDown, "cmp.n",
2918 MiddleBlock->getTerminator());
2919 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2920 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2922 // Get ready to start creating new instructions into the vectorized body.
2923 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2926 LoopVectorPreHeader = Lp->getLoopPreheader();
2927 LoopScalarPreHeader = ScalarPH;
2928 LoopMiddleBlock = MiddleBlock;
2929 LoopExitBlock = ExitBlock;
2930 LoopVectorBody.push_back(VecBody);
2931 LoopScalarBody = OldBasicBlock;
2933 LoopVectorizeHints Hints(Lp, true);
2934 Hints.setAlreadyVectorized();
2938 struct CSEDenseMapInfo {
2939 static bool canHandle(Instruction *I) {
2940 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2941 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2943 static inline Instruction *getEmptyKey() {
2944 return DenseMapInfo<Instruction *>::getEmptyKey();
2946 static inline Instruction *getTombstoneKey() {
2947 return DenseMapInfo<Instruction *>::getTombstoneKey();
2949 static unsigned getHashValue(Instruction *I) {
2950 assert(canHandle(I) && "Unknown instruction!");
2951 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2952 I->value_op_end()));
2954 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2955 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2956 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2958 return LHS->isIdenticalTo(RHS);
2963 /// \brief Check whether this block is a predicated block.
2964 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2965 /// = ...; " blocks. We start with one vectorized basic block. For every
2966 /// conditional block we split this vectorized block. Therefore, every second
2967 /// block will be a predicated one.
2968 static bool isPredicatedBlock(unsigned BlockNum) {
2969 return BlockNum % 2;
2972 ///\brief Perform cse of induction variable instructions.
2973 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2974 // Perform simple cse.
2975 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2976 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2977 BasicBlock *BB = BBs[i];
2978 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2979 Instruction *In = I++;
2981 if (!CSEDenseMapInfo::canHandle(In))
2984 // Check if we can replace this instruction with any of the
2985 // visited instructions.
2986 if (Instruction *V = CSEMap.lookup(In)) {
2987 In->replaceAllUsesWith(V);
2988 In->eraseFromParent();
2991 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2992 // ...;" blocks for predicated stores. Every second block is a predicated
2994 if (isPredicatedBlock(i))
3002 /// \brief Adds a 'fast' flag to floating point operations.
3003 static Value *addFastMathFlag(Value *V) {
3004 if (isa<FPMathOperator>(V)){
3005 FastMathFlags Flags;
3006 Flags.setUnsafeAlgebra();
3007 cast<Instruction>(V)->setFastMathFlags(Flags);
3012 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3013 /// the result needs to be inserted and/or extracted from vectors.
3014 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3015 const TargetTransformInfo &TTI) {
3019 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3022 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3024 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3026 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3032 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3033 // Return the cost of the instruction, including scalarization overhead if it's
3034 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3035 // i.e. either vector version isn't available, or is too expensive.
3036 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3037 const TargetTransformInfo &TTI,
3038 const TargetLibraryInfo *TLI,
3039 bool &NeedToScalarize) {
3040 Function *F = CI->getCalledFunction();
3041 StringRef FnName = CI->getCalledFunction()->getName();
3042 Type *ScalarRetTy = CI->getType();
3043 SmallVector<Type *, 4> Tys, ScalarTys;
3044 for (auto &ArgOp : CI->arg_operands())
3045 ScalarTys.push_back(ArgOp->getType());
3047 // Estimate cost of scalarized vector call. The source operands are assumed
3048 // to be vectors, so we need to extract individual elements from there,
3049 // execute VF scalar calls, and then gather the result into the vector return
3051 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3053 return ScalarCallCost;
3055 // Compute corresponding vector type for return value and arguments.
3056 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3057 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3058 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3060 // Compute costs of unpacking argument values for the scalar calls and
3061 // packing the return values to a vector.
3062 unsigned ScalarizationCost =
3063 getScalarizationOverhead(RetTy, true, false, TTI);
3064 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3065 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3067 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3069 // If we can't emit a vector call for this function, then the currently found
3070 // cost is the cost we need to return.
3071 NeedToScalarize = true;
3072 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3075 // If the corresponding vector cost is cheaper, return its cost.
3076 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3077 if (VectorCallCost < Cost) {
3078 NeedToScalarize = false;
3079 return VectorCallCost;
3084 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3085 // factor VF. Return the cost of the instruction, including scalarization
3086 // overhead if it's needed.
3087 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3088 const TargetTransformInfo &TTI,
3089 const TargetLibraryInfo *TLI) {
3090 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3091 assert(ID && "Expected intrinsic call!");
3093 Type *RetTy = ToVectorTy(CI->getType(), VF);
3094 SmallVector<Type *, 4> Tys;
3095 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3096 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3098 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3101 void InnerLoopVectorizer::vectorizeLoop() {
3102 //===------------------------------------------------===//
3104 // Notice: any optimization or new instruction that go
3105 // into the code below should be also be implemented in
3108 //===------------------------------------------------===//
3109 Constant *Zero = Builder.getInt32(0);
3111 // In order to support reduction variables we need to be able to vectorize
3112 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3113 // stages. First, we create a new vector PHI node with no incoming edges.
3114 // We use this value when we vectorize all of the instructions that use the
3115 // PHI. Next, after all of the instructions in the block are complete we
3116 // add the new incoming edges to the PHI. At this point all of the
3117 // instructions in the basic block are vectorized, so we can use them to
3118 // construct the PHI.
3119 PhiVector RdxPHIsToFix;
3121 // Scan the loop in a topological order to ensure that defs are vectorized
3123 LoopBlocksDFS DFS(OrigLoop);
3126 // Vectorize all of the blocks in the original loop.
3127 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3128 be = DFS.endRPO(); bb != be; ++bb)
3129 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3131 // At this point every instruction in the original loop is widened to
3132 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3133 // that we vectorized. The PHI nodes are currently empty because we did
3134 // not want to introduce cycles. Notice that the remaining PHI nodes
3135 // that we need to fix are reduction variables.
3137 // Create the 'reduced' values for each of the induction vars.
3138 // The reduced values are the vector values that we scalarize and combine
3139 // after the loop is finished.
3140 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3142 PHINode *RdxPhi = *it;
3143 assert(RdxPhi && "Unable to recover vectorized PHI");
3145 // Find the reduction variable descriptor.
3146 assert(Legal->getReductionVars()->count(RdxPhi) &&
3147 "Unable to find the reduction variable");
3148 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3150 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3151 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3152 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3153 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3154 RdxDesc.getMinMaxRecurrenceKind();
3155 setDebugLocFromInst(Builder, ReductionStartValue);
3157 // We need to generate a reduction vector from the incoming scalar.
3158 // To do so, we need to generate the 'identity' vector and override
3159 // one of the elements with the incoming scalar reduction. We need
3160 // to do it in the vector-loop preheader.
3161 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3163 // This is the vector-clone of the value that leaves the loop.
3164 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3165 Type *VecTy = VectorExit[0]->getType();
3167 // Find the reduction identity variable. Zero for addition, or, xor,
3168 // one for multiplication, -1 for And.
3171 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3172 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3173 // MinMax reduction have the start value as their identify.
3175 VectorStart = Identity = ReductionStartValue;
3177 VectorStart = Identity =
3178 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3181 // Handle other reduction kinds:
3182 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3183 RK, VecTy->getScalarType());
3186 // This vector is the Identity vector where the first element is the
3187 // incoming scalar reduction.
3188 VectorStart = ReductionStartValue;
3190 Identity = ConstantVector::getSplat(VF, Iden);
3192 // This vector is the Identity vector where the first element is the
3193 // incoming scalar reduction.
3195 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3199 // Fix the vector-loop phi.
3201 // Reductions do not have to start at zero. They can start with
3202 // any loop invariant values.
3203 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3204 BasicBlock *Latch = OrigLoop->getLoopLatch();
3205 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3206 VectorParts &Val = getVectorValue(LoopVal);
3207 for (unsigned part = 0; part < UF; ++part) {
3208 // Make sure to add the reduction stat value only to the
3209 // first unroll part.
3210 Value *StartVal = (part == 0) ? VectorStart : Identity;
3211 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3212 LoopVectorPreHeader);
3213 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3214 LoopVectorBody.back());
3217 // Before each round, move the insertion point right between
3218 // the PHIs and the values we are going to write.
3219 // This allows us to write both PHINodes and the extractelement
3221 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3223 VectorParts RdxParts = getVectorValue(LoopExitInst);
3224 setDebugLocFromInst(Builder, LoopExitInst);
3226 // If the vector reduction can be performed in a smaller type, we truncate
3227 // then extend the loop exit value to enable InstCombine to evaluate the
3228 // entire expression in the smaller type.
3229 if (VF > 1 && RdxPhi->getType() != RdxDesc.getRecurrenceType()) {
3230 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3231 Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
3232 for (unsigned part = 0; part < UF; ++part) {
3233 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3234 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3235 : Builder.CreateZExt(Trunc, VecTy);
3236 for (Value::user_iterator UI = RdxParts[part]->user_begin();
3237 UI != RdxParts[part]->user_end();)
3239 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3240 RdxParts[part] = Extnd;
3245 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3246 for (unsigned part = 0; part < UF; ++part)
3247 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3250 // Reduce all of the unrolled parts into a single vector.
3251 Value *ReducedPartRdx = RdxParts[0];
3252 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3253 setDebugLocFromInst(Builder, ReducedPartRdx);
3254 for (unsigned part = 1; part < UF; ++part) {
3255 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3256 // Floating point operations had to be 'fast' to enable the reduction.
3257 ReducedPartRdx = addFastMathFlag(
3258 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3259 ReducedPartRdx, "bin.rdx"));
3261 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3262 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3266 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3267 // and vector ops, reducing the set of values being computed by half each
3269 assert(isPowerOf2_32(VF) &&
3270 "Reduction emission only supported for pow2 vectors!");
3271 Value *TmpVec = ReducedPartRdx;
3272 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3273 for (unsigned i = VF; i != 1; i >>= 1) {
3274 // Move the upper half of the vector to the lower half.
3275 for (unsigned j = 0; j != i/2; ++j)
3276 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3278 // Fill the rest of the mask with undef.
3279 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3280 UndefValue::get(Builder.getInt32Ty()));
3283 Builder.CreateShuffleVector(TmpVec,
3284 UndefValue::get(TmpVec->getType()),
3285 ConstantVector::get(ShuffleMask),
3288 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3289 // Floating point operations had to be 'fast' to enable the reduction.
3290 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3291 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3293 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3297 // The result is in the first element of the vector.
3298 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3299 Builder.getInt32(0));
3301 // If the reduction can be performed in a smaller type, we need to extend
3302 // the reduction to the wider type before we branch to the original loop.
3303 if (RdxPhi->getType() != RdxDesc.getRecurrenceType())
3306 ? Builder.CreateSExt(ReducedPartRdx, RdxPhi->getType())
3307 : Builder.CreateZExt(ReducedPartRdx, RdxPhi->getType());
3310 // Create a phi node that merges control-flow from the backedge-taken check
3311 // block and the middle block.
3312 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3313 LoopScalarPreHeader->getTerminator());
3314 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3315 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3316 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3318 // Now, we need to fix the users of the reduction variable
3319 // inside and outside of the scalar remainder loop.
3320 // We know that the loop is in LCSSA form. We need to update the
3321 // PHI nodes in the exit blocks.
3322 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3323 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3324 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3325 if (!LCSSAPhi) break;
3327 // All PHINodes need to have a single entry edge, or two if
3328 // we already fixed them.
3329 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3331 // We found our reduction value exit-PHI. Update it with the
3332 // incoming bypass edge.
3333 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3334 // Add an edge coming from the bypass.
3335 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3338 }// end of the LCSSA phi scan.
3340 // Fix the scalar loop reduction variable with the incoming reduction sum
3341 // from the vector body and from the backedge value.
3342 int IncomingEdgeBlockIdx =
3343 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3344 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3345 // Pick the other block.
3346 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3347 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3348 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3349 }// end of for each redux variable.
3353 // Make sure DomTree is updated.
3356 // Predicate any stores.
3357 for (auto KV : PredicatedStores) {
3358 BasicBlock::iterator I(KV.first);
3359 auto *BB = SplitBlock(I->getParent(), std::next(I), DT, LI);
3360 auto *T = SplitBlockAndInsertIfThen(KV.second, I, /*Unreachable=*/false,
3361 /*BranchWeights=*/nullptr, DT);
3363 I->getParent()->setName("pred.store.if");
3364 BB->setName("pred.store.continue");
3366 DEBUG(DT->verifyDomTree());
3367 // Remove redundant induction instructions.
3368 cse(LoopVectorBody);
3371 void InnerLoopVectorizer::fixLCSSAPHIs() {
3372 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3373 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3374 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3375 if (!LCSSAPhi) break;
3376 if (LCSSAPhi->getNumIncomingValues() == 1)
3377 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3382 InnerLoopVectorizer::VectorParts
3383 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3384 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3387 // Look for cached value.
3388 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3389 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3390 if (ECEntryIt != MaskCache.end())
3391 return ECEntryIt->second;
3393 VectorParts SrcMask = createBlockInMask(Src);
3395 // The terminator has to be a branch inst!
3396 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3397 assert(BI && "Unexpected terminator found");
3399 if (BI->isConditional()) {
3400 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3402 if (BI->getSuccessor(0) != Dst)
3403 for (unsigned part = 0; part < UF; ++part)
3404 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3406 for (unsigned part = 0; part < UF; ++part)
3407 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3409 MaskCache[Edge] = EdgeMask;
3413 MaskCache[Edge] = SrcMask;
3417 InnerLoopVectorizer::VectorParts
3418 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3419 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3421 // Loop incoming mask is all-one.
3422 if (OrigLoop->getHeader() == BB) {
3423 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3424 return getVectorValue(C);
3427 // This is the block mask. We OR all incoming edges, and with zero.
3428 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3429 VectorParts BlockMask = getVectorValue(Zero);
3432 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3433 VectorParts EM = createEdgeMask(*it, BB);
3434 for (unsigned part = 0; part < UF; ++part)
3435 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3441 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3442 InnerLoopVectorizer::VectorParts &Entry,
3443 unsigned UF, unsigned VF, PhiVector *PV) {
3444 PHINode* P = cast<PHINode>(PN);
3445 // Handle reduction variables:
3446 if (Legal->getReductionVars()->count(P)) {
3447 for (unsigned part = 0; part < UF; ++part) {
3448 // This is phase one of vectorizing PHIs.
3449 Type *VecTy = (VF == 1) ? PN->getType() :
3450 VectorType::get(PN->getType(), VF);
3451 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3452 LoopVectorBody.back()-> getFirstInsertionPt());
3458 setDebugLocFromInst(Builder, P);
3459 // Check for PHI nodes that are lowered to vector selects.
3460 if (P->getParent() != OrigLoop->getHeader()) {
3461 // We know that all PHIs in non-header blocks are converted into
3462 // selects, so we don't have to worry about the insertion order and we
3463 // can just use the builder.
3464 // At this point we generate the predication tree. There may be
3465 // duplications since this is a simple recursive scan, but future
3466 // optimizations will clean it up.
3468 unsigned NumIncoming = P->getNumIncomingValues();
3470 // Generate a sequence of selects of the form:
3471 // SELECT(Mask3, In3,
3472 // SELECT(Mask2, In2,
3474 for (unsigned In = 0; In < NumIncoming; In++) {
3475 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3477 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3479 for (unsigned part = 0; part < UF; ++part) {
3480 // We might have single edge PHIs (blocks) - use an identity
3481 // 'select' for the first PHI operand.
3483 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3486 // Select between the current value and the previous incoming edge
3487 // based on the incoming mask.
3488 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3489 Entry[part], "predphi");
3495 // This PHINode must be an induction variable.
3496 // Make sure that we know about it.
3497 assert(Legal->getInductionVars()->count(P) &&
3498 "Not an induction variable");
3500 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3502 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3503 // which can be found from the original scalar operations.
3504 switch (II.getKind()) {
3505 case InductionDescriptor::IK_NoInduction:
3506 llvm_unreachable("Unknown induction");
3507 case InductionDescriptor::IK_IntInduction: {
3508 assert(P->getType() == II.getStartValue()->getType() && "Types must match");
3509 // Handle other induction variables that are now based on the
3511 Value *V = Induction;
3512 if (P != OldInduction) {
3513 V = Builder.CreateSExtOrTrunc(Induction, P->getType());
3514 V = II.transform(Builder, V);
3515 V->setName("offset.idx");
3517 Value *Broadcasted = getBroadcastInstrs(V);
3518 // After broadcasting the induction variable we need to make the vector
3519 // consecutive by adding 0, 1, 2, etc.
3520 for (unsigned part = 0; part < UF; ++part)
3521 Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
3524 case InductionDescriptor::IK_PtrInduction:
3525 // Handle the pointer induction variable case.
3526 assert(P->getType()->isPointerTy() && "Unexpected type.");
3527 // This is the normalized GEP that starts counting at zero.
3528 Value *PtrInd = Induction;
3529 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
3530 // This is the vector of results. Notice that we don't generate
3531 // vector geps because scalar geps result in better code.
3532 for (unsigned part = 0; part < UF; ++part) {
3534 int EltIndex = part;
3535 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3536 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3537 Value *SclrGep = II.transform(Builder, GlobalIdx);
3538 SclrGep->setName("next.gep");
3539 Entry[part] = SclrGep;
3543 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3544 for (unsigned int i = 0; i < VF; ++i) {
3545 int EltIndex = i + part * VF;
3546 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3547 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3548 Value *SclrGep = II.transform(Builder, GlobalIdx);
3549 SclrGep->setName("next.gep");
3550 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3551 Builder.getInt32(i),
3554 Entry[part] = VecVal;
3560 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3561 // For each instruction in the old loop.
3562 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3563 VectorParts &Entry = WidenMap.get(it);
3564 switch (it->getOpcode()) {
3565 case Instruction::Br:
3566 // Nothing to do for PHIs and BR, since we already took care of the
3567 // loop control flow instructions.
3569 case Instruction::PHI: {
3570 // Vectorize PHINodes.
3571 widenPHIInstruction(it, Entry, UF, VF, PV);
3575 case Instruction::Add:
3576 case Instruction::FAdd:
3577 case Instruction::Sub:
3578 case Instruction::FSub:
3579 case Instruction::Mul:
3580 case Instruction::FMul:
3581 case Instruction::UDiv:
3582 case Instruction::SDiv:
3583 case Instruction::FDiv:
3584 case Instruction::URem:
3585 case Instruction::SRem:
3586 case Instruction::FRem:
3587 case Instruction::Shl:
3588 case Instruction::LShr:
3589 case Instruction::AShr:
3590 case Instruction::And:
3591 case Instruction::Or:
3592 case Instruction::Xor: {
3593 // Just widen binops.
3594 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3595 setDebugLocFromInst(Builder, BinOp);
3596 VectorParts &A = getVectorValue(it->getOperand(0));
3597 VectorParts &B = getVectorValue(it->getOperand(1));
3599 // Use this vector value for all users of the original instruction.
3600 for (unsigned Part = 0; Part < UF; ++Part) {
3601 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3603 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3604 VecOp->copyIRFlags(BinOp);
3609 propagateMetadata(Entry, it);
3612 case Instruction::Select: {
3614 // If the selector is loop invariant we can create a select
3615 // instruction with a scalar condition. Otherwise, use vector-select.
3616 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3618 setDebugLocFromInst(Builder, it);
3620 // The condition can be loop invariant but still defined inside the
3621 // loop. This means that we can't just use the original 'cond' value.
3622 // We have to take the 'vectorized' value and pick the first lane.
3623 // Instcombine will make this a no-op.
3624 VectorParts &Cond = getVectorValue(it->getOperand(0));
3625 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3626 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3628 Value *ScalarCond = (VF == 1) ? Cond[0] :
3629 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3631 for (unsigned Part = 0; Part < UF; ++Part) {
3632 Entry[Part] = Builder.CreateSelect(
3633 InvariantCond ? ScalarCond : Cond[Part],
3638 propagateMetadata(Entry, it);
3642 case Instruction::ICmp:
3643 case Instruction::FCmp: {
3644 // Widen compares. Generate vector compares.
3645 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3646 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3647 setDebugLocFromInst(Builder, it);
3648 VectorParts &A = getVectorValue(it->getOperand(0));
3649 VectorParts &B = getVectorValue(it->getOperand(1));
3650 for (unsigned Part = 0; Part < UF; ++Part) {
3653 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3655 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3659 propagateMetadata(Entry, it);
3663 case Instruction::Store:
3664 case Instruction::Load:
3665 vectorizeMemoryInstruction(it);
3667 case Instruction::ZExt:
3668 case Instruction::SExt:
3669 case Instruction::FPToUI:
3670 case Instruction::FPToSI:
3671 case Instruction::FPExt:
3672 case Instruction::PtrToInt:
3673 case Instruction::IntToPtr:
3674 case Instruction::SIToFP:
3675 case Instruction::UIToFP:
3676 case Instruction::Trunc:
3677 case Instruction::FPTrunc:
3678 case Instruction::BitCast: {
3679 CastInst *CI = dyn_cast<CastInst>(it);
3680 setDebugLocFromInst(Builder, it);
3681 /// Optimize the special case where the source is the induction
3682 /// variable. Notice that we can only optimize the 'trunc' case
3683 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3684 /// c. other casts depend on pointer size.
3685 if (CI->getOperand(0) == OldInduction &&
3686 it->getOpcode() == Instruction::Trunc) {
3687 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3689 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3690 InductionDescriptor II = Legal->getInductionVars()->lookup(OldInduction);
3692 ConstantInt::getSigned(CI->getType(), II.getStepValue()->getSExtValue());
3693 for (unsigned Part = 0; Part < UF; ++Part)
3694 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3695 propagateMetadata(Entry, it);
3698 /// Vectorize casts.
3699 Type *DestTy = (VF == 1) ? CI->getType() :
3700 VectorType::get(CI->getType(), VF);
3702 VectorParts &A = getVectorValue(it->getOperand(0));
3703 for (unsigned Part = 0; Part < UF; ++Part)
3704 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3705 propagateMetadata(Entry, it);
3709 case Instruction::Call: {
3710 // Ignore dbg intrinsics.
3711 if (isa<DbgInfoIntrinsic>(it))
3713 setDebugLocFromInst(Builder, it);
3715 Module *M = BB->getParent()->getParent();
3716 CallInst *CI = cast<CallInst>(it);
3718 StringRef FnName = CI->getCalledFunction()->getName();
3719 Function *F = CI->getCalledFunction();
3720 Type *RetTy = ToVectorTy(CI->getType(), VF);
3721 SmallVector<Type *, 4> Tys;
3722 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3723 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3725 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3727 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3728 ID == Intrinsic::lifetime_start)) {
3729 scalarizeInstruction(it);
3732 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3733 // version of the instruction.
3734 // Is it beneficial to perform intrinsic call compared to lib call?
3735 bool NeedToScalarize;
3736 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3737 bool UseVectorIntrinsic =
3738 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3739 if (!UseVectorIntrinsic && NeedToScalarize) {
3740 scalarizeInstruction(it);
3744 for (unsigned Part = 0; Part < UF; ++Part) {
3745 SmallVector<Value *, 4> Args;
3746 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3747 Value *Arg = CI->getArgOperand(i);
3748 // Some intrinsics have a scalar argument - don't replace it with a
3750 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3751 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3752 Arg = VectorArg[Part];
3754 Args.push_back(Arg);
3758 if (UseVectorIntrinsic) {
3759 // Use vector version of the intrinsic.
3760 Type *TysForDecl[] = {CI->getType()};
3762 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3763 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3765 // Use vector version of the library call.
3766 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3767 assert(!VFnName.empty() && "Vector function name is empty.");
3768 VectorF = M->getFunction(VFnName);
3770 // Generate a declaration
3771 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3773 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3774 VectorF->copyAttributesFrom(F);
3777 assert(VectorF && "Can't create vector function.");
3778 Entry[Part] = Builder.CreateCall(VectorF, Args);
3781 propagateMetadata(Entry, it);
3786 // All other instructions are unsupported. Scalarize them.
3787 scalarizeInstruction(it);
3790 }// end of for_each instr.
3793 void InnerLoopVectorizer::updateAnalysis() {
3794 // Forget the original basic block.
3795 SE->forgetLoop(OrigLoop);
3797 // Update the dominator tree information.
3798 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3799 "Entry does not dominate exit.");
3801 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3802 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3803 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3805 // We don't predicate stores by this point, so the vector body should be a
3807 assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
3808 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3810 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
3811 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3812 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3813 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3815 DEBUG(DT->verifyDomTree());
3818 /// \brief Check whether it is safe to if-convert this phi node.
3820 /// Phi nodes with constant expressions that can trap are not safe to if
3822 static bool canIfConvertPHINodes(BasicBlock *BB) {
3823 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3824 PHINode *Phi = dyn_cast<PHINode>(I);
3827 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3828 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3835 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3836 if (!EnableIfConversion) {
3837 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3841 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3843 // A list of pointers that we can safely read and write to.
3844 SmallPtrSet<Value *, 8> SafePointes;
3846 // Collect safe addresses.
3847 for (Loop::block_iterator BI = TheLoop->block_begin(),
3848 BE = TheLoop->block_end(); BI != BE; ++BI) {
3849 BasicBlock *BB = *BI;
3851 if (blockNeedsPredication(BB))
3854 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3855 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3856 SafePointes.insert(LI->getPointerOperand());
3857 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3858 SafePointes.insert(SI->getPointerOperand());
3862 // Collect the blocks that need predication.
3863 BasicBlock *Header = TheLoop->getHeader();
3864 for (Loop::block_iterator BI = TheLoop->block_begin(),
3865 BE = TheLoop->block_end(); BI != BE; ++BI) {
3866 BasicBlock *BB = *BI;
3868 // We don't support switch statements inside loops.
3869 if (!isa<BranchInst>(BB->getTerminator())) {
3870 emitAnalysis(VectorizationReport(BB->getTerminator())
3871 << "loop contains a switch statement");
3875 // We must be able to predicate all blocks that need to be predicated.
3876 if (blockNeedsPredication(BB)) {
3877 if (!blockCanBePredicated(BB, SafePointes)) {
3878 emitAnalysis(VectorizationReport(BB->getTerminator())
3879 << "control flow cannot be substituted for a select");
3882 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3883 emitAnalysis(VectorizationReport(BB->getTerminator())
3884 << "control flow cannot be substituted for a select");
3889 // We can if-convert this loop.
3893 bool LoopVectorizationLegality::canVectorize() {
3894 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3895 // be canonicalized.
3896 if (!TheLoop->getLoopPreheader()) {
3898 VectorizationReport() <<
3899 "loop control flow is not understood by vectorizer");
3903 // We can only vectorize innermost loops.
3904 if (!TheLoop->empty()) {
3905 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3909 // We must have a single backedge.
3910 if (TheLoop->getNumBackEdges() != 1) {
3912 VectorizationReport() <<
3913 "loop control flow is not understood by vectorizer");
3917 // We must have a single exiting block.
3918 if (!TheLoop->getExitingBlock()) {
3920 VectorizationReport() <<
3921 "loop control flow is not understood by vectorizer");
3925 // We only handle bottom-tested loops, i.e. loop in which the condition is
3926 // checked at the end of each iteration. With that we can assume that all
3927 // instructions in the loop are executed the same number of times.
3928 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3930 VectorizationReport() <<
3931 "loop control flow is not understood by vectorizer");
3935 // We need to have a loop header.
3936 DEBUG(dbgs() << "LV: Found a loop: " <<
3937 TheLoop->getHeader()->getName() << '\n');
3939 // Check if we can if-convert non-single-bb loops.
3940 unsigned NumBlocks = TheLoop->getNumBlocks();
3941 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3942 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3946 // ScalarEvolution needs to be able to find the exit count.
3947 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3948 if (ExitCount == SE->getCouldNotCompute()) {
3949 emitAnalysis(VectorizationReport() <<
3950 "could not determine number of loop iterations");
3951 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3955 // Check if we can vectorize the instructions and CFG in this loop.
3956 if (!canVectorizeInstrs()) {
3957 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3961 // Go over each instruction and look at memory deps.
3962 if (!canVectorizeMemory()) {
3963 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3967 // Collect all of the variables that remain uniform after vectorization.
3968 collectLoopUniforms();
3970 DEBUG(dbgs() << "LV: We can vectorize this loop"
3971 << (LAI->getRuntimePointerChecking()->Need
3972 ? " (with a runtime bound check)"
3976 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
3978 // If an override option has been passed in for interleaved accesses, use it.
3979 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
3980 UseInterleaved = EnableInterleavedMemAccesses;
3982 // Analyze interleaved memory accesses.
3984 InterleaveInfo.analyzeInterleaving(Strides);
3986 // Okay! We can vectorize. At this point we don't have any other mem analysis
3987 // which may limit our maximum vectorization factor, so just return true with
3992 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3993 if (Ty->isPointerTy())
3994 return DL.getIntPtrType(Ty);
3996 // It is possible that char's or short's overflow when we ask for the loop's
3997 // trip count, work around this by changing the type size.
3998 if (Ty->getScalarSizeInBits() < 32)
3999 return Type::getInt32Ty(Ty->getContext());
4004 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4005 Ty0 = convertPointerToIntegerType(DL, Ty0);
4006 Ty1 = convertPointerToIntegerType(DL, Ty1);
4007 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4012 /// \brief Check that the instruction has outside loop users and is not an
4013 /// identified reduction variable.
4014 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4015 SmallPtrSetImpl<Value *> &Reductions) {
4016 // Reduction instructions are allowed to have exit users. All other
4017 // instructions must not have external users.
4018 if (!Reductions.count(Inst))
4019 //Check that all of the users of the loop are inside the BB.
4020 for (User *U : Inst->users()) {
4021 Instruction *UI = cast<Instruction>(U);
4022 // This user may be a reduction exit value.
4023 if (!TheLoop->contains(UI)) {
4024 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4031 bool LoopVectorizationLegality::canVectorizeInstrs() {
4032 BasicBlock *Header = TheLoop->getHeader();
4034 // Look for the attribute signaling the absence of NaNs.
4035 Function &F = *Header->getParent();
4036 const DataLayout &DL = F.getParent()->getDataLayout();
4037 if (F.hasFnAttribute("no-nans-fp-math"))
4039 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4041 // For each block in the loop.
4042 for (Loop::block_iterator bb = TheLoop->block_begin(),
4043 be = TheLoop->block_end(); bb != be; ++bb) {
4045 // Scan the instructions in the block and look for hazards.
4046 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4049 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4050 Type *PhiTy = Phi->getType();
4051 // Check that this PHI type is allowed.
4052 if (!PhiTy->isIntegerTy() &&
4053 !PhiTy->isFloatingPointTy() &&
4054 !PhiTy->isPointerTy()) {
4055 emitAnalysis(VectorizationReport(it)
4056 << "loop control flow is not understood by vectorizer");
4057 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4061 // If this PHINode is not in the header block, then we know that we
4062 // can convert it to select during if-conversion. No need to check if
4063 // the PHIs in this block are induction or reduction variables.
4064 if (*bb != Header) {
4065 // Check that this instruction has no outside users or is an
4066 // identified reduction value with an outside user.
4067 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
4069 emitAnalysis(VectorizationReport(it) <<
4070 "value could not be identified as "
4071 "an induction or reduction variable");
4075 // We only allow if-converted PHIs with exactly two incoming values.
4076 if (Phi->getNumIncomingValues() != 2) {
4077 emitAnalysis(VectorizationReport(it)
4078 << "control flow not understood by vectorizer");
4079 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4083 InductionDescriptor ID;
4084 if (InductionDescriptor::isInductionPHI(Phi, SE, ID)) {
4085 Inductions[Phi] = ID;
4086 // Get the widest type.
4088 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4090 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4092 // Int inductions are special because we only allow one IV.
4093 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4094 ID.getStepValue()->isOne() &&
4095 isa<Constant>(ID.getStartValue()) &&
4096 cast<Constant>(ID.getStartValue())->isNullValue()) {
4097 // Use the phi node with the widest type as induction. Use the last
4098 // one if there are multiple (no good reason for doing this other
4099 // than it is expedient). We've checked that it begins at zero and
4100 // steps by one, so this is a canonical induction variable.
4101 if (!Induction || PhiTy == WidestIndTy)
4105 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4107 // Until we explicitly handle the case of an induction variable with
4108 // an outside loop user we have to give up vectorizing this loop.
4109 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4110 emitAnalysis(VectorizationReport(it) <<
4111 "use of induction value outside of the "
4112 "loop is not handled by vectorizer");
4119 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4121 if (Reductions[Phi].hasUnsafeAlgebra())
4122 Requirements->addUnsafeAlgebraInst(
4123 Reductions[Phi].getUnsafeAlgebraInst());
4124 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4128 emitAnalysis(VectorizationReport(it) <<
4129 "value that could not be identified as "
4130 "reduction is used outside the loop");
4131 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4133 }// end of PHI handling
4135 // We handle calls that:
4136 // * Are debug info intrinsics.
4137 // * Have a mapping to an IR intrinsic.
4138 // * Have a vector version available.
4139 CallInst *CI = dyn_cast<CallInst>(it);
4140 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4141 !(CI->getCalledFunction() && TLI &&
4142 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4143 emitAnalysis(VectorizationReport(it) <<
4144 "call instruction cannot be vectorized");
4145 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4149 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4150 // second argument is the same (i.e. loop invariant)
4152 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4153 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4154 emitAnalysis(VectorizationReport(it)
4155 << "intrinsic instruction cannot be vectorized");
4156 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4161 // Check that the instruction return type is vectorizable.
4162 // Also, we can't vectorize extractelement instructions.
4163 if ((!VectorType::isValidElementType(it->getType()) &&
4164 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4165 emitAnalysis(VectorizationReport(it)
4166 << "instruction return type cannot be vectorized");
4167 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4171 // Check that the stored type is vectorizable.
4172 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4173 Type *T = ST->getValueOperand()->getType();
4174 if (!VectorType::isValidElementType(T)) {
4175 emitAnalysis(VectorizationReport(ST) <<
4176 "store instruction cannot be vectorized");
4179 if (EnableMemAccessVersioning)
4180 collectStridedAccess(ST);
4183 if (EnableMemAccessVersioning)
4184 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4185 collectStridedAccess(LI);
4187 // Reduction instructions are allowed to have exit users.
4188 // All other instructions must not have external users.
4189 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4190 emitAnalysis(VectorizationReport(it) <<
4191 "value cannot be used outside the loop");
4200 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4201 if (Inductions.empty()) {
4202 emitAnalysis(VectorizationReport()
4203 << "loop induction variable could not be identified");
4208 // Now we know the widest induction type, check if our found induction
4209 // is the same size. If it's not, unset it here and InnerLoopVectorizer
4210 // will create another.
4211 if (Induction && WidestIndTy != Induction->getType())
4212 Induction = nullptr;
4217 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4218 Value *Ptr = nullptr;
4219 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4220 Ptr = LI->getPointerOperand();
4221 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4222 Ptr = SI->getPointerOperand();
4226 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4230 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4231 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4232 Strides[Ptr] = Stride;
4233 StrideSet.insert(Stride);
4236 void LoopVectorizationLegality::collectLoopUniforms() {
4237 // We now know that the loop is vectorizable!
4238 // Collect variables that will remain uniform after vectorization.
4239 std::vector<Value*> Worklist;
4240 BasicBlock *Latch = TheLoop->getLoopLatch();
4242 // Start with the conditional branch and walk up the block.
4243 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4245 // Also add all consecutive pointer values; these values will be uniform
4246 // after vectorization (and subsequent cleanup) and, until revectorization is
4247 // supported, all dependencies must also be uniform.
4248 for (Loop::block_iterator B = TheLoop->block_begin(),
4249 BE = TheLoop->block_end(); B != BE; ++B)
4250 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4252 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4253 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4255 while (!Worklist.empty()) {
4256 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4257 Worklist.pop_back();
4259 // Look at instructions inside this loop.
4260 // Stop when reaching PHI nodes.
4261 // TODO: we need to follow values all over the loop, not only in this block.
4262 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4265 // This is a known uniform.
4268 // Insert all operands.
4269 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4273 bool LoopVectorizationLegality::canVectorizeMemory() {
4274 LAI = &LAA->getInfo(TheLoop, Strides);
4275 auto &OptionalReport = LAI->getReport();
4277 emitAnalysis(VectorizationReport(*OptionalReport));
4278 if (!LAI->canVectorizeMemory())
4281 if (LAI->hasStoreToLoopInvariantAddress()) {
4283 VectorizationReport()
4284 << "write to a loop invariant address could not be vectorized");
4285 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4289 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4294 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4295 Value *In0 = const_cast<Value*>(V);
4296 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4300 return Inductions.count(PN);
4303 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4304 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4307 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4308 SmallPtrSetImpl<Value *> &SafePtrs) {
4310 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4311 // Check that we don't have a constant expression that can trap as operand.
4312 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4314 if (Constant *C = dyn_cast<Constant>(*OI))
4318 // We might be able to hoist the load.
4319 if (it->mayReadFromMemory()) {
4320 LoadInst *LI = dyn_cast<LoadInst>(it);
4323 if (!SafePtrs.count(LI->getPointerOperand())) {
4324 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4325 MaskedOp.insert(LI);
4332 // We don't predicate stores at the moment.
4333 if (it->mayWriteToMemory()) {
4334 StoreInst *SI = dyn_cast<StoreInst>(it);
4335 // We only support predication of stores in basic blocks with one
4340 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4341 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4343 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4344 !isSinglePredecessor) {
4345 // Build a masked store if it is legal for the target, otherwise scalarize
4347 bool isLegalMaskedOp =
4348 isLegalMaskedStore(SI->getValueOperand()->getType(),
4349 SI->getPointerOperand());
4350 if (isLegalMaskedOp) {
4352 MaskedOp.insert(SI);
4361 // The instructions below can trap.
4362 switch (it->getOpcode()) {
4364 case Instruction::UDiv:
4365 case Instruction::SDiv:
4366 case Instruction::URem:
4367 case Instruction::SRem:
4375 void InterleavedAccessInfo::collectConstStridedAccesses(
4376 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4377 const ValueToValueMap &Strides) {
4378 // Holds load/store instructions in program order.
4379 SmallVector<Instruction *, 16> AccessList;
4381 for (auto *BB : TheLoop->getBlocks()) {
4382 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4384 for (auto &I : *BB) {
4385 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4387 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4391 AccessList.push_back(&I);
4395 if (AccessList.empty())
4398 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4399 for (auto I : AccessList) {
4400 LoadInst *LI = dyn_cast<LoadInst>(I);
4401 StoreInst *SI = dyn_cast<StoreInst>(I);
4403 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4404 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4406 // The factor of the corresponding interleave group.
4407 unsigned Factor = std::abs(Stride);
4409 // Ignore the access if the factor is too small or too large.
4410 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4413 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4414 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4415 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4417 // An alignment of 0 means target ABI alignment.
4418 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4420 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4422 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4426 // Analyze interleaved accesses and collect them into interleave groups.
4428 // Notice that the vectorization on interleaved groups will change instruction
4429 // orders and may break dependences. But the memory dependence check guarantees
4430 // that there is no overlap between two pointers of different strides, element
4431 // sizes or underlying bases.
4433 // For pointers sharing the same stride, element size and underlying base, no
4434 // need to worry about Read-After-Write dependences and Write-After-Read
4437 // E.g. The RAW dependence: A[i] = a;
4439 // This won't exist as it is a store-load forwarding conflict, which has
4440 // already been checked and forbidden in the dependence check.
4442 // E.g. The WAR dependence: a = A[i]; // (1)
4444 // The store group of (2) is always inserted at or below (2), and the load group
4445 // of (1) is always inserted at or above (1). The dependence is safe.
4446 void InterleavedAccessInfo::analyzeInterleaving(
4447 const ValueToValueMap &Strides) {
4448 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4450 // Holds all the stride accesses.
4451 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4452 collectConstStridedAccesses(StrideAccesses, Strides);
4454 if (StrideAccesses.empty())
4457 // Holds all interleaved store groups temporarily.
4458 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4460 // Search the load-load/write-write pair B-A in bottom-up order and try to
4461 // insert B into the interleave group of A according to 3 rules:
4462 // 1. A and B have the same stride.
4463 // 2. A and B have the same memory object size.
4464 // 3. B belongs to the group according to the distance.
4466 // The bottom-up order can avoid breaking the Write-After-Write dependences
4467 // between two pointers of the same base.
4468 // E.g. A[i] = a; (1)
4471 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4472 // above (1), which guarantees that (1) is always above (2).
4473 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4475 Instruction *A = I->first;
4476 StrideDescriptor DesA = I->second;
4478 InterleaveGroup *Group = getInterleaveGroup(A);
4480 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4481 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4484 if (A->mayWriteToMemory())
4485 StoreGroups.insert(Group);
4487 for (auto II = std::next(I); II != E; ++II) {
4488 Instruction *B = II->first;
4489 StrideDescriptor DesB = II->second;
4491 // Ignore if B is already in a group or B is a different memory operation.
4492 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4495 // Check the rule 1 and 2.
4496 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4499 // Calculate the distance and prepare for the rule 3.
4500 const SCEVConstant *DistToA =
4501 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4505 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4507 // Skip if the distance is not multiple of size as they are not in the
4509 if (DistanceToA % static_cast<int>(DesA.Size))
4512 // The index of B is the index of A plus the related index to A.
4514 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4516 // Try to insert B into the group.
4517 if (Group->insertMember(B, IndexB, DesB.Align)) {
4518 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4519 << " into the interleave group with" << *A << '\n');
4520 InterleaveGroupMap[B] = Group;
4522 // Set the first load in program order as the insert position.
4523 if (B->mayReadFromMemory())
4524 Group->setInsertPos(B);
4526 } // Iteration on instruction B
4527 } // Iteration on instruction A
4529 // Remove interleaved store groups with gaps.
4530 for (InterleaveGroup *Group : StoreGroups)
4531 if (Group->getNumMembers() != Group->getFactor())
4532 releaseGroup(Group);
4535 LoopVectorizationCostModel::VectorizationFactor
4536 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4537 // Width 1 means no vectorize
4538 VectorizationFactor Factor = { 1U, 0U };
4539 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4540 emitAnalysis(VectorizationReport() <<
4541 "runtime pointer checks needed. Enable vectorization of this "
4542 "loop with '#pragma clang loop vectorize(enable)' when "
4543 "compiling with -Os/-Oz");
4545 "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4549 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4550 emitAnalysis(VectorizationReport() <<
4551 "store that is conditionally executed prevents vectorization");
4552 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4556 // Find the trip count.
4557 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4558 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4560 unsigned WidestType = getWidestType();
4561 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4562 unsigned MaxSafeDepDist = -1U;
4563 if (Legal->getMaxSafeDepDistBytes() != -1U)
4564 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4565 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4566 WidestRegister : MaxSafeDepDist);
4567 unsigned MaxVectorSize = WidestRegister / WidestType;
4568 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4569 DEBUG(dbgs() << "LV: The Widest register is: "
4570 << WidestRegister << " bits.\n");
4572 if (MaxVectorSize == 0) {
4573 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4577 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4578 " into one vector!");
4580 unsigned VF = MaxVectorSize;
4582 // If we optimize the program for size, avoid creating the tail loop.
4584 // If we are unable to calculate the trip count then don't try to vectorize.
4587 (VectorizationReport() <<
4588 "unable to calculate the loop count due to complex control flow");
4589 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4593 // Find the maximum SIMD width that can fit within the trip count.
4594 VF = TC % MaxVectorSize;
4599 // If the trip count that we found modulo the vectorization factor is not
4600 // zero then we require a tail.
4601 emitAnalysis(VectorizationReport() <<
4602 "cannot optimize for size and vectorize at the "
4603 "same time. Enable vectorization of this loop "
4604 "with '#pragma clang loop vectorize(enable)' "
4605 "when compiling with -Os/-Oz");
4606 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4611 int UserVF = Hints->getWidth();
4613 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4614 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4616 Factor.Width = UserVF;
4620 float Cost = expectedCost(1);
4622 const float ScalarCost = Cost;
4625 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4627 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4628 // Ignore scalar width, because the user explicitly wants vectorization.
4629 if (ForceVectorization && VF > 1) {
4631 Cost = expectedCost(Width) / (float)Width;
4634 for (unsigned i=2; i <= VF; i*=2) {
4635 // Notice that the vector loop needs to be executed less times, so
4636 // we need to divide the cost of the vector loops by the width of
4637 // the vector elements.
4638 float VectorCost = expectedCost(i) / (float)i;
4639 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4640 (int)VectorCost << ".\n");
4641 if (VectorCost < Cost) {
4647 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4648 << "LV: Vectorization seems to be not beneficial, "
4649 << "but was forced by a user.\n");
4650 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4651 Factor.Width = Width;
4652 Factor.Cost = Width * Cost;
4656 unsigned LoopVectorizationCostModel::getWidestType() {
4657 unsigned MaxWidth = 8;
4658 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4661 for (Loop::block_iterator bb = TheLoop->block_begin(),
4662 be = TheLoop->block_end(); bb != be; ++bb) {
4663 BasicBlock *BB = *bb;
4665 // For each instruction in the loop.
4666 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4667 Type *T = it->getType();
4669 // Skip ignored values.
4670 if (ValuesToIgnore.count(it))
4673 // Only examine Loads, Stores and PHINodes.
4674 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4677 // Examine PHI nodes that are reduction variables. Update the type to
4678 // account for the recurrence type.
4679 if (PHINode *PN = dyn_cast<PHINode>(it)) {
4680 if (!Legal->getReductionVars()->count(PN))
4682 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4683 T = RdxDesc.getRecurrenceType();
4686 // Examine the stored values.
4687 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4688 T = ST->getValueOperand()->getType();
4690 // Ignore loaded pointer types and stored pointer types that are not
4691 // consecutive. However, we do want to take consecutive stores/loads of
4692 // pointer vectors into account.
4693 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4696 MaxWidth = std::max(MaxWidth,
4697 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4704 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4706 unsigned LoopCost) {
4708 // -- The interleave heuristics --
4709 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4710 // There are many micro-architectural considerations that we can't predict
4711 // at this level. For example, frontend pressure (on decode or fetch) due to
4712 // code size, or the number and capabilities of the execution ports.
4714 // We use the following heuristics to select the interleave count:
4715 // 1. If the code has reductions, then we interleave to break the cross
4716 // iteration dependency.
4717 // 2. If the loop is really small, then we interleave to reduce the loop
4719 // 3. We don't interleave if we think that we will spill registers to memory
4720 // due to the increased register pressure.
4722 // When we optimize for size, we don't interleave.
4726 // We used the distance for the interleave count.
4727 if (Legal->getMaxSafeDepDistBytes() != -1U)
4730 // Do not interleave loops with a relatively small trip count.
4731 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4732 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4735 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4736 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4740 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4741 TargetNumRegisters = ForceTargetNumScalarRegs;
4743 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4744 TargetNumRegisters = ForceTargetNumVectorRegs;
4747 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4748 // We divide by these constants so assume that we have at least one
4749 // instruction that uses at least one register.
4750 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4751 R.NumInstructions = std::max(R.NumInstructions, 1U);
4753 // We calculate the interleave count using the following formula.
4754 // Subtract the number of loop invariants from the number of available
4755 // registers. These registers are used by all of the interleaved instances.
4756 // Next, divide the remaining registers by the number of registers that is
4757 // required by the loop, in order to estimate how many parallel instances
4758 // fit without causing spills. All of this is rounded down if necessary to be
4759 // a power of two. We want power of two interleave count to simplify any
4760 // addressing operations or alignment considerations.
4761 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4764 // Don't count the induction variable as interleaved.
4765 if (EnableIndVarRegisterHeur)
4766 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4767 std::max(1U, (R.MaxLocalUsers - 1)));
4769 // Clamp the interleave ranges to reasonable counts.
4770 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4772 // Check if the user has overridden the max.
4774 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4775 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4777 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4778 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4781 // If we did not calculate the cost for VF (because the user selected the VF)
4782 // then we calculate the cost of VF here.
4784 LoopCost = expectedCost(VF);
4786 // Clamp the calculated IC to be between the 1 and the max interleave count
4787 // that the target allows.
4788 if (IC > MaxInterleaveCount)
4789 IC = MaxInterleaveCount;
4793 // Interleave if we vectorized this loop and there is a reduction that could
4794 // benefit from interleaving.
4795 if (VF > 1 && Legal->getReductionVars()->size()) {
4796 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4800 // Note that if we've already vectorized the loop we will have done the
4801 // runtime check and so interleaving won't require further checks.
4802 bool InterleavingRequiresRuntimePointerCheck =
4803 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4805 // We want to interleave small loops in order to reduce the loop overhead and
4806 // potentially expose ILP opportunities.
4807 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4808 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4809 // We assume that the cost overhead is 1 and we use the cost model
4810 // to estimate the cost of the loop and interleave until the cost of the
4811 // loop overhead is about 5% of the cost of the loop.
4813 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4815 // Interleave until store/load ports (estimated by max interleave count) are
4817 unsigned NumStores = Legal->getNumStores();
4818 unsigned NumLoads = Legal->getNumLoads();
4819 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4820 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4822 // If we have a scalar reduction (vector reductions are already dealt with
4823 // by this point), we can increase the critical path length if the loop
4824 // we're interleaving is inside another loop. Limit, by default to 2, so the
4825 // critical path only gets increased by one reduction operation.
4826 if (Legal->getReductionVars()->size() &&
4827 TheLoop->getLoopDepth() > 1) {
4828 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4829 SmallIC = std::min(SmallIC, F);
4830 StoresIC = std::min(StoresIC, F);
4831 LoadsIC = std::min(LoadsIC, F);
4834 if (EnableLoadStoreRuntimeInterleave &&
4835 std::max(StoresIC, LoadsIC) > SmallIC) {
4836 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4837 return std::max(StoresIC, LoadsIC);
4840 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4844 // Interleave if this is a large loop (small loops are already dealt with by
4846 // point) that could benefit from interleaving.
4847 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4848 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4849 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4853 DEBUG(dbgs() << "LV: Not Interleaving.\n");
4857 LoopVectorizationCostModel::RegisterUsage
4858 LoopVectorizationCostModel::calculateRegisterUsage() {
4859 // This function calculates the register usage by measuring the highest number
4860 // of values that are alive at a single location. Obviously, this is a very
4861 // rough estimation. We scan the loop in a topological order in order and
4862 // assign a number to each instruction. We use RPO to ensure that defs are
4863 // met before their users. We assume that each instruction that has in-loop
4864 // users starts an interval. We record every time that an in-loop value is
4865 // used, so we have a list of the first and last occurrences of each
4866 // instruction. Next, we transpose this data structure into a multi map that
4867 // holds the list of intervals that *end* at a specific location. This multi
4868 // map allows us to perform a linear search. We scan the instructions linearly
4869 // and record each time that a new interval starts, by placing it in a set.
4870 // If we find this value in the multi-map then we remove it from the set.
4871 // The max register usage is the maximum size of the set.
4872 // We also search for instructions that are defined outside the loop, but are
4873 // used inside the loop. We need this number separately from the max-interval
4874 // usage number because when we unroll, loop-invariant values do not take
4876 LoopBlocksDFS DFS(TheLoop);
4880 R.NumInstructions = 0;
4882 // Each 'key' in the map opens a new interval. The values
4883 // of the map are the index of the 'last seen' usage of the
4884 // instruction that is the key.
4885 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4886 // Maps instruction to its index.
4887 DenseMap<unsigned, Instruction*> IdxToInstr;
4888 // Marks the end of each interval.
4889 IntervalMap EndPoint;
4890 // Saves the list of instruction indices that are used in the loop.
4891 SmallSet<Instruction*, 8> Ends;
4892 // Saves the list of values that are used in the loop but are
4893 // defined outside the loop, such as arguments and constants.
4894 SmallPtrSet<Value*, 8> LoopInvariants;
4897 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4898 be = DFS.endRPO(); bb != be; ++bb) {
4899 R.NumInstructions += (*bb)->size();
4900 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4902 Instruction *I = it;
4903 IdxToInstr[Index++] = I;
4905 // Save the end location of each USE.
4906 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4907 Value *U = I->getOperand(i);
4908 Instruction *Instr = dyn_cast<Instruction>(U);
4910 // Ignore non-instruction values such as arguments, constants, etc.
4911 if (!Instr) continue;
4913 // If this instruction is outside the loop then record it and continue.
4914 if (!TheLoop->contains(Instr)) {
4915 LoopInvariants.insert(Instr);
4919 // Overwrite previous end points.
4920 EndPoint[Instr] = Index;
4926 // Saves the list of intervals that end with the index in 'key'.
4927 typedef SmallVector<Instruction*, 2> InstrList;
4928 DenseMap<unsigned, InstrList> TransposeEnds;
4930 // Transpose the EndPoints to a list of values that end at each index.
4931 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4933 TransposeEnds[it->second].push_back(it->first);
4935 SmallSet<Instruction*, 8> OpenIntervals;
4936 unsigned MaxUsage = 0;
4939 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4940 for (unsigned int i = 0; i < Index; ++i) {
4941 Instruction *I = IdxToInstr[i];
4942 // Ignore instructions that are never used within the loop.
4943 if (!Ends.count(I)) continue;
4945 // Skip ignored values.
4946 if (ValuesToIgnore.count(I))
4949 // Remove all of the instructions that end at this location.
4950 InstrList &List = TransposeEnds[i];
4951 for (unsigned int j=0, e = List.size(); j < e; ++j)
4952 OpenIntervals.erase(List[j]);
4954 // Count the number of live interals.
4955 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4957 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4958 OpenIntervals.size() << '\n');
4960 // Add the current instruction to the list of open intervals.
4961 OpenIntervals.insert(I);
4964 unsigned Invariant = LoopInvariants.size();
4965 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4966 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4967 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4969 R.LoopInvariantRegs = Invariant;
4970 R.MaxLocalUsers = MaxUsage;
4974 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4978 for (Loop::block_iterator bb = TheLoop->block_begin(),
4979 be = TheLoop->block_end(); bb != be; ++bb) {
4980 unsigned BlockCost = 0;
4981 BasicBlock *BB = *bb;
4983 // For each instruction in the old loop.
4984 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4985 // Skip dbg intrinsics.
4986 if (isa<DbgInfoIntrinsic>(it))
4989 // Skip ignored values.
4990 if (ValuesToIgnore.count(it))
4993 unsigned C = getInstructionCost(it, VF);
4995 // Check if we should override the cost.
4996 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4997 C = ForceTargetInstructionCost;
5000 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5001 VF << " For instruction: " << *it << '\n');
5004 // We assume that if-converted blocks have a 50% chance of being executed.
5005 // When the code is scalar then some of the blocks are avoided due to CF.
5006 // When the code is vectorized we execute all code paths.
5007 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5016 /// \brief Check whether the address computation for a non-consecutive memory
5017 /// access looks like an unlikely candidate for being merged into the indexing
5020 /// We look for a GEP which has one index that is an induction variable and all
5021 /// other indices are loop invariant. If the stride of this access is also
5022 /// within a small bound we decide that this address computation can likely be
5023 /// merged into the addressing mode.
5024 /// In all other cases, we identify the address computation as complex.
5025 static bool isLikelyComplexAddressComputation(Value *Ptr,
5026 LoopVectorizationLegality *Legal,
5027 ScalarEvolution *SE,
5028 const Loop *TheLoop) {
5029 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5033 // We are looking for a gep with all loop invariant indices except for one
5034 // which should be an induction variable.
5035 unsigned NumOperands = Gep->getNumOperands();
5036 for (unsigned i = 1; i < NumOperands; ++i) {
5037 Value *Opd = Gep->getOperand(i);
5038 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5039 !Legal->isInductionVariable(Opd))
5043 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5044 // can likely be merged into the address computation.
5045 unsigned MaxMergeDistance = 64;
5047 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5051 // Check the step is constant.
5052 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5053 // Calculate the pointer stride and check if it is consecutive.
5054 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5058 const APInt &APStepVal = C->getValue()->getValue();
5060 // Huge step value - give up.
5061 if (APStepVal.getBitWidth() > 64)
5064 int64_t StepVal = APStepVal.getSExtValue();
5066 return StepVal > MaxMergeDistance;
5069 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5070 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5076 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5077 // If we know that this instruction will remain uniform, check the cost of
5078 // the scalar version.
5079 if (Legal->isUniformAfterVectorization(I))
5082 Type *RetTy = I->getType();
5083 Type *VectorTy = ToVectorTy(RetTy, VF);
5085 // TODO: We need to estimate the cost of intrinsic calls.
5086 switch (I->getOpcode()) {
5087 case Instruction::GetElementPtr:
5088 // We mark this instruction as zero-cost because the cost of GEPs in
5089 // vectorized code depends on whether the corresponding memory instruction
5090 // is scalarized or not. Therefore, we handle GEPs with the memory
5091 // instruction cost.
5093 case Instruction::Br: {
5094 return TTI.getCFInstrCost(I->getOpcode());
5096 case Instruction::PHI:
5097 //TODO: IF-converted IFs become selects.
5099 case Instruction::Add:
5100 case Instruction::FAdd:
5101 case Instruction::Sub:
5102 case Instruction::FSub:
5103 case Instruction::Mul:
5104 case Instruction::FMul:
5105 case Instruction::UDiv:
5106 case Instruction::SDiv:
5107 case Instruction::FDiv:
5108 case Instruction::URem:
5109 case Instruction::SRem:
5110 case Instruction::FRem:
5111 case Instruction::Shl:
5112 case Instruction::LShr:
5113 case Instruction::AShr:
5114 case Instruction::And:
5115 case Instruction::Or:
5116 case Instruction::Xor: {
5117 // Since we will replace the stride by 1 the multiplication should go away.
5118 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5120 // Certain instructions can be cheaper to vectorize if they have a constant
5121 // second vector operand. One example of this are shifts on x86.
5122 TargetTransformInfo::OperandValueKind Op1VK =
5123 TargetTransformInfo::OK_AnyValue;
5124 TargetTransformInfo::OperandValueKind Op2VK =
5125 TargetTransformInfo::OK_AnyValue;
5126 TargetTransformInfo::OperandValueProperties Op1VP =
5127 TargetTransformInfo::OP_None;
5128 TargetTransformInfo::OperandValueProperties Op2VP =
5129 TargetTransformInfo::OP_None;
5130 Value *Op2 = I->getOperand(1);
5132 // Check for a splat of a constant or for a non uniform vector of constants.
5133 if (isa<ConstantInt>(Op2)) {
5134 ConstantInt *CInt = cast<ConstantInt>(Op2);
5135 if (CInt && CInt->getValue().isPowerOf2())
5136 Op2VP = TargetTransformInfo::OP_PowerOf2;
5137 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5138 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5139 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5140 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5142 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5143 if (CInt && CInt->getValue().isPowerOf2())
5144 Op2VP = TargetTransformInfo::OP_PowerOf2;
5145 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5149 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5152 case Instruction::Select: {
5153 SelectInst *SI = cast<SelectInst>(I);
5154 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5155 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5156 Type *CondTy = SI->getCondition()->getType();
5158 CondTy = VectorType::get(CondTy, VF);
5160 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5162 case Instruction::ICmp:
5163 case Instruction::FCmp: {
5164 Type *ValTy = I->getOperand(0)->getType();
5165 VectorTy = ToVectorTy(ValTy, VF);
5166 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5168 case Instruction::Store:
5169 case Instruction::Load: {
5170 StoreInst *SI = dyn_cast<StoreInst>(I);
5171 LoadInst *LI = dyn_cast<LoadInst>(I);
5172 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5174 VectorTy = ToVectorTy(ValTy, VF);
5176 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5177 unsigned AS = SI ? SI->getPointerAddressSpace() :
5178 LI->getPointerAddressSpace();
5179 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5180 // We add the cost of address computation here instead of with the gep
5181 // instruction because only here we know whether the operation is
5184 return TTI.getAddressComputationCost(VectorTy) +
5185 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5187 // For an interleaved access, calculate the total cost of the whole
5188 // interleave group.
5189 if (Legal->isAccessInterleaved(I)) {
5190 auto Group = Legal->getInterleavedAccessGroup(I);
5191 assert(Group && "Fail to get an interleaved access group.");
5193 // Only calculate the cost once at the insert position.
5194 if (Group->getInsertPos() != I)
5197 unsigned InterleaveFactor = Group->getFactor();
5199 VectorType::get(VectorTy->getVectorElementType(),
5200 VectorTy->getVectorNumElements() * InterleaveFactor);
5202 // Holds the indices of existing members in an interleaved load group.
5203 // An interleaved store group doesn't need this as it dones't allow gaps.
5204 SmallVector<unsigned, 4> Indices;
5206 for (unsigned i = 0; i < InterleaveFactor; i++)
5207 if (Group->getMember(i))
5208 Indices.push_back(i);
5211 // Calculate the cost of the whole interleaved group.
5212 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5213 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5214 Group->getAlignment(), AS);
5216 if (Group->isReverse())
5218 Group->getNumMembers() *
5219 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5221 // FIXME: The interleaved load group with a huge gap could be even more
5222 // expensive than scalar operations. Then we could ignore such group and
5223 // use scalar operations instead.
5227 // Scalarized loads/stores.
5228 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5229 bool Reverse = ConsecutiveStride < 0;
5230 const DataLayout &DL = I->getModule()->getDataLayout();
5231 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5232 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5233 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5234 bool IsComplexComputation =
5235 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5237 // The cost of extracting from the value vector and pointer vector.
5238 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5239 for (unsigned i = 0; i < VF; ++i) {
5240 // The cost of extracting the pointer operand.
5241 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5242 // In case of STORE, the cost of ExtractElement from the vector.
5243 // In case of LOAD, the cost of InsertElement into the returned
5245 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5246 Instruction::InsertElement,
5250 // The cost of the scalar loads/stores.
5251 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5252 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5257 // Wide load/stores.
5258 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5259 if (Legal->isMaskRequired(I))
5260 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5263 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5266 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5270 case Instruction::ZExt:
5271 case Instruction::SExt:
5272 case Instruction::FPToUI:
5273 case Instruction::FPToSI:
5274 case Instruction::FPExt:
5275 case Instruction::PtrToInt:
5276 case Instruction::IntToPtr:
5277 case Instruction::SIToFP:
5278 case Instruction::UIToFP:
5279 case Instruction::Trunc:
5280 case Instruction::FPTrunc:
5281 case Instruction::BitCast: {
5282 // We optimize the truncation of induction variable.
5283 // The cost of these is the same as the scalar operation.
5284 if (I->getOpcode() == Instruction::Trunc &&
5285 Legal->isInductionVariable(I->getOperand(0)))
5286 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5287 I->getOperand(0)->getType());
5289 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5290 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5292 case Instruction::Call: {
5293 bool NeedToScalarize;
5294 CallInst *CI = cast<CallInst>(I);
5295 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5296 if (getIntrinsicIDForCall(CI, TLI))
5297 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5301 // We are scalarizing the instruction. Return the cost of the scalar
5302 // instruction, plus the cost of insert and extract into vector
5303 // elements, times the vector width.
5306 if (!RetTy->isVoidTy() && VF != 1) {
5307 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5309 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5312 // The cost of inserting the results plus extracting each one of the
5314 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5317 // The cost of executing VF copies of the scalar instruction. This opcode
5318 // is unknown. Assume that it is the same as 'mul'.
5319 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5325 char LoopVectorize::ID = 0;
5326 static const char lv_name[] = "Loop Vectorization";
5327 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5328 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5329 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5330 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5331 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5332 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5333 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5334 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5335 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5336 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5337 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5338 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5341 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5342 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5346 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5347 // Check for a store.
5348 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5349 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5351 // Check for a load.
5352 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5353 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5359 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5360 bool IfPredicateStore) {
5361 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5362 // Holds vector parameters or scalars, in case of uniform vals.
5363 SmallVector<VectorParts, 4> Params;
5365 setDebugLocFromInst(Builder, Instr);
5367 // Find all of the vectorized parameters.
5368 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5369 Value *SrcOp = Instr->getOperand(op);
5371 // If we are accessing the old induction variable, use the new one.
5372 if (SrcOp == OldInduction) {
5373 Params.push_back(getVectorValue(SrcOp));
5377 // Try using previously calculated values.
5378 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5380 // If the src is an instruction that appeared earlier in the basic block
5381 // then it should already be vectorized.
5382 if (SrcInst && OrigLoop->contains(SrcInst)) {
5383 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5384 // The parameter is a vector value from earlier.
5385 Params.push_back(WidenMap.get(SrcInst));
5387 // The parameter is a scalar from outside the loop. Maybe even a constant.
5388 VectorParts Scalars;
5389 Scalars.append(UF, SrcOp);
5390 Params.push_back(Scalars);
5394 assert(Params.size() == Instr->getNumOperands() &&
5395 "Invalid number of operands");
5397 // Does this instruction return a value ?
5398 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5400 Value *UndefVec = IsVoidRetTy ? nullptr :
5401 UndefValue::get(Instr->getType());
5402 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5403 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5406 if (IfPredicateStore) {
5407 assert(Instr->getParent()->getSinglePredecessor() &&
5408 "Only support single predecessor blocks");
5409 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5410 Instr->getParent());
5413 // For each vector unroll 'part':
5414 for (unsigned Part = 0; Part < UF; ++Part) {
5415 // For each scalar that we create:
5417 // Start an "if (pred) a[i] = ..." block.
5418 Value *Cmp = nullptr;
5419 if (IfPredicateStore) {
5420 if (Cond[Part]->getType()->isVectorTy())
5422 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5423 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5424 ConstantInt::get(Cond[Part]->getType(), 1));
5427 Instruction *Cloned = Instr->clone();
5429 Cloned->setName(Instr->getName() + ".cloned");
5430 // Replace the operands of the cloned instructions with extracted scalars.
5431 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5432 Value *Op = Params[op][Part];
5433 Cloned->setOperand(op, Op);
5436 // Place the cloned scalar in the new loop.
5437 Builder.Insert(Cloned);
5439 // If the original scalar returns a value we need to place it in a vector
5440 // so that future users will be able to use it.
5442 VecResults[Part] = Cloned;
5445 if (IfPredicateStore)
5446 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
5451 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5452 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5453 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5455 return scalarizeInstruction(Instr, IfPredicateStore);
5458 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5462 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5466 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5467 // When unrolling and the VF is 1, we only need to add a simple scalar.
5468 Type *ITy = Val->getType();
5469 assert(!ITy->isVectorTy() && "Val must be a scalar");
5470 Constant *C = ConstantInt::get(ITy, StartIdx);
5471 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");